ESP32 to ESP32 AP/client WiFi connection problem - c++

Trying to communicate from one ESP32 to another ESP32 ,with one acting as a AP and another acting as Client but cant seem to connect the esp client to the esp AP, but connecting to AP using my smartphone works.Sorry if this seems to be a simple questions, I am new to esp32s and WiFI communication.
Code for the Access-point
#include <WiFi.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
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)
{ Serial.println("New Client.");
while (client.connected())
{
Serial.println(client.connected());
Serial.println("Client connected.");
Serial.println("");
}
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Code for the Client
#include <WiFi.h>
#include <SPI.h>
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
scanNetworks();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
}
void loop() {
}
void scanNetworks() {
// scan for nearby networks:
Serial.println("** Scan Networks **");
byte numSsid = WiFi.scanNetworks();
// print the list of networks seen:
Serial.print("SSID List:");
Serial.println(numSsid);
// print the network number and name for each network found:
for (int thisNet = 0; thisNet<numSsid; thisNet++) {
Serial.print(thisNet);
Serial.print(") Network: ");
Serial.println(WiFi.SSID(thisNet));
}
}

As #juraj mentions, in the Arduino code for ESP32, you cannot initiate a scan while an attempt to connect to AP is already ongoing.
Call scanNetworks() before attempting to connect (before the WiFi.begin(ssid, password);).
or
Call scanNetworks() after the connection to the AP has been established (after the while (WiFi.status() != WL_CONNECTED){}).
I don't see any point to scan networks while trying to connect to a known WiFi AP anyway.

ESPnow (see example here ) is easy for ESP to ESP communication. (also ESP8266 etc)

Related

Compilation error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url), How can i solve this issue?

