/ examples / gc_iot_core_simpletest.py
gc_iot_core_simpletest.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  from adafruit_gc_iot_core import Cloud_Core, MQTT_API
 12  
 13  ### WiFi ###
 14  
 15  # Get wifi details and more from a secrets.py file
 16  try:
 17      from secrets import secrets
 18  except ImportError:
 19      print("WiFi secrets are kept in secrets.py, please add them there!")
 20      raise
 21  
 22  # If you are using a board with pre-defined ESP32 Pins:
 23  esp32_cs = DigitalInOut(board.ESP_CS)
 24  esp32_ready = DigitalInOut(board.ESP_BUSY)
 25  esp32_reset = DigitalInOut(board.ESP_RESET)
 26  
 27  # If you have an externally connected ESP32:
 28  # esp32_cs = DigitalInOut(board.D9)
 29  # esp32_ready = DigitalInOut(board.D10)
 30  # esp32_reset = DigitalInOut(board.D5)
 31  
 32  spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
 33  esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
 34  """Use below for Most Boards"""
 35  status_light = neopixel.NeoPixel(
 36      board.NEOPIXEL, 1, brightness=0.2
 37  )  # Uncomment for Most Boards
 38  """Uncomment below for ItsyBitsy M4"""
 39  # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
 40  # Uncomment below for an externally defined RGB LED
 41  # import adafruit_rgbled
 42  # from adafruit_esp32spi import PWMOut
 43  # RED_LED = PWMOut.PWMOut(esp, 26)
 44  # GREEN_LED = PWMOut.PWMOut(esp, 27)
 45  # BLUE_LED = PWMOut.PWMOut(esp, 25)
 46  # status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
 47  wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
 48  
 49  ### Code ###
 50  
 51  # Define callback methods which are called when events occur
 52  # pylint: disable=unused-argument, redefined-outer-name
 53  def connect(client, userdata, flags, rc):
 54      # This function will be called when the client is connected
 55      # successfully to the broker.
 56      print("Connected to MQTT Broker!")
 57      print("Flags: {0}\n RC: {1}".format(flags, rc))
 58      # Subscribes to commands/# topic
 59      google_mqtt.subscribe_to_all_commands()
 60  
 61      # Publish to the default "events" topic
 62      google_mqtt.publish("testing", "events", qos=1)
 63  
 64  
 65  def disconnect(client, userdata, rc):
 66      # This method is called when the client disconnects
 67      # from the broker.
 68      print("Disconnected from MQTT Broker!")
 69  
 70  
 71  def subscribe(client, userdata, topic, granted_qos):
 72      # This method is called when the client subscribes to a new topic.
 73      print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))
 74  
 75  
 76  def unsubscribe(client, userdata, topic, pid):
 77      # This method is called when the client unsubscribes from a topic.
 78      print("Unsubscribed from {0} with PID {1}".format(topic, pid))
 79  
 80  
 81  def publish(client, userdata, topic, pid):
 82      # This method is called when the client publishes data to a topic.
 83      print("Published to {0} with PID {1}".format(topic, pid))
 84  
 85  
 86  def message(client, topic, msg):
 87      # This method is called when the client receives data from a topic.
 88      print("Message from {}: {}".format(topic, msg))
 89  
 90  
 91  # Connect to WiFi
 92  print("Connecting to WiFi...")
 93  wifi.connect()
 94  print("Connected!")
 95  
 96  # Initialize MQTT interface with the esp interface
 97  MQTT.set_socket(socket, esp)
 98  
 99  # Initialize Google Cloud IoT Core interface
100  google_iot = Cloud_Core(esp, secrets)
101  
102  # Optional JSON-Web-Token (JWT) Generation
103  # print("Generating JWT...")
104  # jwt = google_iot.generate_jwt()
105  # print("Your JWT is: ", jwt)
106  
107  # Set up a new MiniMQTT Client
108  client = MQTT.MQTT(
109      broker=google_iot.broker,
110      username=google_iot.username,
111      password=secrets["jwt"],
112      client_id=google_iot.cid,
113  )
114  
115  # Initialize Google MQTT API Client
116  google_mqtt = MQTT_API(client)
117  
118  # Connect callback handlers to Google MQTT Client
119  google_mqtt.on_connect = connect
120  google_mqtt.on_disconnect = disconnect
121  google_mqtt.on_subscribe = subscribe
122  google_mqtt.on_unsubscribe = unsubscribe
123  google_mqtt.on_publish = publish
124  google_mqtt.on_message = message
125  
126  print("Attempting to connect to %s" % client.broker)
127  google_mqtt.connect()
128  
129  # Pump the message loop forever, all events are
130  # handled in their callback handlers
131  # while True:
132  #    google_mqtt.loop()
133  
134  # Start a blocking message loop...
135  # NOTE: NO code below this loop will execute
136  # NOTE: Network reconnection is handled within this loop
137  while True:
138      try:
139          google_mqtt.loop()
140      except (ValueError, RuntimeError) as e:
141          print("Failed to get data, retrying\n", e)
142          wifi.reset()
143          google_mqtt.reconnect()
144          continue
145      time.sleep(1)