-
Notifications
You must be signed in to change notification settings - Fork 16
/
mqtt_client.js
90 lines (80 loc) · 2.57 KB
/
mqtt_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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const common = require('./common');
const gateway = require('./gateway');
const mqtt = require('mqtt');
const mqtt_client = mqtt.connect(common.config.mqtt_url, common.config.mqtt_options);
mqtt_client.on('connect', () => {
common.myLog('mqtt_client.connect', common.colors.green);
// Отправляем состояния устройств
gateway.getState();
gateway.getLamp();
gateway.getIlluminance();
gateway.getPlay();
gateway.getVolume();
mqtt_client.subscribe([common.config.mqtt_topic + '/+/set', common.config.mqtt_topic + '/+/+/set'], function () {
common.myLog('mqtt_client.subscribe', common.colors.green);
});
});
mqtt_client.on('message', (topic, message) => {
common.myLog('Получен topic= ' + topic, common.colors.yellow);
common.myLog('message = ' + message);
try {
switch (topic.split("/")[1]) {
case 'light':
// lumi/light/set
gateway.setLamp(message);
break;
case 'audio':
// lumi/audio/volume/set
// lumi/audio/play/set
switch (topic.split("/")[2]) {
case 'play':
gateway.setPlay(message);
break;
case 'volume':
gateway.setVolume(message);
break;
}
break;
case 'say':
// lumi/say/set
gateway.setSay(message);
break;
case 'alarm':
// lumi/alarm/set
gateway.setAlarm(message);
break;
}
} catch (err) {
common.myLog(err, common.colors.red);
}
});
mqtt_client.on('error', err => {
common.myLog(err, common.colors.red);
});
//////////////////
function publish_json(device, retain = false) {
try {
mqtt_client.publish(device.state_topic, JSON.stringify(device.value), {retain: retain});
} catch (e) {
common.myLog(e, common.colors.red);
}
}
function publish_value(device, retain = false) {
try {
mqtt_client.publish(device.state_topic, device.value.toString(), {retain: retain});
} catch (e) {
common.myLog(e, common.colors.red);
}
}
function publish_homeassistant(device) {
try {
mqtt_client.publish(device.config_topic, JSON.stringify(device.homeassistant), {retain: true});
} catch (e) {
common.myLog(e, common.colors.red);
}
}
module.exports = {
publish_json,
publish_value,
publish_homeassistant
}