3
votes

I'm new on Python and also on MQTT. I was able to write some Python working code to publish connected sensors data to a broker, now I'd like to subscribe to more than one topic and write all the payloads on an LCD 20x4 connected to a raspberry.

Actually I wrote a Python to subscribe on one topic and write the payload on the LCD; no problem, it's working. No way to include other topics in the same Python and write the payload on the LCD.

Following you can find my working Python code for "just" ONE topic.

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# RPi-S-LCD.py
# Created on 8/1/2017
#
# Python program that write payloads on LCD 20x4
#

import time
import sys
import os
import paho.mqtt.client as paho
sys.path.append("/home/pi/Adafruit_Python_CharLCD")
import Adafruit_CharLCD as LCD
import Adafruit_GPIO.MCP230xx as MCP

### Define MCP pins connected to LCD
lcd_rs = 6
lcd_en = 4
lcd_d4 = 3
lcd_d5 = 2
lcd_d6 = 1
lcd_d7 = 0
lcd_backlight = None

### Define LCD type
lcd_columns = 20
lcd_rows = 4

### Initialize MCP23017 for LCD
gpiomcp = MCP.MCP23017(0x20, busnum=1)

### Initialize LCD panel parameters
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight, gpio=gpiomcp)
lcd.show_cursor(False)
lcd.blink(False)
lcd.clear()

### Read data from MQTT broker
def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribed to the broker "+str(mid)+" "+str(granted_qos))


### Print topic data to LCD
def on_message1(client, userdata, msg):
    lcd.set_cursor(0,0)
    lcd.message(msg.payload)

client = paho.Client()
client.on_subscribe = on_subscribe
client.on_message = on_message1
client.connect("10.0.2.10", 1883, 30)
client.subscribe("iDomus/Time",2)

client.loop_forever()
2
I am not familiar with this language/tech but it sounds like you're asking readers to add a new feature to your code (supporting multiple topics). If so, it may be too broad. What strategy do you have to achieve your objective? What are you trying at present?halfer
You just need to add another client.subscribe("...",2) line with the required topic and and the message will be handled by the same on_message1 function.hardillb
halfer, as I said in my post I'm a newbi in python and in mqtt. I'm starting to use mqtt.fx just to understand how the payload is sent through the net. In any case my poor python knowledge will be not an help for me.. I need to reserve some time to read a good python book.Marco
hardllib - Thx for your reply. I added the second subscribe function to my code and added a print function to understand if and how the payload is received. Now I know that subscriptions are made and the payload contain TWO topic's payload. I will find a solution to "split" the payload received.Marco

2 Answers

5
votes

reading more documentation on MQTT I found the function

"message_callback_add"

and now the python program is working fine. This is what I've had in mind. Now I subscribe to all topics but I choose what particular topic I want to treat and the payload is separated for an easy visualisation on LCD. Sorry for my python code.. I'm not a programmer but the following it's working fine for me. Hope it can help other people with my same problem.

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# RPi-S-LCD.py
# Created on 21/1/2017
#
# Python program that use LCD 20x4 to display topics info
#

import time
import sys
import os
import paho.mqtt.client as paho
sys.path.append("/home/pi/Adafruit_Python_CharLCD")
import Adafruit_CharLCD as LCD
import Adafruit_GPIO.MCP230xx as MCP

### Define MCP pins connected to LCD
lcd_rs = 6
lcd_en = 4
lcd_d4 = 3
lcd_d5 = 2
lcd_d6 = 1
lcd_d7 = 0
lcd_backlight = None

### Define LCD type
lcd_columns = 20
lcd_rows = 4

### Initialize MCP23017 for LCD
gpiomcp = MCP.MCP23017(0x20, busnum=1)

### Initialize LCD panel parameters
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight, gpio=gpiomcp)
lcd.show_cursor(False)
lcd.blink(False)
lcd.clear()

### DATE
def on_message_date(mosq, obj, msg):
    lcd.set_cursor(0,0)
    lcd.message(str(msg.payload))

### TIME
def on_message_time(mosq, obj, msg):
    lcd.set_cursor(0,2)
    lcd.message(str(msg.payload))

### RELAY
def on_message_relay(mosq, obj, msg):
    if (str(msg.payload)[3]) == '0':
        lcd.set_cursor(7,2)
        lcd.message("RL1= 0 RL2= 0")
    elif (str(msg.payload)[3]) == '1':
        lcd.set_cursor(7,2)
        lcd.message("RL1= 1 RL2= 0")
    elif (str(msg.payload)[3]) == '2':
        lcd.set_cursor(7,2)
        lcd.message("RL1= 0 RL2= 1")
    elif (str(msg.payload)[3]) == '3':
        lcd.set_cursor(7,2)
        lcd.message("RL1= 1 RL2= 1")
    else:
        lcd.set_cursor(7,2)
        lcd.message("RELAYs ERROR!")

### PUBLIC IP
def on_message_pubip(mosq, obj, msg):
    lcd.set_cursor(0,1)
    lcd.message("                    ")
    lcd.set_cursor(0,1)
    lcd.message("IP = "+str(msg.payload)[0:14])

### TEMPERATURE
def on_message_temp(mosq, obj, msg):
    lcd.set_cursor(0,3)
    lcd.message(str(msg.payload)[0:4]+chr(223)+"C")

### HUMIDITY
def on_message_humi(mosq, obj, msg):
    lcd.set_cursor(7,3)
    lcd.message(str(msg.payload)[0:4]+chr(37))

### PRESSURE
def on_message_pres(mosq, obj, msg):
    lcd.set_cursor(13,3)
    lcd.message(str(msg.payload)+"hPa")

### topic message
def on_message(mosq, obj, msg):
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

mqttc = paho.Client()

#Add message callbacks that will only trigger on a specific   subscription    match
mqttc.message_callback_add('iDomus/Time', on_message_time)
mqttc.message_callback_add('iDomus/Date', on_message_date)
mqttc.message_callback_add('iDomus/PubIPRead', on_message_pubip)
mqttc.message_callback_add('iDomus/RPiS/Sens1/Temp', on_message_temp)
mqttc.message_callback_add('iDomus/RPiS/Sens1/Humi', on_message_humi)
mqttc.message_callback_add('iDomus/RPiN/Sens2/Pres', on_message_pres)
mqttc.message_callback_add('iDomus/RPiS/Rel1/Read', on_message_relay)
mqttc.on_message = on_message
mqttc.connect("10.0.2.10", 1883, 30)
mqttc.subscribe("iDomus/#")

mqttc.loop_forever()
1
votes

I am able to subscribe to multiple topic using paho python mqtt library. I have created a list of topic and passing it to "subscribe.simple". Using below sample program, I am able to subscribe to "topic1" and "topic2".

topic = ["topic1", "topic2"]
hostname_1 = "<mqtt broker host name>"
port_1 = <mqtt broker connection port>
username_1 = "broker username"
password_1 = "broker password"
message = subscribe.simple(topic, hostname=hostname_1, port=port_1, keepalive=60, will=None, auth={'username':username_1,'password':password_1})
print meaasge.payload