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
|
import argparse
import datetime
import logging
import os
import random
import ssl
import time
import jwt
import paho.mqtt.client as mqtt
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
CA_CERTS = 'roots.pem'
HOST = 'mqtt.googleapis.com'
PORT = 8883
JWT_EXPIRE = 20
ALGORITHM = 'RS256'
def create_jwt(project_id, private_key_file, algorithm, expire_minutes):
print('Creating JWT using {} from private key file {}'.format(
algorithm, private_key_file))
token = {
'iat': datetime.datetime.utcnow(),
'exp': datetime.datetime.utcnow() + datetime.timedelta(
minutes=expire_minutes),
'aud': project_id
}
with open(private_key_file, 'r') as f:
private_key = f.read()
return jwt.encode(token, private_key, algorithm=algorithm)
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):
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):
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 get_client(
jwt, project_id, cloud_region, registry_id, device_id,
hostname, port):
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)
client.username_pw_set(username='unused', password=jwt)
client.tls_set(ca_certs=CA_CERTS, tls_version=ssl.PROTOCOL_TLSv1_2)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = lambda client, userdata, mid: print('on_publish')
client.on_message = lambda client, userdata, message: print(
'Received message \'{}\' on topic \'{}\' with Qos {}'.format(
str(message.payload.decode('utf-8')),
message.topic, str(message.qos)))
client.connect(hostname, port)
mqtt_config_topic = '/devices/{}/config'.format(device_id)
client.subscribe(mqtt_config_topic, qos=1)
mqtt_command_topic = '/devices/{}/commands/#'.format(device_id)
client.subscribe(mqtt_command_topic, qos=0)
return client
def mqtt_device_demo(
project_id, cloud_region, registry_id, device_id,
server, server_port,
private_key_file, algorithm, jwt_expires_minutes):
global minimum_backoff_time
global MAXIMUM_BACKOFF_TIME
jwt_iat = datetime.datetime.utcnow()
jwt_exp_mins = jwt_expires_minutes
jwt = create_jwt(project_id, private_key_file, algorithm, jwt_exp_mins)
client = get_client(
jwt, project_id, cloud_region, registry_id, device_id,
server, server_port)
while True:
# 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(server, server_port)
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))
client.loop()
client.disconnect()
jwt_iat = datetime.datetime.utcnow()
jwt = create_jwt(
project_id, private_key_file, algorithm, jwt_exp_mins)
client = get_client(
jwt, project_id, cloud_region, registry_id, device_id,
server, server_port)
for i in range(0, 60):
time.sleep(1)
client.loop()
def parse_command_line_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description=(
'Example Google Cloud IoT Core MQTT device connection code.'))
parser.add_argument(
'--cloud_region', default='us-central1', help='GCP cloud region')
parser.add_argument(
'--device_id', required=True, help='Cloud IoT Core device id')
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 main():
args = parse_command_line_args()
mqtt_device_demo(
args.project_id, args.cloud_region,
args.registry_id, args.device_id,
HOST, PORT,
args.private_key_file, ALGORITHM, JWT_EXPIRE)
print('Finished.')
if __name__ == '__main__':
main()
|