-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathDL-RAD.ex
More file actions
99 lines (77 loc) · 2.53 KB
/
DL-RAD.ex
File metadata and controls
99 lines (77 loc) · 2.53 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# https://www.decentlab.com/products/radar-distance-level-sensor-for-lorawan
defmodule DecentlabDecoder do
@protocol_version 2
defp sensor_defs do
[
%{
length: 4,
values: [
%{
:name => "Distance",
:convert => fn x -> Enum.at(x, 0) end,
:unit => "mm"
},
%{
:name => "Temperature",
:convert => fn x -> (Enum.at(x, 1) - 32768) / 100 end,
:unit => "°C"
},
%{
:name => "Reliability",
:convert => fn x -> (Enum.at(x, 2) - 32768) / 100 end,
:unit => "dB"
},
%{
:name => "Status",
:convert => fn x -> Enum.at(x, 3) end,
:unit => nil
}
]
},
%{
length: 1,
values: [
%{
:name => "Battery voltage",
:convert => fn x -> Enum.at(x, 0) / 1000 end,
:unit => "V"
}
]
}
]
end
def decode(msg, :hex) do
{:ok, bytes} = Base.decode16(msg, case: :mixed)
decode(bytes)
end
def decode(msg) when is_binary(msg), do: decode_binary(msg)
def decode(msg), do: to_string(msg) |> decode
defp decode_binary(<<@protocol_version, device_id::size(16), flags::binary-size(2), bytes::binary>>) do
bytes
|> bytes_to_words()
|> sensor(flags, sensor_defs())
|> Map.put("Device ID", device_id)
|> Map.put("Protocol version", @protocol_version)
end
defp bytes_to_words(<<>>), do: []
defp bytes_to_words(<<word::size(16), rest::binary>>), do: [word | bytes_to_words(rest)]
defp sensor(words, <<flags::size(15), 1::size(1)>>, [%{length: len, values: value_defs} | rest]) do
{x, rest_words} = Enum.split(words, len)
value(value_defs, x)
|> Map.merge(sensor(rest_words, <<0::size(1), flags::size(15)>>, rest))
end
defp sensor(words, <<flags::size(15), 0::size(1)>>, [_cur | rest]) do
sensor(words, <<0::size(1), flags::size(15)>>, rest)
end
defp sensor([], _flags, []), do: %{}
defp value([], _x), do: %{}
defp value([%{convert: nil} | rest], x), do: value(rest, x)
defp value([%{name: name, unit: unit, convert: convert} | rest], x) do
value(rest, x)
|> Map.put(name, %{"unit" => unit, "value" => convert.(x)})
end
defp where(true, if_true, _if_false), do: if_true
defp where(false, _if_true, if_false), do: if_false
end
IO.inspect(DecentlabDecoder.decode("02586b0003074c88b68a8c00000b93", :hex))
IO.inspect(DecentlabDecoder.decode("02586b00020b93", :hex))