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