-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp.js
executable file
·180 lines (146 loc) · 5.18 KB
/
app.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
'use strict'
const MQTT_TOPIC = "/hvac/intesis"
const MQTT_STATE_TOPIC = "/stat" + MQTT_TOPIC
const MQTT_COMMAND_TOPIC = "/cmnd" + MQTT_TOPIC
const argv = require('yargs')
.usage('Usage: $0 [--discover] --mqtt [mqtt url] [--mqttuser user --mqttpass pass] [--wmp ip address(,ip address,...)] [--retain [true/false]]')
.demandOption(['mqtt'])
.argv;
let supplied_intesis_ips = [];
if (argv.wmp) {
supplied_intesis_ips = argv.wmp.split(',');
}
let retain_flag = (argv.retain === "true") ? true:false;
const mqtt_url = argv.mqtt;
var winston = require('winston');
const logger = winston.createLogger({
level: 'debug',
format: winston.format.combine(
winston.format.splat(),
winston.format.simple()
),
transports: [
new winston.transports.Console()
]
});
const options = {}
if (argv.mqttuser && argv.mqttpass) {
options.username = argv.mqttuser
options.password = argv.mqttpass
}
console.log('options', { options })
const mqtt = require('mqtt')
const wmp = require('./wmp');
//todo detect connection failures
let mqttClient = mqtt.connect(mqtt_url, options)
mqttClient.on('error', function (error) {
logger.error("Error from mqtt broker: %v", error)
});
mqttClient.on('connect', function (connack) {
logger.info("Connected to mqtt broker")
});
let runWMP2Mqtt = function (mqttClient, wmpclient) {
wmpclient.on('update', function (data) {
logger.debug('Sending to MQTT: ' + JSON.stringify(data));
mqttClient.publish(MQTT_STATE_TOPIC + "/" + wmpclient.mac + "/settings/" + data.feature.toLowerCase(), data.value.toString().toLowerCase(), {retain:retain_flag})
});
}
let parseCommand = function (topic, payload) {
// format of commands is /<topic>/<mac>/<area>/<feature> payload (for set only is value
let rv = {};
//strip prefix and split
let parts = topic.substr(MQTT_COMMAND_TOPIC.length).replace(/^\/+/g, '').split("/");
rv['mac'] = parts[0];
switch (parts[1].toUpperCase()) {
case "SETTINGS":
rv['feature'] = parts[2]
if (payload && payload.length > 0) {
rv['command'] = "SET";
rv['value'] = payload;
} else {
rv['command'] = "GET";
}
break;
default:
rv['command'] = parts[1];
}
return rv;
}
var runMqtt2WMP = function (mqttClient, wmpclientMap) {
mqttClient.subscribe(MQTT_COMMAND_TOPIC + "/#")
mqttClient.on('message', function (topic, message) {
let cmd = parseCommand(topic, message);
let wmpclient = wmpclientMap[cmd.mac];
if (!wmpclient) {
logger.warn("Cannot find WMP server with MAC " + cmd.mac + "! Ignoring...")
return;
}
switch (cmd.command) {
case "ID":
wmpclient.id().then(function (data) {
logger.debug("published to mqtt: %", JSON.stringify(data))
mqttClient.publish(MQTT_STATE_TOPIC, JSON.stringify(data), {retain:retain_flag})
});
break;
case "INFO":
wmpclient.info().then(function (data) {
logger.debug("published to mqtt: %", JSON.stringify(data))
mqttClient.publish(MQTT_STATE_TOPIC, JSON.stringify(data), {retain:retain_flag})
});
break;
case "GET":
wmpclient.get(cmd.feature);
break;
case "SET":
wmpclient.set(cmd.feature, cmd.value);
break;
}
})
let keepalive = setInterval(function() {
try {
let wmpclients = Object.keys(wmpclientMap)
wmpclients.forEach(function(mac) {
logger.info("keepalive: keeping alive MAC " + mac)
let wmpclient = wmpclientMap[mac];
wmpclient.id().then(function (data) {
//todo: something useful with keepalive?
});
});
} catch (err) {
logger.warn(err);
logger.warn("Failure in keepalive (connection dead?)");
}
}, 30000);
}
var macToClient = {};
let wmpConnect = function (ip) {
//todo: prevent duplicate registrations
wmp.connect(ip).then(function (wmpclient) {
logger.info("Connected to WMP at IP " + ip + " with MAC " + wmpclient.mac);
wmpclient.on('close', function () {
logger.warn('WMP Connection closed! Closing MQTT connection and exiting...');
mqttClient.end(false, {}, () => process.exit(-1));
});
macToClient[wmpclient.mac] = wmpclient
runWMP2Mqtt(mqttClient, wmpclient)
})
};
supplied_intesis_ips.map(function (ip) {
wmpConnect(ip);
});
const DISCOVER_WAIT = 10; //seconds
let doDiscover = function() {
wmp.discover(1000, function (data) {
logger.info("Discovered")
wmpConnect(data.ip);
}, function(){
if(Object.keys(macToClient).length === 0) {
logger.info("Nothing connected, retrying discovery in " + DISCOVER_WAIT + " seconds..");
setTimeout(doDiscover, DISCOVER_WAIT * 1000)
}
});
}
if (argv.discover) {
doDiscover();
};
runMqtt2WMP(mqttClient, macToClient);