@@ -84,14 +84,21 @@ def cloud_to_device_message_received(self, body: str, properties: dict) -> None:
84
84
:param dict properties: The propreties sent with the mesage
85
85
"""
86
86
87
- def device_twin_desired_updated (self , desired_property_name : str , desired_property_value , desired_version : int ) -> None :
87
+ def device_twin_desired_updated (
88
+ self , desired_property_name : str , desired_property_value , desired_version : int
89
+ ) -> None :
88
90
"""Called when the device twin desired properties are updated
89
91
:param str desired_property_name: The name of the desired property that was updated
90
92
:param desired_property_value: The value of the desired property that was updated
91
93
:param int desired_version: The version of the desired property that was updated
92
94
"""
93
95
94
- def device_twin_reported_updated (self , reported_property_name : str , reported_property_value , reported_version : int ) -> None :
96
+ def device_twin_reported_updated (
97
+ self ,
98
+ reported_property_name : str ,
99
+ reported_property_value ,
100
+ reported_version : int ,
101
+ ) -> None :
95
102
"""Called when the device twin reported values are updated
96
103
:param str reported_property_name: The name of the reported property that was updated
97
104
:param reported_property_value: The value of the reported property that was updated
@@ -107,11 +114,17 @@ class IoTMQTT:
107
114
def _gen_sas_token (self ) -> str :
108
115
token_expiry = int (time .time () + self ._token_expires )
109
116
uri = self ._hostname + "%2Fdevices%2F" + self ._device_id
110
- signed_hmac_sha256 = DeviceRegistration .compute_derived_symmetric_key (self ._key , uri + "\n " + str (token_expiry ))
117
+ signed_hmac_sha256 = DeviceRegistration .compute_derived_symmetric_key (
118
+ self ._key , uri + "\n " + str (token_expiry )
119
+ )
111
120
signature = parse .quote (signed_hmac_sha256 , "~()*!.'" )
112
- if signature .endswith ("\n " ): # somewhere along the crypto chain a newline is inserted
121
+ if signature .endswith (
122
+ "\n "
123
+ ): # somewhere along the crypto chain a newline is inserted
113
124
signature = signature [:- 1 ]
114
- token = "SharedAccessSignature sr={}&sig={}&se={}" .format (uri , signature , token_expiry )
125
+ token = "SharedAccessSignature sr={}&sig={}&se={}" .format (
126
+ uri , signature , token_expiry
127
+ )
115
128
return token
116
129
117
130
# Workaround for https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/issues/25
@@ -143,15 +156,16 @@ def _try_create_mqtt_client(self, hostname: str) -> None:
143
156
self ._mqtts .connect ()
144
157
145
158
def _create_mqtt_client (self ) -> None :
146
- try :
147
- self ._try_create_mqtt_client (self ._hostname )
148
- except ValueError :
149
- # Workaround for https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/issues/25
150
- self ._try_create_mqtt_client ("https://" + self ._hostname )
159
+ self ._try_create_mqtt_client (self ._hostname )
151
160
152
161
# pylint: disable=C0103, W0613
153
162
def _on_connect (self , client , userdata , _ , rc ) -> None :
154
- self ._logger .info ("- iot_mqtt :: _on_connect :: rc = " + str (rc ) + ", userdata = " + str (userdata ))
163
+ self ._logger .info (
164
+ "- iot_mqtt :: _on_connect :: rc = "
165
+ + str (rc )
166
+ + ", userdata = "
167
+ + str (userdata )
168
+ )
155
169
if rc == 0 :
156
170
self ._mqtt_connected = True
157
171
self ._auth_response_received = True
@@ -178,7 +192,9 @@ def _on_disconnect(self, client, userdata, rc) -> None:
178
192
self ._callback .connection_status_change (False )
179
193
180
194
def _on_publish (self , client , data , topic , msg_id ) -> None :
181
- self ._logger .info ("- iot_mqtt :: _on_publish :: " + str (data ) + " on topic " + str (topic ))
195
+ self ._logger .info (
196
+ "- iot_mqtt :: _on_publish :: " + str (data ) + " on topic " + str (topic )
197
+ )
182
198
183
199
# pylint: disable=W0703
184
200
def _handle_device_twin_update (self , msg : str , topic : str ) -> None :
@@ -189,7 +205,12 @@ def _handle_device_twin_update(self, msg: str, topic: str) -> None:
189
205
try :
190
206
twin = json .loads (msg )
191
207
except json .JSONDecodeError as e :
192
- self ._logger .error ("ERROR: JSON parse for Device Twin message object has failed. => " + msg + " => " + str (e ))
208
+ self ._logger .error (
209
+ "ERROR: JSON parse for Device Twin message object has failed. => "
210
+ + msg
211
+ + " => "
212
+ + str (e )
213
+ )
193
214
return
194
215
195
216
if "reported" in twin :
@@ -199,11 +220,15 @@ def _handle_device_twin_update(self, msg: str, topic: str) -> None:
199
220
reported_version = reported ["$version" ]
200
221
reported .pop ("$version" )
201
222
else :
202
- self ._logger .error ("ERROR: Unexpected payload for reported twin update => " + msg )
223
+ self ._logger .error (
224
+ "ERROR: Unexpected payload for reported twin update => " + msg
225
+ )
203
226
return
204
227
205
228
for property_name , value in reported .items ():
206
- self ._callback .device_twin_reported_updated (property_name , value , reported_version )
229
+ self ._callback .device_twin_reported_updated (
230
+ property_name , value , reported_version
231
+ )
207
232
208
233
is_patch = "desired" not in twin
209
234
@@ -216,11 +241,15 @@ def _handle_device_twin_update(self, msg: str, topic: str) -> None:
216
241
desired_version = desired ["$version" ]
217
242
desired .pop ("$version" )
218
243
else :
219
- self ._logger .error ("ERROR: Unexpected payload for desired twin update => " + msg )
244
+ self ._logger .error (
245
+ "ERROR: Unexpected payload for desired twin update => " + msg
246
+ )
220
247
return
221
248
222
249
for property_name , value in desired .items ():
223
- self ._callback .device_twin_desired_updated (property_name , value , desired_version )
250
+ self ._callback .device_twin_desired_updated (
251
+ property_name , value , desired_version
252
+ )
224
253
225
254
def _handle_direct_method (self , msg : str , topic : str ) -> None :
226
255
index = topic .find ("$rid=" )
@@ -249,7 +278,14 @@ def _handle_direct_method(self, msg: str, topic: str) -> None:
249
278
ret_message = json .dumps (ret_json )
250
279
251
280
next_topic = "$iothub/methods/res/{}/?$rid={}" .format (ret_code , method_id )
252
- self ._logger .info ("C2D: => " + next_topic + " with data " + ret_message + " and name => " + method_name )
281
+ self ._logger .info (
282
+ "C2D: => "
283
+ + next_topic
284
+ + " with data "
285
+ + ret_message
286
+ + " and name => "
287
+ + method_name
288
+ )
253
289
self ._send_common (next_topic , ret_message )
254
290
255
291
def _handle_cloud_to_device_message (self , msg : str , topic : str ) -> None :
@@ -282,14 +318,18 @@ def _on_message(self, client, msg_topic, payload) -> None:
282
318
topic = str (msg_topic )
283
319
284
320
if topic .startswith ("$iothub/" ):
285
- if topic .startswith ("$iothub/twin/PATCH/properties/desired/" ) or topic .startswith ("$iothub/twin/res/200/?$rid=" ):
321
+ if topic .startswith (
322
+ "$iothub/twin/PATCH/properties/desired/"
323
+ ) or topic .startswith ("$iothub/twin/res/200/?$rid=" ):
286
324
self ._handle_device_twin_update (str (msg ), topic )
287
325
elif topic .startswith ("$iothub/methods" ):
288
326
self ._handle_direct_method (str (msg ), topic )
289
327
else :
290
328
if not topic .startswith ("$iothub/twin/res/" ): # not twin response
291
329
self ._logger .error ("ERROR: unknown twin! - {}" .format (msg ))
292
- elif topic .startswith ("devices/{}/messages/devicebound" .format (self ._device_id )):
330
+ elif topic .startswith (
331
+ "devices/{}/messages/devicebound" .format (self ._device_id )
332
+ ):
293
333
self ._handle_cloud_to_device_message (str (msg ), topic )
294
334
else :
295
335
self ._logger .error ("ERROR: (unknown message) - {}" .format (msg ))
@@ -315,7 +355,10 @@ def _send_common(self, topic: str, data) -> None:
315
355
self ._logger .debug ("Data sent" )
316
356
break
317
357
except RuntimeError as runtime_error :
318
- self ._logger .info ("Could not send data, retrying after 0.5 seconds: " + str (runtime_error ))
358
+ self ._logger .info (
359
+ "Could not send data, retrying after 0.5 seconds: "
360
+ + str (runtime_error )
361
+ )
319
362
retry = retry + 1
320
363
321
364
if retry >= 10 :
@@ -364,18 +407,24 @@ def __init__(
364
407
self ._hostname = hostname
365
408
self ._key = key
366
409
self ._token_expires = token_expires
367
- self ._username = "{}/{}/api-version={}" .format (self ._hostname , device_id , constants .IOTC_API_VERSION )
410
+ self ._username = "{}/{}/api-version={}" .format (
411
+ self ._hostname , device_id , constants .IOTC_API_VERSION
412
+ )
368
413
self ._passwd = self ._gen_sas_token ()
369
414
self ._logger = logger if logger is not None else logging .getLogger ("log" )
370
415
self ._is_subscribed_to_twins = False
371
416
372
417
def _subscribe_to_core_topics (self ):
373
418
self ._mqtts .subscribe ("devices/{}/messages/events/#" .format (self ._device_id ))
374
- self ._mqtts .subscribe ("devices/{}/messages/devicebound/#" .format (self ._device_id ))
419
+ self ._mqtts .subscribe (
420
+ "devices/{}/messages/devicebound/#" .format (self ._device_id )
421
+ )
375
422
self ._mqtts .subscribe ("$iothub/methods/#" )
376
423
377
424
def _subscribe_to_twin_topics (self ):
378
- self ._mqtts .subscribe ("$iothub/twin/PATCH/properties/desired/#" ) # twin desired property changes
425
+ self ._mqtts .subscribe (
426
+ "$iothub/twin/PATCH/properties/desired/#"
427
+ ) # twin desired property changes
379
428
self ._mqtts .subscribe ("$iothub/twin/res/#" ) # twin properties response
380
429
381
430
def connect (self ) -> bool :
@@ -391,7 +440,10 @@ def connect(self) -> bool:
391
440
while self ._auth_response_received is None :
392
441
self .loop ()
393
442
394
- self ._logger .info (" - iot_mqtt :: connect :: on_connect must be fired. Connected ? " + str (self .is_connected ()))
443
+ self ._logger .info (
444
+ " - iot_mqtt :: connect :: on_connect must be fired. Connected ? "
445
+ + str (self .is_connected ())
446
+ )
395
447
if not self .is_connected ():
396
448
return False
397
449
@@ -448,7 +500,9 @@ def loop(self) -> None:
448
500
449
501
self ._mqtts .loop ()
450
502
451
- def send_device_to_cloud_message (self , message , system_properties : dict = None ) -> None :
503
+ def send_device_to_cloud_message (
504
+ self , message , system_properties : dict = None
505
+ ) -> None :
452
506
"""Send a device to cloud message from this device to Azure IoT Hub
453
507
:param message: The message data as a JSON string or a dictionary
454
508
:param system_properties: System properties to send with the message
@@ -484,5 +538,7 @@ def send_twin_patch(self, patch) -> None:
484
538
:raises RuntimeError: if the internet connection is not responding or is unable to connect
485
539
"""
486
540
self ._logger .info ("- iot_mqtt :: sendProperty :: " + str (patch ))
487
- topic = "$iothub/twin/PATCH/properties/reported/?$rid={}" .format (int (time .time ()))
541
+ topic = "$iothub/twin/PATCH/properties/reported/?$rid={}" .format (
542
+ int (time .time ())
543
+ )
488
544
self ._send_common (topic , patch )
0 commit comments