-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmqtt.js
86 lines (75 loc) · 2.68 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
let Mqtt = require('mqtt');
let paramters = require('./parameters').parameters;
let logger = require('./log').logger;
function MqttHandler() {
const self = this;
if (!paramters.mqtt) {
return;
}
if (paramters) {
this.client = Mqtt.connect(paramters.mqtt.server, {
clientId: paramters.mqtt.clientId,
connectTimeout: paramters.mqtt.connectTimeout,
keepalive: paramters.mqtt.keepalive,
password: paramters.mqtt.password,
username: paramters.mqtt.username,
reconnectPeriod: paramters.mqtt.reconnectPeriod,
port: paramters.mqtt.port
});
this.client.on('error', (topic, message) => {
message = typeof message !== 'undefined' ? message : '';
logger.error('mqtt error - ' + topic + ' : ' + message.toString());
});
this.client.on('close', () => {
logger.error('mqtt close');
});
this.client.on('reconnect', () => {
logger.error('mqtt reconnect');
});
this.client.on('connect', function () {
logger.info('connected');
});
};
this.connect = function () {
this.client = Mqtt.connect(paramters.mqtt.server, {
clientId: paramters.mqtt.clientId,
connectTimeout: paramters.mqtt.connectTimeout,
keepalive: paramters.mqtt.keepalive,
password: paramters.mqtt.password,
username: paramters.mqtt.username,
reconnectPeriod: paramters.mqtt.reconnectPeriod,
port: paramters.mqtt.port
});
};
this.publish = function (part, data) {
try {
if (typeof data === 'undefined') {
throw new Error('data not defined')
}
if (data === null) {
return;
}
const topic = 'voc-to-mqtt/data/' + part;
if (typeof data === 'boolean' && paramters.convertToOpenHab) {
data = data ? 'ON' : 'OFF';
}
data = (typeof data === 'string' ? data : JSON.stringify(data));
logger.info('mqtt - publish on topic - ' + topic + ' ' + data);
this.client.publish(topic, data, { qos: 2, retain: false });
} catch (e) {
logger.error(e);
}
};
this.subscribeToLockEvent = function(){
self.client.subscribe('voc-to-mqtt/data/carLock');
};
this.subscribeToHeatEvent = function(){
self.client.subscribe('voc-to-mqtt/data/heat');
};
this.subscribeToRefreshEvent = function (){
self.client.subscribe('voc-to-mqtt/data/refresh');
};
}
module.exports = {
mqttHandler: new MqttHandler()
}