MQTT Setup on MATRIX PORTAL

Moderators: adafruit_support_bill, adafruit

Forum rules
If you're posting code, please make sure your code does not include your Adafruit IO Active Key or WiFi network credentials.
Locked
User avatar
Auto101
 
Posts: 20
Joined: Wed Jun 03, 2020 5:50 pm

MQTT Setup on MATRIX PORTAL

Post by Auto101 »

Hi
I am trying to setup MQTT on matrix portal and receiving below error for ssl .

code.py output:
Traceback (most recent call last):
File "code.py", line 4, in <module>
ImportError: no module named 'ssl'

Circuit Python Ver :6.3
I have also update the the ESP firmware to NINA_W102-1.7.4 but no luck .

--Code

Code: Select all

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

import ssl
import socketpool
import wifi
import adafruit_minimqtt.adafruit_minimqtt as MQTT

# 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 ###

# MQTT Topic
# Use this topic if you'd like to connect to a standard MQTT broker
mqtt_topic = "test/topic"

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

### 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 callled when a client's subscribed feed has a new value.
    print("New message on topic {0}: {1}".format(topic, message))


# 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!")

print("Unsubscribing from %s" % mqtt_topic)
mqtt_client.unsubscribe(mqtt_topic)

print("Disconnecting from %s" % mqtt_client.broker)
mqtt_client.disconnect()
Last edited by adafruit_support_carter on Tue Aug 31, 2021 1:57 pm, edited 1 time in total.
Reason: added [code] tags

User avatar
jerryn
 
Posts: 1868
Joined: Sat Sep 14, 2013 9:05 am

Re: MQTT Setup on MATRIX PORTAL

Post by jerryn »

The code you are using is not for the matrix-portal -- it is for an esp32s2 (or something with native wifi).
The Matrrix portals is like the pyportal and uses the add-on esp32 "airlift" coprocessor
Take a look at the examples here https://learn.adafruit.com/mqtt-in-circ ... wifi-usage
for the "airlift" -- school down a ways in the page.

I hope that helps.
Note: I don't represent Adafruit. Just trying to help.

User avatar
Auto101
 
Posts: 20
Joined: Wed Jun 03, 2020 5:50 pm

Re: MQTT Setup on MATRIX PORTAL

Post by Auto101 »

I appreciate the help . The code that you mentioned is for using Adafruit I/O as MQTT broker. I run a self hosted MQTT broker and hence I am using the code that I posted .As per the guide posterd here : https://learn.adafruit.com/mqtt-in-circ ... qtt-broker , this was the code which was supposed to be used when connecting to a self hosted broker

Thanks !

User avatar
jerryn
 
Posts: 1868
Joined: Sat Sep 14, 2013 9:05 am

Re: MQTT Setup on MATRIX PORTAL

Post by jerryn »

I think you will just have to modify the part that connects to wifi to use the "airlift" modules as in the AIO example. The matrix portal with esp32 coprocessor requires a diffident configuration of the wifi as noted. The MQTT calls in the example should be OK.

User avatar
Auto101
 
Posts: 20
Joined: Wed Jun 03, 2020 5:50 pm

Re: MQTT Setup on MATRIX PORTAL

Post by Auto101 »

I have edited the code and I am able to connect to wifi but now I get a different error :

code.py output:

Connecting to WiFi...
Connected!
Attempting to connect to 192.168.XX.XXX
Traceback (most recent call last):
File "code.py", line 110, in <module>
File "adafruit_minimqtt/adafruit_minimqtt.py", line 441, in connect
File "adafruit_minimqtt/adafruit_minimqtt.py", line 243, in _get_connect_socket
AttributeError: 'NoneType' object has no attribute 'getaddrinfo'

Code done running.

Here is the code

Code: Select all

import time
import board
import busio
from digitalio import DigitalInOut
import neopixel
from adafruit_esp32spi import adafruit_esp32spi
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
import adafruit_esp32spi.adafruit_esp32spi_socket as socket

import adafruit_minimqtt.adafruit_minimqtt as MQTT

