Hello,
I was working on a project to contol an LED connected to the Pi 4 using the subscribe feature in ThingSpeak MQTT. While I was able to publish data to ThingSpeak MQTT using the Pi 4 without any issues, I faced trouble while trying to subscribe to a channel in ThingSpeak MQTT to read data from a field to control an LED connected to the Pi.
Initially, I had interfaced both the LED and a BMP180 sensor to the same Pi and wanted to publish data from the BMP180 to a ThingSpeak channel and subscribe to the channel to control my LED based on the temperature values (I ran seperate scripts on the Pi 4 for the Publish and subscribe simuntaneously). Though the publish part worked, the subscribe part did not. I thought this was because I was using the same device (the Pi) to publish and subscribe to the channel.
So later, I installed the MQTT.fx app in my PC and used it to publish values to a new private ThingSpeak channel. I then used the Pi to subscribe to the same channel, receive values and control the LED that was interfaced to it. This did not work either. I am unable to receive messages from the ThingSpeak MQTT channel when I subscribe to it from the Pi 4.
I double checked the Channel ID and API keys were correct. I'm using the Paho MQTT library for publish and subscribe to ThingSpeak MQTT. I used port 1883.
I will share the python code I used to subscribe to the ThingSpeak MQTT channel. I have the following doubts:
- Please help me resolve the above issue. (highlighted)
- Is it possible to use the same device to publish and subscribe to ThingSpeak MQTT, as I did in the first case? If yes, how?
Code I used to subscribe to the ThingSpeak MQTT channel using the R Pi 4:
import paho.mqtt.client as mqttClient
import time
from gpiozero import LED
import random
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to broker")
global Connected
Connected = True
else:
print("Connection failed")
def on_message(client, userdata, message):
print (message.payload)
Connected = False
broker_address= "mqtt.thingspeak.com" #Broker address
port = 1883 #Broker port
user = "pi_led" #Connection username
password = "XXXXXXXXXXXXXXXXX"#Connection password - Used my MQTT API key from My Profile
client = mqttClient.Client("Python") #create new instance
client.username_pw_set(user, password=password) #set username and password
client.on_connect= on_connect #attach function to callback
client.on_message= on_message #attach function to callback
client.connect(broker_address, port=port) #connect to broker
client.loop_start() #start the loop
while Connected != True: #Wait for connection
time.sleep(0.1)
channelID = "1304227"
READapiKey = "YYYYYYYYYYYYYYYY"
topic = "channels/" + channelID + "/subscribe/field/field1/" + READapiKey
#led = LED(27)
client.subscribe(topic, qos=0)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print ("exiting")
client.disconnect()
client.loop_stop()
0 Comments
Sign in to comment.