Current section
Files
Jump to
Current section
Files
lib/pmsa003i.ex
defmodule PMSA003I do
use GenServer
require Logger
alias PMSA003I.Comm
@default_polling_interval_ms 10_000
def start_link(init_arg \\ []) do
options = Keyword.take(init_arg, [:name])
GenServer.start_link(__MODULE__, init_arg, options)
end
def measure(pid) do
GenServer.call(pid, :measure)
end
@impl true
@spec init(keyword) ::
{:ok, %{device_addr: any, i2c: reference, last_reading: PMSA003I.Measurement.t()}}
def init(options \\ []) do
# Sample options keyword list :
# [transport: {"i2c-1", 0x5B}]
# [polling_interval: 5_000]
polling_interval = Keyword.get(options, :polling_interval, @default_polling_interval_ms)
{bus_name, device_addr} = Keyword.get(options, :transport, Comm.discover())
Logger.info(
"Starting PMSA00I on bus: #{bus_name}, address: #{device_addr} : " <>
"Polling interval : #{polling_interval}"
)
i2c = Comm.open(bus_name)
:timer.send_interval(polling_interval, :measure)
state = %{
i2c: i2c,
device_addr: device_addr,
last_reading: %PMSA003I.Measurement{}
}
{:ok, state}
end
@impl true
def handle_info(
:measure,
%{i2c: i2c, device_addr: device_addr} = state
) do
updated_with_reading = %{
state
| last_reading: PMSA003I.Register.read(i2c, device_addr)
}
{:noreply, updated_with_reading}
end
@impl true
def handle_call(:measure, _from, state) do
{:reply, {:ok, state.last_reading}, state}
end
end