Pico W Micro Python MQTT of data to a RP4B

RP2040 based microcontroller boards running MicroPython.
Target audience: MicroPython users with an RP2040 boards.
This does not include conventional Linux-based Raspberry Pi boards.
beetle
Posts: 51
Joined: Sat Oct 16, 2021 11:35 am

Re: Pico W Micro Python MQTT of data to a RP4B

Post by beetle » Wed Aug 24, 2022 10:04 pm

Just out of interest, where in the world are you beetle?
In Norfolk UK. And please send some rain this way. Where are you?

beetle
Posts: 51
Joined: Sat Oct 16, 2021 11:35 am

Re: Pico W Micro Python MQTT of data to a RP4B

Post by beetle » Thu Aug 25, 2022 12:17 am

Rissy,

Although I expect your funny code examples of MQTT_PW_Vars.py, Globals.py and PicoW_Vars.py was just trying to show using global variables to print them out from another program, but your real programs will do much more. Nevertheless, even as you now know your use of global vars for separately running program is flawed, if they were to be used as modules the approach you examples as shown are wide of the mark so I could not resist showing, in the terms of your code, how is could be done.

Fisrt I show you an amended MQTT_PW_Vars.py that prints the mqtt messages without trying to pass that to another module.

I then show you a MQTT_PW_Vars_module.py (as copied from MQTT_PW_Vars.py) , a Globals.py and a PicoW_Vars.py. The PicoW_vars.py is the main program that imports MQTT_PW_Vars_module. Copy these programs into a directory of their own. Run the PicoW_vars program. Publish some mqtt data and see the results print (every 10 seconds, but amend as desired). As you can see MQTT_PW_Vars_module.py updates the Globals.py and PicoW_vars.py starts the mqtt connection as found in the MQTT_PW_Vars_module.py and reads the Globals.py module to print them out. What a palaver. But I hope it may be food for thought, and if nothing else cements the use of shared Globals should you ever wish to use them, but this is not recommended.