I run this code and get the massage:
Compilation error: call to 'HTTPClient::begin' declared with attribute error: obsolete API, use ::begin(WiFiClient, url)
what can I do?
//----------------------------------------Include the NodeMCU ESP8266 Library
//----------------------------------------see here: https://www.youtube.com/watch?v=8jMr94B8iN0 to add NodeMCU ESP8266 library and board
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
//----------------------------------------
#define ON_Board_LED 2 //--> Defining an On Board LED (GPIO2 = D4), used for indicators when the process of connecting to a wifi router
#define LED_D8 15 //--> Defines an LED Pin. D8 = GPIO15
//---------------------------------------SSID and Password of your WiFi router.
const char* ssid = "*wifi name*"; //--> Your wifi name or SSID.
const char* password = "*Wfif password*"; //--> Your wifi password.
//----------------------------------------
//----------------------------------------Web Server address / IPv4
// If using IPv4, press Windows key + R then type cmd, then type ipconfig (If using Windows OS).
const char *host = "https://localhost/";
//----------------------------------------
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(500);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password); //--> Connect to your WiFi router
Serial.println("");
pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board
pinMode(LED_D8,OUTPUT); //--> LED port Direction output
digitalWrite(LED_D8, LOW); //--> Turn off Led
//----------------------------------------Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
//----------------------------------------Make the On Board Flashing LED on the process of connecting to the wifi router.
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
//----------------------------------------
}
//----------------------------------------
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.
//----------------------------------------If successfully connected to the wifi router, the IP Address that will be visited is displayed in the serial monitor
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
//----------------------------------------
}
void loop() {
// put your main code here, to run repeatedly:
HTTPClient http; //--> Declare object of class HTTPClient
WiFiClient WiFiClient;
//----------------------------------------Getting Data from MySQL Database
String GetAddress, LinkGet, getData;
int id = 0; //--> ID in Database
GetAddress = "rafael/GetData.php";
LinkGet = host + GetAddress; //--> Make a Specify request destination
getData = "ID=" + String(id);
Serial.println("----------------Connect to Server-----------------");
Serial.println("Get LED Status from Server or Database");
Serial.print("Request Link : ");
Serial.println(LinkGet);
http.begin("LinkGet");
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCodeGet = http.POST(getData); //--> Send the request
String payloadGet = http.getString(); //--> Get the response payload from server
Serial.print("Response Code : "); //--> If Response Code = 200 means Successful connection, if -1 means connection failed. For more information see here : https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Serial.println(httpCodeGet); //--> Print HTTP return code
Serial.print("Returned data from Server : ");
Serial.println(payloadGet); //--> Print request response payload
if (payloadGet == "1") {
digitalWrite(LED_D8, HIGH); //--> Turn off Led
}
if (payloadGet == "0") {
digitalWrite(LED_D8, LOW); //--> Turn off Led
}
//----------------------------------------
Serial.println("----------------Closing Connection----------------");
http.end(); //--> Close connection
Serial.println();
Serial.println("Please wait 5 seconds for the next connection.");
Serial.println();
delay(5000); //--> GET Data at every 5 seconds
}
I want my esp8266 to connect to my database(MySql) and get a value to turn on/off a led light.
The esp im using is the NodeMCU epp8266.
Apart from the actual issue that causes the compile error there are several other things wrong with this code. I fixed the most obvious ones. See the explanations for the callouts below the code.
// <1>
#include <ESP8266WiFi.h>
//#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
//#include <ESP8266WiFi.h>
//#include <WiFiClient.h>
//#include <ESP8266WebServer.h>
//#include <ESP8266HTTPClient.h>
//#include <WiFiClientSecureBearSSL.h>
#define ON_Board_LED 2
#define LED_D8 15
const char* ssid = "********";
const char* password = "********";
// <2>
// <3>
const char* host = "http://192.168.1.1/";
// <4>
String GetAddress, LinkGet, getData;
int id = 0;
// <5>
HTTPClient http;
WiFiClient client;
// <6>
void connectWiFi() {
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
}
digitalWrite(ON_Board_LED, HIGH);
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
}
void setup() {
Serial.begin(115200);
delay(500);
// <7>
GetAddress = "rafael/GetData.php";
LinkGet = host + GetAddress;
getData = "ID=" + String(id);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
pinMode(ON_Board_LED, OUTPUT);
digitalWrite(ON_Board_LED, HIGH);
pinMode(LED_D8, OUTPUT);
digitalWrite(LED_D8, LOW);
}
void loop() {
// <8>
// // put your main code here, to run repeatedly:
// HTTPClient http; //--> Declare object of class HTTPClient
// WiFiClient WiFiClient;
// <9>
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
Serial.println("----------------Connect to Server-----------------");
Serial.println("Get LED Status from Server or Database");
Serial.print("Request Link : ");
Serial.println(LinkGet);
// <10>
http.begin(client, LinkGet);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCodeGet = http.POST(getData);
String payloadGet = http.getString();
Serial.print("Response Code : ");
Serial.println(httpCodeGet);
Serial.print("Returned data from Server : ");
Serial.println(payloadGet);
if (payloadGet == "1") {
digitalWrite(LED_D8, HIGH);
}
if (payloadGet == "0") {
digitalWrite(LED_D8, LOW);
}
Serial.println("----------------Closing Connection----------------");
http.end();
Serial.println();
Serial.println("Please wait 5 seconds for the next connection.");
Serial.println();
delay(5000);
}
Clean up the includes such that only those remain which you actually need.
With this sketch your host cannot be (and likely is not) reachable using SSL/TLS encryption (https -> http).
localhost is wrong as this would point to the ESP8266 itself (loopback). You need the PC IP address or possibly its hostname here.
Declare global variables globally i.e. outside loop().
Declare and initialize the HTTPClient and WiFiClient globally rather than inside the loop(). See my answer here https://stackoverflow.com/a/59701884/131929 for more.
Put the WiFi-connecting code in a separate function - you'll need it later.
Initialize the global variables in setup() rather than loop(); goes along with <4>.
Don't instantiate those over and over again; goes along with <5>.
Verify the device is still connected to WiFi every time loop() is invoked and re-connect if not.
Compile error: http.begin() takes a WiFiClient plus that actual HTTP address. This is what the compile error message tells you.

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

ESP32 using BLE and WiFi API calls gives error code -1

