-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathDL-DLR2-012.php
90 lines (77 loc) · 2.53 KB
/
DL-DLR2-012.php
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
<?php
/* https://www.decentlab.com/products/analog-or-digital-sensor-device-for-lorawan */
abstract class DecentlabDecoder
{
const PROTOCOL_VERSION = 2;
protected $sensors;
public function decode($payload = '')
{
$bytes = hex2bin($payload);
$parts = [];
$parts['version'] = ord($bytes[0]);
if ($parts['version'] != self::PROTOCOL_VERSION) {
$parts['error'] = sprintf("protocol version %u doesn't match v2", $parts['version']);
return $parts;
}
$parts['device_id'] = unpack('n', substr($bytes, 1))[1];
$flags = unpack('n', substr($bytes, 3))[1];
/* decode payload */
$k = 5;
foreach ($this->sensors as $sensor) {
if (($flags & 1) == 1) {
$x = [];
/* convert data to 16-bit integer array */
for ($j = 0; $j < $sensor['length']; $j++) {
array_push($x, unpack('n', substr($bytes, $k))[1]);
$k += 2;
}
/* decode sensor values */
foreach ($sensor['values'] as $value) {
if ($value['convert'] != NULL) {
$parts[$value['name'] . '_value'] = $value['convert']($x);
if ($value['unit'] != NULL) {
$parts[$value['name'] . '_unit'] = $value['unit'];
}
}
}
}
$flags >>= 1;
}
return $parts;
}
}
class DL_DLR2_012_Decoder extends DecentlabDecoder {
public function __construct()
{
$this->sensors = [
[
'length' => 2,
'values' => [
[
'name' => 'strain_gauge',
'convert' => function ($x) { return (($x[0] + $x[1]*65536) / 8388608 - 1) / 64 * 4 / 2.02 * 1000000; },
'unit' => 'µm⋅m⁻¹',
],
],
],
[
'length' => 1,
'values' => [
[
'name' => 'battery_voltage',
'convert' => function ($x) { return $x[0] / 1000; },
'unit' => 'V',
],
],
],
];
}
}
$decoder = new DL_DLR2_012_Decoder();
$payloads = [
'0217830003162e00870c33',
'02178300020c33',
];
foreach($payloads as $payload) {
var_dump($decoder->decode($payload));
}