-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.js
142 lines (118 loc) · 4.78 KB
/
index.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
/*
* IoT Hub Raspberry Pi NodeJS - Microsoft Sample Code - Copyright (c) 2017 - Licensed MIT
*/
'use strict';
const fs = require('fs');
const path = require('path');
// wiring-pi is not upto date with wiring and kernel verions
const wpi = require('wiringpi-node');
const sleep = require('sleep');
const Client = require('azure-iot-device').Client;
const ConnectionString = require('azure-iot-device').ConnectionString;
const Message = require('azure-iot-device').Message;
const Protocol = require('azure-iot-device-mqtt').Mqtt;
const bi = require('az-iot-bi');
const MessageProcessor = require('./messageProcessor.js');
var sendingMessage = true;
var messageId = 0;
var client, config, messageProcessor;
function sendMessage() {
if (!sendingMessage) { return; }
messageId++;
messageProcessor.getMessage(messageId, (content, temperatureAlert) => {
var message = new Message(content);
message.properties.add('temperatureAlert', temperatureAlert ? 'true' : 'false');
//console.log('Sending message: ' + content);
client.sendEvent(message, (err) => {
if (err) {
console.log(err.message);
console.error('Failed to send message to Azure IoT Hub');
} else {
blinkLED();
console.log('Message sent to Azure IoT Hub');
}
setTimeout(sendMessage, config.interval);
});
});
}
function onStart(request, response) {
console.log('Try to invoke method start(' + request.payload || '' + ')');
sendingMessage = true;
response.send(200, 'Successully start sending message to cloud', function (err) {
if (err) {
console.error('[IoT hub Client] Failed sending a method response:\n' + err.message);
}
});
}
function onStop(request, response) {
console.log('Try to invoke method stop(' + request.payload || '' + ')')
sendingMessage = false;
response.send(200, 'Successully stop sending message to cloud', function (err) {
if (err) {
console.error('[IoT hub Client] Failed sending a method response:\n' + err.message);
}
});
}
function blinkLED() {
// Light up LED for 500 ms
wpi.digitalWrite(config.LEDPin, 1);
wpi.delay(500);
wpi.digitalWrite(config.LEDPin, 0);
}
function initClient(connectionStringParam, credentialPath) {
var connectionString = ConnectionString.parse(connectionStringParam);
var deviceId = connectionString.DeviceId;
// fromConnectionString must specify a transport constructor, coming from any transport package.
client = Client.fromConnectionString(connectionStringParam, Protocol);
// Configure the client to use X509 authentication if required by the connection string.
if (connectionString.x509) {
// Read X.509 certificate and private key.
// These files should be in the current folder and use the following naming convention:
// [device name]-cert.pem and [device name]-key.pem, example: myraspberrypi-cert.pem
var connectionOptions = {
cert: fs.readFileSync(path.join(credentialPath, deviceId + '-cert.pem')).toString(),
key: fs.readFileSync(path.join(credentialPath, deviceId + '-key.pem')).toString()
};
client.setOptions(connectionOptions);
console.log('[Device] Using X.509 client certificate authentication');
}
return client;
}
(function (connectionString) {
// read in configuration in config.json
try {
config = require('./config.json');
} catch (err) {
console.error('Failed to load config.json: ' + err.message);
return;
}
// set up wiring
wpi.setup('wpi');
wpi.pinMode(config.LEDPin, wpi.OUTPUT);
var i = 0;
messageProcessor = new MessageProcessor(config);
bi.start();
var deviceInfo = { device: "RaspberryPi", language: "NodeJS" };
if (bi.isBIEnabled()) {
bi.trackEventWithoutInternalProperties('yes', deviceInfo);
bi.trackEvent('success', deviceInfo);
}
else {
bi.trackEventWithoutInternalProperties('no', deviceInfo);
}
bi.flush();
// create a client
// read out the connectionString from process environment
connectionString = connectionString || process.env['AzureIoTHubDeviceConnectionString'];
client = initClient(connectionString, config);
client.open((err) => {
if (err) {
console.error('[IoT hub Client] Connect error: ' + err.message);
return;
}
// set C2D and device method callback
client.onDeviceMethod('start', onStart);
client.onDeviceMethod('stop', onStop);
sendMessage();
});
})(process.argv[2]);