forked from jdomeij/node-red-contrib-node-lifx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt.js
72 lines (56 loc) · 1.67 KB
/
mqtt.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
var LightServer = require('node-red-contrib-node-lifx');
var mqtt = require('mqtt');
var config = {
mqtt: 'mqtt://<mqtt server>',
server: {
}
}
// List of all detected lights
var lightsList = {};
var mqttClient = mqtt.connect(config.mqtt);
// Wait for connection
mqttClient.on('connect', () => {
// List of all detected lights with topic
var allLights = [];
var server = new LightServer(config.server);
server.on('light-new', (lightInfo) => {
var baseTopic = 'lights/' + lightInfo.id;
if (lightsList.hasOwnProperty(baseTopic))
return;
var handle = server.getLightHandler(lightInfo.id);
// Remember base topic
lightsList[baseTopic] = handle;
// Subscribe to topics
mqttClient.subscribe(baseTopic + '/on');
mqttClient.subscribe(baseTopic + '/brightness');
allLights.push({
name: lightInfo.info.name,
topic: baseTopic
});
// publish list of all detected lights
mqttClient.publish('lights', JSON.stringify(allLights), { retain: true} );
});
});
// Handle messages
mqttClient.on('message', (topic, message) => {
var pattern = /^(.*)\/(on|brightness)$/;
// Check that the pattern match
var match;
if ((match = pattern.exec(topic)) == null)
return;
// Check so we have the light
if (!lightsList.hasOwnProperty(match[1]))
return;
var light = lightsList[match[1]];
var data = message.toString();
if (match[2] === 'on') {
if (!/^(true|false)$/.test(data))
return;
light.setLightState({ 'on': (data === 'true') });
}
else if (match[2] === 'brightness') {
if (!/^[0-9]+$/.test(data))
return;
light.setLightState({ 'brightness': parseInt(data, 10) })
}
});