-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqttTest.py
469 lines (389 loc) · 17.3 KB
/
mqttTest.py
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
# [START iot_mqtt_includes]
import argparse
import datetime
import logging
import os
import random
import ssl
import time
import jwt
import paho.mqtt.client as mqtt
# [END iot_mqtt_includes]
logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.CRITICAL)
# The initial backoff time after a disconnection occurs, in seconds.
minimum_backoff_time = 1
# The maximum backoff time before giving up, in seconds.
MAXIMUM_BACKOFF_TIME = 32
# Whether to wait with exponential backoff before publishing.
should_backoff = False
# [START iot_mqtt_jwt]
def create_jwt(project_id, private_key_file, algorithm):
"""Creates a JWT (https://jwt.io) to establish an MQTT connection.
Args:
project_id: The cloud project ID this device belongs to
private_key_file: A path to a file containing either an RSA256 or
ES256 private key.
algorithm: The encryption algorithm to use. Either 'RS256' or 'ES256'
Returns:
A JWT generated from the given project_id and private key, which
expires in 20 minutes. After 20 minutes, your client will be
disconnected, and a new JWT will have to be generated.
Raises:
ValueError: If the private_key_file does not contain a known key.
"""
token = {
# The time that the token was issued at
'iat': datetime.datetime.utcnow(),
# The time the token expires.
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=20),
# The audience field should always be set to the GCP project id.
'aud': project_id
}
# Read the private key file.
with open(private_key_file, 'r') as f:
private_key = f.read()
print('Creating JWT using {} from private key file {}'.format(
algorithm, private_key_file))
return jwt.encode(token, private_key, algorithm=algorithm)
# [END iot_mqtt_jwt]
# [START iot_mqtt_config]
def error_str(rc):
"""Convert a Paho error to a human readable string."""
return '{}: {}'.format(rc, mqtt.error_string(rc))
def on_connect(unused_client, unused_userdata, unused_flags, rc):
"""Callback for when a device connects."""
print('on_connect', mqtt.connack_string(rc))
# After a successful connect, reset backoff time and stop backing off.
global should_backoff
global minimum_backoff_time
should_backoff = False
minimum_backoff_time = 1
def on_disconnect(unused_client, unused_userdata, rc):
"""Paho callback for when a device disconnects."""
print('on_disconnect', error_str(rc))
# Since a disconnect occurred, the next loop iteration will wait with
# exponential backoff.
global should_backoff
should_backoff = True
def on_publish(unused_client, unused_userdata, unused_mid):
"""Paho callback when a message is sent to the broker."""
print('on_publish')
def on_message(unused_client, unused_userdata, message):
"""Callback when the device receives a message on a subscription."""
payload = str(message.payload.decode('utf-8'))
print('Received message \'{}\' on topic \'{}\' with Qos {}'.format(
payload, message.topic, str(message.qos)))
def get_client(
project_id, cloud_region, registry_id, device_id, private_key_file,
algorithm, ca_certs, mqtt_bridge_hostname, mqtt_bridge_port):
"""Create our MQTT client. The client_id is a unique string that identifies
this device. For Google Cloud IoT Core, it must be in the format below."""
client_id = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(
project_id, cloud_region, registry_id, device_id)
print('Device client_id is \'{}\''.format(client_id))
client = mqtt.Client(client_id=client_id)
# With Google Cloud IoT Core, the username field is ignored, and the
# password field is used to transmit a JWT to authorize the device.
client.username_pw_set(
username='unused',
password=create_jwt(
project_id, private_key_file, algorithm))
# Enable SSL/TLS support.
client.tls_set(ca_certs=ca_certs, tls_version=ssl.PROTOCOL_TLSv1_2)
# Register message callbacks. https://eclipse.org/paho/clients/python/docs/
# describes additional callbacks that Paho supports. In this example, the
# callbacks just print to standard out.
client.on_connect = on_connect
client.on_publish = on_publish
client.on_disconnect = on_disconnect
client.on_message = on_message
# Connect to the Google MQTT bridge.
client.connect(mqtt_bridge_hostname, mqtt_bridge_port)
# This is the topic that the device will receive configuration updates on.
mqtt_config_topic = '/devices/{}/config'.format(device_id)
# Subscribe to the config topic.
client.subscribe(mqtt_config_topic, qos=1)
# The topic that the device will receive commands on.
mqtt_command_topic = '/devices/{}/commands/#'.format(device_id)
# Subscribe to the commands topic, QoS 1 enables message acknowledgement.
print('Subscribing to {}'.format(mqtt_command_topic))
client.subscribe(mqtt_command_topic, qos=0)
return client
# [END iot_mqtt_config]
def detach_device(client, device_id):
"""Detach the device from the gateway."""
# [START iot_detach_device]
detach_topic = '/devices/{}/detach'.format(device_id)
print('Detaching: {}'.format(detach_topic))
client.publish(detach_topic, '{}', qos=1)
# [END iot_detach_device]
def attach_device(client, device_id, auth):
"""Attach the device to the gateway."""
# [START iot_attach_device]
attach_topic = '/devices/{}/attach'.format(device_id)
attach_payload = '{{"authorization" : "{}"}}'.format(auth)
client.publish(attach_topic, attach_payload, qos=1)
# [END iot_attach_device]
def parse_command_line_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description=(
'Google Cloud IoT Core MQTT device connection code.'))
parser.add_argument(
'--algorithm',
choices=('RS256', 'ES256'),
required=True,
help='Which encryption algorithm to use to generate the JWT.')
parser.add_argument(
'--ca_certs',
default='roots.pem',
help='CA root from https://pki.google.com/roots.pem')
parser.add_argument(
'--cloud_region', default='us-central1', help='GCP cloud region')
parser.add_argument(
'--data',
default='Hello there',
help='The telemetry data sent on behalf of a device')
parser.add_argument(
'--device_id', required=True, help='Cloud IoT Core device id')
parser.add_argument(
'--gateway_id', required=False, help='Gateway identifier.')
parser.add_argument(
'--jwt_expires_minutes',
default=20,
type=int,
help='Expiration time, in minutes, for JWT tokens.')
parser.add_argument(
'--cert_expires_minutes',
default=10080, #7 days
type=int,
help='Expiration time, in minutes, for primary cert.')
parser.add_argument(
'--backup_cert_expires_minutes',
default=2419200, #28 days
type=int,
help='Expiration time, in minutes, for backup cert.')
parser.add_argument(
'--listen_dur',
default=60,
type=int,
help='Duration (seconds) to listen for configuration messages')
parser.add_argument(
'--message_type',
choices=('event', 'state'),
default='event',
help=('Indicates whether the message to be published is a '
'telemetry event or a device state message.'))
parser.add_argument(
'--mqtt_bridge_hostname',
default='mqtt.googleapis.com',
help='MQTT bridge hostname.')
parser.add_argument(
'--mqtt_bridge_port',
choices=(8883, 443),
default=443,
type=int,
help='MQTT bridge port.')
parser.add_argument(
'--num_messages',
type=int,
default=100,
help='Number of messages to publish.')
parser.add_argument(
'--private_key_file',
required=True,
help='Path to private key file.')
parser.add_argument(
'--project_id',
default=os.environ.get('GOOGLE_CLOUD_PROJECT'),
help='GCP cloud project name')
parser.add_argument(
'--registry_id', required=True, help='Cloud IoT Core registry id')
return parser.parse_args()
def mqtt_device_cert_update(args, key_to_use_temporarily):
"""Connects a device, sends data, and receives data."""
# [START iot_mqtt_run]
global minimum_backoff_time
global MAXIMUM_BACKOFF_TIME
# Rotate keys
cmd = "./rotateKeys.sh"
print(cmd)
os.system(cmd)
# Allow time for keys to be generated and rotate
for i in range(0, 10):
time.sleep(1)
# read public keys
file = open("ec_public_at_bat.pem", "r")
key1 = file.read()
file.close()
file = open("ec_public_on_deck.pem", "r")
key2 = file.read()
file.close()
file = open("ec_public_on_base.pem", "r")
key3 = file.read()
file.close()
# convert public keys and other needed information to JSON format
data = {}
data['certs'] = {}
data['certs'].update({
'device-id': args.device_id,
'at_bat': key1,
'on_deck': key2,
'on_base': key3,
'project-id': args.project_id,
'cloud-region': args.cloud_region,
'registry-id': args.registry_id,
})
keyPayload = json.dumps(data)
mqtt_device_run(args,keyPayload)
print('Keys rotated')
key_to_use_temporarily = "ec_public_on_base.pem"
# Publish to the events or state topic based on the flag.
#sub_topic = 'events' if args.message_type == 'event' else 'state'
sub_topic = 'events/test-cert-info' # topic for cert updates
mqtt_topic = '/devices/{}/{}'.format(args.device_id, sub_topic)
#cert_iat = datetime.datetime.utcnow()
#cert_exp_mins = args.cert_expires_minutes
jwt_iat = datetime.datetime.utcnow()
jwt_exp_mins = args.jwt_expires_minutes
client = get_client(
args.project_id, args.cloud_region, args.registry_id,
args.device_id, key_to_use_temporarily, args.algorithm,
args.ca_certs, args.mqtt_bridge_hostname, args.mqtt_bridge_port)
# Process network events.
client.loop()
payload = '{}'.format(
keyPayload)
print('Publishing message: {}'.format(
payload))
# [START iot_mqtt_jwt_refresh]
seconds_since_issue = (datetime.datetime.utcnow() - jwt_iat).seconds
if seconds_since_issue > 60 * jwt_exp_mins:
print('Refreshing token after {}s'.format(seconds_since_issue))
jwt_iat = datetime.datetime.utcnow()
client.loop()
client.disconnect()
client = get_client(
args.project_id, args.cloud_region,
args.registry_id, args.device_id, key_to_use_temporarily,
args.algorithm, args.ca_certs, args.mqtt_bridge_hostname,
args.mqtt_bridge_port)
# [END iot_mqtt_jwt_refresh]
# 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.
client.publish(mqtt_topic, payload, qos=1)
# Send events every second. State should not be updated as often
for i in range(0, 10):
time.sleep(1)
client.loop() # Gives the Paho MQTT client time to read to/write from buffers
# [END iot_mqtt_cert_update]
return key_to_use_temporarily
def rotate_cert_check(current_key, cert_expires_minutes):
# [START check_for_cert_rotation]
# Find the amount of time since a cert was issued
at_bat_dt=os.path.getmtime(current_key) # get the datetime stamp on the public key file
at_bat_cert_iat=datetime.datetime.utcfromtimestamp(at_bat_dt) # convert the datetime stamp to UTC
#on_deck_dt=os.path.getmtime('ec_public_on_deck.pem')
#on_deck_cert_iat=datetime.datetime.utcfromtimestamp(on_deck_dt)
#print('At-bat cert issued at: {}'.format(at_bat_cert_iat))
#print('On-deck cert issued at: {}'.format(on_deck_cert_iat))
timeNow=datetime.datetime.utcnow()
#print('UTC now: {}'.format(timeNow))
at_bat_time_difference = timeNow - at_bat_cert_iat
at_bat_seconds_since_issue = at_bat_time_difference.days * 24 * 3600 + at_bat_time_difference.seconds
#on_deck_time_difference = timeNow - on_deck_cert_iat
#on_deck_seconds_since_issue = on_deck_time_difference.days * 24 * 3600 + on_deck_time_difference.seconds
#print('Seconds since at-bat cert issued: {}'.format(at_bat_seconds_since_issue))
#print('Seconds since on-deck cert issued: {}'.format(on_deck_seconds_since_issue))
if at_bat_seconds_since_issue > 60 * cert_expires_minutes:
print('Refreshing cert after {}s'.format(at_bat_seconds_since_issue))
return "ec_public_on_deck.pem"
else:
return current_key
# [END check_for_cert_rotation]
def mqtt_device_run(args):
"""Connects a device, sends data, and receives data."""
# [START iot_mqtt_run]
global minimum_backoff_time
global MAXIMUM_BACKOFF_TIME
# Which key should be used
current_key_file = args.private_key_file
# Whether key rotation is currently underway
key_rotation_in_progress = False
# Publish to the events or state topic based on the flag.
sub_topic = 'events' if args.message_type == 'event' else 'state'
#sub_topic = 'events/test-cert-info'
mqtt_topic = '/devices/{}/{}'.format(args.device_id, sub_topic)
#cert_iat = datetime.datetime.utcnow()
#cert_exp_mins = args.cert_expires_minutes
jwt_iat = datetime.datetime.utcnow()
jwt_exp_mins = args.jwt_expires_minutes
client = get_client(
args.project_id, args.cloud_region, args.registry_id,
args.device_id, current_key_file, args.algorithm,
args.ca_certs, args.mqtt_bridge_hostname, args.mqtt_bridge_port)
# Publish num_messages messages to the MQTT bridge.
for i in range(1, args.num_messages + 1):
# Process network events.
client.loop()
# Wait if backoff is required.
if should_backoff:
# If backoff time is too large, give up.
if minimum_backoff_time > MAXIMUM_BACKOFF_TIME:
print('Exceeded maximum backoff time. Giving up.')
break
# Otherwise, wait and connect again.
delay = minimum_backoff_time + random.randint(0, 1000) / 1000.0
print('Waiting for {} before reconnecting.'.format(delay))
time.sleep(delay)
minimum_backoff_time *= 2
client.connect(args.mqtt_bridge_hostname, args.mqtt_bridge_port)
payload = '{}/{}-payload-{}'.format(
args.registry_id, args.device_id, i)
print('Publishing message {}/{}: \'{}\''.format(
i, args.num_messages, payload))
## [START iot_mqtt_cert_refresh]
# Check if refresh is already in progress
if key_rotation_in_progress == False:
# See if the current cert should be rotated out -- if so, return the filename of the backup key to use during cert rotation
key_to_use_going_forward = rotate_cert_check(current_key_file, args.cert_expires_minutes)
if key_to_use_going_forward != current_key_file:
key_rotation_in_progress = True
#Create new certs and send them upstream
current_key_file = mqtt_device_cert_update(args, key_to_use_going_forward)
client.loop()
client.disconnect()
client = get_client(
args.project_id, args.cloud_region,
args.registry_id, args.device_id, current_key_file,
args.algorithm, args.ca_certs, args.mqtt_bridge_hostname,
args.mqtt_bridge_port)
## [END iot_mqtt_cert_refresh]
# [START iot_mqtt_jwt_refresh]
seconds_since_issue = (datetime.datetime.utcnow() - jwt_iat).seconds
if seconds_since_issue > 60 * jwt_exp_mins:
print('Refreshing token after {}s'.format(seconds_since_issue))
jwt_iat = datetime.datetime.utcnow()
client.loop()
client.disconnect()
client = get_client(
args.project_id, args.cloud_region,
args.registry_id, args.device_id, current_key_file,
args.algorithm, args.ca_certs, args.mqtt_bridge_hostname,
args.mqtt_bridge_port)
# [END iot_mqtt_jwt_refresh]
# 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.
client.publish(mqtt_topic, payload, qos=1)
# Send events every second. State should not be updated as often
for i in range(0, 10):
time.sleep(1)
client.loop() # Gives the Paho MQTT client time to read to/write from buffers
# [END iot_mqtt_run]
def main():
args = parse_command_line_args()
mqtt_device_run(args)
print('Finished.')
if __name__ == '__main__':
main()