MQTT: Retrieving message on connect

CircuitPython on hardware including Adafruit's boards, and CircuitPython libraries using Blinka on host computers.

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
naunca
 
Posts: 11
Joined: Tue May 08, 2018 2:55 am

MQTT: Retrieving message on connect

Post by naunca »

I have a raspberry pi Pico W that is running the latest version of circuitpython. I created an adafruit.io feed that contains a value of either 0 or 1. I would like to connect to the adafruit MQTT broker and retrieve the most recent value contained within this feed as an initial condition for the device. I cannot find the necessary command in the API. I have managed to subscribe to the feed and can alter the state of an LED on my device by changing the value.

This is awkward but easily doable using my arduino/C++ setup but I can't find a relevant example for circuitpython. It seems like basic functionality for using switches in the dashboard. Any suggestions?

Current Code:

Code: Select all

# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import board
import digitalio
import ssl
import socketpool
import wifi
import time
import adafruit_minimqtt.adafruit_minimqtt as MQTT

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
# source control.
# pylint: disable=no-name-in-module,wrong-import-order
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

print("Connecting to %s" % secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!" % secrets["ssid"])

### Topic Setup ###

# Adafruit IO-style Topic
# Use this topic if you'd like to connect to io.adafruit.com
mqtt_topic = secrets["aio_username"] + '/feeds/gurple'

### Code ###
# Define callback methods which are called when events occur
# pylint: disable=unused-argument, redefined-outer-name
def connect(mqtt_client, userdata, flags, rc):
    # This function will be called when the mqtt_client is connected
    # successfully to the broker.
    print("Connected to MQTT Broker!")
    print("Flags: {0}\n RC: {1}".format(flags, rc))


def disconnect(mqtt_client, userdata, rc):
    # This method is called when the mqtt_client disconnects
    # from the broker.
    print("Disconnected from MQTT Broker!")


def subscribe(mqtt_client, userdata, topic, granted_qos):
    # This method is called when the mqtt_client subscribes to a new feed.
    print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))


def unsubscribe(mqtt_client, userdata, topic, pid):
    # This method is called when the mqtt_client unsubscribes from a feed.
    print("Unsubscribed from {0} with PID {1}".format(topic, pid))


def publish(mqtt_client, userdata, topic, pid):
    # This method is called when the mqtt_client publishes data to a feed.
    print("Published to {0} with PID {1}".format(topic, pid))

def message(client, topic, message):
    # Method called when a client's subscribed feed has a new value.
    print("New message on topic {0}: {1}".format(topic, message))
    print(message)
    if message == '1':
        led.value = True
        print("led on")
    if message == '0':
        led.value = False
        print("led off")

# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)

# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(
    broker=secrets["broker"],
    port=secrets["port"],
    username=secrets["aio_username"],
    password=secrets["aio_key"],
    socket_pool=pool,
    ssl_context=ssl.create_default_context(),
)

# Connect callback handlers to mqtt_client
mqtt_client.on_connect = connect
mqtt_client.on_disconnect = disconnect
mqtt_client.on_subscribe = subscribe
mqtt_client.on_unsubscribe = unsubscribe
mqtt_client.on_publish = publish
mqtt_client.on_message = message

print("Attempting to connect to %s" % mqtt_client.broker)
mqtt_client.connect()

print("Subscribing to %s" % mqtt_topic)
mqtt_client.subscribe(mqtt_topic)

# print("Publishing to %s" % mqtt_topic)
# mqtt_client.publish(mqtt_topic, "Hello Broker!")

while True:
    try:
        mqtt_client.loop()
    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying\n", e)
        wifi.reset()
        mqtt_client.reconnect()
        continue
    time.sleep(1)



User avatar
Hexen_Wulf
 
Posts: 27
Joined: Tue Aug 02, 2022 9:49 am

Re: MQTT: Retrieving message on connect

Post by Hexen_Wulf »

I'm not sure if I've misunderstood you, but I found this section on Read The Docs:
Receive Data
You can get the last inserted value by using the receive(feed) method.

# Import library and create instance of REST client.
from Adafruit_IO import Client
aio = Client('YOUR ADAFRUIT IO USERNAME', 'YOUR ADAFRUIT IO KEY')

# Get the last value of the temperature feed.
data = aio.receive('Test')

# Print the value and a message if it's over 100. Notice that the value is
# converted from string to int because it always comes back as a string from IO.
temp = int(data.value)
print('Temperature: {0}'.format(temp))
if temp > 100:
print 'Hot enough for you?'
data = aio.receive('FEEDNAME') would assign the last value uploaded to the feed to the data variable.

User avatar
naunca
 
Posts: 11
Joined: Tue May 08, 2018 2:55 am

Re: MQTT: Retrieving message on connect

Post by naunca »

Thanks for the recommendation, I tried importing that library and it appears to be a Python library and not included in the adafruit circuitpython set. I'll keep plugging at this.

User avatar
vladak
 
Posts: 91
Joined: Thu Jan 06, 2022 7:05 pm

Re: MQTT: Retrieving message on connect

Post by vladak »

The Adafruit IO library is part of the Adafruit CircuitPython Bundle. It can be easily installed via https://github.com/adafruit/circup/.

Locked
Please be positive and constructive with your questions and comments.

Return to “Adafruit CircuitPython”