tuanpmt / espduino Goto Github PK
View Code? Open in Web Editor NEWESP8266 network client (mqtt, restful) for Arduino
Home Page: http://tuanpm.net/post/espduino
License: MIT License
ESP8266 network client (mqtt, restful) for Arduino
Home Page: http://tuanpm.net/post/espduino
License: MIT License
dear tuanpmt
my problem is esp8266 didn't connect again if i turn off then turn on my router, i
sorry for my bad english
thank you
After Setup, i found this on debug port terminal output:- (Continuously)
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc:�CMD:
I have followed the installation guide (flashed esp w/ firmware, connected arduino uno and esp as shown, uploaded example MQTT sketch to arduino uno) but I receive garbage in the serial port. I've tried both the FTDI and ardunio port at several different baud rates. I've tried both the release and debug firmwares. I know I can use the esp in stand alone but I would like to add wifi to my ardunio. I also have a nano and tried and received identical results I'm not sure what else to try... Do I need the FTDI controller once it is flashed? Any suggestions? Any help direction would be greatly appreciated.
Hi!
I was mystified - for awhile, your firmware in this repository was the only thing that I could connect to https://api.parse.com (and others) with.
Eventually (using bsdiff and friends) I figured out that it looks like you built using 0.9.3-patch1 and the fixed libssl.a from http://bbs.espressif.com/viewtopic.php?f=7&t=365
If this is true, it'd be nice to have it in the documents. :)
Thanks!
Hi,
I tried to post in the forums to no avail, also I'm not entirely sure something is broken but here goes. I apologize if this is in the wrong place.
I have espduino flashed on esp01, and arduino nano rev3. I've gotten that combination to work perfectly with restful action, and thingspeak updating. I have also managed to get mqtt to work on the esp01 without an arduino and i've gotten mqtt to work with local clients using cloudmqtt broker.
The problem is i have not managed to get mqtt working with espduino. The debug pins show I connected fine, I use the same script on the readme but when I subscribe I don't see any updated topics.
To confirm the only changes i made are:
!mqtt.begin("DVES_duino", "admin", "Isb_C4OGD4c3", 12
client: I think DVES_duino is client
username: "admin"
password/key (not md5'd?): Isb_C4OGD4c3"
And I changed this:
mqtt.connect("yourserver.com", 1883, false);
Server, port,
false stands for ssl or not ? not sure for that one bug guessed.
Anyway I could have gotten things wrong for sure so wanted to double check and get feedback. Also how can i trigger callbacks or actions on subscribed topic on the arduino from mqtt?
I would really like a way to trigger an action based on something from mqtt parsed. So say a door opened at the entrance triggers a light to turn on an espduino in another room ?
Could somebody elucidate that possibility and thoughts on making that more useable :)..
Any help is much appreciated and thank you for the fantastic esp/duino library. Definitely makes a lot of things possible.
Hey friends,
i got a problem with my MQTT connection. I sent a message through MQTT.fx (desktop client) a message to the topic /network/mode (message: 1). On the Arduino i only get this:
TCP: data received 18 bytes
nothing more... my callback method isnt called by espduino. In my desktop client I get the message normaly. If i try to sent a message to /mode then I get a message and my callback method working normaly...
TCP: data received 11 bytes
Callback method
Received: topic=/mode..
data=1...
I think there is a problem with multiple level in topics?
Does someone has the same problem?
As mqtt broker I use mosquitto (on a unix system).
On Ubuntu 14.10 using the default arduino ide in the repo I got the error:
/home/xxxxx/sketchbook/libraries/espduino/mqtt_msg.h:3:21: fatal error: c_types.h: No such file or directory #include <c_types.h>
Removed the #include <c_types.h> from mqtt_msg.h and now everything compiles fine.
Might be a version or OS issue - not sure but just thought I'd mention it here in case anyone else sees it.
Hello all,
Is there a way to read the esp8266's MAC using this beautiful library??
Hi,
I'm trying to power down the ESP in this great piece of software. Disabling works well, now I'm wondering which steps to take to get the ESP back connected.
I've tried enabling, resetting and connecting the ESP. Can you describe which steps to take?
thanks for helping!
Hi,
I'm trying to get the example work, but it does not get past while(!esp.ready());
line.
MQTT and REST, both examples stop at this line, and on the debug port there's some random gibberish, something like B..aC�^<kp�Wp~v|
just after esp.ready()
call. And I also see small blink of blue LED on ESP module.
I even updated the Arduino lib from pull request posted few hours ago on this repo. Still same result.
Any pointers where I should look for? wiring? baud rate setting?
I've been trying to figure this out for several days with no luck: http://stackoverflow.com/questions/32283135/post-to-flask-from-espduino-timing-out/
I made a simple local server to test the reliability of the espduino. Basically the espduino simply POST
s a number to the server, the server logs the number, and then the number gets incremented. It seems to be working correctly -- the number gets posted and logged with every request.
However, every request also times out (response code 0
in the debug log and takes 5 seconds (default timeout) to complete). I don't understand why this is happening.
I can use the exact same code (and just change the host) and correctly post to Pushover.net (200 response code) or to Requestb.in (200 response code) without any timeouts. I can even start up nginx on my local computer and post to the exact same app as above and get a 200 response code without any timeouts.
However, I've tried both POST
and GET
with a local Python Flask server, with the built-in Python http.server
, with Ruby's built-in httpd
, and with Nodejs http-server
, and all of these time out and get a 0
response code.
I've tried examining everything I can think of down to tcpdump and netcat to try to see why nginx works but all these others won't. Please let me know if you have any suggestions or any idea what is causing the timeouts with everything except nginx.
Hi,
We are trying to use your library for IOT related course project and we have a use case for Persistant client sessions. So when i use your espduino library to subscribe to a topic with QoS >0, it always defaults to 0. Also, we suspect the clean session flag is not getting set to false. These two issues is stopping us from using your library. We tried to debug the code but to no avail. We would appreciate any help regarding the same.
If I understand correctly when TCP send fails the process method will just stop doing anything. Is there some way I could identify this state in the Arduino script so it could try reconnecting?
Hi
Is there a way to change the baud rate at which the arduino and the esp can communicate?
Hi,
Now that it is possible to get an Arduino-compatible IDE with ESP8266 support, I think having an Arduino next to the ESP8266 is becoming less and less a necessity. It would be great if espduino would be compatible with that environment. I don't know how much this is going to be difficult to realize, but this could be a real leap for the ESP8266 as MQTT and REST are pretty much the standards for IoT today.
There are alternatives compatible with the Arduino env like PubSubClient for example, but it lacks some support for QoS (only QoS 0 and 1 for sub, and only QoS 0 for pub) and SSL is not available.
Thanks for your reading.
I have been having problems getting espduino to work reliably with my arduino and esp, and then I just realized that the max input voltages on the ESP are only 3.6V, and the arduino is 5V. Shouldn't your example drawing state that you should use a 3.3V arduino, or you need level shifters?
Hi. Can you tell us if retransmit for QoS1 and QoS2 is supported on this library?
Hi,
I've build two ESP8266 - Arduino pro mini devices. Both identical, running the same code.
One runs just fine. The other runs just fine, but then stops responding after a day or two, until i restart it.
Is there a way for the arduino to check the connection to the wifi / connection to the ESP... and if it is faulty restart the ESP, then the arudino... ?
Hi.
I do have a failry comply sketch making use of a SeedStudio TFT Touch screen, and a bunch of sensors on a mega 2560 using the ESP8266 to publish/subscribe on/from a mosquitto server using mqtt calls.
The code runs for a few seconds/minutes (that is, the mega publish and receive from the bróker with no problem), and at some point hangs.
I did trace the hang to ESP::process; it goes through the default case, write the value onto proto.buf, but does not return,
Sometimes, after several minutes, the process continues (ie, it return to the main loop and run as normal), then stops again after a few seconds/minutes.
I have spend many days trying to understand what happen, but I am stuck at this point. Any clue?
Thank you and have a good day.
Regards,
Carlos
Example:
mqtt.publish("/room1/motion", "ON");
Another mqtt client will receive this data: "ON\0\0" (with two trailing zero characters).
I've been using Tuan's lib with mqtt for a while now with great succes (thanks !!), but now I want to download setting via REST before i setup the mqtt part. When I try to use them both by including both:
#include <mqtt.h>
#include <rest.h>
and using:
MQTT mqtt(&esp);
REST rest(&esp);
in my code i get build errors (the error differs depending on the order i include them so i'm guessing this is a lib code bug)
As this new firmware doesn't work with AT commands, is there any way to get MAC address of this module so I can use it in sketch?
Also, it will be very useful to use mDNS or other ways to find module in network. What are plans for that?
If not, can you point me in the right direction so I can find out how to do it myself?
Hi,
I have been using an arduino + ESP-01 module and wired them as depicted on your github page.
Apparently an arduino sketch has been functional from a couple of days, and when I started it today, I get the following error
TCP: Reconnect to: m11.cloudmqtt.com:17478
DNS: found ip 107.22.157.224
TCP: connecting...
TCP: Reconnect to m11.cloudmqtt.com:17478
Free memory
TCP: Connect to domain m11.cloudmqtt.com:17478
TCP: Reconnect to: m11.cloudmqtt.com:17478
DNS: found ip 107.22.157.224
TCP: connecting...
TCP: Reconnect to m11.cloudmqtt.com:17478
Free memory
TCP: Connect to domain m11.cloudmqtt.com:17478
TCP: Reconnect to: m11.cloudmqtt.com:17478
DNS: found ip 107.22.157.224
TCP: connecting...
TCP: Reconnect to m11.cloudmqtt.com:17478
Free memory
TCP: Connect to domain m11.cloudmqtt.com:17478
TCP: Reconnect to: m11.cloudmqtt.com:17478
DNS: found ip 107.22.157.224
TCP: connecting...
TCP: Reconnect to m11.cloudmqtt.com:17478
I could not figure out why it would do this. Is this because some setting has changed on the broker?
I'm working on a relay that is controlled by MQTT topic. I want to add a fallback state for each relay so that if the connection to the broker is lost the relay will revert to the fallback state. I can do this if the broker actively disconnects via the mqtt.disconnectedCb. What I'm not seeing is a callback if the TCP connection to the broker is lost or if no response is received from the MQTT keepalive.
I'm testing by disabling the network connection on the broker and watching the espduino debug. I see:
MQTT: Send keepalive packet to 10.0.0.1:1883!
MQTT: Sending, type: 12, id: 0000
TCP: Reconnect to 10.0.0.1:1883
Free memory
TCP: Connect to ip 10.0.0.1:1883
TCP: Reconnect to: 10.0.0.1:1883
TCP: Reconnect to 10.0.0.1:1883
I never see a call to the mqtt.disconnectedCb callback. What is the best way to accomplish what I'm trying to do?
Hello,
When I upload software to esp8266 I get an error that is below. Please help me !!!.
pi@raspberrypi /usr/share/arduino/libraries/espduino $ sudo esp8266/tools/esptool.py -p /dev/ttyUSB0 write_flash 0x00000 esp8266/release/0x00000.bin 0x40000 esp8266/release/0x40000.bin
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to [:<exec_prefix>]
Traceback (most recent call last):
File "esp8266/tools/esptool.py", line 22, in
import serial
ImportError: No module named serial
Hi, recently I tried to use this project for communicating with a rest api. I downloaded the library and loaded the example but something is wrong. The arduino compiler says:
libraries\espduino/rest.h:30:3: error: 'ESP' does not name a type ESP *esp;
It also says:
libraries\espduino/rest.h:38:12: error: expected ')' before '*' token REST(ESP *e);
I didn't make any changes in the library or what so ever. Just downloaded it, restarted arduino. Imported the library and copy+pasted the sketch.
Someone has a clue what's going on?
Thanks in advance,
Jan Paul
Hi, (complete newbie here), I've flashed ESPduino on my ESP8266 and uploaded a slightly modified version of the MQTT client with a config file. The serial monitor off the FTDI is showing a looping connected/disconnected after what appears to be a successful setup.
I'm trying to simply pull down the state of a toggle from Adafruit.io but regardless of what I put into the MQTT_SUBSCRIBED_TOPIC nothing shows up on the serial monitor.
Have I put all the correct constants in the correct places? (I can't seem to decipher where the mqtt.connect and mqtt.disconnect's being called from; I tried looking around into the esp.process() as it is the only thing called in the loop() but quickly was dumbfounded.
Any ideas or good guides/tutorials/documentation for ESPduino help?
@tuanpmt first nice work and thank you for library! This is more of a question / feature request than an issue, per se.
I'm trying to use the REST module to download a large file (a few hundred kilobytes) by modifying the rest example to do: rest.get("/test.hex");
in loop
. Printed to the debug console I get ARDUINO: Invalid CRC
each time through loop
. I'm not sure why that is happening, perhaps the rest module is not intended to be used as an arbitrary HTTP client accessing a path. Using the ESP8266 AT software, it works fine.
That aside, if I do rest.get("/test.hex");
in loop
and the length of my response is longer than the buffer passed to getResponse
I only get the part of the data that fits in my buffer (which is great, because buffer overruns are a curse). However, it would be very nice if there were a way to progressively download the entire contents in a progressive manner. Again using the ESP8266 AT software, it works fine.
The use case would be when I know I can't store the entire contents of a download in RAM, but I can buffer chunks in RAM and write them off to an external memory like an SD card of SPI Flash.
So what do you think? Can it be implemented easily? Is it already implemented and I just don't know how to exercise the implementation? Thanks again!
Can someone please help.
I am getting garbage after esp.ready()
Output:
ARDUINO: Starting Device
ARDUINO: Waiting for ESP!!!
�_�â‚�º[ØÐ�PŠþ�X¹a‚ç·â�Ìþ�8��+ˆ�¢·A¢Ãâ�ª��šF¢ª�Â�«PT"p©ÅS0Ø���8
Code Sample:
`
SoftwareSerial espPort(9, 10); // RX, TX
ESP esp(&espPort, &Serial, esp8266reset);
MQTT mqtt(&esp);
boolean wifiConnected = false;
.
.
.
.
.
.
void setup() {
Serial.begin(19200);
espPort.begin(19200);
Serial.println("ARDUINO: Starting Device");
esp.enable();
delay(500);
esp.reset();
delay(500);
delay(1000);
Serial.println("ARDUINO: Waiting for ESP!!!");
while(!esp.ready());
Serial.println("ARDUINO: ESP is Ready");
`
With espduino library, how do I get the values of ChipID, FlashID and other hardware related data? This is useful to assign station id and some other scenarios.
Something similar to https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en#nodechipid
What is required to make it work with Arduino Leonardo (ATMega 32U4) ?
I am using the tuanpmt code & libraries to run an Arduino multi sensor to send mqtt messages through a ESP8266 (Bridge Mode)
The code below runs ok, but the trouble is that it only publishes the message ONCE....(after a certain amount of time, it debugs a "beacon timeout" and it starts to connect and publish again)
I would like to publish maybe each 10 seconds, and keeping alive the Wifi Connection
I don't know exactly how to call the publish method from the loop?, or to stablish a period of time to run this cycle until the arduino is reseted
Could you help me giving me some clues or help?
thanks in advance from Spain.
`
/**
ESP8266 MQTT Bridge example
Tuan PM [email protected]
SoftwareSerial debugPort(2, 3); // RX, TX
ESP esp(&Serial, &debugPort, 4);
MQTT mqtt(&esp);
boolean wifiConnected = false;
void wifiCb(void* response)
{
uint32_t status;
RESPONSE res(response);
if(res.getArgc() == 1) {
res.popArgs((uint8_t_)&status, 4);
if(status == STATION_GOT_IP) {
debugPort.println("WIFI CONNECTED");
mqtt.connect("1.0.1.1", 1883);
//mqtt.connect("1.0.1.1", 1883, false);
wifiConnected = true;
//or mqtt.connect("host", 1883); /_without security ssl*/
} else {
wifiConnected = false;
mqtt.disconnect();
}
}
}
void mqttConnected(void* response)
{
debugPort.println("Connected");
//mqtt.subscribe("/topic/0"); //or mqtt.subscribe("topic"); /with qos = 0/
//mqtt.subscribe("/topic/1");
//mqtt.subscribe("/topic/2");
mqtt.publish("/test01", "ASDFG 313");
}
void mqttDisconnected(void* response)
{
}
void mqttData(void* response)
{
RESPONSE res(response);
debugPort.print("Received: topic=");
String topic = res.popString();
debugPort.println(topic);
debugPort.print("data=");
String data = res.popString();
debugPort.println(data);
}
void mqttPublished(void* response)
{
}
void setup() {
Serial.begin(19200);
debugPort.begin(19200);
esp.enable();
delay(500);
esp.reset();
delay(500);
while(!esp.ready());
debugPort.println("ARDUINO: setup mqtt client");
if(!mqtt.begin("UNIT01", NULL, NULL, 120, 1)) {
debugPort.println("ARDUINO: fail to setup mqtt");
while(1);
}
debugPort.println("ARDUINO: setup mqtt lwt");
mqtt.lwt("/lwt", "offline", 0, 0); //or mqtt.lwt("/lwt", "offline");
/*setup mqtt events */
mqtt.connectedCb.attach(&mqttConnected);
mqtt.disconnectedCb.attach(&mqttDisconnected);
mqtt.publishedCb.attach(&mqttPublished);
mqtt.dataCb.attach(&mqttData);
/setup wifi/
debugPort.println("ARDUINO: setup wifi");
esp.wifiCb.attach(&wifiCb);
esp.wifiConnect("SSID","password");
debugPort.println("ARDUINO: system started");
}
void loop() {
esp.process();
if (wifiConnected){
}
}
`
I have been working with this wonderful library.
in my latest project i am trying to send a "RFID number" using esp8266.
I am getting the error "malloc assert!" in my serial window of arduino.
The sequence of events shown in my serial monitor of arduino are as follows:
"ARDUINO: setup wifi
ARDUINO: system started
scandone
add 0
aid 7
pm open phy2,type:2 0 0
cnip:192.168.10.108,mask:255.255.255.0,gw:192.168.10.1
CONNECTED TO WIFI NETWORK
mqtt Connected Successfully
null
malloc assert!"
for all other programs that i have done, i have not encountered this issue. So, i can say its because of RFID that i might be getting this problem.
My question is, is this the issue with esp8266 or the library? because, i am unable to find "malloc assert!" sentence anywhere in the mqtt library.
sorry for the long question. Hope anyone can help me out! Thanks in advance..
Hello all,
I encounter some problem to use espduino library ...
I flash my ESP8266 with your espduino in debug mode, like it's written in the README. I don't know how to check if it's correct and if the ESP8266 boot correctly ?
I download your MQTT example, change some variables (internet and mqtt settings, things like that !), and try it : the "esp.ready()" function always return "0" ... I don't know why ?
For information, i try with 19200 baud, but also with 115200 baud, because before with AT firmware, I can't talk with my ESP8266 without put 115200 baud instead of only 9600. Still blocked ...
Can you help me ? I really wan't/need to have a good MQTT library on my arduino for my project ... And your library is apparently the best !
Hi
Thanks for the nice port and coding!
Unfortunately i've got a crash, the code is waiting indefinitly for a callback...
Perhaps you guys can pinpoint me in the right direction?
the debug output:
MD: 1, cb: 0, ret: 0, argc: 0
Read CRC: 8555, calculated crc:ú(cÖ�¼��6a����a��Ñ):X $ $�Ö��eH)i�ÿJ�ôþ!ÿ�mode : sta(18:fe:34:9d:f1:e5)
add if0
CMD: 2, cb: 0, ret: 1, argc: 0
Read CRC: 0690, calculated crc: 0690
CMD: Check ready
CMD: Response return value: 1, cmd: 2
ARDUINO: setup mqtt client
CMD: 4, cb: 0, ret: 1, argc: 9
Arg[0], len: 8:45-53-50-38-32-36-36-00-
Arg[1], len: 8:61-64-6D-69-6E-00-00-00-
Arg[2], len: 4:31-32-33-34-
Arg[3], len: 4:0A-00-00-00-
Arg[4], len: 4:01-00-00-00-
Arg[5], len: 4:6A-05-00-00-
Arg[6], len: 4:70-05-00-00-
Arg[7], len: 4:76-05-00-00-
Arg[8], len: 4:7C-05-00-00-
Read CRC: 9976, calculated crc: 9976
MQTT: clientid = ESP8266, user = admin, pass = 1234, keepalive = 10, session = 1
MQTT_InitClient
CMD: Response return value: 1073687384, cmd: 4
ARDUINO: setup mqtt lwt
CMD: 9, cb: 0, ret: 1, argc: 5
Arg[0], len: 4:58-2B-FF-3F-
Arg[1], len: 4:2F-6C-77-74-
Arg[2], len: 8:6F-66-66-6C-69-6E-65-00-
Arg[3], len: 4:00-00-00-00-
Arg[4], len: 4:00-00-00-00-
Read CRC: AF54, calculated crc: AF54
MQTT: lwt client addr = 1073687384
MQTT: lwt topic = /lwt, message = offline, qos = 0, retain = 0
CMD: Response return value: 1, cmd: 9
ARDUINO: setup wifi
ARDUINO: system started
Dht Sensor Started
CMD: 3, cb: 842, ret: 0, argc: 2
Arg[0], len: 8:67-61-73-74-32-5F-34-00-
Arg[1], len: 16:76-69-6E-63-65-6E-74-64-65-67-65-6B-73-74-65-00-
Read CRC: 23C2, calculated crc: 23C2
WIFI_INIT
WIFI: set ssid = gast2_4, pass= 1234
STATION_IDLE
CMD: 6, cb: 0, ret: 0, argc: 1
Arg[0], len: 4:58-2B-FF-3F-
Read CRC: BF84, calculated crc: BF84
scandone
STATION_IDLE
add 0
aid 1
pm open phy_2,type:2 0 0
cnt
connected with gast2_4, channel 9
dhcp client start...
STATION_IDLE
STATION_IDLE
ip:192.168.1.101,mask:255.255.255.0,gw:192.168.1.1
WIFI CONNECTED
CMD: 5, cb: 0, ret: 0, argc: 4
Arg[0], len: 4:58-2B-FF-3F-
1:1883
MTT: Sending type: 1, i: 0000
TCP: Sent
TCP: data received 4 bytes
MQTT: Connected to 192.168.1.131:1883
MQTT: Connected
Callback data: 1386, 1392, 1398, 1404
after this point, the arduino doesn't print anything to the debug output, nor is my blinking action showing.
The code is used:
#include <SoftwareSerial.h>
#include <espduino.h>
#include <mqtt.h>
#include <avr/wdt.h>
#include <RemoteTransmitter.h>
//#include <VirtualWire.h>
#include "DHT.h"
#define DHTTYPE DHT11 // DHT 11
#define PIN_TX A1
#define PIN_LDR A0
#define PIN_DHT 4
#define LED 13
//
// Putting on light 1: 31,A,01 -> 1F 41 01
//
//Transmitter stuff
ElroTransmitter elroTransmitter(PIN_TX);
ActionTransmitter actionTransmitter(PIN_TX);
KaKuTransmitter kaKuTransmitter(PIN_TX);
BlokkerTransmitter blokkerTransmitter(PIN_TX);
//DHT / TEMP stuff
DHT dht(PIN_DHT, DHTTYPE);
int temperature;
int humidity;
int light;
long lastMillis = millis();
long lastBlink = millis();
int lastUpdated = 0;
SoftwareSerial debugPort(2, 3); // RX, TX
ESP esp(&Serial, &debugPort, 4);
MQTT mqtt(&esp);
boolean wifiConnected = false;
boolean _mqttConnected = false;
void wifiCb(void* response)
{
uint32_t status;
RESPONSE res(response);
if(res.getArgc() == 1) {
res.popArgs((uint8_t*)&status, 4);
if(status == STATION_GOT_IP) {
debugPort.println("WIFI CONNECTED");
mqtt.connect("192.168.1.131", 1883, false);
wifiConnected = true;
//or mqtt.connect("host", 1883); /*without security ssl*/
}
else {
wifiConnected = false;
mqtt.disconnect();
}
}
}
void mqttConnected(void* response)
{
debugPort.println("Connected");
mqtt.subscribe("/remote/elro");
mqtt.subscribe("/topic/0"); //or mqtt.subscribe("topic"); /*with qos = 0*/
mqtt.subscribe("/topic/1");
mqtt.subscribe("/topic/2");
mqtt.publish("/topic/0", "data0");
publishInt("/hub/init", 1234);
_mqttConnected = true;
debugPort.println(":) :) :) connected");
}
void mqttDisconnected(void* response)
{
_mqttConnected = false;
debugPort.println("!!!ERROR, disconnected");
}
void mqttData(void* response)
{
RESPONSE res(response);
debugPort.print("Received: topic=");
String topic = res.popString();
debugPort.println(topic);
debugPort.print("data=");
String data = res.popString();
debugPort.println(data);
if(topic== "/remote/elro"){
handleElro(data);
}
}
void mqttPublished(void* response)
{
}
void handleElro(String cmd){
int code = getValue(cmd, ',', 0).toInt();
char device = getValue(cmd, ',', 1)[0];
int state = getValue(cmd, ',', 2).toInt();
//elro needs systemcode (numerical), device (upper char), and boolean
debugPort.println("sending");
debugPort.println(code,DEC);
debugPort.println(device);
debugPort.println(state);
elroTransmitter.sendSignal(code, device, state);
}
void setup() {
Serial.begin(19200);
debugPort.begin(19200);
debugPort.println("Setup..");
;
// vw_set_tx_pin(PIN_TX);
// vw_set_ptt_inverted(true); // Required for DR3100
// vw_setup(2000); // Bits per sec
debugPort.println("VirtualWire stared");
esp.enable();
delay(500);
esp.reset();
delay(500);
while(!esp.ready());
debugPort.println("ARDUINO: setup mqtt client");
if(!mqtt.begin("ESP8266", "admin", "1234", 10, 1)) {
debugPort.println("ARDUINO: fail to setup mqtt");
while(1);
}
debugPort.println("ARDUINO: setup mqtt lwt");
mqtt.lwt("/lwt", "offline", 0, 0); //or mqtt.lwt("/lwt", "offline");
/*setup mqtt events */
mqtt.connectedCb.attach(&mqttConnected);
mqtt.disconnectedCb.attach(&mqttDisconnected);
mqtt.publishedCb.attach(&mqttPublished);
mqtt.dataCb.attach(&mqttData);
/*setup wifi*/
debugPort.println("ARDUINO: setup wifi");
esp.wifiCb.attach(&wifiCb);
esp.wifiConnect("gast2_4","vincentdegekste");
debugPort.println("ARDUINO: system started");
//start DHT sensor
dht.begin();
debugPort.println("Dht Sensor Started");
}
void publishInt(const char* key, int data){
char t[5];
String t1;
t1 = String(data);
t1.toCharArray(t, 5);
mqtt.publish(key, t);
}
void loop() {
blinker();
esp.process();
if(wifiConnected) {
light = analogRead(PIN_LDR);
humidity = dht.readHumidity();
temperature = dht.readTemperature();
if(millis() - lastMillis >= 10000){
mqtt.publish("/hub/ping", "a");
if(_mqttConnected){
// debugPort.print("=====");
// debugPort.print(millis(),DEC);
// debugPort.println("=====");
switch(lastUpdated){
case 0:
publishInt("/hub/light", light);
// debugPort.print("light:" );
// debugPort.println(light, DEC);
break;
case 1:
publishInt("/hub/temperature", temperature);
// debugPort.print("temperature:" );
// debugPort.println(temperature, DEC);
break;
case 2:
publishInt("/hub/humidity", humidity);
// debugPort.print("humidity:" );
// debugPort.println(humidity, DEC);
break;
case 3:
// publishInt("/hub/ping", millis());
break;
}
lastUpdated++;
if (lastUpdated > 3)
lastUpdated = 0;
}
lastMillis = millis();
}
}
}
void blinker(){
if(!wifiConnected){
if(millis() - lastBlink >= 100){
digitalWrite(LED, !digitalRead(LED));
lastBlink = millis();
}
}
else if(!_mqttConnected){
if(millis() - lastBlink >= 250){
digitalWrite(LED, !digitalRead(LED));
lastBlink = millis();
}
}
else{
//running 'stable'
if(millis() - lastBlink >= 750){
digitalWrite(LED, !digitalRead(LED));
lastBlink = millis();
}
}
}
//
// Helper stuff
//
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {
0, -1 };
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
Cheers!
I have a ESP-01, do I need to flash it with the new firmware to make espduino work? I don't have a USB-Serial converter and was wondering this flashing can be done using an Arduino.
Hi I was trying to work the code with arduino mega. The only change I did was use Hardware serial3 instead of software serial on pins 2 and 3. However when I run the code I keep getting the following error:
ARDUINO: Invalid CRC in a loop. From what I could understand the program is getting stuck at esp.ready function(). What does this mean and how can I correct this error.
Tried with pushbullet example with AT command, but failed. then tried with browser and got to know pushbullet doesn't support http. so what to do? I had posted data to at&t cloud via at command.but pushbullet is creating problem.
Thanks @tuanpmt, for make this work well with esp8266 MQTT.
I'm looking to make softap when first connect to wifi uno. It will create a webserver to getting ssid, pass word and write to EEPROM on uno.
It look like now espduino only have an api for MQTT and clientTCP right?
If I want to do this thing I need to edit esp_bridge right?
Thanks.
There is some bug in ESP library. When I setup TLS connection to Mosquitto it starts to generate this log:
error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number.
After forced TLS 1.1 everything works OK.
Thanks for help
I try to publish the data that received back to the broker but it seem like it loop multiple my publish data.
I test code like this.
void mqttData(void* response)
{
RESPONSE res(response);
debugPort.print("Received: topic=");
String topic = res.popString();
debugPort.println(topic);
debugPort.print("data=");
String data = res.popString();
debugPort.println(data);
mqtt.publish("test", "test");
char buffTopic[64], buffPayload[64];
topic.toCharArray(buffTopic, topic.length() + 1);
data.toCharArray(buffPayload, data.length() + 1);
mqtt.publish((const char*)buffTopic, (char*)buffPayload);
}
as expected it should send data to broker like.
olddata
test
but I got a lot of data like this.
olddata
test
olddata
test
olddata
test
olddata
test
olddata
test
What I'm wrong or this is a bug?
Hi,
I'm trying to use https rest api with different servers: with a lot of server doesn't works infact
rest.getResponse returns 0
For example connecting using https with github.com it doesn't work...some ideas or help?
Thank you
Sergio
Setting headers works well, but changing the user agent seems to have no effect.
I'm not sure if this is a bug with esp_bridge or just the particular version compiled and included here.
Hi
I'm wondering is is possible to use SS for esp connection?
hi ,
I have a problem with the first example of MQTT client , I did everything according to the debugging scheme, however esp8266 lights when part Arduino and turns off immediately after flashing blue LED , only if I unplug the d4 from Arduino esp8266 stays on .
if I leave the d4 connected , debugging gives me this :
\0xc4\0x1c\0x12aA\0x9a\0xde9\0x97\0xcd\0x11S\0xf0\0xdekcAO\0xc4\0xe3\0x97\0xc6\0xdb\0x9c\0xd5\0x17\0xc1\0x94]\0x13\0xda\0xb1\0x94\0xd8/CNAu\0xc1\0xdb8\0xd5\0x8a\0xd3^\0x10\0xf0\0x14B\0x91\0xe2\0x13\0xf8\0xdb8\0xd5\0x8a\0xff\0x85\0xd8\0x91
what can I do?
thank you
Usually the following code hangs. Has anyone done this successfully?
it is a stripped out code so there might be some mistake but presenting here for understanding.
void mqttData(void* response)
{
RESPONSE res(response);
String topic = res.popString();
String data = res.popString();
//Serial.println(topic + "::" + data);
parseData(data);
}
void parseData(String payload) {
//Parse the payload and prepare a response
String topicString = "/ResponseTopic";
char topic[topicString.length() + 1];
topicString.toCharArray(topic, topicString.length() + 1);
char char_array[payload.length() + 1];
payload.toCharArray(char_array, payload.length() + 1);
const char * c = topicString.c_str();
mqtt.publish(c, char_array);
}
Hi Tuan
I am using your ESP8266 firmware with your mqtt library on Arduino Nano. Using a modified version of the example program (see below), I can send and receive individual messages OK.
However, when I try to receive five messages that have been sent in quick succession from another client program, only the first two are received. Then I see the following debug message and the program hangs.
Get another published message
TCP: data received 114 bytes
Checking the messages at the same time using MQTT.fx client, I can see that all five messages are received OK.
Any idea what the cause might be?
Thanks
Ray
#include <myPushSwitch.h>
#define SWITCH_PIN 8
PushSwitch testSwitch(SWITCH_PIN, INPUT_PULLUP, LOW, false); // Enable internal pullup; use default debounce time; wait for double press
switchEvent sEvent;
#include<SoftwareSerial.h>
#include <espduino.h>
#include <mqtt.h>
SoftwareSerial debugPort(2, 3); // RX, TX
ESP esp(&Serial, &debugPort, 4);
MQTT mqtt(&esp);
boolean wifiConnected = false;
boolean mqttIsConnected = false;
boolean sentFirstMQTT = false;
#define BUFFER_SIZE 50
char buffer[BUFFER_SIZE];
void wifiCb(void* response)
{
uint32_t status;
RESPONSE res(response);
if (res.getArgc() == 1)
{
res.popArgs((uint8_t*)&status, 4);
if (status == STATION_GOT_IP)
{
debugPort.println(F("WIFI CONNECTED"));
wifiConnected = true;
mqtt.connect("hackscribble.ddns.net", 1883, false);
}
else
{
debugPort.println(F("WIFI NOT CONNECTED"));
wifiConnected = false;
mqtt.disconnect();
}
}
}
void mqttConnected(void* response)
{
debugPort.println(F("MQTT CONNECTED"));
mqtt.subscribe("hackscribble/controls/query");
mqtt.subscribe("hackscribble/controls/led");
mqtt.subscribe("hackscribble/controls/pwm");
mqttIsConnected = true;
}
void mqttDisconnected(void* response)
{
}
void mqttData(void* response)
{
RESPONSE res(response);
debugPort.print(F("Received: topic="));
String topic = res.popString();
debugPort.println(topic);
debugPort.print(F("data="));
String data = res.popString();
debugPort.println(data);
topic.toCharArray(buffer, BUFFER_SIZE);
if (strstr(buffer, "controls/query"))
{
reportSwitchState();
}
if (strstr(buffer, "controls/led"))
{
data.toCharArray(buffer, BUFFER_SIZE);
if (strstr(buffer, "true"))
{
digitalWrite(13, HIGH);
}
else if (strstr(buffer, "false"))
{
digitalWrite(13, LOW);
}
}
}
void mqttPublished(void* response)
{
}
void reportSwitchState()
{
if (testSwitch.read() == switchWasPressed)
{
mqtt.publish("hackscribble/controls/switch", "closed");
}
else if (testSwitch.read() == switchWasReleased)
{
mqtt.publish("hackscribble/controls/switch", "open");
}
}
void setup()
{
Serial.begin(19200);
debugPort.begin(19200);
debugPort.println(F("ARDUINO: running test-mqtt\r\n\n"));
pinMode(13, OUTPUT);
testSwitch.begin();
sEvent = testSwitch.update();
esp.enable();
delay(500);
esp.reset();
delay(500);
while (!esp.ready())
{
// empty
}
debugPort.println(F("ARDUINO: setting up mqtt client"));
if (!mqtt.begin("ESP8266", "hackscribble", "hackscribble", 120, 1))
{
debugPort.println("ARDUINO: fail to setup mqtt");
while (1);
}
debugPort.println(F("ARDUINO: setting up mqtt lwt"));
mqtt.lwt("/lwt", "offline", 0, 0);
/*setup mqtt events */
mqtt.connectedCb.attach(&mqttConnected);
mqtt.disconnectedCb.attach(&mqttDisconnected);
mqtt.publishedCb.attach(&mqttPublished);
mqtt.dataCb.attach(&mqttData);
/*setup wifi*/
debugPort.println(F("ARDUINO: setting up wifi"));
esp.wifiCb.attach(&wifiCb);
esp.wifiConnect("<snip>", "<snip>");
debugPort.println(F("ARDUINO: system started"));
}
void loop()
{
esp.process();
if (wifiConnected)
{
// empty
}
if (mqttIsConnected)
{
if (!sentFirstMQTT)
{
mqtt.publish("hackscribble/controls/status", "ESP8266 is connected");
sentFirstMQTT = true;
}
}
sEvent = testSwitch.update();
if ((sEvent != switchNoChange) && mqttIsConnected)
{
reportSwitchState();
}
}
After update your ESP8266 Firmware, AT Commands are not working.
Actually I want to start web server, For that I use the following commands
AT+CIPSERVER=1,80 and AT+CWJAP.......
But now these commands are not working.
Pls help me in this...
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.