I have a program trying to connect to a Bluetooth device and then sending an ack over a server (the server is private so I just used some pseudonym).
The first ACK on setup, goes through with 204 http return code which is fine, then it searches for a device, and whether it finds one or not it gives an error code of -1, then further on it gives 204 as well.
Here is the code that I have: (I have another project so this is just stripped down version trying things). This is also largely based form the Bluetooth client connect example on the esp32.
Code:
#include "BLEDevice.h"
#include "esp_bt.h"
#include "WiFi.h"
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Arduino_JSON.h>
//WiFi variables
//HTTPClient http;
const char* ssid = "SSID";
const char* password = "Password";
char* serverName = "ServerName";
char* serverQR = "ServerName1";
String serverPath;
String httpRequestData;
bool wifiOn = 0;
bool wifiAck = 0;
int Connection = 0;
int httpResponseCode;
String Data = "";
String externalID = "";
bool answer = "false";
String payload = "{}";
BLEScan* pBLEScan;
// The remote service we wish to connect to.
static BLEUUID serviceUUID("0000fff0-0000-1000-8000-00805f9b34fb");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("0000fff1-0000-1000-8000-00805f9b34fb");
static boolean doConnect = false; //should esp connect to ble device
static boolean connected = false; // is esp connected to a ble device
static boolean doScan = false; //should esp scan for ble devices
static BLERemoteCharacteristic* pRemoteCharacteristic; //init remote characterestic
static BLEAdvertisedDevice* myDevice; //init device found
static void notifyCallback( //beginning of functions, parameters follow
BLERemoteCharacteristic* pBLERemoteCharacteristic, //this is the device characterisitc value
uint8_t* pData, //data it received
size_t length,//length of data received
bool isNotify) {
Serial.print("Notify callback for characteristic ");
Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
Serial.print(" of data length ");
Serial.println(length);
Serial.print("data: ");
Serial.println((char*)pData);
esp_bt_controller_deinit();
esp_bt_controller_disable();
}
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {//when connecting
connected = true;
Serial.println("onConnect");
}
void onDisconnect(BLEClient* pclient) {//when disconnecting
connected = false;
Serial.println("onDisconnect");
}
};
bool connectToServer() {//connect to ble device
Serial.print("Forming a connection to ");
Serial.println(myDevice->getAddress().toString().c_str());
BLEClient* pClient = BLEDevice::createClient();//create esp as a client
Serial.println(" - Created client");
pClient->setClientCallbacks(new MyClientCallback());//set the function of client callbacks
// Connect to the remove BLE server.
pClient->connect(myDevice); // if you pass BLEAdvertisedDevice instead of address, it will be
recognized type of peer device address (public or private)
Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);//can we connect to ble device
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our service");
// Obtain a reference to the characteristic in the service of the remote BLE server.
pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);//does the ble device have the
characteristic function we want?
if (pRemoteCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(charUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our characteristic");
// Read the value of the characteristic.
if (pRemoteCharacteristic->canRead()) {
std::string value = pRemoteCharacteristic->readValue();
Serial.print("The characteristic value was: ");
Serial.println(value.c_str());
}
if (pRemoteCharacteristic->canNotify()) //if ble server transmits data do a callback
pRemoteCharacteristic->registerForNotify(notifyCallback);
connected = true;
return true;
}
/**
Scan for BLE servers and find the first one that advertises the service we are looking for.
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {//When a scan is activated
/**
Called for each advertising BLE server.
*/
void onResult(BLEAdvertisedDevice advertisedDevice) {//when a ble device is found
Serial.print("BLE Advertised Device found: ");
Serial.println(advertisedDevice.toString().c_str());
// We have found a device, let us now see if it contains the service we are looking for.
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);//ble server connected
doConnect = true;//has to connect
doScan = true;//has to scan
} // Found our server
} // onResult
}; // MyAdvertisedDeviceCallbacks
void setup() {
Serial.begin(115200);
Serial.println("Starting Arduino BLE Client application...");
BLEDevice::init("");
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 5 seconds.
pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
//WiFi setup
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("Connecting to WiFi...");
delay(1000);
}//end while
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
HTTPClient http;
serverPath = serverName;
if (WiFi.status() == WL_CONNECTED) {
// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());
// Data to send with HTTP POST
JSONVar json_test;
json_test["id"] = WiFi.macAddress();
httpRequestData = JSON.stringify(json_test);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
httpResponseCode = http.POST(httpRequestData);
payload = " {}";
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println("This is the response code");
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
WiFi.disconnect(true);
delay(1); // disable WIFI altogether
WiFi.mode(WIFI_OFF);
delay(1);
} else
{
Serial.println("WiFi disconnected");
}
} // End of setup.
// This is the Arduino main loop function.
void loop() {
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BLE);
if (!connected)
{
Serial.println("Initialising");
pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
Serial.println("Scan starting");
pBLEScan->start(30, false);
Serial.println("Scan ended");
}
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {//if ble server was found connect to it
if (connectToServer()) {
Serial.println("We are now connected to the BLE Server.");
} else {
Serial.println("We have failed to connect to the server; there is nothin more we will do.");
}
doConnect = false;
}
esp_bt_controller_deinit();
esp_bt_controller_disable();
//WiFi setup
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
//WiFi.config(staticIP, gateway, subnet);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("Connecting to WiFi...");
delay(1000);
}//end while
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
HTTPClient http;
serverPath = serverName;
if (WiFi.status() == WL_CONNECTED) {
// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());
// Data to send with HTTP POST
JSONVar json_test;
json_test["id"] = WiFi.macAddress();
httpRequestData = JSON.stringify(json_test);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println("This is the loop");
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
Serial.println("This is the loop");
}
// Free resources
http.end();
WiFi.disconnect(true);
delay(1); // disable WIFI altogether
WiFi.mode(WIFI_OFF);
delay(1);
} else
{
Serial.println("WiFi disconnected");
}
delay(1000); // Delay a second between loops.
} // End of loop
The output of the code is:
Starting Arduino BLE Client application...
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the response code IS this done? Initialising Scan starting BLE Advertised Device found: Name: , Address: address, manufacturer data:random stuff Scan ended Forming a connection to addresss
- Created client onConnect
- Connected to server
- Found our service
- Found our characteristic We are now connected to the BLE Server.
Connecting to SSID Connecting to WiFi... Connected, IP address: IP Error code: -1 This is the loop
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the loop
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the loop
My question basically is does anyone know what an erro0 rcode if -1 is? On my main project I am unable to send a get request after scanning for a ble device even if I disabl the controller.
To answer your question about error code -1:
It means that a connection was not successful according to this example from the HTTPClient repository.
Your log shows that you are able to connect to your server and afterwards to your BLE peripheral. But it seems like you never disconnect from the peripheral and continue to block the other wifi connections. Have a look at this for further ideas on using BLE and WiFi together.

