/ examples / minimqtt_pub_sub_blocking_topic_callbacks.py
minimqtt_pub_sub_blocking_topic_callbacks.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
  7  from adafruit_esp32spi import adafruit_esp32spi_wifimanager
  8  import adafruit_esp32spi.adafruit_esp32spi_socket as socket
  9  
 10  import adafruit_minimqtt.adafruit_minimqtt as MQTT
 11  
 12  ### WiFi ###
 13  
 14  # Get wifi details and more from a secrets.py file
 15  try:
 16      from secrets import secrets
 17  except ImportError:
 18      print("WiFi secrets are kept in secrets.py, please add them there!")
 19      raise
 20  
 21  # If you are using a board with pre-defined ESP32 Pins:
 22  esp32_cs = DigitalInOut(board.ESP_CS)
 23  esp32_ready = DigitalInOut(board.ESP_BUSY)
 24  esp32_reset = DigitalInOut(board.ESP_RESET)
 25  
 26  # If you have an externally connected ESP32:
 27  # esp32_cs = DigitalInOut(board.D9)
 28  # esp32_ready = DigitalInOut(board.D10)
 29  # esp32_reset = DigitalInOut(board.D5)
 30  
 31  spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 32  esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 33  """Use below for Most Boards"""
 34  status_light = neopixel.NeoPixel(
 35      board.NEOPIXEL, 1, brightness=0.2
 36  )  # Uncomment for Most Boards
 37  """Uncomment below for ItsyBitsy M4"""
 38  # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 39  # Uncomment below for an externally defined RGB LED
 40  # import adafruit_rgbled
 41  # from adafruit_esp32spi import PWMOut
 42  # RED_LED = PWMOut.PWMOut(esp, 26)
 43  # GREEN_LED = PWMOut.PWMOut(esp, 27)
 44  # BLUE_LED = PWMOut.PWMOut(esp, 25)
 45  # status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 46  wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 47  
 48  ### Code ###
 49  
 50  # Define callback methods which are called when events occur
 51  # pylint: disable=unused-argument, redefined-outer-name
 52  def connected(client, userdata, flags, rc):
 53      # This function will be called when the client is connected
 54      # successfully to the broker.
 55      print("Connected to MQTT Broker!")
 56  
 57  
 58  def disconnected(client, userdata, rc):
 59      # This method is called when the client is disconnected
 60      print("Disconnected from MQTT Broker!")
 61  
 62  
 63  def subscribe(client, userdata, topic, granted_qos):
 64      # This method is called when the client subscribes to a new feed.
 65      print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
 66  
 67  
 68  def unsubscribe(client, userdata, topic, pid):
 69      # This method is called when the client unsubscribes from a feed.
 70      print("Unsubscribed from {0} with PID {1}".format(topic, pid))
 71  
 72  
 73  def on_battery_msg(client, topic, message):
 74      # Method called when device/batteryLife has a new value
 75      print("Battery level: {}v".format(message))
 76  
 77      # client.remove_topic_callback("device/batteryLevel")
 78  
 79  
 80  def on_message(client, topic, message):
 81      # Method callled when a client's subscribed feed has a new value.
 82      print("New message on topic {0}: {1}".format(topic, message))
 83  
 84  
 85  # Connect to WiFi
 86  print("Connecting to WiFi...")
 87  wifi.connect()
 88  print("Connected!")
 89  
 90  MQTT.set_socket(socket, esp)
 91  
 92  # Set up a MiniMQTT Client
 93  client = MQTT.MQTT(broker=secrets["broker"], port=secrets["broker_port"])
 94  
 95  # Setup the callback methods above
 96  client.on_connect = connected
 97  client.on_disconnect = disconnected
 98  client.on_subscribe = subscribe
 99  client.on_unsubscribe = unsubscribe
100  client.on_message = on_message
101  client.add_topic_callback("device/batteryLevel", on_battery_msg)
102  
103  # Connect the client to the MQTT broker.
104  print("Connecting to MQTT broker...")
105  client.connect()
106  
107  # Subscribe to all notifications on the device/ topic
108  client.subscribe("device/#", 1)
109  
110  # Start a blocking message loop...
111  # NOTE: NO code below this loop will execute
112  while True:
113      try:
114          client.loop()
115      except (ValueError, RuntimeError) as e:
116          print("Failed to get data, retrying\n", e)
117          wifi.reset()
118          client.reconnect()
119          continue
120      time.sleep(1)