package carbon

  1. Overview
  2. Docs
OCaml library for accessing various Carbon Intensity APIs

Install

Dune Dependency

Authors

Maintainers

Sources

carbon-0.1.0.tbz
sha256=7fa704f5c5ff3bbc17d8e1cb8360e1dcb8e12fe909d5eac43a1242232560a97a
sha512=88cd08f1f12911bfc8651297111a45972e972278ae137b4bc3e28fddd02f57ced1d10b25fafc57fb760b9424cfd686d4ca48f3292ed4030838e2f66021440d8b

doc/src/carbon/co2_signal.ml.html

Source file co2_signal.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
module Zone = Zone

type t = { token : string; net : Eio.Net.t }

let v ~api_key net = { token = api_key; net }

module Endpoints = struct
  let base = "api.co2signal.com"
  let version = "v1"

  let uri ~path ~query =
    Uri.make ~scheme:"https" ~host:base ~path:(version ^ "/" ^ path) ~query ()
end

let headers t =
  Http.Header.of_list
    [
      ("Accept", "application/json");
      ("auth-token", t.token);
      ("Host", Endpoints.base);
    ]

module Intensity = struct
  type t = {
    zone : Zone.t;
    datetime : string;
    carbon_intensity : int;
    fossil_fuel_percentage : float;
  }

  let intensity t = t.carbon_intensity
  let datetime t = t.datetime
  let zone t = t.zone
  let pp_co2 ppf v = Fmt.pf ppf "%i gCO2/kWh" v

  let pp ppf t =
    Fmt.pf ppf
      "zone: %s@.datetime: %s@.intensity: %a@.fossil fuel percentage: %f"
      (Zone.to_string t.zone) t.datetime pp_co2 t.carbon_intensity
      t.fossil_fuel_percentage
end

let get_intensity ~zone t =
  let headers = headers t in
  let resource =
    Endpoints.uri ~path:"latest"
      ~query:[ ("countryCode", [ Zone.to_string zone ]) ]
    |> Uri.path_and_query
  in
  let data =
    Http_client.get_json ~net:t.net ~headers Endpoints.(base, resource)
    |> J.path [ "data" ]
  in
  Fmt.pr "%s" (Ezjsonm.value_to_string data);
  match
    ( J.find data [ "datetime" ],
      J.find data [ "carbonIntensity" ],
      J.find data [ "fossilFuelPercentage" ] )
  with
  | Some date, Some ci, Some ffp ->
      {
        Intensity.zone;
        datetime = J.to_string date;
        carbon_intensity = J.to_int ci;
        fossil_fuel_percentage = J.to_float ffp;
      }
  | _ -> invalid_arg "Malformed JSON data for get_intensity"
OCaml

Innovation. Community. Security.