-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt_client.js
68 lines (57 loc) · 2.1 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
//@ts-check
const mqtt = require('mqtt');
const { logger } = require('./logger.js');
const { mqtt_url, chargeModeTopic, chargeStateTopic, plannerActiveTopic } = require("./config");
function connect(handler) {
const client = mqtt.connect(mqtt_url);
// connect to same client and subscribe to same topic name
client.on('connect', () => {
logger.info("connected, subscribing....");
// can also accept objects in the form {'topic': qos}
client.subscribe(chargeModeTopic, (err, granted) => {
if (err) {
logger.error(err, 'err');
}
logger.info("subscribed to %s", chargeModeTopic);
});
client.subscribe(chargeStateTopic, (err, granted) => {
if (err) {
logger.error(err, 'err');
}
logger.info("subscribed to %s", chargeStateTopic);
});
client.subscribe(plannerActiveTopic, (err, granted) => {
if (err) {
logger.error(err, 'err');
}
logger.info("subscribed to %s", plannerActiveTopic);
});
});
// on receive message event, log the message to the console
client.on('message', (topic, message, packet) => {
logger.trace(packet);
if (topic === chargeModeTopic) {
let newMode =packet.payload.toString();
logger.trace('read chargeMode %s', newMode);
handler.setChargeMode(newMode);
return;
}
if (topic === chargeStateTopic) {
let newState = JSON.parse(packet.payload.toString());
logger.trace('read chargeState %s', newState);
handler.setCharging(newState);
return;
}
if (topic === plannerActiveTopic) {
let newState = JSON.parse(packet.payload.toString());
logger.trace('read plannerActive %s', newState);
handler.setPlannerActive(newState);
return;
}
});
client.on("packetsend", (packet) => {
logger.trace(packet, 'packet2');
});
return client;
}
exports.connect = connect;