dromloc/src/msg.ml
2023-05-08 14:49:54 +02:00

57 lines
1.5 KiB
OCaml

type pos =
{ latitude : float
; longitude : float
; accuracy : float
; timestamp_ms : float
}
let pos_to_string pos =
Format.sprintf
{|
{ latitude = %f
; longitude = %f
; accuracy = %f
; timestamp_ms = %f
}|}
pos.latitude pos.longitude pos.accuracy pos.timestamp_ms
open Data_encoding
let pos_to_tuple { latitude; longitude; accuracy; timestamp_ms } =
(latitude, longitude, accuracy, timestamp_ms)
let tuple_to_pos (latitude, longitude, accuracy, timestamp_ms) =
{ latitude; longitude; accuracy; timestamp_ms }
let pos_encoding = conv pos_to_tuple tuple_to_pos (tup4 float float float float)
let pos_with_id_encoding = tup2 string pos_encoding
let encode_pos v =
match Binary.to_string pos_encoding v with
| Error e ->
Error (Format.asprintf "Failed to encode pos: %a" Binary.pp_write_error e)
| Ok s -> Ok (Format.sprintf "%S" s)
let encode_pos_with_id v =
match Binary.to_string pos_with_id_encoding v with
| Error e ->
Error
(Format.asprintf "Failed to encode pos with id: %a" Binary.pp_write_error
e )
| Ok s -> Ok (Format.sprintf "%S" s)
let decode_pos v =
let v = Scanf.sscanf v "%S" (fun s -> s) in
Result.map_error
(fun e -> Format.asprintf "Failed to decode pos: %a" Binary.pp_read_error e)
(Binary.of_string pos_encoding v)
let decode_pos_with_id v =
let v = Scanf.sscanf v "%S" (fun s -> s) in
Result.map_error
(fun e ->
Format.asprintf "Failed to decode pos with id: %a" Binary.pp_read_error e
)
(Binary.of_string pos_with_id_encoding v)