-
Notifications
You must be signed in to change notification settings - Fork 4
/
device.ts
293 lines (237 loc) · 9.58 KB
/
device.ts
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
import { Mqtt } from 'azure-iot-device-mqtt';
import { SymmetricKeySecurityClient } from 'azure-iot-security-symmetric-key';
import { ProvisioningDeviceClient } from 'azure-iot-provisioning-device';
import { Mqtt as ProvisioningTransport } from 'azure-iot-provisioning-device-mqtt';
import {
Client as IoTDeviceClient,
Twin,
Message as IoTMessage,
DeviceMethodRequest,
DeviceMethodResponse
} from 'azure-iot-device';
import {
extname as pathExtName,
basename as pathBaseName
} from 'path';
import {
stat as fsStat,
createReadStream as fsCreateReadStream
} from 'fs';
import * as moment from 'moment';
import { log } from 'util';
const dpsProvisioningHost = 'global.azure-devices-provisioning.net';
const CommandUploadFile = 'COMMAND_UPLOAD_FILE';
const TelemetrySystemHeartbeat = 'TELEMETRY_SYSTEM_HEARTBEAT';
const EventUploadFile = 'EVENT_UPLOAD_FILE';
const SettingFilenameSuffix = 'SETTING_FILENAME_SUFFIX';
const CommandResponseStatusCode = 'COMMANDRESPONSE_STATUSCODE';
const CommandResponseMessage = 'COMMANDRESPONSE_MESSAGE';
const CommandResponseData = 'COMMANDRESPONSE_DATA';
interface IFileUploadResponse {
statusCode: number;
message: string;
filename: string;
}
interface IDeviceSettings {
[SettingFilenameSuffix]: string;
}
export class IoTCentralDevice {
private log: (message: string) => void;
private scopeId: string;
private deviceId: string;
private deviceKey: string;
private modelId: string;
private deviceClient: IoTDeviceClient;
private deviceTwin: Twin;
private deviceSettings: IDeviceSettings;
constructor(logFunc: (message: string) => void, scopeId: string, deviceId: string, deviceKey: string, modelId: string) {
this.log = logFunc;
this.scopeId = scopeId;
this.deviceId = deviceId;
this.deviceKey = deviceKey;
this.modelId = modelId;
this.deviceSettings = {
[SettingFilenameSuffix]: moment.utc().format('YYYYMMDD-HHmmss')
};
}
public async provisionDeviceClient(): Promise<string> {
let connectionString = '';
try {
const provisioningSecurityClient = new SymmetricKeySecurityClient(this.deviceId, this.deviceKey);
const provisioningClient = ProvisioningDeviceClient.create(
dpsProvisioningHost,
this.scopeId,
new ProvisioningTransport(),
provisioningSecurityClient
);
const provisioningPayload = {
iotcModelId: this.modelId
};
provisioningClient.setProvisioningPayload(provisioningPayload);
connectionString = await new Promise<string>((resolve, reject) => {
provisioningClient.register((dpsError, dpsResult) => {
if (dpsError) {
return reject(dpsError);
}
this.log('DPS registration succeeded');
return resolve(`HostName=${dpsResult.assignedHub};DeviceId=${dpsResult.deviceId};SharedAccessKey=${this.deviceKey}`);
});
});
}
catch (ex) {
this.log(`Failed to instantiate client interface from configuration: ${ex.message}`);
}
return connectionString;
}
public async connectDeviceClient(connectionString: string): Promise<void> {
try {
this.deviceClient = await IoTDeviceClient.fromConnectionString(connectionString, Mqtt);
if (!this.deviceClient) {
this.log(`Failed to connect device client interface from connection string - device: ${this.deviceId}`);
return;
}
setInterval(async () => {
await this.getHealth();
}, 1000 * 30);
await this.deviceClient.open();
this.deviceTwin = await this.deviceClient.getTwin();
this.deviceTwin.on('properties.desired', this.onHandleDeviceProperties.bind(this));
this.deviceClient.on('error', this.onDeviceClientError.bind(this));
this.deviceClient.onDeviceMethod(CommandUploadFile, this.uploadFileCommand.bind(this));
this.log(`IoT Central successfully connected device: ${this.deviceId}`);
}
catch (ex) {
this.log(`IoT Central connection error: ${ex.message}`);
}
}
private async getHealth(): Promise<void> {
await this.sendMeasurement({
[TelemetrySystemHeartbeat]: 1
});
}
private async onHandleDeviceProperties(desiredChangedSettings: any) {
try {
const patchedProperties = {};
for (const setting in desiredChangedSettings) {
if (!Object.prototype.hasOwnProperty.call(desiredChangedSettings, setting)) {
continue;
}
if (setting === '$version') {
continue;
}
const value = desiredChangedSettings[setting];
switch (setting) {
case SettingFilenameSuffix:
this.log(`Updating setting: ${setting} with value: ${value}`);
// NOTE: validation should be in place for legal folder names
patchedProperties[setting] = this.deviceSettings[setting] = value || moment.utc().format('YYYYMMDD-HHmmss');
break;
default:
this.log(`Received desired property change for unknown setting '${setting}'`);
break;
}
}
if (Object.keys(patchedProperties).length) {
await this.updateDeviceProperties(patchedProperties);
}
}
catch (ex) {
this.log(`Exception while handling desired properties: ${ex.message}`);
}
}
private onDeviceClientError(error: Error) {
this.log(`Device client connection error: ${error.message}`);
}
private async sendMeasurement(data: any): Promise<void> {
if (!data || !this.deviceClient) {
return;
}
try {
this.log(`Sending telemetry: ${JSON.stringify(data, null, 4)}`);
const iotcMessage = new IoTMessage(JSON.stringify(data));
await this.deviceClient.sendEvent(iotcMessage);
}
catch (ex) {
this.log(`sendMeasurement: ${ex.message}`);
}
}
private async updateDeviceProperties(properties: any): Promise<void> {
if (!properties || !this.deviceTwin) {
return;
}
this.log(`Updating twin properties: ${JSON.stringify(properties, null, 4)}`);
try {
await new Promise((resolve, reject) => {
this.deviceTwin.properties.reported.update(properties, (error) => {
if (error) {
return reject(error);
}
return resolve('');
});
});
}
catch (ex) {
this.log(`Error updating device properties: ${ex.message}`);
}
}
private async getFileStats(filePath: string): Promise<any> {
let fileStats = {};
try {
fileStats = await new Promise((resolve, reject) => {
fsStat(filePath, (err, stats) => {
if (err) {
return reject(err);
}
return resolve(stats);
});
});
}
catch (ex) {
log(`An error occurred while getting file stats: ${ex.message}`);
}
return fileStats;
}
private async uploadFile(filePath: string): Promise<IFileUploadResponse> {
const result: IFileUploadResponse = {
statusCode: 202,
message: '',
filename: ''
};
try {
const blobNameSuffix = this.deviceSettings[SettingFilenameSuffix];
const fileExtName = pathExtName(filePath);
const fileBaseName = pathBaseName(filePath, fileExtName);
const fileStats = await this.getFileStats(filePath);
const blobFilename = `${fileBaseName}-${blobNameSuffix}${fileExtName}`;
const readableStream = fsCreateReadStream(filePath);
this.log(`uploadContent - data length: ${fileStats.size}, blob filename: ${blobFilename}`);
await this.deviceClient.uploadToBlob(blobFilename, readableStream, fileStats.size);
await this.sendMeasurement({
[EventUploadFile]: `${blobFilename}`
});
result.message = `deviceId: '${this.deviceId}' uploaded a file named '${blobFilename}' to the Azure storage container`;
this.log(result.message);
result.filename = blobFilename;
}
catch (ex) {
result.message = `Error during deviceClient.uploadToBlob: ${ex.message}`;
this.log(result.message);
}
return result;
}
// @ts-ignore (commandRequest)
private async uploadFileCommand(commandRequest: DeviceMethodRequest, commandResponse: DeviceMethodResponse) {
this.log('Received upload file command');
const fileUploadResult = await this.uploadFile('./datafile.json');
await commandResponse.send(200);
await this.updateDeviceProperties({
[CommandUploadFile]: {
value: {
[CommandResponseStatusCode]: 202,
[CommandResponseMessage]: fileUploadResult.message,
[CommandResponseData]: ''
}
}
});
}
}