/ examples / adafruit_io_mqtt / adafruit_io_time.py
adafruit_io_time.py
  1  # Adafruit IO provides some built-in MQTT topics
  2  # for obtaining the current server time, if you don't have
  3  # access to a RTC module.
  4  import time
  5  import board
  6  import busio
  7  from digitalio import DigitalInOut
  8  from adafruit_esp32spi import adafruit_esp32spi
  9  from adafruit_esp32spi import adafruit_esp32spi_wifimanager
 10  import adafruit_esp32spi.adafruit_esp32spi_socket as socket
 11  import neopixel
 12  
 13  import adafruit_minimqtt.adafruit_minimqtt as MQTT
 14  from adafruit_io.adafruit_io import IO_MQTT
 15  
 16  ### WiFi ###
 17  
 18  # Get wifi details and more from a secrets.py file
 19  try:
 20      from secrets import secrets
 21  except ImportError:
 22      print("WiFi secrets are kept in secrets.py, please add them there!")
 23      raise
 24  
 25  # If you are using a board with pre-defined ESP32 Pins:
 26  esp32_cs = DigitalInOut(board.ESP_CS)
 27  esp32_ready = DigitalInOut(board.ESP_BUSY)
 28  esp32_reset = DigitalInOut(board.ESP_RESET)
 29  
 30  # If you have an externally connected ESP32:
 31  # esp32_cs = DigitalInOut(board.D9)
 32  # esp32_ready = DigitalInOut(board.D10)
 33  # esp32_reset = DigitalInOut(board.D5)
 34  
 35  spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 36  esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 37  """Use below for Most Boards"""
 38  status_light = neopixel.NeoPixel(
 39      board.NEOPIXEL, 1, brightness=0.2
 40  )  # Uncomment for Most Boards
 41  """Uncomment below for ItsyBitsy M4"""
 42  # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 43  # Uncomment below for an externally defined RGB LED
 44  # import adafruit_rgbled
 45  # from adafruit_esp32spi import PWMOut
 46  # RED_LED = PWMOut.PWMOut(esp, 26)
 47  # GREEN_LED = PWMOut.PWMOut(esp, 27)
 48  # BLUE_LED = PWMOut.PWMOut(esp, 25)
 49  # status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 50  wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 51  
 52  # Define callback functions which will be called when certain events happen.
 53  # pylint: disable=unused-argument
 54  def connected(client):
 55      # Connected function will be called when the client is connected to Adafruit IO.
 56      # This is a good place to subscribe to feed changes.  The client parameter
 57      # passed to this function is the Adafruit IO MQTT client so you can make
 58      # calls against it easily.
 59      print("Connected to Adafruit IO!")
 60  
 61      # Subscribe to time/seconds topic
 62      # https://io.adafruit.com/api/docs/mqtt.html#time-seconds
 63      io.subscribe_to_time("seconds")
 64  
 65      # Subscribe to time/millis topic
 66      # https://io.adafruit.com/api/docs/mqtt.html#time-millis
 67      io.subscribe_to_time("millis")
 68  
 69      # Subscribe to time/ISO-8601 topic
 70      # https://io.adafruit.com/api/docs/mqtt.html#time-iso-8601
 71      io.subscribe_to_time("iso")
 72  
 73      # Subscribe to time/hours topic
 74      # NOTE: This topic only publishes once every hour.
 75      # https://io.adafruit.com/api/docs/mqtt.html#adafruit-io-monitor
 76      io.subscribe_to_time("hours")
 77  
 78  
 79  # pylint: disable=unused-argument
 80  def disconnected(client):
 81      # Disconnected function will be called when the client disconnects.
 82      print("Disconnected from Adafruit IO!")
 83  
 84  
 85  # pylint: disable=unused-argument
 86  def message(client, feed_id, payload):
 87      # Message function will be called when a subscribed feed has a new value.
 88      # The feed_id parameter identifies the feed, and the payload parameter has
 89      # the new value.
 90      print("Feed {0} received new value: {1}".format(feed_id, payload))
 91  
 92  
 93  # Connect to WiFi
 94  print("Connecting to WiFi...")
 95  wifi.connect()
 96  print("Connected!")
 97  
 98  # Initialize MQTT interface with the esp interface
 99  MQTT.set_socket(socket, esp)
100  
101  # Initialize a new MQTT Client object
102  mqtt_client = MQTT.MQTT(
103      broker="io.adafruit.com", username=secrets["aio_user"], password=secrets["aio_key"],
104  )
105  
106  # Initialize an Adafruit IO MQTT Client
107  io = IO_MQTT(mqtt_client)
108  
109  # Connect the callback methods defined above to Adafruit IO
110  io.on_connect = connected
111  io.on_disconnect = disconnected
112  io.on_message = message
113  
114  # Connect to Adafruit IO
115  io.connect()
116  
117  
118  # Start a blocking message loop...
119  # NOTE: NO code below this loop will execute
120  # NOTE: Network reconnection is handled within this loop
121  while True:
122      try:
123          io.loop()
124      except (ValueError, RuntimeError) as e:
125          print("Failed to get data, retrying\n", e)
126          wifi.reset()
127          io.reconnect()
128          continue
129      time.sleep(1)