/ examples / azureiot_hub_simpletest.py
azureiot_hub_simpletest.py
  1  import json
  2  import random
  3  import time
  4  import board
  5  import busio
  6  from digitalio import DigitalInOut
  7  import neopixel
  8  from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
  9  import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 10  from adafruit_ntp import NTP
 11  
 12  # Get wifi details and more from a secrets.py file
 13  try:
 14      from secrets import secrets
 15  except ImportError:
 16      print("WiFi secrets are kept in secrets.py, please add them there!")
 17      raise
 18  
 19  # ESP32 Setup
 20  try:
 21      esp32_cs = DigitalInOut(board.ESP_CS)
 22      esp32_ready = DigitalInOut(board.ESP_BUSY)
 23      esp32_reset = DigitalInOut(board.ESP_RESET)
 24  except AttributeError:
 25      esp32_cs = DigitalInOut(board.D13)
 26      esp32_ready = DigitalInOut(board.D11)
 27      esp32_reset = DigitalInOut(board.D12)
 28  
 29  spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 30  esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 31  
 32  """Use below for Most Boards"""
 33  status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)  # Uncomment for Most Boards
 34  """Uncomment below for ItsyBitsy M4"""
 35  # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 36  # Uncomment below for an externally defined RGB LED
 37  # import adafruit_rgbled
 38  # from adafruit_esp32spi import PWMOut
 39  # RED_LED = PWMOut.PWMOut(esp, 26)
 40  # GREEN_LED = PWMOut.PWMOut(esp, 27)
 41  # BLUE_LED = PWMOut.PWMOut(esp, 25)
 42  # status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 43  wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 44  
 45  print("Connecting to WiFi...")
 46  
 47  wifi.connect()
 48  
 49  print("Connected to WiFi!")
 50  
 51  print("Getting the time...")
 52  
 53  ntp = NTP(esp)
 54  # Wait for a valid time to be received
 55  while not ntp.valid_time:
 56      time.sleep(5)
 57      ntp.set_time()
 58  
 59  print("Time:", str(time.time()))
 60  
 61  # You will need an Azure subscription to create an Azure IoT Hub resource
 62  #
 63  # If you don't have an Azure subscription:
 64  #
 65  # If you are a student, head to https://aka.ms/FreeStudentAzure and sign up, validating with your
 66  #  student email address. This will give you $100 of Azure credit and free tiers of a load of
 67  #  service, renewable each year you are a student
 68  #
 69  # If you are not a student, head to https://aka.ms/FreeAz and sign up to get $200 of credit for 30
 70  #  days, as well as free tiers of a load of services
 71  #
 72  # Create an Azure IoT Hub and an IoT device in the Azure portal here: https://aka.ms/AzurePortalHome.
 73  # Instructions to create an IoT Hub and device are here: https://aka.ms/CreateIoTHub
 74  #
 75  # The free tier of IoT Hub allows up to 8,000 messages a day, so try not to send messages too often
 76  # if you are using the free tier
 77  #
 78  # Once you have a hub and a device, copy the device primary connection string.
 79  # Add it to the secrets.py file in an entry called device_connection_string
 80  #
 81  # The adafruit-circuitpython-azureiot library depends on the following libraries:
 82  #
 83  # From the Adafruit CircuitPython Bundle (https://github.com/adafruit/Adafruit_CircuitPython_Bundle):
 84  # * adafruit-circuitpython-minimqtt
 85  # * adafruit-circuitpython-requests
 86  from adafruit_azureiot import IoTHubDevice
 87  
 88  # Create an IoT Hub device client and connect
 89  device = IoTHubDevice(socket, esp, secrets["device_connection_string"])
 90  
 91  print("Connecting to Azure IoT Hub...")
 92  
 93  # Connect to IoT Central
 94  device.connect()
 95  
 96  print("Connected to Azure IoT Hub!")
 97  
 98  message_counter = 60
 99  
100  while True:
101      try:
102          # Send a device to cloud message every minute
103          # You can see the overview of messages sent from the device in the Overview tab
104          # of the IoT Hub in the Azure Portal
105          if message_counter >= 60:
106              message = {"Temperature": random.randint(0, 50)}
107              device.send_device_to_cloud_message(json.dumps(message))
108              message_counter = 0
109          else:
110              message_counter = message_counter + 1
111  
112          # Poll every second for messages from the cloud
113          device.loop()
114      except (ValueError, RuntimeError) as e:
115          print("Connection error, reconnecting\n", str(e))
116          # If we lose connectivity, reset the wifi and reconnect
117          wifi.reset()
118          wifi.connect()
119          device.reconnect()
120          continue
121  
122      time.sleep(1)