from __future__ import print_function
import paho.mqtt.publish as publish
from bmp180 import bmp180
from time import sleep
import smbus
import sys
channelID = "1304227" #Enter your Channel ID here
apiKey = "XXXXXXXXXXXX" #Enter your WriteAPI key here
useUnsecuredTCP = False
useUnsecuredWebsockets = False
useSSLWebsockets = True
mqttHost = "mqtt.thingspeak.com"
if useUnsecuredTCP:
tTransport = "tcp"
tPort = 1883
tTLS = None
if useUnsecuredWebsockets:
tTransport = "websockets"
tPort = 80
tTLS = None
if useSSLWebsockets:
import ssl
tTransport = "websockets"
tTLS = {'ca_certs':"/etc/ssl/certs/ca-certificates.crt",'tls_version':ssl.PROTOCOL_TLSv1}
tPort = 443
topic = "channels/" + channelID + "/publish/" + apiKey
sensor = bmp180(0x77)
temp = ""
pressure = ""
while(True):
temp = sensor.get_temp()
pressure = sensor.get_pressure()
print (" Temperature =",temp ," Pressure =", pressure)
tPayload = "field1=" + str(temp) + "&field2=" + str(pressure)
try:
publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport)
except (KeyboardInterrupt):
break
except:
print ("There was an error while publishing the data.")
Subscribe code:
import paho.mqtt.subscribe as subscribe
from bmp180 import bmp180
from time import sleep
import smbus
import sys
from gpiozero import LED
channelID = "1304227"
READapiKey = "YYYYYYYYYYYY"
useUnsecuredTCP = False
useUnsecuredWebsockets = False
useSSLWebsockets = True
mqttHost = "mqtt.thingspeak.com"
if useUnsecuredTCP:
tTransport = "tcp"
tPort = 1883
tTLS = None
if useUnsecuredWebsockets:
tTransport = "websockets"
tPort = 80
tTLS = None
if useSSLWebsockets:
import ssl
tTransport = "websockets"
tTLS = {'ca_certs':"/etc/ssl/certs/ca-certificates.crt",'tls_version':ssl.PROTOCOL_TLSv1}
tPort = 443
# Create the topic string
topicR = "channels/" + channel1ID + "/subscribe/field/field1/" + READapiKey
led = LED(27)
while(True):
temp_data = subscribe.simple(topicR, hostname = mqttHost)
print(temp_data.payload)
if (temp_data.payload >=32):
led.on()
else:
led.off()
Hello, I am facing the same issue. I am working on a project to interface the BME 280 sensor with ESP32 and use the publish-subscribe operation of MQTT using ThinSpeak as the broker. I could easily publish to the ThingSpeak channel, but I am facing some issues while trying to subscribe to the channel in order to get data from the ThingSpeak server to my ESP32. I am able to connect to the MQTT server, but unable to subscribe and receive any messages from the ThingSpeak MQTT.
I am posting my subscribe code along with the query, please help me resolve the above highlighted issue.
CODE:
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
const char ssid[] = "xyz"; //Insert your SSID
const char pass [] = "xyz"; //Insert Your password
const char* mqtt_server = "mqtt.thingspeak.com";
const char* mqttUserName = " xyz"; // Thingspeak username.
const char* mqttPass = "xyz"; // Change to your MQTT API Key from Account > MyProfile.
const char* ChannelID = " xyz"; // Thingspeak Channel ID
const char* APIKey = "xyz"; // Thingspeak Channel Read API Key
String Temp_String;
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println("Data received: ");
Serial.println("Temperature ");
for (int i = 0; i < length; i++) {
char receivedChar = (char)payload[i];
Temp_String += (char)payload[i];
}
float TS_Temp = Temp_String.toFloat();
Serial.print(TS_Temp);
TS_Temp = 0;
Temp_String = "";
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266", mqttUserName, mqttPass)) {
Serial.println("connected");
// ... and subscribe to topic
client.subscribe("channels/ChannelID/subscribe/fields/field1/APIKey");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(115200);
delay(250);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
WiFi.disconnect();
delay(100);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.print("OK");
Serial.println();
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();