How do I let the compiler know which virtual to use from the imported library?

I am getting a call of overloaded 'connect(IPAddress, int)' is ambiguous error when using the <ArduinoMqttClient.h> library. This only happens when I use an IP address instead of a host.
I am working on writing some code to connect to an MQTT broker running on AWS. When I use the host name, I am unable to create a secure connection but when I use the IP address of the service this problem goes away. The sample code I have modified originally implemented the host name version of the connect call but since I need to use an IP address, I am running into this issue.
#include <ArduinoMqttClient.h>
#include <WiFi101.h>
const char ssid[] = "ssid";
const char pass[] = "password";
IPAddress broker(x, x, x, x);
WiFiSSLClient wifiSSLClient;
MqttClient mqttClient(wifiSSLClient);
unsigned long lastMillis = 0;
void loop() {
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
if (!mqttClient.connected()) {
// MQTT client is disconnected, connect
connectMQTT();
}
// poll for new MQTT messages and send keep alives
mqttClient.poll();
// publish a message roughly every 5 seconds.
if (millis() - lastMillis > 5000) {
lastMillis = millis();
publishMessage();
}
}
unsigned long getTime() {
// get the current time from the WiFi module
return WiFi.getTime();
}
void connectWiFi() {
Serial.print("Attempting to connect to SSID: ");
Serial.print(ssid);
Serial.print(" ");
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println();
Serial.println("You're connected to the network");
Serial.println();
}
void connectMQTT() {
Serial.print("Attempting connection to MQTT broker: ");
Serial.print(broker);
Serial.println(" ");
mqttClient.setUsernamePassword("username", "password");
while (!mqttClient.connect(broker, 8883)) { // <-- this is where the error is being thrown
// failed, retry
Serial.print(".");
delay(5000);
}
Serial.println();
Serial.println("You're connected to the MQTT broker");
Serial.println();
// subscribe to a topic
mqttClient.subscribe("arduino/incoming");
}
Ideally it would accept the parameters but I am getting the following error:
virtual int connect(const IPAddress& ip, uint16_t port) { }; /* ESP8266 core defines this pure virtual in Client.h */
^~~~~~~
exit status 1
call of overloaded 'connect(IPAddress&, int)' is ambiguous

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!