Related
For a project I am working on a mesh network on ESP32 (devkit).
I'm using the https://gitlab.com/painlessMesh/painlessMesh library for this to work.
The data received by the other ESP32's need to be sended to an REST API on Home Assistent with adres: http://192.168.1.4:8123/api/states/sensor.mesh.
To to this I am using the https://www.arduino.cc/reference/en/libraries/http/ library to send these HTTP requests.
This is my code:
#include <painlessMesh.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#define MESH_PREFIX "MeshNetwork"
#define MESH_PASSWORD "MeshPassword"
#define MESH_PORT 5555
const char* ssid_wifi = "<wifissid>";
const char* password_wifi = "<wifipassword>";
painlessMesh mesh;
Scheduler userScheduler;
void receivedCallback( uint32_t from, String &msg ) {
Serial.printf("Received from %u msg=%s\n", from, msg.c_str());
// Send To Home Assistent
Serial.printf("Node %u sends to HA....\n", from);
WiFiClient client;
HTTPClient http;
String serverName = "http://192.168.1.4:8123/api/states/sensor.mesh";
http.begin(client, serverName);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Bearer <TOKEN>");
String httpRequestData = "{\"state\":"+ String(random(0,30));
Serial.println(httpRequestData + ", \"attributes\": {\"unit_of_measurement\": \"°C\"}}");
int httpResponseCode = http.POST(httpRequestData + ", \"attributes\": {\"unit_of_measurement\": \"°C\"}}");
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
void newConnectionCallback(uint32_t nodeId) {
Serial.printf("startHere: New Connection found!, nodeId = %u\n", nodeId);
}
void changedConnectionCallback() {
Serial.printf("Changed connections\n");
}
void nodeTimeAdjustedCallback(int32_t offset) {
Serial.printf("Adjusted time %u. Offset = %d\n", mesh.getNodeTime(),offset);
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid_wifi, password_wifi);
Serial.printf("\n Connecting to Wifi: %s", ssid_wifi);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n Connected to Wifi! \n ");
// start Mesh Network
mesh.setDebugMsgTypes(ERROR | MESH_STATUS | CONNECTION | SYNC | COMMUNICATION | GENERAL | MSG_TYPES | REMOTE );
mesh.init( MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT);
// Set Root Node
mesh.setContainsRoot(true);
// Mesh Events
mesh.onReceive(&receivedCallback);
mesh.onNewConnection(&newConnectionCallback);
mesh.onChangedConnections(&changedConnectionCallback);
mesh.onNodeTimeAdjusted(&nodeTimeAdjustedCallback);
}
void loop() {
mesh.update();
}
When the data is sending it gives me the following error
[E][WiFiClient.cpp:258] connect(): socket error on fd 61, errno: 113, "Software caused connection abort"
HTTP Response code: -1
I don't know what to do know,I have tried a lot of things.
Can anybody help me?
Thanks!
Update: When requesting the HTTP POST in the setup() it works. Not in the loop()
I am using the WiFiSecureClient example n arduino studio. I first ran the example on my ESP 32 cam with the website howsmyssl and it works.
Then I created and hosted my own nodejs app on a domain and generated a letsencrypt certificate for it so all requests are directed to ssl.
I than exported the certificate from google chrome and changed the howsmyssl certificate to my own site's certificate.
The problem is that it does not connect and I get the message connection failed in the serial monitor.
Here is my code,
Essentially its the same code as in the example but for some reason the server is not connecting. Would appreciate any advise on how to debug/correct this.:
/*
Wifi secure connection example for ESP32
Running on TLS 1.2 using mbedTLS
Suporting the following chipersuites:
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_CCM","TLS_DHE_RSA_WITH_AES_256_CCM","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8","TLS_DHE_RSA_WITH_AES_256_CCM_8","TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","TLS_DHE_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CCM","TLS_DHE_RSA_WITH_AES_128_CCM","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA","TLS_DHE_RSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8","TLS_DHE_RSA_WITH_AES_128_CCM_8","TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA","TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA","TLS_DHE_PSK_WITH_AES_256_GCM_SHA384","TLS_DHE_PSK_WITH_AES_256_CCM","TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384","TLS_DHE_PSK_WITH_AES_256_CBC_SHA384","TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA","TLS_DHE_PSK_WITH_AES_256_CBC_SHA","TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_PSK_DHE_WITH_AES_256_CCM_8","TLS_DHE_PSK_WITH_AES_128_GCM_SHA256","TLS_DHE_PSK_WITH_AES_128_CCM","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256","TLS_DHE_PSK_WITH_AES_128_CBC_SHA256","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA","TLS_DHE_PSK_WITH_AES_128_CBC_SHA","TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_PSK_DHE_WITH_AES_128_CCM_8","TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA","TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA","TLS_RSA_WITH_AES_256_GCM_SHA384","TLS_RSA_WITH_AES_256_CCM","TLS_RSA_WITH_AES_256_CBC_SHA256","TLS_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA","TLS_RSA_WITH_AES_256_CCM_8","TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA","TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_RSA_WITH_AES_128_GCM_SHA256","TLS_RSA_WITH_AES_128_CCM","TLS_RSA_WITH_AES_128_CBC_SHA256","TLS_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA","TLS_RSA_WITH_AES_128_CCM_8","TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA","TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_RSA_PSK_WITH_AES_256_GCM_SHA384","TLS_RSA_PSK_WITH_AES_256_CBC_SHA384","TLS_RSA_PSK_WITH_AES_256_CBC_SHA","TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_RSA_PSK_WITH_AES_128_GCM_SHA256","TLS_RSA_PSK_WITH_AES_128_CBC_SHA256","TLS_RSA_PSK_WITH_AES_128_CBC_SHA","TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA","TLS_PSK_WITH_AES_256_GCM_SHA384","TLS_PSK_WITH_AES_256_CCM","TLS_PSK_WITH_AES_256_CBC_SHA384","TLS_PSK_WITH_AES_256_CBC_SHA","TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_PSK_WITH_AES_256_CCM_8","TLS_PSK_WITH_AES_128_GCM_SHA256","TLS_PSK_WITH_AES_128_CCM","TLS_PSK_WITH_AES_128_CBC_SHA256","TLS_PSK_WITH_AES_128_CBC_SHA","TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_PSK_WITH_AES_128_CCM_8","TLS_PSK_WITH_3DES_EDE_CBC_SHA","TLS_EMPTY_RENEGOTIATION_INFO_SCSV"]
2017 - Evandro Copercini - Apache 2.0 License.
*/
#include <WiFiClientSecure.h>
const char* ssid = "myap"; // your network SSID (name of wifi network)
const char* password = "mypass"; // your network password
const char* server = "growgreen.life"; // Server URL
// www.howsmyssl.com root certificate authority, to verify the server
// change it to your server root CA
// SHA1 fingerprint is broken now!
const char* test_root_ca= \
"-----BEGIN CERTIFICATE-----\n" \
"MIIFNTCCBB2gAwIBAgISA923aMjf7A21sbQ131UqqWdiMA0GCSqGSIb3DQEBCwUA\n" \
"MDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD\n" \
"EwJSMzAeFw0yMTA3MTIwNTI3MzJaFw0yMTEwMTAwNTI3MzFaMBkxFzAVBgNVBAMT\n" \
"Dmdyb3dncmVlbi5saWZlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\n" \
"ocNfRneLCVSsl6ZOHaQQ9wQqtEjfuX/rn625xP/VWmikNlPkFrhP6Hm5HbXkpMSB\n" \
"+vGX3ms6tjoIWgipeusHo3shz+RsqVDGpfdxsNbKApHL8JxaIWjYaAlJDfw7SPOP\n" \
"lv+wqJXR7it83l5DuPrgu2jxbmDgrWdWbbXJYTs2kLbMANIMplYgHua3wGSovpGt\n" \
"PcK8LeohsEJk1cntqtcaznJFxA6s54hKtv/L03WgkNUlONX2BWrwv/OBsGkCN123\n" \
"5JmZ7iyocjaH6x5ixp7ULAtPKpsI5OQ+2zcgQIBRxLW3Tv4rBF0p7JAXlJHjuAqH\n" \
"52LW8pySppIeLsR+FM6O+wIDAQABo4ICXDCCAlgwDgYDVR0PAQH/BAQDAgWgMB0G\n" \
"A1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMB0GA1Ud\n" \
"DgQWBBT9KWvWs7GmeyfSgnS/eWMmku/5sTAfBgNVHSMEGDAWgBQULrMXt1hWy65Q\n" \
"CUDmH6+dixTCxjBVBggrBgEFBQcBAQRJMEcwIQYIKwYBBQUHMAGGFWh0dHA6Ly9y\n" \
"My5vLmxlbmNyLm9yZzAiBggrBgEFBQcwAoYWaHR0cDovL3IzLmkubGVuY3Iub3Jn\n" \
"LzAtBgNVHREEJjAkgg5ncm93Z3JlZW4ubGlmZYISd3d3Lmdyb3dncmVlbi5saWZl\n" \
"MEwGA1UdIARFMEMwCAYGZ4EMAQIBMDcGCysGAQQBgt8TAQEBMCgwJgYIKwYBBQUH\n" \
"AgEWGmh0dHA6Ly9jcHMubGV0c2VuY3J5cHQub3JnMIIBAwYKKwYBBAHWeQIEAgSB\n" \
"9ASB8QDvAHUARJRlLrDuzq/EQAfYqP4owNrmgr7YyzG1P9MzlrW2gagAAAF6mWY+\n" \
"9QAABAMARjBEAiAhHEeGYKpneNn2/GnYzvgXtflgAap8sRpzzu5h123/YwIgQ0jb\n" \
"xgImVVDW2usWjENjmgnIUYk4W03p8AdyuKchtgsAdgD2XJQv0XcwIhRUGAgwlFaO\n" \
"400TGTO/3wwvIAvMTvFk4wAAAXqZZj7vAAAEAwBHMEUCIQCIMPL8yUXTwl9dFvsT\n" \
"Fy+WKRlPEImFQiiNYkyAXUmFLgIgJlTi2679ZvYIlLUq4wS/CXJHsYIzFI6qILfu\n" \
"V+7d0BIwDQYJKoZIhvcNAQELBQADggEBAKOXihmS7Byw5Q4cYXbVmqFZqLuXJod5\n" \
"1GZYIfsfmeH6By93Hjlqcm58L5/DLNA6Yfqnu9mmWrAPd0MYz7PGvlxzDbN/ggGK\n" \
"fD0PjwuREln5vgHXKOysYCJ7ho58g9DN4mkS2679FD2WiYXMpntYQtQP24noIaw1\n" \
"DmeS8h6xXQcDIEVVWki9Rst/S3dvI/LQUaQ0UCe8EeDbrYgKj9eMZH32ENqcb5NE\n" \
"LikNcXQpl/cgAbb3xczFAMBL7Vo8QxAM9bMiyfp58zh0bcFJkH9bNDEQ9uQdkHTP\n" \
"nukplj5DC7V5+FHPyBvTdUCRTPKf9cjHEvbCLCMicCMbeCjZ69cYhSo=\n" \
"-----END CERTIFICATE-----\n";
// You can use x.509 client certificates if you want
//const char* test_client_key = ""; //to verify the client
//const char* test_client_cert = ""; //to verify the client
WiFiClientSecure client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
delay(100);
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
// attempt to connect to Wifi network:
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
// wait 1 second for re-trying
delay(1000);
}
Serial.print("Connected to ");
Serial.println(ssid);
client.setCACert(test_root_ca);
//client.setCertificate(test_client_key); // for client verification
//client.setPrivateKey(test_client_cert); // for client verification
Serial.println("\nStarting connection to server...");
if (!client.connect(server, 443))
Serial.println("Connection failed!");
else {
Serial.println("Connected to server!");
// Make a HTTP request:
client.println("GET https://growgreen.life");
client.println("Host: growgreen.life");
client.println("Connection: close");
client.println();
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
client.stop();
}
}
void loop() {
// do nothing
}
I changed the leaf certificate with the root certificate and now I am able to connect to the server. But for some reason I am getting the bad request 400 response...following is the response in the serial monitor:
Starting connection to server...
Connected to server!
headers received
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.14.0 (Ubuntu)</center>
</body>
</html>
const char* host="Your host server" ;
const int httpsPort = 443;
//use below inside the function u want to connect with server
WiFiClientSecure client;
client.setInsecure();
HTTPClient http;
client.connect(host, httpsPort);
http.begin(client, host);
String payload;
if (http.GET() == HTTP_CODE_OK)
payload = http.getString();
I have a web server running on the esp8266.
The code is here:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include "index.h"
#include "login.h"
ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'
ESP8266WebServer server(80); // Create a webserver object that listens for HTTP request on port 80
void handleRoot(); // function prototypes for HTTP handlers
void handleLogin();
void handleNotFound();
void setup(void){
Serial.begin(115200); // Start the Serial communication to send messages to the computer
delay(100);
wifiMulti.addAP("DIGISOL", "edot2017"); // add Wi-Fi networks you want to connect to
Serial.println("Connecting ...");
while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
delay(250);
Serial.print('.');
}
Serial.println('\n');
Serial.print("Connected to ");
Serial.println(WiFi.SSID()); // Tell us what network we're connected to
Serial.print("IP address:\t");
Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
server.on("/", HTTP_GET, handleRoot); // Call the 'handleRoot' function when a client requests URI "/"
server.on("/login", HTTP_POST, handleLogin); // Call the 'handleLogin' function when a POST request is made to URI "/login"
server.on("/back",HTTP_POST,handleRoot);
server.onNotFound(handleNotFound); // When a client requests an unknown URI (i.e. something other than "/"), call function "handleNotFound"
server.begin(); // Actually start the server
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient(); // Listen for HTTP requests from clients
}
void handleRoot() { // When URI / is requested, send a web page
String indexPage = MAIN_page;
server.send(200, "text/html",indexPage);
}
void handleLogin() { // If a POST request is made to URI /login
String message = "";
if( ! server.hasArg("data") || server.arg("data") == NULL ){ // If the POST request doesn't have username and password data
server.send(400, "text/plain", "400: Invalid Request"); // The request is invalid, so send HTTP status 400
return;
}
else
{
message += server.arg("data"); //Get the name of the parameter
Serial.println(message);
String loginpage = LOGIN_PAGE;
server.send(200, "text/html",loginpage);
}
}
void handleNotFound(){
server.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (Not Found) when there's no handler for the URI in the request
}
Then I have a sketch to display a message on to the ledp10 display which is working fine.
ledp10 display message code:
#include <SPI.h>
#include <DMD2.h>
#include <fonts/SystemFont5x7.h>
#include <fonts/Arial14.h>
#include <fonts/Droid_Sans_24.h>
#include <fonts/Droid_Sans_16.h>
// Set Width to the number of displays wide you have
const int WIDTH = 1;
const int COUNTDOWN_FROM = 0;
int counter = COUNTDOWN_FROM;
// You can change to a smaller font (two lines) by commenting this line,
// and uncommenting the line after it:
const uint8_t *FONT = SystemFont5x7;
const uint8_t *FONT2 = SystemFont5x7;
const char *MESSAGE = "GOA";
SoftDMD dmd(WIDTH,1); // DMD controls the entire display
DMD_TextBox box(dmd, 0, 1);
DMD_TextBox box1(dmd,11,1); // "box" provides a text box to automatically write to/scroll the display
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
dmd.setBrightness(255);
//dmd.selectFont(FONT);
dmd.begin();
}
// the loop routine runs over and over again forever:
void loop() {
dmd.selectFont(FONT);
box.print(counter);
dmd.selectFont(FONT2);
const char *next = MESSAGE;
while(*next) {
Serial.print(*next);
box1.print(*next);
delay(500);
next++;
}
box.println(F(""));
counter++;
if(counter == 60) {
dmd.clearScreen();
counter = 0;
}
}
Now I need to communicate between the esp8266 and atmega328p. I.e the message sent on the web page needs to be displayed on to the ledp10 display.
How should I do it?
Please help only in serial communication between esp8266 and atmega328p.
modify the lcd Atmega sketch to receive a text from Serial Monitor.
Then connect the esp8266 to Serial of Atmega and the Atmega sketch will receive the text you print to Serial in the esp sketch
This is my first post so tell me where I go wrong.
Here is my setup.
I have a sensor connected via SCL and STA to a ESP8266 developer kit.
My language is arduino. This works, I can get it to put out the temperature and humidity into the serial monitor. I also have a raspberry pi (3?) that currently works as a wifi router. I used hostapd to do this. I have also signed up for amazon AWS, and have AWSIoT connected with the pi, which i have mosquitto running as the broker. My goal is to be able to leave the pi and esp with sensor in a location, pi connected with ethernet, and have the temperature and humidity come to kibana browser and I be able to see the data.
Here is my problem. mosquitto works with the mosquitto_sub and mosquitto_pub client. However, my arduino code cannot connect. I suspected that this was a problem with the IP address, so I consulted the internet, and got many test sites, but none told me where to find the IP to put as the mqtt broker server. I have included my code, and I live in japan, so don`t be frightened by the time settings. As you can see, I have been trying many different things that maybe could work :/.
#include "SparkFun_Si7021_Breakout_Library.h"
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <time.h>
#include <WiFiUdp.h>
float humidity = 0;
float tempf = 0;
const char* SSID = "ssid";
const char* PASSWORD = "password";
const int MQTTPORT = 1883;
I tried many different ips here, but none of them worked.
(Using the const char* format below)(The reason I exclude them is for security(right?))
//const char* MQTTSERVER = "mosquitto.service";
//const char* MQTTSERVER = "systemctl";
//const char* MQTTSERVER = "bridgeawsiot2";
const char* MQTTINITTOPIC = "/dev/init/msg/";
const char* MQTTSNTOPIC = "/ras-xdv2/Si7021";
const char* MQTTINITTOPICMSG = "{\"dev\"=\"Si7021\",\"msg\"=\"init\"}";
// APRIME
WiFiUDP ntpUDP;
const char* NTPSERVER = "ntp.nict.jp";
const int NTPTIMEOFFSET = 9 * 60 * 60;
WiFiClient espClient;
PubSubClient client(espClient);
//Create Instance of HTU21D or SI7021 temp and humidity sensor and MPL3115A2 barrometric sensor
Weather sensor;
//---------------------------------------------------------------
void setup_wifi() {
delay(10);
Serial.print("WiFi CONNECTION...");
Serial.println(SSID);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print("Waiting...");
}
randomSeed(micros());
Serial.println(" ");
Serial.println("WiFi connected");
Serial.println("ESP8266 ip:");
Serial.println(WiFi.localIP());
}
//---------------------------------------------------------------
void mqttConnect() {
// client.setServer(MQTTSERVER, MQTTPORT);
while (!client.connected()) {
Serial.print("MQTT communications need more time...");
String clientId = "ESP8266-";
clientId += String(random(0xffff));
delay(3000);
if (client.connect(clientId.c_str())) {
Serial.println("MQTT communications online!");
client.publish(MQTTINITTOPIC, MQTTINITTOPICMSG);
} else {
Serial.print("MQTT communications unavailible, rc=");
Serial.print(client.state());
delay(2000);
Serial.println("Attempting connection in t-2 Seconds...");
delay(2000);
}
}
}
//---------------------------------------------------------------
void setup()
{
Serial.begin(115200);
sensor.begin();
setup_wifi();
client.setServer(MQTTSERVER, MQTTPORT);
delay(5000);
/*if (!sensor.begin()) {
Serial.print("sensor ded :(");
while (1);
}*/
configTime( NTPTIMEOFFSET, 0, NTPSERVER );
}
//---------------------------------------------------------------
void loop()
{
time_t t = time(NULL);
struct tm *tm;
tm = localtime(&t);
char dt[25];
sprintf(dt, "%04d-%02d-%02dT%02d:%02d:%02d+09:00", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
Serial.printf(dt);
if(!client.connected()){
mqttConnect();
} else {
client.loop();
}
char pub_json[100];
//Get readings from all sensors
getWeather();
printInfo();
delay(10000);
char tempfbuf[4];
char humiditybuf[4];
sprintf(pub_json,"{\"Temperature\":%s,\"Humidity\": %s, \"#timestamp\": %s}]}",dtostrf(tempf, 4, 2, tempfbuf), dtostrf(humidity, 4, 2, humiditybuf), dt);
client.publish(MQTTSNTOPIC, pub_json);
Serial.println("TEMPERATURE BEING PUBLISHED...");
Serial.println(pub_json);
delay(60000 * 10);
}
//---------------------------------------------------------------
void getWeather()
{
// Measure Relative Humidity from the HTU21D or Si7021
humidity = sensor.getRH();
// Measure Temperature from the HTU21D or Si7021
tempf = sensor.getTemp();
// Temperature is measured every time RH is requested.
// It is faster, therefore, to read it from previous RH
// measurement with getTemp() instead with readTemp()
}
//---------------------------------------------------------------
void printInfo()
{
//This function prints the weather data out to the default Serial Port
Serial.print("Temp:");
Serial.print(tempf);
Serial.print("F, ");
Serial.print("Humidity:");
Serial.print(humidity);
Serial.println("%");
}
The mosquitto.conf file was nonexistant when I first downloaded mosquitto, so I created it and used this:
Please tell me if I posted sensitive information: I am new to this :)
c4message_size_limit 0
clientid bridgeawsiot2
persistence true
persistence_file mosquitto.db
persistence_location /var/mosquitto/
log_type all
connection_messages true
log_timestamp true
allow_anonymous true
password_file /etc/mosquitto/conf.d/users
allow_anonymous true
listener 9001 127.0.0.1
protocol websockets
connection_messages true
log_timestamp true
listener 1883
connection <awsiot>
address yl42kju76zjjodsbm6nfl4yycq.ap-northeast-1.es.amazonaws.com:8883
topic /esp8266/Si7021/slack out 1
cleansession true
notifications false
start_type automatic
bridge_cafile /etc/mosquitto/certs/root-CA.crt
bridge_certfile /etc/mosquitto/certs/RAS-XD.cert.pem
bridge_keyfile /etc/mosquitto/certs/RAS-XD.private.key
Maybe the problem is the websockets thing?
Any help is appreciated!
Literally any :)
I am doing some pretty good work with the esp8266 and mqtt using arduino IDE. I have mine logging on to my own mqtt broker I set up in a centos 7 box with encryption using x509 certs.
I use mosquitto-auth-plug to manage user access with a mysql database set up on the same machine
when you think about it the operating system is free, mosquitto broker is free, and mysql server is free.
the only expense to having your own setup is a fixed IP and fast enough connection. Which you could set up pretty cheap in a virtual machine on azure.
Anyhow when I first started a friend (the guy who sold me my first nodemcu .9 board). Hooked me up with this script and I have been able to get it all done using this as my example.
the part I liked was if you monitored your mqtt from a client like mqtt box or others. When the chip first starts it sends payload "Start" to topic "device_name/status". This way you can always tell when it's online.
I copied the notes he gave me they are located below.
good luck
/*
* Skeleton for ESPP based sensors.
* Supports:
* - OTA fw update via HTTP
* http://ipaddr/update
* - REST access
* http://ipaddr:8080/<id>
* - MQTT publish and subscribe
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
#include <aREST.h>
// Define device name
const char* device_name = "myHostName";
const char* ssid = "WiFiSSID";
const char* password = "wiFiPassword";
const char* mqtt_server = "mqtt_hostname.example.com";
char host[14];
int rest_test = 7467;
/* WiFi Client */
WiFiClient espClient;
/* MQTT Client */
PubSubClient client(espClient);
/* HTTP client, for remote updates */
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;
/* Rest server */
aREST rest = aREST();
WiFiServer restServer(8080);
void setup() {
char topic[80];
Serial.begin(115200);
/* Start WiFi */
setup_wifi();
/* Setup MQTT client */
client.setServer(mqtt_server, 1883);
client.setCallback(mqtt_callback);
/* Start the HTTP update server */
MDNS.begin(host);
httpUpdater.setup(&httpServer);
httpServer.begin();
MDNS.addService("http", "tcp", 80);
/* Set REST variables */
rest.set_id("1");
rest.set_name(host);
rest.variable("test", &rest_test);
/*
rest.variable("temperature", &temp);
rest.variable("distance", &dist);
rest.variable("reset_count", &reset_count);
rest.set_id("1");
rest.set_name("esp8266");
*/
restServer.begin();
/* Connect to the MQTT broker */
reconnect();
client.subscribe("network/broadcast");
sprintf(topic, "network/%s", device_name);
client.subscribe(topic);
sprintf(topic, "%s/status", device_name);
client.publish(topic, "start");
Serial.print("Node ");
Serial.print(device_name);
Serial.println(" started.");
Serial.print("Hostname ");
Serial.println(host);
Serial.print("IP Address ");
Serial.println(WiFi.localIP());
}
void setup_wifi() {
uint8_t mac[6];
delay(10);
WiFi.begin(ssid, password);
WiFi.macAddress(mac);
sprintf(host, "esp-%02x%02x%02x", mac[3], mac[4], mac[5]);
WiFi.hostname(host);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
/* Handle incoming MQTT messages */
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
char payloadStr[80];
if (length > 79) {
length = 79;
}
memcpy(payloadStr, payload, length);
payloadStr[length] = '\0';
if (strcmp(payloadStr, "discover") == 0) {
delay(random(10, 1000));
client.publish("network/presence", device_name);
}
if (strcmp(payloadStr, "refresh") == 0) {
/* Publish all sensor data */
}
}
/* Connect (or re-connect) to the MQTT broker */
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
// Attempt to connect
/* TODO: Create this based on the MAC address */
if (client.connect(host)) {
} else {
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
WiFiClient restClient;
/* Check MQTT connection, reconnect if needed */
if (!client.connected()) {
reconnect();
}
/* Process MQTT tasks */
client.loop();
/* Process HTTP FW update requests */
httpServer.handleClient();
/* Process REST requests */
restClient = restServer.available();
if (restClient) {
while (!restClient.available()) {
delay(1);
}
rest.handle(restClient);
}
/* Insert normal sensor code here. */
/* Publish results with client.publish(topic, value); */
}
My code sets up it's own device name, subscribes to the MQTT topics "network/broadcast", "network/(device name)".
When it starts it sends "(device_name)/status" with a payload of "start".
When it gets a "network/broadcast" with a payload of "discover" it replies by publishing a "network/presence" and its name.
Basically, you sent MQTT events with client.publish(topic, payload).
You subscribe to events with client.subscribe(topic).
When an event is received that matches your subscription it will call mqtt_callback and give it the topic, the payload, and the length.
Hope that helps.
I'm using NodeMCU v3, and can already send some information on its server.
But how can I receive some information from other web pages, let say for beginning, a plain text?
You need a HttpClient to communicate with a web server.
Good way to start is to use the HttpClient sample -> ReuseConnection.
This will allow you to make more requests than one.
You can see in Serial Monitor in Arduino IDE to see the response from the request.
Sample code:
Note: replace " http://:/someroute " with the desired http page you want to get.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial
ESP8266WiFiMulti WiFiMulti;
HTTPClient http;
void setup() {
USE_SERIAL.begin(115200);
// USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFiMulti.addAP("SSID", "PASSWORD");
// allow reuse (if server supports it)
http.setReuse(true);
}
void loop() {
// wait for WiFi connection
if((WiFiMulti.run() == WL_CONNECTED)) {
http.begin("http://<IP>:<Port>/someroute");
int httpCode = http.GET();
if(httpCode > 0) {
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(3000);
}