@@ -35,6 +35,10 @@ def timestamp():
35
35
return int (time .time ())
36
36
37
37
38
+ def log_enabled (level ):
39
+ return logging .getLogger ().isEnabledFor (level )
40
+
41
+
38
42
class ArduinoCloudObject (SenmlRecord ):
39
43
def __init__ (self , name , ** kwargs ):
40
44
self .on_read = kwargs .pop ("on_read" , None )
@@ -97,10 +101,11 @@ def value(self, value):
97
101
)
98
102
self ._updated = True
99
103
self .timestamp = timestamp ()
100
- logging .debug (
101
- f"%s: { self .name } value: { value } ts: { self .timestamp } "
102
- % ("Init" if self .value is None else "Update" )
103
- )
104
+ if log_enabled (logging .DEBUG ):
105
+ logging .debug (
106
+ f"%s: { self .name } value: { value } ts: { self .timestamp } "
107
+ % ("Init" if self .value is None else "Update" )
108
+ )
104
109
self ._value = value
105
110
106
111
def __getattr__ (self , attr ):
@@ -181,7 +186,8 @@ def __init__(
181
186
# Use M2Crypto to load key and cert from HSM.
182
187
import M2Crypto # noqa
183
188
except (ImportError , AttributeError ):
184
- logging .error ("The m2crypto module is required to use HSM." )
189
+ if log_enabled (logging .ERROR ):
190
+ logging .error ("The m2crypto module is required to use HSM." )
185
191
sys .exit (1 )
186
192
187
193
# Convert args to bytes if they are passed as strings.
@@ -235,18 +241,21 @@ def update_systime(self, server, timeout):
235
241
ntptime .host = server
236
242
ntptime .timeout = timeout
237
243
ntptime .settime ()
238
- logging .info ("RTC time set from NTP." )
244
+ if log_enabled (logging .INFO ):
245
+ logging .info ("RTC time set from NTP." )
239
246
except ImportError :
240
247
pass # No ntptime module.
241
248
except Exception as e :
242
- logging .error (f"Failed to set RTC time from NTP: { e } ." )
249
+ if log_enabled (logging .ERROR ):
250
+ logging .error (f"Failed to set RTC time from NTP: { e } ." )
243
251
244
252
def create_task (self , name , coro , * args , ** kwargs ):
245
253
if callable (coro ):
246
254
coro = coro (* args )
247
255
if self .started :
248
256
self .tasks [name ] = asyncio .create_task (coro )
249
- logging .info (f"task: { name } created." )
257
+ if log_enabled (logging .INFO ):
258
+ logging .info (f"task: { name } created." )
250
259
else :
251
260
# Defer task creation until there's a running event loop.
252
261
self .tasks [name ] = coro
@@ -275,12 +284,15 @@ def senml_generic_callback(self, record, **kwargs):
275
284
# This callback catches all unknown/umatched sub/records that were not part of the pack.
276
285
rname , sname = record .name .split (":" ) if ":" in record .name else [record .name , None ]
277
286
if rname in self .records :
278
- logging .info (f"Ignoring cloud initialization for record: { record .name } " )
287
+ if log_enabled (logging .INFO ):
288
+ logging .info (f"Ignoring cloud initialization for record: { record .name } " )
279
289
else :
280
- logging .warning (f"Unkown record found: { record .name } value: { record .value } " )
290
+ if log_enabled (logging .WARNING ):
291
+ logging .warning (f"Unkown record found: { record .name } value: { record .value } " )
281
292
282
293
def mqtt_callback (self , topic , message ):
283
- logging .debug (f"mqtt topic: { topic [- 8 :]} ... message: { message [:8 ]} ..." )
294
+ if log_enabled (logging .DEBUG ):
295
+ logging .debug (f"mqtt topic: { topic [- 8 :]} ... message: { message [:8 ]} ..." )
284
296
self .senmlpack .clear ()
285
297
for record in self .records .values ():
286
298
# If the object is uninitialized, updates are always allowed even if it's a read-only
@@ -307,18 +319,22 @@ async def discovery_task(self, interval=0.100):
307
319
lastval_record .add_to_pack (self .senmlpack )
308
320
self .mqtt .subscribe (self .create_topic ("shadow" , "i" ), qos = 1 )
309
321
self .mqtt .publish (self .create_topic ("shadow" , "o" ), self .senmlpack .to_cbor (), qos = 1 )
310
- logging .info ("Device configured via discovery protocol." )
322
+
323
+ if log_enabled (logging .INFO ):
324
+ logging .info ("Device configured via discovery protocol." )
311
325
await asyncio .sleep (interval )
312
326
raise DoneException ()
313
327
314
328
async def conn_task (self , interval = 1.0 , backoff = 1.2 ):
315
- logging .info ("Connecting to Arduino IoT cloud..." )
329
+ if log_enabled (logging .INFO ):
330
+ logging .info ("Connecting to Arduino IoT cloud..." )
316
331
while True :
317
332
try :
318
333
self .mqtt .connect ()
319
334
break
320
335
except Exception as e :
321
- logging .warning (f"Connection failed { e } , retrying after { interval } s" )
336
+ if log_enabled (logging .WARNING ):
337
+ logging .warning (f"Connection failed { e } , retrying after { interval } s" )
322
338
await asyncio .sleep (interval )
323
339
interval = min (interval * backoff , 4.0 )
324
340
@@ -338,15 +354,17 @@ async def mqtt_task(self, interval=0.100):
338
354
if record .updated :
339
355
record .add_to_pack (self .senmlpack , push = True )
340
356
if len (self .senmlpack ._data ):
341
- logging .debug ("Pushing records to Arduino IoT cloud:" )
342
- for record in self .senmlpack ._data :
343
- logging .debug (f" ==> record: { record .name } value: { str (record .value )[:48 ]} ..." )
357
+ if log_enabled (logging .DEBUG ):
358
+ logging .debug ("Pushing records to Arduino IoT cloud:" )
359
+ for record in self .senmlpack ._data :
360
+ logging .debug (f" ==> record: { record .name } value: { str (record .value )[:48 ]} ..." )
344
361
self .mqtt .publish (self .topic_out , self .senmlpack .to_cbor (), qos = 1 )
345
362
self .last_ping = timestamp ()
346
363
elif self .keepalive and (timestamp () - self .last_ping ) > self .keepalive :
347
364
self .mqtt .ping ()
348
365
self .last_ping = timestamp ()
349
- logging .debug ("No records to push, sent a ping request." )
366
+ if log_enabled (logging .DEBUG ):
367
+ logging .debug ("No records to push, sent a ping request." )
350
368
await asyncio .sleep (interval )
351
369
raise DoneException ()
352
370
@@ -375,9 +393,9 @@ async def run(self):
375
393
if task .done ():
376
394
self .tasks .pop (name )
377
395
self .records .pop (name , None )
378
- if isinstance (task_except , DoneException ):
396
+ if isinstance (task_except , DoneException ) and log_enabled ( logging . INFO ) :
379
397
logging .info (f"task: { name } complete." )
380
- elif task_except is not None :
398
+ elif task_except is not None and log_enabled ( logging . ERROR ) :
381
399
logging .error (f"task: { name } raised exception: { str (task_except )} ." )
382
400
if name == "mqtt_task" :
383
401
self .create_task ("conn_task" , self .conn_task )
0 commit comments