Skip to content

Commit

Permalink
Merge pull request #9 from brentru/update-minimqtt
Browse files Browse the repository at this point in the history
Update for minimqtt PR
  • Loading branch information
brentru authored Mar 17, 2020
2 parents 8702e0e + 0032b09 commit 7e1ab12
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
10 changes: 9 additions & 1 deletion adafruit_gc_iot_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,14 @@ def disconnect(self):
# De-initialize MiniMQTT Client
self._client.deinit()

def reconnect(self):
"""Reconnects to the Google MQTT Broker.
"""
try:
self._client.reconnect()
except:
raise MQTT_API_ERROR("Error reconnecting to Google MQTT.")

def connect(self):
"""Connects to the Google MQTT Broker.
"""
Expand Down Expand Up @@ -331,7 +339,7 @@ def __init__(self, esp, secrets, log=False):
self._reg_id = secrets["registry_id"]
self._device_id = secrets["device_id"]
self._private_key = secrets["private_key"]
self.broker = "mqtt.googleapis.com"
self.broker = "https://mqtt.googleapis.com"
self.username = b"unused"
self.cid = self.client_id

Expand Down
32 changes: 21 additions & 11 deletions examples/gc_iot_core_simpletest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import time
import board
import busio
from digitalio import DigitalInOut
Expand All @@ -6,7 +7,7 @@
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_minimqtt import MQTT
import adafruit_minimqtt as MQTT
from adafruit_gc_iot_core import Cloud_Core, MQTT_API

### WiFi ###
Expand Down Expand Up @@ -92,6 +93,9 @@ def message(client, topic, msg):
wifi.connect()
print("Connected!")

# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)

# Initialize Google Cloud IoT Core interface
google_iot = Cloud_Core(esp, secrets)

Expand All @@ -101,14 +105,10 @@ def message(client, topic, msg):
# print("Your JWT is: ", jwt)

# Set up a new MiniMQTT Client
client = MQTT(
socket,
broker=google_iot.broker,
username=google_iot.username,
password=secrets["jwt"],
client_id=google_iot.cid,
network_manager=wifi,
)
client = MQTT.MQTT(broker=google_iot.broker,
username=google_iot.username,
password=secrets["jwt"],
client_id=google_iot.cid)

# Initialize Google MQTT API Client
google_mqtt = MQTT_API(client)
Expand All @@ -129,5 +129,15 @@ def message(client, topic, msg):
# while True:
# google_mqtt.loop()

# Attempt to loop forever and handle network disconnection
google_mqtt.loop_blocking()
# Start a blocking message loop...
# NOTE: NO code below this loop will execute
# NOTE: Network reconnection is handled within this loop
while True:
try:
google_mqtt.loop()
except (ValueError, RuntimeError) as e:
print("Failed to get data, retrying\n", e)
wifi.reset()
google_mqtt.reconnect()
continue
time.sleep(1)

0 comments on commit 7e1ab12

Please sign in to comment.