/
device.js
199 lines (164 loc) · 5.35 KB
/
device.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 Losant IoT, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var debug = require('debug')('losant:device');
var EJSON = require('ejson');
var config = require('./config');
var MQTT = require('./mqtt');
/**
* Device constructor.
*/
function Device(options) {
EventEmitter.call(this);
// Check required fields.
if(!options || !options.id) {
throw new Error('ID is required.');
}
this.options = options;
this.id = options.id;
// Default the options and remove whitespace.
options.id = (options.id || '').replace(/ /g, '');
options.key = (options.key || '').replace(/ /g, '');
options.secret = (options.secret || '').replace(/ /g, '');
// The MQTT topics that this device will use.
this.commandTopic = util.format(config.topicFormatCommand, options.id);
this.stateTopic = util.format(config.topicFormatState, options.id);
this.mqtt = options.mqtt || new MQTT();
this.mqtt.on('message', this.handleMessage.bind(this));
// Only want 'connect' to be emitted the first time. Every time after
// will only emit the reconnected event.
var firstConnect = true;
this.mqtt.on('connect', (function() {
this.handleConnect();
if(firstConnect) {
firstConnect = false;
this.emit('connect');
}
else {
this.emit('reconnected');
}
}).bind(this));
this.mqtt.on('reconnect', (function() {
this.emit('reconnect');
}).bind(this));
this.mqtt.on('close', (function() {
this.emit('close');
}).bind(this));
this.mqtt.on('offline', (function() {
this.emit('offline');
}).bind(this));
this.mqtt.on('error', (function(err) {
this.emit('error', err);
}).bind(this));
}
util.inherits(Device, EventEmitter);
/**
* Returns whether or not the device is connected.
*/
Device.prototype.isConnected = function() {
return this.mqtt.isConnected();
};
/**
* Occurs whenever the underlying mqtt client connects or reconnects.
*/
Device.prototype.handleConnect = function() {
debug('Subscribing to MQTT topic: ' + this.commandTopic);
this.mqtt.subscribe(this.commandTopic);
};
/**
* Connects to the Losant platform.
*/
Device.prototype.connect = function(callback) {
this.mqtt.connect(this.options, callback);
};
/**
* Disconnects the underlying mqtt connection.
*/
Device.prototype.disconnect = function(callback) {
debug('Disconnect MQTT client.');
if(this.mqtt.client) {
this.mqtt.client.end(callback);
}
else {
callback();
}
};
/**
* Handles a message sent from the Losant broker.
* topic: the mqtt topic.
* message: the message as a Buffer.
* Returns null if message is invalid. Returns the parsed JavaScript
* object if the message is valid.
*/
Device.prototype.handleMessage = function(topic, message) {
// This message is not intended for this device.
if(topic !== this.commandTopic) {
return null;
}
message = this.parseMessage(message);
if(!message) {
return null;
}
debug('Received MQTT message on topic: ' + topic);
debug(JSON.stringify(message));
this.emit('command', message);
return message;
};
/**
* Parses an incoming mqtt message from the Losant broker..
* Returns an object or null.
* message: the incoming Buffer to parse and validate.
*/
Device.prototype.parseMessage = function(message) {
// Attempt to parse the message.
try { message = EJSON.parse(message.toString()); }
catch(e) { return null; }
// The message has to be something.
if(!message) {
return null;
}
return message;
};
/**
* Sends device state to Losant.
* deviceId: the ID of the device to report state for.
* state: the state to send. Typically an object with { attribute: value }
* time (optional): the time at which the state occurred (defaults to now)
* cb: the callback handling the response.
*/
Device.prototype.sendState = function(state, time, callback) {
if(typeof(time) === 'function') {
callback = time;
time = null;
}
time = time || new Date();
var payload = { time: time, data: state };
debug('Publishing state:');
debug(EJSON.stringify(payload));
debug('Topic: ' + this.stateTopic);
this.mqtt.publish(this.stateTopic, EJSON.stringify(payload), callback);
return { topic: this.stateTopic, payload: payload };
};
module.exports = Device;