WiFiClient.cpp socket error "Software caused connection abort - PlatformIo - c++

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()

Related

How to set up a TCP server on a ESP8266 using ESPAsyncTCP library and how pointers work

I need help with how i can send a tcp message using the ESPAsyncTCP library. The reason i have decided to use ESPAsyncTCP is that it is the only way i have gotten TCP server to work on my ESP8266 and not refuse the connection, but the example code confuses me a little since i dont know how the arrow/pointer operator work.
The code i have included below is the example code from the library, i have modified it to connect to a WiFi instead of being an access point, it works like it should but i dont understand how i can get this to send a message from the loop.
I have seen that it uses client->add() to add the message to a buffer and then sending it with client->send().
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <vector>
#include "config.h"
static std::vector<AsyncClient*> clients; // a list to hold all clients
/* clients events */
static void handleError(void* arg, AsyncClient* client, int8_t error) {
Serial.printf("\n connection error %s from client %s \n", client->errorToString(error), client->remoteIP().toString().c_str());
}
static void handleData(void* arg, AsyncClient* client, void *data, size_t len) {
Serial.printf("\n data received from client %s \n", client->remoteIP().toString().c_str());
Serial.write((uint8_t*)data, len);
// reply to client
// ----- This is where the example code from the library sends a reply and is what i would like to understand how to do from the loop ------
if (client->space() > 32 && client->canSend()) {
char reply[32];
sprintf(reply, "this is from %s", SERVER_HOST_NAME);
client->add(reply, strlen(reply));
client->send();
}
}
static void handleDisconnect(void* arg, AsyncClient* client) {
Serial.printf("\n client %s disconnected \n", client->remoteIP().toString().c_str());
}
static void handleTimeOut(void* arg, AsyncClient* client, uint32_t time) {
Serial.printf("\n client ACK timeout ip: %s \n", client->remoteIP().toString().c_str());
}
/* server events */
static void handleNewClient(void* arg, AsyncClient* client) {
Serial.printf("\n new client has been connected to server, ip: %s", client->remoteIP().toString().c_str());
// add to list
clients.push_back(client);
// register events
client->onData(&handleData, NULL);
client->onError(&handleError, NULL);
client->onDisconnect(&handleDisconnect, NULL);
client->onTimeout(&handleTimeOut, NULL);
}
void setup() {
Serial.begin(9600);
delay(20);
// connect to wifi
WiFi.begin(SSID, PASSWORD);
Serial.println("Connecting to WiFi..");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to the WiFi network");
Serial.println(WiFi.localIP());
AsyncServer* server = new AsyncServer(TCP_PORT); // start listening on tcp port 7050
server->onClient(&handleNewClient, server);
server->begin();
}
void loop() {}

Guru Meditation Error Core 0 panic'ed (LoadProhibited). Exception was unhandled

