@@ -67,6 +67,12 @@ var argv = require(`yargs`)
6767 requiresArg : true ,
6868 type : 'number'
6969 } ,
70+ token_exp_mins : {
71+ default : 20 ,
72+ description : 'Minutes to JWT token expiration.' ,
73+ requiresArg : true ,
74+ type : 'number'
75+ } ,
7076 mqtt_bridge_hostname : {
7177 default : 'mqtt.googleapis.com' ,
7278 description : 'MQTT bridge hostname.' ,
@@ -127,6 +133,31 @@ function publishAsync (messageCount, numMessages) {
127133 // If we have published fewer than numMessage messages, publish payload
128134 // messageCount + 1 in 1 second.
129135 setTimeout ( function ( ) {
136+ let secsFromIssue = parseInt ( Date . now ( ) / 1000 ) - iatTime ;
137+ if ( secsFromIssue > argv . token_exp_mins * 60 ) {
138+ iatTime = parseInt ( Date . now ( ) / 1000 ) ;
139+ console . log ( `\tRefreshing token after ${ secsFromIssue } seconds.` ) ;
140+
141+ client . end ( ) ;
142+ connectionArgs . password = createJwt ( argv . project_id , argv . private_key_file , argv . algorithm ) ;
143+ client = mqtt . connect ( connectionArgs ) ;
144+
145+ client . on ( 'connect' , ( ) => {
146+ console . log ( 'connect' , arguments ) ;
147+ } ) ;
148+
149+ client . on ( 'close' , ( ) => {
150+ console . log ( 'close' , arguments ) ;
151+ } ) ;
152+
153+ client . on ( 'error' , ( ) => {
154+ console . log ( 'error' , arguments ) ;
155+ } ) ;
156+
157+ client . on ( 'packetsend' , ( ) => {
158+ // Too verbose to log here
159+ } ) ;
160+ }
130161 publishAsync ( messageCount + 1 , numMessages ) ;
131162 } , delayMs ) ;
132163 } else {
@@ -146,17 +177,19 @@ const mqttClientId = `projects/${argv.project_id}/locations/${argv.cloud_region}
146177// non-empty. The password field is used to transmit a JWT to authorize the
147178// device. The "mqtts" protocol causes the library to connect using SSL, which
148179// is required for Cloud IoT Core.
149- const connectionArgs = {
180+ let connectionArgs = {
150181 host : argv . mqtt_bridge_hostname ,
151182 port : argv . mqtt_bridge_port ,
152183 clientId : mqttClientId ,
153184 username : 'unused' ,
154185 password : createJwt ( argv . project_id , argv . private_key_file , argv . algorithm ) ,
155- protocol : 'mqtts'
186+ protocol : 'mqtts' ,
187+ secureProtocol : 'TLSv1_2_method'
156188} ;
157189
158190// Create a client, and connect to the Google MQTT bridge.
159- const client = mqtt . connect ( connectionArgs ) ;
191+ let iatTime = parseInt ( Date . now ( ) / 1000 ) ;
192+ let client = mqtt . connect ( connectionArgs ) ;
160193
161194// The MQTT topic that this device will publish data to. The MQTT
162195// topic name is required to be in the format below. The topic name must end in
@@ -180,7 +213,7 @@ client.on('error', () => {
180213} ) ;
181214
182215client . on ( 'packetsend' , ( ) => {
183- console . log ( 'packetsend' , arguments ) ;
216+ // Note: logging packet send is very verbose
184217} ) ;
185218
186219// Once all of the messages have been published, the connection to Google Cloud
0 commit comments