-
Notifications
You must be signed in to change notification settings - Fork 5
/
udp-json.js
80 lines (60 loc) · 2.21 KB
/
udp-json.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
73
74
75
76
77
78
79
80
'use strict';
const dgram = require('dgram');
let Service, Characteristic;
module.exports = (homebridge) => {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-udp-json', 'UDPJSON', UDPJSONPlugin);
};
class UDPJSONPlugin
{
constructor(log, config) {
this.log = log;
this.name = config.name;
this.name_temperature = config.name_temperature || this.name;
this.name_humidity = config.name_humidity || this.name;
this.listen_port = config.listen_port || 8268;
this.informationService = new Service.AccessoryInformation();
this.informationService
.setCharacteristic(Characteristic.Manufacturer, "Bosch")
.setCharacteristic(Characteristic.Model, "RPI-UDPJSON")
.setCharacteristic(Characteristic.SerialNumber, this.device);
this.temperatureService = new Service.TemperatureSensor(this.name_temperature);
this.temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.setProps({
minValue: -100,
maxValue: 100
});
this.humidityService = new Service.HumiditySensor(this.name_humidity);
this.server = dgram.createSocket('udp4');
this.server.on('error', (err) => {
console.log(`udp server error:\n${err.stack}`);
this.server.close();
});
this.server.on('message', (msg, rinfo) => {
console.log(`server received udp: ${msg} from ${rinfo.address}`);
let json;
try {
json = JSON.parse(msg);
} catch (e) {
console.log(`failed to decode JSON: ${e}`);
return;
}
const temperature_c = json.temperature_c;
//const pressure_hPa = json.pressure_hPa; // TODO
//const altitude_m = json.altitude_m;
const humidity_percent = json.humidity_percent;
this.temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.setValue(temperature_c);
this.humidityService
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.setValue(humidity_percent);
});
this.server.bind(this.listen_port);
}
getServices() {
return [this.informationService, this.temperatureService, this.humidityService]
}
}