-
Notifications
You must be signed in to change notification settings - Fork 24
/
azureiothub.js
351 lines (300 loc) · 13.1 KB
/
azureiothub.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
module.exports = function (RED) {
var Client = require('azure-iot-device').Client;
var Registry = require('azure-iothub').Registry;
var Message = require('azure-iot-device').Message;
var Protocols = {
amqp: require('azure-iot-device-amqp').Amqp,
mqtt: require('azure-iot-device-mqtt').Mqtt,
http: require('azure-iot-device-http').Http,
amqpWs: require('azure-iot-device-amqp').AmqpWs
};
var EventHubClient = require('@azure/event-hubs').Client;
var client = null;
var clientConnectionString = "";
var newConnectionString = "";
var newProtocol = "";
var clientProtocol = "";
var statusEnum = {
disconnected: { color: "red", text: "Disconnected" },
connected: { color: "green", text: "Connected" },
sent: { color: "blue", text: "Sent message" },
received: { color: "yellow", text: "Received" },
error: { color: "grey", text: "Error" }
};
var setStatus = function (node, status) {
node.status({ fill: status.color, shape: "dot", text: status.text });
}
var sendData = function (node, data) {
node.log('Sending Message to Azure IoT Hub :\n Payload: ' + JSON.stringify(data));
// Create a message and send it to the IoT Hub every second
var message = new Message(JSON.stringify(data));
client.sendEvent(message, function (err, res) {
if (err) {
node.error('Error while trying to send message:' + err.toString());
setStatus(node, statusEnum.error);
} else {
node.log('Message sent.');
node.send({payload: "Message sent."});
setStatus(node, statusEnum.sent);
}
});
};
var sendMessageToIoTHub = function (node, message, reconnect) {
if (!client || reconnect) {
node.log('Connection to IoT Hub not established or configuration changed. Reconnecting.');
// Update the connection string
clientConnectionString = newConnectionString;
// update the protocol
clientProtocol = newProtocol;
// If client was previously connected, disconnect first
if (client)
disconnectFromIoTHub(node);
// Connect the IoT Hub
connectToIoTHub(node, message);
} else {
sendData(node, message);
}
};
var connectToIoTHub = function (node, pendingMessage) {
node.log('Connecting to Azure IoT Hub:\n Protocol: ' + newProtocol + '\n Connection string :' + newConnectionString);
client = Client.fromConnectionString(newConnectionString, Protocols[newProtocol]);
client.open(function (err) {
if (err) {
node.error('Could not connect: ' + err.message);
setStatus(node, statusEnum.disconnected);
// works for me..
client = undefined;
} else {
node.log('Connected to Azure IoT Hub.');
setStatus(node, statusEnum.connected);
// Check if a message is pending and send it
if (pendingMessage) {
node.log('Message is pending. Sending it to Azure IoT Hub.');
// Send the pending message
sendData(node, pendingMessage);
}
client.on('message', function (msg) {
// We received a message
node.log('Message received from Azure IoT Hub\n Id: ' + msg.messageId + '\n Payload: ' + msg.data);
var outpuMessage = new Message();
outpuMessage.payload = msg.data;
setStatus(node, statusEnum.received);
node.log(JSON.stringify(outpuMessage));
node.send(outpuMessage);
client.complete(msg, printResultFor(node,'Completed'));
});
client.on('error', function (err) {
node.error(err.message);
});
client.on('disconnect', function () {
disconnectFromIoTHub(node);
});
}
});
};
var disconnectFromIoTHub = function (node) {
if (client) {
node.log('Disconnecting from Azure IoT Hub');
client.removeAllListeners();
client.close(printResultFor(node, 'close'));
client = null;
setStatus(node, statusEnum.disconnected);
}
};
function nodeConfigUpdated(cs, proto) {
return ((clientConnectionString != cs) || (clientProtocol != proto));
}
// Main function called by Node-RED
function AzureIoTHubNode(config) {
// Store node for further use
var node = this;
//nodeConfig = config;
// Create the Node-RED node
RED.nodes.createNode(this, config);
node.on('input', function (msg) {
var messageJSON = null;
if (typeof (msg.payload) != "string") {
node.log("JSON");
messageJSON = msg.payload;
} else {
node.log("String");
//Converting string to JSON Object
//Sample string: {"deviceId": "name", "key": "jsadhjahdue7230-=13", "protocol": "amqp", "data": "25"}
messageJSON = JSON.parse(msg.payload);
}
//Creating connectionString
//Sample
//HostName=sample.azure-devices.net;DeviceId=sampleDevice;SharedAccessKey=wddU//P8fdfbSBDbIdghZAoSSS5gPhIZREhy3Zcv0JU=
newConnectionString = "HostName=" + node.credentials.hostname + ";DeviceId=" + messageJSON.deviceId + ";SharedAccessKey=" + messageJSON.key
if( typeof messageJSON.protocol !== 'undefined'){
newProtocol = messageJSON.protocol;
} else {
newProtocol = config.protocol;
}
// Sending data to Azure IoT Hub Hub using specific connectionString
sendMessageToIoTHub(node, messageJSON.data, nodeConfigUpdated(newConnectionString, newProtocol));
});
node.on('close', function () {
disconnectFromIoTHub(node, this);
});
}
function IoTHubRegistry(config) {
RED.nodes.createNode(this, config);
var node = this;
node.on('input', function (msg) {
if (typeof (msg.payload) == 'string') {
msg.payload = JSON.parse(msg.payload);
}
var registry = Registry.fromConnectionString(node.credentials.connectionString);
registry.create(msg.payload, function (err, device) {
if (err) {
node.error('Error while trying to create a new device: ' + err.toString());
setStatus(node, statusEnum.error);
} else {
node.log("Device created: " + JSON.stringify(device));
node.log("Device ID: " + device.deviceId + " - primaryKey: " + device.authentication.SymmetricKey.primaryKey + " - secondaryKey: " + device.authentication.SymmetricKey.secondaryKey);
node.send("Device ID: " + device.deviceId + " - primaryKey: " + device.authentication.SymmetricKey.primaryKey + " - secondaryKey: " + device.authentication.SymmetricKey.secondaryKey);
}
});
});
node.on('close', function () {
disconnectFromIoTHub(node, this);
});
}
var disconnectFromEventHub = function( node ){
if( node.reconnectTimer ){
clearTimeout( node.reconnectTimer );
node.reconnectTimer = null;
}
if (node.client) {
node.log('Disconnecting from Azure IoT Hub');
node.client.close();
node.client = null;
setStatus(node, statusEnum.disconnected);
}
};
var connectToEventHub = function( node, connectionString ){
// Open connection
node.client = EventHubClient.fromConnectionString(connectionString);
node.client.open()
.then(node.client.getPartitionIds.bind(node.client))
.then((partitionIds)=>{
return Promise.all( partitionIds.map( (partitionId)=> {
return node.client.createReceiver('$Default', partitionId, { 'startAfterTime' : Date.now()}).then(function(receiver) {
node.log('Created Event Hub partition receiver: ' + partitionId);
// Allthough 'errorReceived' event is defined in azure-event-hubs function documentation, it does not appear to throw one when disconnected
receiver.on('errorReceived', function( err ){
node.log('Receiver error: ', err.message);
setStatus(node, statusEnum.error);
});
receiver.on('message', function( message ){
setStatus(node, statusEnum.received);
let msg = {
deviceId: message.annotations["iothub-connection-device-id"],
//topic: message.properties.subject||message.properties.to,
payload: message.body
};
node.send(msg);
});
});
}));
}).then(()=>{
node.log("Connected to each partition receiver - ready to receive data!");
setStatus(node, statusEnum.connected);
// Since EventHubClient does not provide any mechanism to catch disconnection nor override AMQP retry policy, the only available option is to listen to it's private _amqp member directly
node.client._amqp.once('connection:closed', function(){
node.log("AMQP disconnected");
process.nextTick(()=>{
disconnectFromEventHub(node);
connectToEventHub( node, connectionString );
});
});
}).catch(function(error){
node.log("Event Hub connection threw an error: " + error.message);
disconnectFromEventHub(node);
node.reconnectTimer = setTimeout( function(){
node.reconnectTimer = null;
if( !node.client ) connectToEventHub( node, connectionString );
}, 30000);
});
};
function AzureIoTHubReceiverNode(config) {
// Store node for further use
var node = this;
this.client = null;
this.reconnectTimer = null;
// Create the Node-RED node
RED.nodes.createNode(this, config);
setStatus(node, statusEnum.disconnected);
connectToEventHub( this, node.credentials.connectionString );
node.on('close', function() {
disconnectFromEventHub(node);
});
}
function AzureIoTHubDeviceTwin(config){
RED.nodes.createNode(this, config);
var node = this;
node.on('input', function (msg) {
var registry = Registry.fromConnectionString(node.credentials.connectionString);
if( typeof msg.payload === "string" ) var query = registry.createQuery("SELECT * FROM devices WHERE deviceId ='" + msg.payload + "'");
else var query = registry.createQuery("SELECT * FROM devices");
query.nextAsTwin( function(err, results){
if (err) {
node.error('Error while trying to retrieve device twins: ' + err.message);
msg.error = err;
delete msg.payload;
node.send(msg);
} else {
msg.payload = results;
disconnectFromIoTHub(node, this);
node.send(msg);
}
});
});
node.on('close', function () {
disconnectFromIoTHub(node, this);
});
}
// Registration of the node into Node-RED
RED.nodes.registerType("azureiothub", AzureIoTHubNode, {
credentials: {
hostname: { type: "text" }
},
defaults: {
name: { value: "Azure IoT Hub" },
protocol: { value: "amqp" }
}
});
// Registration of the node into Node-RED
RED.nodes.registerType("azureiothubregistry", IoTHubRegistry, {
credentials: {
connectionString: { type: "text" }
},
defaults: {
name: { value: "Azure IoT Hub Registry" },
}
});
RED.nodes.registerType("azureiothubreceiver", AzureIoTHubReceiverNode, {
credentials: {
connectionString: { type: "text" }
},
defaults: {
name: { value: "Azure IoT Hub Receiver" }
}
});
RED.nodes.registerType("azureiothubdevicetwin", AzureIoTHubDeviceTwin, {
credentials: {
connectionString: { type: "text" }
},
defaults: {
name: { value: "Azure IoT Hub Device Twin" }
}
});
// Helper function to print results in the console
function printResultFor(node, op) {
return function printResult(err, res) {
if (err) node.error(op + ' error: ' + err.toString());
if (res) node.log(op + ' status: ' + res.constructor.name);
};
}
}