error project
Guru Meditation Error in project
Core 0 panic'ed (LoadProhibited). Exception was unhandled.
I have project using pulsesensor with ESP32, Data from ESP32 is saved in database.
I tried many times but could not
help me
#include <ssl_client.h>
#include <WiFiClientSecure.h>
#include <WiFi.h>
#include <SPI.h>
#include <WiFiClient.h>
#include <HTTPClient.h>
#define USE_SERIAL Serial
/* Konfigurasi pada SSID dan Password Wifi */
const char* ssid = "berdikari";
const char* password = "alfian24";
/* Konfigurasi koneksi ke server */
char server[] = "192.168.43.108"; // Ganti dengan IP Address komputer aplikasi
int port = 81;
/*konfigurasi*/
int PulseSensorPurplePin = 34; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED21 = 21; // The on-board Arduion LED
int Signal; // holds the incoming raw data. Signal value can range from 0-102
float pulse=0;
WiFiClient client;
void setup() {
USE_SERIAL.begin(115200); // Baudrate/kec. komunikasi pengiriman data ke serial terminal
delay(10);
Serial.println('\n');
WiFi.begin(ssid, password);
USE_SERIAL.print("Terhubung ke ");
USE_SERIAL.print(ssid);
// WiFi.config(local_IP, gateway, subnet, dns);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
USE_SERIAL.print('.');
}
USE_SERIAL.print('\n');
USE_SERIAL.println("Identitas ESP-32");
USE_SERIAL.print("IP Address:\t");
USE_SERIAL.println(WiFi.localIP()); // IP Address ESP-32
USE_SERIAL.print('\n');
USE_SERIAL.println("Identitas Web Server");
USE_SERIAL.println("IP Address:");
USE_SERIAL.print(server);
USE_SERIAL.print("\tport:\t");
USE_SERIAL.print(port);
}
void loop() {
Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor’s value.
// Send the Signal value to Serial Plotter.
delay(1000);
pulse = Signal;
USE_SERIAL.println(pulse);
if(WiFi.status() == WL_CONNECTED){
//URL target untuk menyimpan data sensor Pulse ke database
String url = "http://192.168.43.108:81/";
url += "sistem_monitoring/Monitoring/simpan/";
url += String(pulse);
HTTPClient http;
USE_SERIAL.print("[HTTP] begin...\n");
http.begin(url);
USE_SERIAL.print("[HTTP] GET...\n");
int httpCode = http.GET();
if(httpCode > 0) {
USE_SERIAL.printf("[HTTP] GET... code: %d\n",
httpCode);
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();
}
}
please help me.
What should I do??
I've seen this question asked a few times but never got a good answer.

ESP32 to ESP32 WiFi Server/Client Problem

I've got one ESP32 acting as client and another ESP32 acting as an access-point for direct communication and outdoor use.
I have set up a server on the AP end and would like the client to communicate with it but I can't seem to make this work.
I would like to know two things:
How do I send or write data to the server from the client?
How do I read and display the data that was sent to the server from the client?
I have attached the code below:
Code for AP/Server
//SERVER
//Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
//Set web server port number to 80
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println("Setting AP (Access Point)…");
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address ");
Serial.println(IP);
Serial.print("MAC address ");
Serial.println(WiFi.softAPmacAddress());
server.begin();
}
void loop(){
WiFiClient client = server.available(); //Listen for incoming clients
if (client)
{ //If a new client connects,
Serial.println("New Client."); //print a message out in the serial port
while (client.connected())
{
Serial.println("Client connected.");
Serial.println(client.available());
if (client.available() > 0)
{
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}
}
client.stop();
Serial.println("Client disconnected.");
Serial.println();
}
}
Code for Client
//Client
#include <WiFi.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
WiFiClient client;
IPAddress server(192, 168, 4, 1);
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" connected");
if(client.connect(server, 80))
{
Serial.println("connected to server");
client.write("Data");
}
else
{
Serial.println("failed to connect to server");
}
}
void loop()
{
}
Alternatively to the previous answer, you could use espnow as a protocol between various esp32. Here an example.
You must implement some sort of protocol like TCP, UDP to exchange data.
Example Project using TCP
https://www.instructables.com/id/WiFi-Communication-Between-Two-ESP8266-Based-MCU-T/
Example Project using UDP
https://circuits4you.com/2018/01/01/esp-to-esp-communication/
Look at this very handy function:
void SetWifi(const char *name, const char *password) { // Turn on wifi with server
Serial.println("Starting server");
WiFi.disconnect();
WiFi.softAP(name, password);
delay(2000);
IPAddress IP = WiFi.softAPIP();
Serial.print("Server IP : ");
Serial.println(IP);
server.begin();
server.setNoDelay(true);
Serial.println("Server started");
}
You can write data with this function :
void sendDataTCP(String message) { // function to send message back to client
if (client && client.connected()) { //check if client is there
client.println(message);
}
client.flush();
}
Receive data with this function:
void availableMessage() {
if (client.available()) {//check if client is there
while (client.available()) {
String message = client.readStringUntil('\n'); //read string until enter (end of message)
Serial.println("Received: " + message);
message.toCharArray(buffer, BUFFER); // put message in char array (buffer)
client.flush(); // discard all bytes that have been read
}
}
}
Check if someone has connected:
void connectClient() {
if (server.hasClient()) // if server has a client
{
if (client = server.available()) { // if client is connected
Serial.println("Connected");
}
}
}
I think this will get you in the direction of accomplishing your goal, good luck!

Serial communication between esp8266 and atmega328p

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

How to get data from web by NodeMCU

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);
}