The MQTT_PW_Vars.py (a stand alone receive mqtt and print program

Code: Select all

#!/usr/bin/env python
#!/bin/bash
#MQTT_PW_Vars.py

import time
import paho.mqtt.client as mqtt

broker = '10.0.1.141'
port = 1883
mqttclient = "PiLogger2"
client = mqtt.Client(mqttclient)

topic1 = 'OS_Temp'
topic2 = 'OS_Hum'
topic3 = 'Pico_Temp'

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print(f"Connected to MQTT Broker with result: {rc}")
    else:
        print("Failed to connect to Broker, return code = ", rc)

def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection!")

def on_message(client, userdata, message):
    topics = message.topic
    payload = message.payload.decode("utf-8")
    
    if topics == topic1:
        print(f"Received: {(message.payload.decode('utf-8'))} from Topic: {message.topic}")
        temp = float(message.payload)
        print(topic1, 'is ', temp)
        
    if topics == topic2:
        print(f"Received: {(message.payload.decode('utf-8'))} from Topic: {message.topic}")
        hum = float(payload)
        print(topic2, 'is ', hum)
    
    if topics == topic3:
        print(f"Received: {(message.payload.decode('utf-8'))} from Topic: {message.topic}")
        pico_temp = float(payload)
        print(topic3, 'is ', pico_temp)
        
client.connect(broker, port)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
time.sleep(3)
client.subscribe(topic1)
client.subscribe(topic2)
client.subscribe(topic3)
client.on_message = on_message
time.sleep(10)
client.loop_forever()
The MQTT_PW_Vars_module.py (a copy of MQTT_PW_Vars.py that update global variables and does not print.)

Code: Select all

#MQTT_PW_Vars.py

import time
import paho.mqtt.client as mqtt
import Globals


broker = '10.0.1.141'
port = 1883
mqttclient = "PiLogger2"
client = mqtt.Client(mqttclient)

topic1 = 'OS_Temp'
topic2 = 'OS_Hum'
topic3 = 'Pico_Temp'

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print(f"Connected to MQTT Broker with result: {rc}")
    else:
        print("Failed to connect to Broker, return code = ", rc)

def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection!")

def on_message(client, userdata, message):
    topics = message.topic
    payload = message.payload.decode("utf-8")
    
    if topics == topic1:
        print(f"Received: {(message.payload.decode('utf-8'))} from Topic: {message.topic}")
        temp = float(message.payload)
        Globals.OS_Temp = temp
        
    if topics == topic2:
        print(f"Received: {(message.payload.decode('utf-8'))} from Topic: {message.topic}")
        hum = float(payload)
        Globals.OS_Hum = hum
    
    if topics == topic3:
        print(f"Received: {(message.payload.decode('utf-8'))} from Topic: {message.topic}")
        pico_temp = float(payload)
        Globals.Pico_Temp = pico_temp

def mqtt_connect():        
    client.connect(broker, port)
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    time.sleep(3)
    client.subscribe(topic1)
    client.subscribe(topic2)
    client.subscribe(topic3)
    client.on_message = on_message
    time.sleep(10)
    client.loop_start()

Globals.py (a module to hold global variables shared between other modules)

Code: Select all

OS_Temp = 0.0
OS_Hum = 0.0
Pico_Temp = 0.0
PicoW_Vars.py (the main program that imports MQTT_PW_Vars_module.py and Globals.py)

Code: Select all

import Globals
import MQTT_PW_Vars_module as mqtt
import time

def print_globals():
    print("temperature: ", Globals.OS_Temp)
    print("humidity: ", Globals.OS_Hum)
    print("Pico temp: ", Globals.Pico_Temp)

# start the mqtt
mqtt.mqtt_connect()
   
while True:
    # prints the globals every sec seconds
    sec = 10
    print_globals()
    time.sleep(sec)
Whether all this helps or not I'm not sure, but I could not help noticing you kept putting in a gVar variable in your code which was just an example variable from my code snippets. I was at a loss at to what it was doing in your code and I expect you were not understanding my examples so I thought I would give this fuller example for your better understanding. PS I changed the broker for my address to check it all worked, so you need to change it back to your ip address.

Rissy
Posts: 116
Joined: Sun Aug 14, 2022 8:15 am

Re: Pico W Micro Python MQTT of data to a RP4B

Post by Rissy » Thu Aug 25, 2022 6:16 am

It's an interesting potential answer if I don't need the MQTT to display anything, but still pass its received values on to a module which does display them as well as log them to a spreadsheet incrementally. Although my thought on this was that I wouldn't be able to see if the MQTT program had frozen or something as a result of losing comms with the broker.

If you saw my whole display and log file you'd see fully what i'm doing. Basically its another copied version of the other two similar running modules i have for my BME280 sensors in the loft, one for each so that values are displayed and logged independently and two separate spreadsheets are produced (this is what i wanted).
Although i'm currently generating this third spreadsheet from the MQTT values, I may be tempted to role the code for that one into the other two so that I have an immediate comparison between the indoor figures and the outdoor figures on each of the two spreadsheets in each case.
I was watching Coreys youtube video on fstrings last night. I might be temped to "upgrade" my existing code to make use of those instead of formatted ones as they are currently.

Looks like this forum is going to make this thread read only soon, so i'll close out with three things.

1. I'm going to do my code swapping for the Pico W and the RP4B next, as well as small mods like fstrings
2. I'm going to have to make my BME280 (and a BMP280) sensors work with my Pico W next and my SHT30 work with my RP4B. I'm sure i'll need help with this, but in another thread (especially with the micropython stuff as this forum is intended after all)
3. I'm a Scottish guy who lives in Rugby, Warwickshire, UK. So not far from Norfolk, UK.

Peace out. (Drops the mic)

Post Reply