-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtl_client.js
72 lines (61 loc) · 1.73 KB
/
rtl_client.js
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
const udp = require('dgram');
const db = require('./redis');
const server = udp.createSocket('udp4');
function tryParsePayload(payload) {
let string = payload.reduce((s, byte) => s + String.fromCharCode(byte), '');
try {
return JSON.parse(string);
} catch(e) {
return null;
}
}
function preprocess(data) {
data.key = createId(data);
if (data.payload && Array.isArray(data.payload)) {
let parsed = tryParsePayload(data.payload);
if (parsed) {
Object.assign(data, parsed);
}
}
}
function start (host = '127.0.0.1', port = 1433) {
server.bind(port, host);
server.on('error', function (error) {
console.log('Error: ' + error);
server.close();
});
server.on('message', async function (msg, info) {
const raw = msg.toString();
try {
const data = JSON.parse(raw.split(' ').slice(7).join());
preprocess(data);
await db.storeReading(data);
} catch (error) {
console.error('Handling Event failed with', error);
console.error('Data received from client : ' + msg.toString());
console.error('Received %d bytes from %s:%d\n', msg.length, info.address, info.port);
}
});
server.on('listening', function () {
var address = server.address();
var port = address.port;
var family = address.family;
var ipaddr = address.address;
console.log(`RTL_433 client ist listening at ${family} ${ipaddr}:${port}`);
});
server.on('close', function () {
console.log('Socket is closed !');
});
}
const client = {
server,
start
};
function createId (data) {
let ret = '';
if (data.model) { ret += data.model; }
if (data.id) { ret += ':' + data.id; }
if (data.channel) { ret += '@' + data.channel; }
return ret;
}
module.exports = client;