### 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

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:
# esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards"""
status_light = neopixel.NeoPixel(
    board.NEOPIXEL, 1, brightness=0.2
)  # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4"""
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
# Uncomment below for an externally defined RGB LED
# import adafruit_rgbled
# from adafruit_esp32spi import PWMOut
# RED_LED = PWMOut.PWMOut(esp, 26)
# GREEN_LED = PWMOut.PWMOut(esp, 27)
# BLUE_LED = PWMOut.PWMOut(esp, 25)
# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

### Topic Setup ###

# MQTT Topic
# Use this topic if you'd like to connect to a standard MQTT broker
mqtt_topic = "airquality/co2"

### 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 callled when a client's subscribed feed has a new value.
    print("New message on topic {0}: {1}".format(topic, message))


# Set up a MiniMQTT Client
mqtt_client =  MQTT.MQTT(broker = secrets['broker'],
                    username = secrets['user'],
                    password = secrets['pass'],
                    port = 1883)

# 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!")

print("Unsubscribing from %s" % mqtt_topic)
mqtt_client.unsubscribe(mqtt_topic)

print("Disconnecting from %s" % mqtt_client.broker)
mqtt_client.disconnect()
Last edited by adafruit_support_carter on Tue Aug 31, 2021 1:58 pm, edited 1 time in total.
Reason: added [code] tags

User avatar
Auto101
 
Posts: 20
Joined: Wed Jun 03, 2020 5:50 pm

Re: MQTT Setup on MATRIX PORTAL

Post by Auto101 »

Can some one please help ?

Thanks !

User avatar
adafruit_support_carter
 
Posts: 29150
Joined: Tue Nov 29, 2016 2:45 pm

Re: MQTT Setup on MATRIX PORTAL

Post by adafruit_support_carter »

You aren't specifying a socket pool:
https://github.com/adafruit/Adafruit_Ci ... est.py#L84
so it's None and failing when it gets here:
https://github.com/adafruit/Adafruit_Ci ... tt.py#L243

User avatar
Auto101
 
Posts: 20
Joined: Wed Jun 03, 2020 5:50 pm

Re: MQTT Setup on MATRIX PORTAL

Post by Auto101 »

Thanks for the reply . I have added the socket pool and imported it . It failed on first line with below error

code.py output:
Traceback (most recent call last):
File "code.py", line 1, in <module>
ImportError: no module named 'socketpool'

Code done running.

I have attached a screen shot showing the list of libraries that are currently on the board
Attachments
Screen Shot 2021-08-31 at 1.13.53 PM.png
Screen Shot 2021-08-31 at 1.13.53 PM.png (329.31 KiB) Viewed 155 times

User avatar
adafruit_support_carter
 
Posts: 29150
Joined: Tue Nov 29, 2016 2:45 pm

Re: MQTT Setup on MATRIX PORTAL

Post by adafruit_support_carter »

For the MatrixPortal, wifi is provided by an ESP32 acting as a SPI peripheral. See the examples here:
https://github.com/adafruit/Adafruit_Ci ... s/esp32spi
for general usage.

User avatar
Auto101
 
Posts: 20
Joined: Wed Jun 03, 2020 5:50 pm

Re: MQTT Setup on MATRIX PORTAL

Post by Auto101 »

Before using the socket pool, I was able to connect to the wifi using the posted code. I 'd appreciate iff someone could provide the code for matrixportal to be ale to interact with self hosted MQTT broker . Thanks !

User avatar
neradoc
 
Posts: 542
Joined: Wed Apr 27, 2016 2:38 pm

Re: MQTT Setup on MATRIX PORTAL

Post by neradoc »

It looks like you are missing some of the init of the MQTT module ?

Code: Select all

socket.set_interface(esp)
MQTT.set_socket(socket, esp)
minimqtt_simpletest_esp32spi.py

User avatar
Auto101
 
Posts: 20
Joined: Wed Jun 03, 2020 5:50 pm

Re: MQTT Setup on MATRIX PORTAL

Post by Auto101 »

That was it , thanks so much !

code.py output:
Connecting to WiFi...
Connected!
Attempting to connect to 192.168.XX.XX
Connected to MQTT Broker!

Locked
Forum rules
If you're posting code, please make sure your code does not include your Adafruit IO Active Key or WiFi network credentials.

Return to “Internet of Things: Adafruit IO and Wippersnapper”