-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
MQTT Subscribe not working #163
Comments
One more point -> Connection to server is frequently getting disconnected. However, I am able to see almost all the data from ESP2866 client to which my mobile application is subscribed to. |
You did not specify that a callback should be executed when a message is received. In setup(), after you do client.setServer(arg, arg), you specify which callback to execute, as follows: client.setCallback(callbackName); // callback executed when message received |
Thanks for your quick response. I posted little older code first time but then I corrected it. Please check below mentioned code void callback(char* topic, byte* payload, unsigned int length); PubSubClient client(mqtt_server, 1883, callback, espClient); void setup() { Best Regards, From: MartijnvdB [mailto:[email protected]] You did not specify that a callback should be executed when a message is received. In setup(), after you do client.setServer(arg, arg), you specify which callback to execute, as follows: client.setCallback(callbackName); // callback executed when message received — |
Hi, Did you uncommment the line that says: //client.setServer(mqtt_server, 1883); and did you add the following line after that: client.setCallback(callback); // callback executed when message received ? |
Yes, I commented this line as I’ve added this line on the top -> PubSubClient client(mqtt_server, 1883, callback, espClient); Isn’t above line serve the same purpose? Nevertheless, I can try uncommenting this line and also add the line you suggested and will get back to you. client.setServer(mqtt_server, 1883); client.setCallback(callback); // callback executed when message received |
Hm, that should work too, indeed (according to the docs). |
Thanks. I'll check and revert back to you in few hours. |
Unfortunately it doesn't work. Sometime data appears but most of the time it doesn't. What could be the problem? |
Check the data flowing to the server using WireShark. |
Any update? |
Hi Knolleary, Picking up the issue...Mqtt_Esp8266 example doesn't receive/serial print on inTopic (publishes outTopic fine) nor toggle LED. See Serial Output below. Two other clients connected and receive publish outTopic and published inTopics. Wemos D1 mini is ESP8266 module. serial output: |
looking at line 92 of the example ;
https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino
check the return value of the subscribe call
client.subscribe("inTopic");
maybe it gives an error?? ( == false) for some reason.
good luck,
Edwin
On Tue, Nov 29, 2016 at 5:40 AM, Kerr1st ***@***.***> wrote:
Hi Knolleary, Picking up the issue...Mqtt_Esp8266 example doesn't
receive/serial print on inTopic (publishes outTopic fine) nor toggle LED.
See Serial Output below. Two other clients connected and receive publish
outTopic and published inTopics. Wemos D1 mini is ESP8266 module.
…
serial output:
WiFi connected
IP address:
192.168.1.96
Attempting MQTT connection...connected
Publish message: hello world #1
Publish message: hello world #2
Publish message: hello world #3
Publish message: hello world #4
Publish message: hello world #5
Publish message: hello world #6
Publish message: hello world #7
Publish message: hello world #8
Publish message: hello world #9
Publish message: hello world #10
Publish message: hello world #11
Publish message: hello world #12
Publish message: hello world #13
Publish message: hello world #14
Publish message: hello world #15
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or mute the thread.
|
Hi there, here is my experience with ESP8266 (01 and 12 models) and MQTT using PubSubClient. The publishing works quite well and is also reliable (with an ESP8266-12), but the subscribing is just a real pain (IMO !)... for me the subscribe method mostly returns 0, "randomly" and very few times it returns 1... same behaviour with 3 ESP8266-12 modules... Note : I'm using "EasyIot Cloud" MQTT server, dunno if it can be the reason ! I'll try a local MQTT server and send the result here. |
Hi there, iam using 2 Wemos D1 R2, 1 for publisher and 1 for subscriber. connected to mosquitto broker on my pc, but everytime publisher publish message, the subscriber got disconneted and reconnecting to the broker, so the subscriber never get the message from the publisher, anyone know how to fix that? |
@hudanar please don't ask your own questions on other issues. My guess is you are using the same clientid for both clients and they are kicking each other off the broker. Make use you give each client a unique id |
Hi Nick
This connects to WiFi fine & to an MQTT server running on a raspberry Pi I am not sure where to go next? Richard |
Hi Richard,
Your code seems to be OK.
Which MQTT broker are you using on your Raspberry ?
Does the subscribe("switch") call is successfully returning 1 ?
I had a lot of headache making my ESP8266-12 working (mainly with EasyIOT
MQTT broker... in fact...) but now it's OK with my Raspberry hosting a
Mosquitto MQTT broker.
Best regards,
Florian
2017-01-05 23:13 GMT+01:00 hatfieldr <[email protected]>:
… Hi Nick
I have a similar problem using PubSubClient. It connects to wifi & to MQTT
server & publishes fine but does not receive subscribe data.
I have an ESP8266-01 connected to Arduino Mega (with level conversions)
Code:
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
//#include "SoftwareSerial.h"
#include <PubSubClient.h>
IPAddress server(192,168,1,xxx);
char ssid[] = "xxxxxxxxx"; // your network SSID (name)
char pass[] = "xxxxxxxxxx"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Initialize the Ethernet client object
WiFiEspClient espClient;
PubSubClient client(espClient);
//SoftwareSerial soft(2,3); // RX, TX
void setup() {
// initialize serial for debugging
Serial.begin(115200);
// initialize serial for ESP module
Serial1.begin(115200);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true);
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}
// you're connected now, so print out the data
Serial.println("You're connected to the network");
//connect to MQTT server
client.setServer(server, 1883);
client.setCallback(callback);
}
//print any message received for subscribed topic
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
char receivedChar = (char)payload[i];
Serial.print(receivedChar);
if (receivedChar == '0')
Serial.println("Off");
if (receivedChar == '1')
Serial.println("On");
}
Serial.println();
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
client.loop();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect, just a name to identify the client
if (client.connect("AMega","xxxxxx","xxxxxxxxxxx")) {
Serial.println("connected");
// Once connected, publish an announcement...
// client.publish("Hello World");
// ... and resubscribe
client.subscribe("switch");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
This connects to WiFi fine & to an MQTT server running on a raspberry Pi
It posts to the Pi but does not receive subscribed messages.
I also have an MQTT client on my android phone. This communicates fine
with the RPi
Again the Arduino can publish to my phone but cannot receive with subscribe
I am not sure where to go next?
Any help would be appreciated
Richard
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#163 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AM7O1fCLdDv-MQBBbESHnJZflsxeg8duks5rPWrsgaJpZM4Ifkl7>
.
|
Hi Florian I am at a loss as to what to try next! Regards Richard |
Hi Richard, I'm using Mosquitto without any issue (Raspberry B model 2) As I previously asked it to you, did you checked the subscribe("switch") return ? (should be 0 if it don't succeed to subscribe) Also, did you tried to make a retry logic ? (I think the subscribe method should fails) Best regards, Florian |
Hi Florian I have a BT router, all my current experiments are on my home network, I don't think its a router problem. The mosquitto server on my Pi 3 seems to work fine with other devices (eg the MQTT client on my android phone) would love to solve it! Regards Richard |
Hi Richard, I was asking you about the router because my smartphones was perfectly working (connect, subscribe, publish), but my ESP8266 was rarely and randomly working. It's very strange that subscribe() returns 1 and if you don't receive anything on callback method. I'm calling setCallback() before setServer(), don't know if it can change anything... You seems to have a working broker, but have you tried mosquitto_pub mosquitto_sub batch calls directly on your Raspberry ? If you want, I can send to you my working code by mail, if it can helps. Florian |
Hi Florian I'm not sure what to try next.... Regards |
Hi, |
Hi |
Ah, got it now - sorry for misunderstanding... Then off-topic reaction: What about bypassing the issue for now with regular querying the channel for retained messages? |
Update 2 command line publish on the Rpi works fine I have tried installing mosquitto on my PC.... I have tried an ESP8266-12 with the Mega with the same result It connects to the WiFi network & to the MQTT broker, It publishes fine client.subscribe() returns true but no messages are received Desperate for an answer............ Richard |
Hi @hatfieldr , I was tidying up some working code and I experienced the same issue. I believe I'm on to something, but it's too late for me to investigate further. However, try as I may, the callback is not entered. Subscribe Status is 1. I then change the payload to something simple like 'Hello'. It arrives! Hoping this helps. I will do some more testing in coming days. Edit: scratch that. Changing the QOS to 1 and waiting for a few loops results in the message arriving. |
I solved the problem by calling: |
Have you used escape characters for "" ? ie \"desired_temp\"
…On Mon, Jan 30, 2017 at 5:20 PM, tororm ***@***.***> wrote:
Hi @hatfieldr <https://github.com/hatfieldr> ,
I was tidying up some working code and I experienced the same issue. I
believe I'm on to something, but it's too late for me to investigate
further.
My mqtt payload looks like this:
{"desired_hysterisis":0,"desired_temp": 50,"desired_humidity":20,"
desired_FanOn":off,"desired_FanBreak":5.0}
However, try as I may, the callback is not entered. Subscribe Status is 1.
I then change the payload to something simple like 'Hello'.
It arrives!
Hoping this helps. I will do some more testing in coming days.
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#163 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AH9rt1_kR-jVIamRDcl2A3H_OV70wMMhks5rXc6RgaJpZM4Ifkl7>
.
|
I have ESP8266 with pubsub. Arduino IDE. No Arduino hardware, just ESP8266 ESP-01. If both publish and subscribe then nothing useful in callback. Device resets frequently.
and (because I don't know the length of payload)
Uncomment callback in pubsub and in my sketch the topic can be printed. However, length is consistently 5 and payload "not human readable". A difference between topic and payload is that topic is char* and payload is uint8_t. Probably red herring. But keep in back of mind as similar problems to what we are seeing occur in pubsub when using arduinojson-master to prepare json payload and publish. Picking up on confusedtoo's comments about scope (whether variables are persistent outside the function in which they are declared) I added static to the declaration of both payload and topic in pubsub function boolean PubSubClient::loop()
buffer is already declared global. This lets me successfully use the following in my sketch callback function:-
The device seems to maintain its connection more reliably. FWIW I met similar problem (scope) a couple of weeks ago. A library which compiled and ran on Arduino Uno and Mega hung on a Teensy. Its quite possible that people are getting different results from pubsub on different hardware. I haven't yet figured out why the length of the payload provided by callback is always 5. I also haven't yet tested with publishing and subscribing at the same time. Nor do I understand why the message is frequently garbled when first received into buffer. Experience suggests there's more than one problem with pubsub on ESP8266. I'm not a C++ programmer. I have limited understanding. |
after some more testing my ESP8266 sketch now both publishes and subscribes. Note that with Arduino IDE (on Win 10) sketches compiled for ESP8266 (Adafruit HUZZAH) have different outcome to same sketch compiled for Uno or Mega. In ESP8266 variables declared inside a function do not persist after completion of function. The problem occurs here in callback. It applies generally to return from any function. following are required changes to PubSubClient.cpp line 304 declare *payload as static line 313 declare *topic as static add line 314 declare new variable plen as static add line 319 assign value (calculated length of payload) to plen change line 320 callback with new variable plen add line 331 assign value (calculated length of payload) to plen change line 332 callback with new variable plen Thanks for very useful library. I've now tested publishing at 1000 messages per second and receive occasional subscribed messages with mosquitto on raspberry pi 3. |
@epicycler much easier if you can propose changes as a pull request |
@knolleary thanks. I'm totally new to Github and all things Linux. Its very foreign to me. Not your fault, but when I read the info on pull request I left with absolutely no idea. Common problem for me, lots of info on how but not a lot about why. |
@epicycler there's no guarantees if/when these changes will get into the library. You'll see there are lots of outstanding PRs against this library, all waiting for me to find the time and energy to review and decide what to merge. The point of a PR is it puts the proposed changes into context. GitHub makes it quite easy to do a pull request on a single file. Go to that files page (https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.cpp), click the edit button in the top right and it'll walk you through. |
well that was interesting. I expected to see my pull request appear in the list of pull requests. how do I delete epicycler/pubsubclient? |
Aslo having troubles on an ESP8266-12 with subscribe. Are using the example code. Publish works fine, subscribe don't work. The code changes @epicycler suggested did not change anything in my setup. |
I started with the ESP8266 example. client.loop() is where pubsubclient reads incoming. While debugging I also published some messages with retain flag set. |
I have done some more testing. Seems like my problem was not related to this issue. I have already build an ESP with this library where I set the clientId to a static string. When I reused that code in a new project I had two ESP with the same clientId. Changing the clientId fixed my issues and the subscribe function is OK with the original library code base. |
Hello, #include <PubSubClient.h> void setup() void loop() void reconnect() // Connect to the MQTT broker } else void callback(char* topic, byte* payload, unsigned int length) { int mqttSubscribe(long subChannelID,int field,char* readKey){ String myTopic="channels/"+String(subChannelID)+"/subscribe/fields/field"+String(field)+"/"+String(readKey); Anyone please help me out |
Please edit your last message and format your code! Nobody wants to read this messed up code. Thx! |
@vignesh: you have forgotten the delay in the loop() ... without that no wlan for esp8266 .. |
The comment from sunnydevtale about adding a delay(100) after client.loop() worked for me. This same code used to work without the delay months ago, not sure why it does not now. This tcpdump shows the difference with and without the added delay sudo tcpdump -i wlan0 port 1883 -Xvf | grep -i -B6 -A6 setSleepTime
and with the delay
Sorry, I should have added ... |
This seems to be a common problem even after years. Also I have the problem, that I can connect and send MQTT messages without problems, even the subscribtion gives back true, but my callback function is not called at all. Last summer (a year ago), almoast the same code worked fine. I think the main thing I did this time is updating all libraries. After reading the full storry here and searching for the bug two full days, I would be very happy if someone can help me anf maybe also others with answer. Hardware:
My Code:
|
For me, adding client.loop() twice after each client.subscribe(topic) call
in reconnect resolved this issue (I did not have to add this for just a
single topic but did have to after subscribing to two or more topics.
…On Mon, Aug 20, 2018 at 9:27 AM, tsknightstorm ***@***.***> wrote:
This seems to be a common problem even after years. Also I have the
problem, that I can connect and send MQTT messages without problems, but my
callback function is not called at all. Last year, almoast the same code
worked fine. I think the main thing I did is updating all libraries. After
reading the full storry here and working 2 full days, I would be very happy
if someone can help me anf maybe also others with answer.
Hardware:
- ESP8266 12-F
- RPi 3 with Mosquitto
- Win10 and AtmelStudio / visual Micro
My Code:
I added many delays for tests. Of corse, I do not let them all stay in my
code. Also I post just the MQTT part. I splited the WiFi code and some
logic things with buttons to other .cpp / .h files.
`
#define mqtt_waitTimeMs 100
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
void mqtt_setup(void){
delay(200);
// Loop until we're reconnected
while(! mqttClient.connected()){
Serial.print("Setup MQTT \t| ");
String mqttClientID = _generateUniqID();
mqttClient.setServer(mqtt_server,mqtt_port);
delay(100);
mqttClient.setCallback(_mqtt_callback);
delay(100);
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if( mqttClient.connect(mqttClientID.c_str(), mqtt_user, mqtt_password)){
// subscribe to Topics
_mqtt_subscribe();
Serial.println("connected...rc=" + String(mqttClient.state()));
if (mqttClient.publish("debug", mqttClientID.c_str())) { // comment for start
Serial.println("MQTT Publish ok");
}else {
Serial.println("Publish failed!...");
}
Serial.println();
}else{
Serial.print("failed, rc=");
Serial.print( mqttClient.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying, blocking because nothing should run without connection
delay(5000);
}
}
}
void mqtt_loop(void){
static long oldTimeMs = millis();
if( (millis()-oldTimeMs) > mqtt_waitTimeMs){
mqtt_setup(); //to reconnect
oldTimeMs = millis();
}
mqttQueue_DequeueAndSend();
}
void mqtt_publish(String topic, byte payload){
mqttQueue_Enqueue(topic, payload);
}
void mqtt_publish_directOut(char* topic, char* payload){
if ( mqttClient.publish(topic, payload) ){
Serial.println("OK");
}else{
Serial.println(" ERROR: Send MQTT fail........................");
}
}
void _mqtt_callback(char* topic, byte* payload , unsigned int length){
Serial.println("........Debug: MQTT callback");
byte numPayload = _bytePToInt(payload, length);
byte numInChannel;
byte numOutChannel;
if(_inTopicToChannel(topic, &numInChannel)){
led_setValue(numInChannel, numPayload);
}
if(_outTopicToChannel(topic, &numOutChannel)){
switch_setState(numOutChannel, numPayload);
}
Serial.println( "Receive MQTT\t| topic: " +
String(topic) +
"\t| payload: " +
String(numPayload) +
"\t| channel: " +
String(numInChannel)
);
}
void _mqtt_subscribe(void){
Serial.println("........Debug: MQTT Subscribe start");
mqttClient.subscribe("debug");
// subscribe to update LED's
for(int i = 0; i < numberOfLed; i++){
if(mqttClient.subscribe(mqtt_inTopicString[i].c_str())){
Serial.println("........Debug: MQTT Subscribe true");
}else{
Serial.println("........Debug: MQTT Subscribe false");
}
delay(100);
}
// subscribe to update switch states
for(int i = 0; i < numberOfSwitch; i++){
//mqttClient.subscribe((char*)mqtt_outTopicString[i].c_str()); //////////// mqtt connection crashes with both arrays subscribed
delay(100);
}
Serial.println("........Debug: MQTT Subscribe end");
}
`
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#163 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AduW1kvvw0NewYYLcA3RCrKXZQC5iEnFks5uSuOHgaJpZM4Ifkl7>
.
|
Thanks a lot! With your comment, you were able to bring me to solve my problem... It was too obviouse... I never did call client.loop().... At some point, I must have deleted this line by acident and while reading the comments in this forum, I was thinking that everyboadi is talking about the general loop not this particular function. |
Glad it worked out for you, I had the exact issue not to long ago which is
why I remembered it
…On Mon, Aug 20, 2018 at 1:03 PM, tsknightstorm ***@***.***> wrote:
Thanks a lot! With your comment, you were able to bring me to solve my
problem... It was too obviouse...
*I never did call client.loop()....*
At some point, I must have deleted this line by acident and while reading
the comments in this forum, I was thinking that everyboadi is talking about
the general loop not this particular function.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
<#163 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AduW1rHAZIkO3IuzofDH0FRKpw6fEJD1ks5uSxYFgaJpZM4Ifkl7>
.
|
haai all, I've tried everything. my code looks bad with all your parts in it i cant subscribe Iam coding in VS Code, and everything is running on WIN10 servers now,,, i know its the callback when i run: I only get 1`s I can toggle the switch in Node-red ui, it updates in the DB but cant read can someone please send a link with a working .ino The SQLTest/# is my publish thank you in advance |
I too am facing issues with the Subscribe messages not being processed reliably, although the sending of data is working flawlessly. I am using an Arduino Mega with an ESP8266 module connected via pins 18 and 19 with a baud rate of 115200. The serial interface for output of messages is set at a baud rate of 9600. Note: I've also tested the ESP8266 at 9600 and it provides the same results as outlined below. I am using a Raspberry Pi 2 with Node Red, which is also running Mosquitto MQTT. I am also using the latest build of the PubSubClient, version 2.7 I originally faced a problem with the connection dropping and showing the -4, MQTT_CONNECTION_TIMEOUT error. to solve this I changed the MQTT_VERSION to use 3_1 instead of 3_1_1. I had to add a delay of 1ms in the main loop(). This stopped the connection dropping every couple of minutes and remained stable in a 12 hour test. I noted that if I spam the queue with requests, eventually the Arduino picks up the message. It's as if the Arduino is only listening/monitoring for 0.2 of a second out of every 1 second and unless the message hits the queue in that 0.2 window, it's not noticed and processed. I've built, and replicated the issue with the sample code below, which is as bare bones as I could get it for the purpose of testing. The goal, just output "D" to the interface if it picks up a message. Note, that other devices on the same network ARE picking up these messages flawlessly, it's not a network issue or an issue with the broker. I've tried all of the suggestions within this thread with one exception, but none have solved the problem. The exception being the comments from vignesh-123 in February. I wasn't able to find exact matches to the code referenced, so didn't make these changes. I have also tried the same code on pins 2,3 using an Arduino Uno with the same results. I'm currently out of ideas and couldn't find any additional recommendations to test. If anybody has any suggestions I would be grateful and willing to test them. The ESP8266 module is currently drawing power from the onboard 3.3v pin of the Arduino, although I am going to hook this up to a power supply shortly in case the issue is caused by lack of power to the module. I didn't see others comment on their module setup, so not sure if perhaps this is a common theme between them. I'll follow up with the result of this test once it's completed. Sample code: (masked usernames/passwords etc).
|
@Noodleyman Try changing the
|
@xibriz , thanks for the suggestion. I've just tested that out, but the behaviour remained the same. Here is the revised code to do as you suggested. I did have another thought, two things to validate.
|
Thank you so much xibriz! |
Thanks @pmarcomini |
I found a buffer overrun in pubsubclient.cpp. After changing the buffer size with |
I just wanted to add that I had the same issue subscribing to a retained topic where i was only calling the client.loop() a few times in setup() due to running off battery and switching to deepsleep. It turned out that the client.loop has to run between 100-200 times before the callback is triggered, even on retained messages. The solution in my case was to create a for loop that ran the client.loop() upto 200 times (with no delay required) to ensure the callback fires. Seems odd to me that it requires this many loops, but it works! |
Thank you my problem was resolved after increasing buffer size to 4096. |
Thanks! This worked for me. The incoming message from Thingspeak was > 256 (MQTT_MAX_PACKET_SIZE) for me, since I have subscribed to the full channel, and not to one single field of this channel. I.e. Subscribing to the full channel with topic: Subscribing to only one field with topic: |
Just to repeat a solution which worked for me (its around 1/3 of the thread) - super simple, might not occur in real projects but if you try a demo solution (Mega with ESP) and have nothing in loop beside client.loop() - try adding delay of 100 or 300. Then callbacks started working for me. |
Just adding a my bit: the I ended up using this policy for testing purposes: {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:Connect",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iot:Publish",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iot:Subscribe",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iot:Receive",
"Resource": "*"
}
]
} and it immediately worked. |
I am very new to ESP8266 and MQTT. So Apologies if I haven't done it properly. I am using test.mosquitto.org server and trying to publish and subscribe the data. I am able to publish the data but subscribe part is not working. Nevertheless, I have tested subscribe part between two mobile and I am able to receive the data but I am not getting any data in the callback routine though I subscribed explicitly in the code. I have attached my code for your reference.
`
include <ESP8266WiFi.h>
include <PubSubClient.h>
define wifi_ssid ""
define wifi_password ""
define mqtt_server "test.mosquitto.org"
define mqtt_user "test"
define mqtt_password "test"
define topic1 "SmartIOT/Temperature"
define topic2 "SmartIOT/Humidity"
define topic3 "SmartIOT/Switch"
void callback(char* topic, byte* payload, unsigned int length);
WiFiClient espClient;
PubSubClient client(mqtt_server, 1883, callback, espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
//client.setServer(mqtt_server, 1883);
client.subscribe(topic3);
}
// Callback function
void callback(char* topic, byte* payload, unsigned int length) {
// In order to republish this payload, a copy must be made
// as the orignal payload buffer will be overwritten whilst
// constructing the PUBLISH packet.
Serial.println("Incoming data : ");
Serial.println(topic);
//Serial.println(payload);
// Allocate the correct amount of memory for the payload copy
byte* p = (byte*)malloc(length);
// Copy the payload to the new buffer
memcpy(p,payload,length);
//client.publish("outTopic", p, length);
// Free the memory
free(p);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("TestMQTT")) { //* See //NOTE below
Serial.println("connected");
}
//NOTE: if a user/password is used for MQTT connection use:
//if(client.connect("TestMQTT", mqtt_user, mqtt_password)) {
void pubMQTT(String topic,float topic_val){
Serial.print("Newest topic " + topic + " value:");
Serial.println(String(topic_val).c_str());
client.publish(topic.c_str(), String(topic_val).c_str(), true);
}
//Variables used in loop()
long lastMsg = 0;
float t1 = 75.5;
float t2 = 50.5;
void loop() {
if (!client.connected()) {
reconnect();
client.subscribe(topic3);
}
client.loop();
//2 seconds minimum between Read Sensors and Publish
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
//Read Sensors (simulate by increasing the values, range:0-90)
t1 = t1>90 ? 0 : ++t1;
t2 = t2>90 ? 0 : ++t2;
//Publish Values to MQTT broker
pubMQTT(topic1,t1);
pubMQTT(topic2,t2);
}
}
`
The text was updated successfully, but these errors were encountered: