-
Notifications
You must be signed in to change notification settings - Fork 0
/
publisher.js
874 lines (798 loc) · 25.6 KB
/
publisher.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
// [START iot_mqtt_include]
const fs = require('fs');
const jwt = require('jsonwebtoken');
const mqtt = require('mqtt');
// [END iot_mqtt_include]
// The initial backoff time after a disconnection occurs, in seconds.
const MINIMUM_BACKOFF_TIME = 1;
// The maximum backoff time before giving up, in seconds.
const MAXIMUM_BACKOFF_TIME = 32;
// Whether to wait with exponential backoff before publishing.
let shouldBackoff = false;
// The current backoff time.
let backoffTime = 1;
// Whether an asynchronous publish chain is in progress.
let publishChainInProgress = false;
console.log('Google Cloud IoT Core MQTT IOT Mini-Implementation');
// Create a Cloud IoT Core JWT for the given project id, signed with the given
// private key.
// [START iot_mqtt_jwt]
const createJwt = (projectId, privateKeyFile, algorithm) => {
// Create a JWT to authenticate this device. The device will be disconnected
// after the token expires, and will have to reconnect with a new token. The
// audience field should always be set to the GCP project id.
const token = {
iat: parseInt(Date.now() / 1000),
exp: parseInt(Date.now() / 1000) + 20 * 60, // 20 minutes
aud: projectId,
};
const privateKey = fs.readFileSync(privateKeyFile);
return jwt.sign(token, privateKey, {algorithm: algorithm});
};
// [END iot_mqtt_jwt]
// Publish numMessages messages asynchronously, starting from message
// messagesSent.
// [START iot_mqtt_publish]
const publishAsync = (
mqttTopic,
client,
iatTime,
messagesSent,
numMessages,
connectionArgs
) => {
// If we have published enough messages or backed off too many times, stop.
if (messagesSent > numMessages || backoffTime >= MAXIMUM_BACKOFF_TIME) {
if (backoffTime >= MAXIMUM_BACKOFF_TIME) {
console.log('Backoff time is too high. Giving up.');
}
console.log('Closing connection to MQTT. Goodbye!');
client.end();
publishChainInProgress = false;
return;
}
// Publish and schedule the next publish.
publishChainInProgress = true;
let publishDelayMs = 0;
if (shouldBackoff) {
publishDelayMs = 1000 * (backoffTime + Math.random());
backoffTime *= 2;
console.log(`Backing off for ${publishDelayMs}ms before publishing.`);
}
setTimeout(() => {
//const payload = `${argv.registryId}/${argv.deviceId}-payload-${messagesSent}`;
const payload = '{'+
'"registry":"'+argv.registryId +
'","deviceID":"'+argv.deviceId +
'","deviceName":"dragline2"' +
',"pressure":'+Math.random() +
',"speed":'+Math.floor(Math.random() * Math.floor(10)) +
',"engineUpTime":'+Math.floor(Math.random() * Math.floor(10)) +
',"oilLevel":'+Math.floor(Math.random() * Math.floor(100)) +
',"timestamp":"'+new Date().toISOString() +'"'+
'}';
// Publish "payload" to the MQTT topic. qos=1 means at least once delivery.
// Cloud IoT Core also supports qos=0 for at most once delivery.
console.log('Publishing message:', payload);
client.publish(mqttTopic, payload, {qos: 1}, err => {
if (!err) {
shouldBackoff = false;
backoffTime = MINIMUM_BACKOFF_TIME;
}
});
const schedulePublishDelayMs = argv.messageType === 'events' ? 1000 : 2000;
setTimeout(() => {
// [START iot_mqtt_jwt_refresh]
const secsFromIssue = parseInt(Date.now() / 1000) - iatTime;
if (secsFromIssue > argv.tokenExpMins * 60) {
iatTime = parseInt(Date.now() / 1000);
console.log(`\tRefreshing token after ${secsFromIssue} seconds.`);
client.end();
connectionArgs.password = createJwt(
argv.projectId,
argv.privateKeyFile,
argv.algorithm
);
connectionArgs.protocolId = 'MQTT';
connectionArgs.protocolVersion = 4;
connectionArgs.clean = true;
client = mqtt.connect(connectionArgs);
// [END iot_mqtt_jwt_refresh]
client.on('connect', success => {
console.log('connect');
if (!success) {
console.log('Client not connected...');
} else if (!publishChainInProgress) {
publishAsync(
mqttTopic,
client,
iatTime,
messagesSent,
numMessages,
connectionArgs
);
}
});
client.on('close', () => {
console.log('close');
shouldBackoff = true;
});
client.on('error', err => {
console.log('error', err);
});
client.on('message', (topic, message) => {
console.log(
'message received: ',
Buffer.from(message, 'base64').toString('ascii')
);
});
client.on('packetsend', () => {
// Note: logging packet send is very verbose
});
}
publishAsync(
mqttTopic,
client,
iatTime,
messagesSent + 1,
numMessages,
connectionArgs
);
}, schedulePublishDelayMs);
}, publishDelayMs);
};
// [END iot_mqtt_publish]
const mqttDeviceDemo = (
deviceId,
registryId,
projectId,
region,
algorithm,
privateKeyFile,
mqttBridgeHostname,
mqttBridgePort,
messageType,
numMessages
) => {
// [START iot_mqtt_run]
// const projectId = `my-project-name-123`;
// const deviceId = `myDevice`;
// const registryId = `myRegistry`;
// const region = `us-central1`;
// const algorithm = `RS256`;
// const privateKeyFile = `./rsa_private.pem`;
// const mqttBridgeHostname = `mqtt.googleapis.com`;
// const mqttBridgePort = 8883;
// const messageType = `events`;
// const numMessages = 5;
// The mqttClientId is a unique string that identifies this device. For Google
// Cloud IoT Core, it must be in the format below.
const mqttClientId = `projects/${projectId}/locations/${region}/registries/${registryId}/devices/${deviceId}`;
// With Google Cloud IoT Core, the username field is ignored, however it must be
// non-empty. The password field is used to transmit a JWT to authorize the
// device. The "mqtts" protocol causes the library to connect using SSL, which
// is required for Cloud IoT Core.
const connectionArgs = {
host: mqttBridgeHostname,
port: mqttBridgePort,
clientId: mqttClientId,
username: 'unused',
password: createJwt(projectId, privateKeyFile, algorithm),
protocol: 'mqtts',
secureProtocol: 'TLSv1_2_method',
};
// Create a client, and connect to the Google MQTT bridge.
const iatTime = parseInt(Date.now() / 1000);
const client = mqtt.connect(connectionArgs);
// Subscribe to the /devices/{device-id}/config topic to receive config updates.
// Config updates are recommended to use QoS 1 (at least once delivery)
client.subscribe(`/devices/${deviceId}/config`, {qos: 1});
// Subscribe to the /devices/{device-id}/commands/# topic to receive all
// commands or to the /devices/{device-id}/commands/<subfolder> to just receive
// messages published to a specific commands folder; we recommend you use
// QoS 0 (at most once delivery)
client.subscribe(`/devices/${deviceId}/commands/#`, {qos: 0});
// The MQTT topic that this device will publish data to. The MQTT topic name is
// required to be in the format below. The topic name must end in 'state' to
// publish state and 'events' to publish telemetry. Note that this is not the
// same as the device registry's Cloud Pub/Sub topic.
const mqttTopic = `/devices/${deviceId}/${messageType}`;
client.on('connect', success => {
console.log('connect');
if (!success) {
console.log('Client not connected...');
} else if (!publishChainInProgress) {
publishAsync(mqttTopic, client, iatTime, 1, numMessages, connectionArgs);
}
});
client.on('close', () => {
console.log('close');
shouldBackoff = true;
});
client.on('error', err => {
console.log('error', err);
});
client.on('message', (topic, message) => {
let messageStr = 'Message received: ';
if (topic === `/devices/${deviceId}/config`) {
messageStr = 'Config message received: ';
} else if (topic.startsWith(`/devices/${deviceId}/commands`)) {
messageStr = 'Command message received: ';
}
messageStr += Buffer.from(message, 'base64').toString('ascii');
console.log(messageStr);
});
client.on('packetsend', () => {
// Note: logging packet send is very verbose
});
// Once all of the messages have been published, the connection to Google Cloud
// IoT will be closed and the process will exit. See the publishAsync method.
// [END iot_mqtt_run]
};
// Attaches a device to a gateway.
const attachDevice = (deviceId, client, jwt) => {
// [START attach_device]
// const deviceId = 'my-unauth-device';
const attachTopic = `/devices/${deviceId}/attach`;
console.log(`Attaching: ${attachTopic}`);
let attachPayload = '{}';
if (jwt && jwt !== '') {
attachPayload = `{ 'authorization' : ${jwt} }`;
}
client.publish(attachTopic, attachPayload, {qos: 1}, err => {
if (!err) {
shouldBackoff = false;
backoffTime = MINIMUM_BACKOFF_TIME;
} else {
console.log(err);
}
});
// [END attach_device]
};
// Detaches a device from a gateway.
const detachDevice = (deviceId, client, jwt) => {
// [START detach_device]
const detachTopic = `/devices/${deviceId}/detach`;
console.log(`Detaching: ${detachTopic}`);
let detachPayload = '{}';
if (jwt && jwt !== '') {
detachPayload = `{ 'authorization' : ${jwt} }`;
}
client.publish(detachTopic, detachPayload, {qos: 1}, err => {
if (!err) {
shouldBackoff = false;
backoffTime = MINIMUM_BACKOFF_TIME;
} else {
console.log(err);
}
});
// [END detach_device]
};
// Publish numMessages messages asynchronously through a gateway client connection
const publishAsyncGateway = (
client,
iatTime,
tokenExpMins,
messagesSent,
numMessages,
registryId,
deviceId,
gatewayId,
connectionArgs,
projectId,
privateKeyFile,
algorithm
) => {
// If we have published enough messages or backed off too many times, stop.
if (messagesSent > numMessages || backoffTime >= MAXIMUM_BACKOFF_TIME) {
if (backoffTime >= MAXIMUM_BACKOFF_TIME) {
console.log('Backoff time is too high. Giving up.');
}
if (messagesSent >= numMessages) {
detachDevice(deviceId, client);
}
console.log('Closing connection to MQTT. Goodbye!');
client.end();
publishChainInProgress = false;
return;
}
// Publish and schedule the next publish.
publishChainInProgress = true;
let publishDelayMs = 0;
if (shouldBackoff) {
publishDelayMs = 1000 * (backoffTime + Math.random());
backoffTime *= 2;
console.log(`Backing off for ${publishDelayMs}ms before publishing.`);
}
let mqttTopic = `/devices/${gatewayId}/state`;
let payload = `${registryId}/${gatewayId}-connected-${new Date().getTime()}`;
console.log(`Publishing message ${messagesSent}/${numMessages}`);
if (messagesSent > 0) {
mqttTopic = `/devices/${deviceId}/state`;
payload = `${registryId}/${deviceId}-payload-${messagesSent}`;
}
setTimeout(() => {
// Publish "payload" to the MQTT topic. qos=1 means at least once delivery.
// Cloud IoT Core also supports qos=0 for at most once delivery.
console.log(`Publishing message: ${payload} to ${mqttTopic}`);
client.publish(mqttTopic, payload, {qos: 1}, err => {
if (!err) {
shouldBackoff = false;
backoffTime = MINIMUM_BACKOFF_TIME;
}
});
const schedulePublishDelayMs = 5000; // messageType === 'events' ? 1000 : 2000;
setTimeout(() => {
const secsFromIssue = parseInt(Date.now() / 1000) - iatTime;
if (secsFromIssue > tokenExpMins * 60) {
iatTime = parseInt(Date.now() / 1000);
console.log(`\tRefreshing token after ${secsFromIssue} seconds.`);
client.end();
connectionArgs.password = createJwt(
projectId,
privateKeyFile,
algorithm
);
client = mqtt.connect(connectionArgs);
}
publishAsyncGateway(
client,
iatTime,
tokenExpMins,
messagesSent + 1,
numMessages,
registryId,
deviceId,
gatewayId
);
}, schedulePublishDelayMs);
}, publishDelayMs);
};
// Sends data from a gateway on behalf of a device that is bound to that gateway.
const sendDataFromBoundDevice = (
deviceId,
gatewayId,
registryId,
projectId,
region,
algorithm,
privateKeyFile,
mqttBridgeHostname,
mqttBridgePort,
numMessages,
tokenExpMins
) => {
// [START iot_send_data_from_bound_device]
// const deviceId = `myDevice`;
// const gatewayId = `mygateway`;
// const registryId = `myRegistry`;
// const region = `us-central1`;
// const algorithm = `RS256`;
// const privateKeyFile = `./rsa_private.pem`;
// const mqttBridgeHostname = `mqtt.googleapis.com`;
// const mqttBridgePort = 8883;
// const numMessages = 5;
// const tokenExpMins = 60;
const mqttClientId = `projects/${projectId}/locations/${region}/registries/${registryId}/devices/${gatewayId}`;
console.log(`MQTT client id: ${mqttClientId}`);
const connectionArgs = {
host: mqttBridgeHostname,
port: mqttBridgePort,
clientId: mqttClientId,
username: 'unused',
password: createJwt(projectId, privateKeyFile, algorithm),
protocol: 'mqtts',
qos: 1,
secureProtocol: 'TLSv1_2_method',
};
// Create a client, and connect to the Google MQTT bridge.
const iatTime = parseInt(Date.now() / 1000);
const client = mqtt.connect(connectionArgs);
client.on('connect', success => {
if (!success) {
console.log('Client not connected...');
} else if (!publishChainInProgress) {
console.log('Client connected: Attaching device');
attachDevice(deviceId, client);
setTimeout(() => {
console.log('Client connected: Gateway is ready to relay');
publishAsyncGateway(
client,
iatTime,
tokenExpMins,
0,
numMessages,
registryId,
deviceId,
gatewayId,
connectionArgs,
projectId,
privateKeyFile,
algorithm
);
}, 5000);
}
});
client.on('close', () => {
console.log('Connection closed');
shouldBackoff = true;
});
client.on('error', err => {
console.log('error', err);
});
client.on('message', (topic, message) => {
console.log(
'message received: ',
Buffer.from(message, 'base64').toString('ascii')
);
});
client.on('packetsend', () => {
// Note: logging packet send is very verbose
});
// [END iot_send_data_from_bound_device]
};
// Listen for configuration messages on a gateway and bound device.
const listenForConfigMessages = (
deviceId,
gatewayId,
registryId,
projectId,
region,
algorithm,
privateKeyFile,
mqttBridgeHostname,
mqttBridgePort,
clientDuration
) => {
// [START iot_listen_for_config_messages]
// const deviceId = `myDevice`;
// const gatewayId = `mygateway`;
// const registryId = `myRegistry`;
// const region = `us-central1`;
// const algorithm = `RS256`;
// const privateKeyFile = `./rsa_private.pem`;
// const mqttBridgeHostname = `mqtt.googleapis.com`;
// const mqttBridgePort = 8883;
// const clientDuration = 60000;
const mqttClientId = `projects/${projectId}/locations/${region}/registries/${registryId}/devices/${gatewayId}`;
console.log(mqttClientId);
const connectionArgs = {
host: mqttBridgeHostname,
port: mqttBridgePort,
clientId: mqttClientId,
username: 'unused',
password: createJwt(projectId, privateKeyFile, algorithm),
protocol: 'mqtts',
qos: 1,
secureProtocol: 'TLSv1_2_method',
};
// Create a client, and connect to the Google MQTT bridge.
const client = mqtt.connect(connectionArgs);
client.on('connect', success => {
if (!success) {
console.log('Client not connected...');
} else {
console.log('Client connected: Gateway is listening, attaching device');
attachDevice(deviceId, client);
setTimeout(() => {
// Subscribe to any configuration topics.
client.subscribe(`/devices/${gatewayId}/config`, {qos: 1});
client.subscribe(`/devices/${deviceId}/config`, {qos: 1});
setTimeout(() => {
detachDevice(deviceId, client);
console.log('Closing connection to MQTT. Goodbye!');
client.end(true);
}, clientDuration); // Safely detach device and close connection.
}, 5000);
}
});
client.on('close', () => {
console.log('Connection closed');
shouldBackoff = true;
});
client.on('error', err => {
console.log('error', err);
});
client.on('message', (topic, message) => {
const decodedMessage = Buffer.from(message, 'base64').toString('ascii');
if (topic === `/devices/${gatewayId}/errors`) {
console.log(`message received on error topic: ${decodedMessage}`);
} else {
console.log(`message received on topic ${topic}: ${decodedMessage}`);
}
});
client.on('packetsend', () => {
// Note: logging packet send is very verbose
});
// [END iot_listen_for_config_messages]
};
// Listen for error messages on a gateway.
const listenForErrorMessages = (
deviceId,
gatewayId,
registryId,
projectId,
region,
algorithm,
privateKeyFile,
mqttBridgeHostname,
mqttBridgePort,
clientDuration
) => {
// [START iot_listen_for_error_messages]
// const deviceId = `myDevice`;
// const gatewayId = `mygateway`;
// const registryId = `myRegistry`;
// const projectId = `my-project-123`;
// const region = `us-central1`;
// const algorithm = `RS256`;
// const privateKeyFile = `./rsa_private.pem`;
// const mqttBridgeHostname = `mqtt.googleapis.com`;
// const mqttBridgePort = 8883;
// const clientDuration = 60000;
const mqttClientId = `projects/${projectId}/locations/${region}/registries/${registryId}/devices/${gatewayId}`;
console.log(mqttClientId);
const connectionArgs = {
host: mqttBridgeHostname,
port: mqttBridgePort,
clientId: mqttClientId,
username: 'unused',
password: createJwt(projectId, privateKeyFile, algorithm),
protocol: 'mqtts',
qos: 1,
secureProtocol: 'TLSv1_2_method',
};
// Create a client, and connect to the Google MQTT bridge.
const client = mqtt.connect(connectionArgs);
client.on('connect', success => {
if (!success) {
console.log('Client not connected...');
} else {
setTimeout(() => {
// Subscribe to gateway error topic.
client.subscribe(`/devices/${gatewayId}/errors`, {qos: 0});
attachDevice(deviceId, client);
setTimeout(() => {
console.log('Closing connection to MQTT. Goodbye!');
client.end(true);
}, clientDuration); // Safely detach device and close connection.
}, 5000);
}
});
client.on('close', () => {
console.log('Connection closed');
shouldBackoff = true;
});
client.on('error', err => {
console.log('error', err);
});
client.on('message', (topic, message) => {
const decodedMessage = Buffer.from(message, 'base64').toString('ascii');
console.log(`message received on error topic ${topic}: ${decodedMessage}`);
});
client.on('packetsend', () => {
// Note: logging packet send is very verbose
});
// [END iot_listen_for_error_messages]
};
const {argv} = require('yargs')
.options({
projectId: {
default:
process.env.GOOGLE_CLOUD_PROJECT || process.env.GOOGLE_CLOUD_PROJECT,
description:
'The Project ID to use. Defaults to the value of the GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.',
requiresArg: true,
type: 'string',
},
cloudRegion: {
default: 'us-central1',
description: 'GCP cloud region.',
requiresArg: true,
type: 'string',
},
registryId: {
description: 'Cloud IoT registry ID.',
requiresArg: true,
demandOption: true,
type: 'string',
},
deviceId: {
description: 'Cloud IoT device ID.',
requiresArg: true,
demandOption: true,
type: 'string',
},
privateKeyFile: {
description: 'Path to private key file.',
requiresArg: true,
demandOption: true,
type: 'string',
},
algorithm: {
description: 'Encryption algorithm to generate the JWT.',
requiresArg: true,
demandOption: true,
choices: ['RS256', 'ES256'],
type: 'string',
},
tokenExpMins: {
default: 20,
description: 'Minutes to JWT token expiration.',
requiresArg: true,
type: 'number',
},
mqttBridgeHostname: {
default: 'mqtt.googleapis.com',
description: 'MQTT bridge hostname.',
requiresArg: true,
type: 'string',
},
mqttBridgePort: {
default: 8883,
description: 'MQTT bridge port.',
requiresArg: true,
type: 'number',
},
})
.command(
'mqttDeviceDemo',
'Connects a device, sends data, and receives data',
{
messageType: {
default: 'events',
description: 'Message type to publish.',
requiresArg: true,
choices: ['events', 'state'],
type: 'string',
},
numMessages: {
default: 10,
description: 'Number of messages to publish.',
demandOption: true,
type: 'number',
},
},
opts => {
mqttDeviceDemo(
opts.deviceId,
opts.registryId,
opts.projectId,
opts.cloudRegion,
opts.algorithm,
opts.privateKeyFile,
opts.mqttBridgeHostname,
opts.mqttBridgePort,
opts.messageType,
opts.numMessages
);
}
)
.command(
'sendDataFromBoundDevice',
'Sends data from a gateway on behalf of a bound device.',
{
gatewayId: {
description: 'Cloud IoT gateway ID.',
requiresArg: true,
demandOption: true,
type: 'string',
},
numMessages: {
default: 10,
description: 'Number of messages to publish.',
demandOption: true,
type: 'number',
},
},
opts => {
sendDataFromBoundDevice(
opts.deviceId,
opts.gatewayId,
opts.registryId,
opts.projectId,
opts.cloudRegion,
opts.algorithm,
opts.privateKeyFile,
opts.mqttBridgeHostname,
opts.mqttBridgePort,
opts.numMessages,
opts.tokenExpMins
);
}
)
.command(
'listenForConfigMessages',
'Listens for configuration changes on a gateway and bound device.',
{
gatewayId: {
description: 'Cloud IoT gateway ID.',
requiresArg: true,
demandOption: true,
type: 'string',
},
clientDuration: {
default: 60000,
description: 'Duration in milliseconds for MQTT client to run.',
requiresArg: true,
type: 'number',
},
},
opts => {
listenForConfigMessages(
opts.deviceId,
opts.gatewayId,
opts.registryId,
opts.projectId,
opts.cloudRegion,
opts.algorithm,
opts.privateKeyFile,
opts.mqttBridgeHostname,
opts.mqttBridgePort,
opts.clientDuration
);
}
)
.command(
'listenForErrorMessages',
'Listens for error messages on a gateway.',
{
gatewayId: {
description: 'Cloud IoT gateway ID.',
requiresArg: true,
demandOption: true,
type: 'string',
},
clientDuration: {
default: 60000,
description: 'Duration in milliseconds for MQTT client to run.',
requiresArg: true,
type: 'number',
},
},
opts => {
listenForErrorMessages(
opts.deviceId,
opts.gatewayId,
opts.registryId,
opts.projectId,
opts.cloudRegion,
opts.algorithm,
opts.privateKeyFile,
opts.mqttBridgeHostname,
opts.mqttBridgePort,
opts.clientDuration
);
}
)
.example(
'node $0 mqttDeviceDemo --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --numMessages=10 \\\n'
)
.example(
'node $0 sendDataFromBoundDevice --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n'
)
.example(
'node $0 listenForConfigMessages --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n\t--clientDuration=300000 \\\n'
)
.example(
'node $0 listenForErrorMessages --projectId=blue-jet-123 \\\n\t--registryId=my-registry --deviceId=my-node-device \\\n\t--privateKeyFile=../rsa_private.pem --algorithm=RS256 \\\n\t--cloudRegion=us-central1 --gatewayId=my-node-gateway \\\n\t--clientDuration=300000 \\\n'
)
.wrap(120)
.recommendCommands()
.epilogue('For more information, see https://cloud.google.com/iot-core/docs')
.help()
.strict();