diff --git a/lib/Ds1820.ml b/lib/Ds1820.ml index 8ef432b..0e9c7aa 100644 --- a/lib/Ds1820.ml +++ b/lib/Ds1820.ml @@ -1,19 +1,45 @@ open! Base -let parse s = - Stdlib.Scanf.sscanf s "%s@ t=%f" (fun _ t -> t /. 1000.) +type t = Temperature of float + +let temperature f = Temperature f -let%test_unit "parse temperature" = - [%test_eq: float ] (parse "brol\nmore junk text t=18241") 18.241 +let value (Temperature f) = f + +let parse s = + let re = Str.regexp " t=\\([0-9]+\\)" in + try + if (Str.search_forward re s 0) > 0 + then Some (Float.of_string (Str.matched_group 1 s) /. 1000.0) + else None + with Stdlib.Not_found -> None + +let%test_unit "parse temperature" = + [%test_eq: float option] (parse "brol\nmore junk text t=18241") (Some 18.241) let read_temperature file_name = let open Lwt.Infix in - let rec aux () = - Lwt_io.with_file ~mode:Lwt_io.Input file_name (fun ic -> - Lwt_io.read_all ic >>= function - | None -> aux () - | Some s -> Lwt.return (parse s) + Lwt_io.with_file ~mode:Lwt_io.Input file_name (fun ic -> + Lwt_io.read ic >>= (fun s -> + parse s |> Option.map ~f:temperature |> Lwt.return ) - in - aux + ) + +let write_test_file file_name = + Lwt_io.with_file ~mode:Lwt_io.Output file_name (fun oc -> + Lwt_io.write_line oc "brol\nmore junk text t=18241" + ) + +let%test "read temperature from file" = + let open Lwt.Infix in + let file_name = "test_temperature.txt" in + let aux = write_test_file file_name + >>= fun () -> (read_temperature file_name) + >>= function + | Some (Temperature t) -> Lwt.return Float.(t = 18.241) + | _ -> Lwt.return false + in Lwt_main.run aux + + + diff --git a/lib/dune b/lib/dune index 2ab082f..092c453 100644 --- a/lib/dune +++ b/lib/dune @@ -1,5 +1,5 @@ (library (name oblub) (inline_tests) - (libraries lwt lwt.unix) + (libraries str lwt lwt.unix lwt_ppx) (preprocess (pps ppx_inline_test ppx_assert ppx_expect)))