code.py
1 # SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries 2 # SPDX-License-Identifier: MIT 3 4 import time 5 import json 6 import digitalio 7 import supervisor 8 import board 9 import rtc 10 import socketpool 11 import wifi 12 import adafruit_ntp 13 from adafruit_azureiot import IoTHubDevice 14 import adafruit_scd4x 15 16 # Get wifi details and more from a secrets.py file 17 try: 18 from secrets import secrets 19 except ImportError: 20 print("WiFi secrets are kept in secrets.py, please add them there!") 21 raise 22 23 print("Connecting to WiFi...") 24 wifi.radio.connect(secrets["ssid"], secrets["password"]) 25 26 print("Connected to WiFi!") 27 28 # ntp clock - update tz_offset to your timezone 29 pool = socketpool.SocketPool(wifi.radio) 30 ntp = adafruit_ntp.NTP(pool, tz_offset=0) 31 rtc.RTC().datetime = ntp.datetime 32 33 if time.localtime().tm_year < 2022: 34 print("Setting System Time in UTC") 35 rtc.RTC().datetime = ntp.datetime 36 37 else: 38 print("Year seems good, skipping set time.") 39 40 esp = None 41 pool = socketpool.SocketPool(wifi.radio) 42 # Create an IoT Hub device client and connect 43 device = IoTHubDevice(pool, esp, secrets["device_connection_string"]) 44 45 print("Connecting to Azure IoT Hub...") 46 47 # Connect to IoT Central 48 device.connect() 49 50 print("Connected to Azure IoT Hub!") 51 52 # setup for I2C 53 i2c = board.STEMMA_I2C() 54 # setup for SCD40 55 scd4x = adafruit_scd4x.SCD4X(i2c) 56 57 # start measuring co2 with SCD40 58 scd4x.start_periodic_measurement() 59 co2 = scd4x.CO2 60 61 # setup boot button as input 62 button = digitalio.DigitalInOut(board.BUTTON) 63 button.switch_to_input(pull=digitalio.Pull.UP) 64 65 # clock to count down to sending data to Azure 66 azure_clock = 500 67 68 # button debounce state 69 button_pressed = False 70 71 while True: 72 try: 73 # button debouncing 74 if button.value and button_pressed: 75 button_pressed = False 76 # if you press boot 77 if not button.value and not button_pressed: 78 # pack message 79 message = {"CO2": co2, 80 "QT Connected": 1} 81 # send co2 measurement 82 device.send_device_to_cloud_message(json.dumps(message)) 83 # measure co2 84 co2 = scd4x.CO2 85 # when the azure clock runs out 86 if azure_clock > 500: 87 print("getting msg") 88 # pack message 89 message = {"CO2": co2, 90 "QT Connected": 1} 91 print("sending json") 92 device.send_device_to_cloud_message(json.dumps(message)) 93 print("data sent") 94 # reset azure clock 95 azure_clock = 0 96 # if no clocks are running out 97 # increase counts by 1 98 else: 99 azure_clock += 1 100 # ping azure 101 device.loop() 102 # if something disrupts the loop, reconnect 103 # pylint: disable=broad-except 104 except (ValueError, RuntimeError, OSError, ConnectionError) as e: 105 print("Network error, reconnecting\n", str(e)) 106 time.sleep(10) 107 supervisor.reload() 108 continue 109 # delay 110 time.sleep(1)