Skip to content

Example for using miniMQTT with the PyPortal #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 31, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions examples/minimqtt_pub_sub_pyportal
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import time
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_minimqtt import MQTT
import adafruit_pyportal

pyportal = adafruit_pyportal.PyPortal()

### WiFi ###

# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise

wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(pyportal._esp,
secrets, None)

# ------------- MQTT Topic Setup ------------- #
mqtt_topic = 'test/topic'

### Code ###
# Define callback methods which are called when events occur
# pylint: disable=unused-argument, redefined-outer-name
def connected(client, userdata, flags, rc):
# This function will be called when the client is connected
# successfully to the broker.
print('Subscribing to %s' % (mqtt_topic))
client.subscribe(mqtt_topic)

def disconnected(client, userdata, rc):
# This method is called when the client is disconnected
print('Disconnected from MQTT Broker!')

def message(client, topic, message):
"""Method callled when a client's subscribed feed has a new
value.
:param str topic: The topic of the feed with a new value.
:param str message: The new value
"""
print('New message on topic {0}: {1}'.format(topic, message))

# Connect to WiFi
wifi.connect()

# Set up a MiniMQTT Client
mqtt_client = MQTT(socket,
broker=secrets['broker'],
username=secrets['user'],
password=secrets['pass'],
is_ssl=False,
network_manager=wifi)

# Setup the callback methods above
mqtt_client.on_connect = connected
mqtt_client.on_disconnect = disconnected
mqtt_client.on_message = message

# Connect the client to the MQTT broker.
mqtt_client.connect()

photocell_val = 0
while True:
# Poll the message queue
mqtt_client.loop()

# Send a new message
print('Sending photocell value: %d' % photocell_val)
mqtt_client.publish(mqtt_topic, photocell_val)
photocell_val += 1
time.sleep(1)