code.py
 1  # SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
 2  # SPDX-License-Identifier: MIT
 3  
 4  import time
 5  import os
 6  import json
 7  import busio
 8  import microcontroller
 9  import board
10  import rtc
11  import socketpool
12  import wifi
13  import adafruit_ntp
14  import adafruit_ahtx0
15  from adafruit_azureiot import IoTCentralDevice
16  
17  #  use Pico W's GP0 for SDA and GP1 for SCL
18  i2c = busio.I2C(board.GP1, board.GP0)
19  aht20 = adafruit_ahtx0.AHTx0(i2c)
20  
21  print("Connecting to WiFi...")
22  wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))
23  
24  print("Connected to WiFi!")
25  
26  #  ntp clock
27  pool = socketpool.SocketPool(wifi.radio)
28  ntp = adafruit_ntp.NTP(pool)
29  rtc.RTC().datetime = ntp.datetime
30  
31  if time.localtime().tm_year < 2022:
32      print("Setting System Time in UTC")
33      rtc.RTC().datetime = ntp.datetime
34  
35  else:
36      print("Year seems good, skipping set time.")
37  
38  # Create an IoT Hub device client and connect
39  esp = None
40  pool = socketpool.SocketPool(wifi.radio)
41  device = IoTCentralDevice(
42      pool, esp, os.getenv('id_scope'), os.getenv('device_id'), os.getenv('device_primary_key')
43  )
44  
45  print("Connecting to Azure IoT Central...")
46  
47  device.connect()
48  
49  print("Connected to Azure IoT Central!")
50  
51  #  clock to count down to sending data to Azure
52  azure_clock = 500
53  
54  while True:
55      try:
56  		#  when the azure clock runs out
57          if azure_clock > 500:
58  			#  pack message
59              message = {"Temperature": aht20.temperature,
60                         "Humidity": aht20.relative_humidity}
61              print("sending json")
62              device.send_telemetry(json.dumps(message))
63              print("data sent")
64  			#  reset azure clock
65              azure_clock = 0
66          else:
67              azure_clock += 1
68  		#  ping azure
69          device.loop()
70  	#  if something disrupts the loop, reconnect
71      # pylint: disable=broad-except
72      #  any errors, reset Pico W
73      except Exception as e:
74          print("Error:\n", str(e))
75          print("Resetting microcontroller in 10 seconds")
76          time.sleep(10)
77          microcontroller.reset()
78  	#  delay
79      time.sleep(1)
80      print(azure_clock)