Keep ESP32 AutoConnect Captive Portal Always Running - esp32

I have an ESP32 that is running in softap mode with AutoConnect. I'm trying to get the captive portal to always be active, even if the client portion is connected to an AP. The current problem is once the ESP32 establishes the client connection with the router or after the initial timeout period, the captive portal goes away and you have to manually enter the IP address of the of the softap in the web browser.
Is there a setting I'm missing that allows this to happen?
//Config.autoRise = true;
Config.immediateStart = true;
Config.portalTimeout = 30 * 1000;
Config.retainPortal = true;
Config.title = "ESP32 AP";
Config.homeUri = "/";
portal.config(Config);

AutoConnectConfig Config;
//Config.bootUri=URI;
Config.homeUri="/_ac";
Config.apid = "Vedesp32-1";
Config.psk = "vedesp32";
Config.apip=IPAddress(10,1,1,1);
//Config.immediateStart = true;
Config.hostName = "esp32.local";
Config.title = "NBrowser";
Config.autoSave = AC_SAVECREDENTIAL_AUTO;
Config.autoReset = false;
Config.autoReconnect = true;
Config.reconnectInterval = 6;
Config.autoRise = true;
Config.retainPortal = true;
Portal.onDetect(atDetect);
Portal.config(Config);

extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <WiFiClient.h>
#include <time.h>
#include <sys/time.h>
#include <AutoConnect.h>
#define IND 2
#define BUZZER 5
#define SWITCH_ON "True"
#define SWITCH_OFF "False"
#define CREDENTIAL_OFFSET 0
const char* URI = "/_ac";
TimerHandle_t wifiReconnectTimer;
AutoConnect Portal;
void pinInit() {
pinMode(BUZZER, OUTPUT);
pinMode(IND, OUTPUT);
}
void connectToWifi() {
Serial.println("Connecting to Wi-Fi... ->");
if (WiFi.status() == WL_CONNECTED) {
delay(5000);
Serial.print(".");
}
}
void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch (event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(BUZZER, HIGH);
digitalWrite(IND, HIGH);
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
digitalWrite(IND, LOW);
xTimerStart(wifiReconnectTimer, 0);
break;
}
}
void setup() {
Serial.begin(115200);
Serial.println();
pinInit();
digitalWrite(IND, LOW);
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
AutoConnectConfig Config;
//Config.bootUri=URI;
Config.homeUri="/_ac";
Config.apid = "Ved";
Config.psk = "vedesp32";
Config.apip=IPAddress(10,1,1,1);
//Config.immediateStart = true;
Config.hostName = "esp32.local";
Config.title = "NBrowser";
Config.autoSave = AC_SAVECREDENTIAL_AUTO;
Config.autoReset = false; // Not reset the module even by intentional disconnection using AutoConnect menu.
Config.autoReconnect = true; // Reconnect to known access points.
Config.reconnectInterval = 6; // Reconnection attempting interval is 3[min].
Config.autoRise = true;
Config.retainPortal = true; // Keep the captive portal open.
Portal.onDetect(atDetect);
Portal.config(Config);
// Start
if (Portal.begin()) {
Serial.println("WiFi connected: " + WiFi.localIP().toString());
digitalWrite(IND, HIGH);
}
connectToWifi();
}
bool atDetect(IPAddress& softapIP) {
Serial.println("Captive portal started, SoftAP IP:" + softapIP.toString());
return true;
}
void loop() {
Portal.handleClient();
}

Related

How to recieve a Direct Method on the ESP32 with azure-sdk-for-c-arduino

For a school project I am using IoT Hub to connect between different devices (ESP32), The intention is to use a web application to retrieve data from a device. I want to do this by using a Direct Method.
Now I have seen in the past some direct methods using python and how I can use this in Azure Functions but not yet on an ESP32. By the way, I am programming in C on the ESP32.
Does anyone have an example code for this? I am not finding really much info about direct methods in C with the library "azure-sdk-for-c-arduino".
Thanks in advance
My code at the moment (This is test code):
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
/*
This is an Arduino-based Azure IoT Hub sample for ESPRESSIF ESP32 boards.
It uses our Azure Embedded SDK for C to help interact with Azure IoT.
For reference, please visit https://github.com/azure/azure-sdk-for-c.
To connect and work with Azure IoT Hub you need an MQTT client, connecting, subscribing
and publishing to specific topics to use the messaging features of the hub.
Our azure-sdk-for-c is an MQTT client support library, helping composing and parsing the
MQTT topic names and messages exchanged with the Azure IoT Hub.
This sample performs the following tasks:
- Synchronize the device clock with a NTP server;
- Initialize our "az_iot_hub_client" (struct for data, part of our azure-sdk-for-c);
- Initialize the MQTT client (here we use ESPRESSIF's esp_mqtt_client, which also handle the tcp connection and TLS);
- Connect the MQTT client (using server-certificate validation, SAS-tokens for client authentication);
- Periodically send telemetry data to the Azure IoT Hub.
To properly connect to your Azure IoT Hub, please fill the information in the `iot_configs.h` file.
*/
//Variabeles for drukknop
const int PushButton = 35;
//Variables for weight sensor;
double weight = 5.0;
// C99 libraries
#include <cstdlib>
#include <string.h>
#include <time.h>
// Libraries for MQTT client and WiFi connection
#include <WiFi.h>
#include <mqtt_client.h>
// Azure IoT SDK for C includes
#include <az_core.h>
#include <az_iot.h>
#include <azure_ca.h>
// Libraries for SendingJson
#include <ArduinoJson.h>
// Additional sample headers
#include "AzIoTSasToken.h"
#include "SerialLogger.h"
#include "iot_configs.h"
// When developing for your own Arduino-based platform,
// please follow the format '(ard;<platform>)'.
#define AZURE_SDK_CLIENT_USER_AGENT "c/" AZ_SDK_VERSION_STRING "(ard;esp32)"
// Utility macros and defines
#define sizeofarray(a) (sizeof(a) / sizeof(a[0]))
#define NTP_SERVERS "pool.ntp.org", "time.nist.gov"
#define MQTT_QOS1 1
#define DO_NOT_RETAIN_MSG 0
#define SAS_TOKEN_DURATION_IN_MINUTES 60
#define UNIX_TIME_NOV_13_2017 1510592825
#define PST_TIME_ZONE -8
#define PST_TIME_ZONE_DAYLIGHT_SAVINGS_DIFF 1
#define GMT_OFFSET_SECS (PST_TIME_ZONE * 3600)
#define GMT_OFFSET_SECS_DST ((PST_TIME_ZONE + PST_TIME_ZONE_DAYLIGHT_SAVINGS_DIFF) * 3600)
// Translate iot_configs.h defines into variables used by the sample
static const char* ssid = IOT_CONFIG_WIFI_SSID;
static const char* password = IOT_CONFIG_WIFI_PASSWORD;
static const char* host = IOT_CONFIG_IOTHUB_FQDN;
static const char* mqtt_broker_uri = "mqtts://" IOT_CONFIG_IOTHUB_FQDN;
static const char* device_id = IOT_CONFIG_DEVICE_ID;
static const int mqtt_port = AZ_IOT_DEFAULT_MQTT_CONNECT_PORT;
// Memory allocated for the sample's variables and structures.
static esp_mqtt_client_handle_t mqtt_client;
static az_iot_hub_client client;
static char mqtt_client_id[128];
static char mqtt_username[128];
static char mqtt_password[200];
static uint8_t sas_signature_buffer[256];
static unsigned long next_telemetry_send_time_ms = 0;
static char telemetry_topic[128];
static uint8_t telemetry_payload[100];
static uint32_t telemetry_send_count = 0;
#define INCOMING_DATA_BUFFER_SIZE 128
static char incoming_data[INCOMING_DATA_BUFFER_SIZE];
// Auxiliary functions
#ifndef IOT_CONFIG_USE_X509_CERT
static AzIoTSasToken sasToken(
&client,
AZ_SPAN_FROM_STR(IOT_CONFIG_DEVICE_KEY),
AZ_SPAN_FROM_BUFFER(sas_signature_buffer),
AZ_SPAN_FROM_BUFFER(mqtt_password));
#endif // IOT_CONFIG_USE_X509_CERT
static void connectToWiFi()
{
Logger.Info("Connecting to WIFI SSID " + String(ssid));
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Logger.Info("WiFi connected, IP address: " + WiFi.localIP().toString());
}
static void initializeTime()
{
Logger.Info("Setting time using SNTP");
configTime(GMT_OFFSET_SECS, GMT_OFFSET_SECS_DST, NTP_SERVERS);
time_t now = time(NULL);
while (now < UNIX_TIME_NOV_13_2017)
{
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("");
Logger.Info("Time initialized!");
}
void receivedCallback(char* topic, byte* payload, unsigned int length)
{
Logger.Info("Received [");
Logger.Info(topic);
Logger.Info("]: ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println("");
}
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event)
{
switch (event->event_id)
{
int i, r;
case MQTT_EVENT_ERROR:
Logger.Info("MQTT event MQTT_EVENT_ERROR");
break;
case MQTT_EVENT_CONNECTED:
Logger.Info("MQTT event MQTT_EVENT_CONNECTED");
r = esp_mqtt_client_subscribe(mqtt_client, AZ_IOT_HUB_CLIENT_C2D_SUBSCRIBE_TOPIC, 1);
if (r == -1)
{
Logger.Error("Could not subscribe for cloud-to-device messages.");
}
else
{
Logger.Info("Subscribed for cloud-to-device messages; message id:" + String(r));
}
break;
case MQTT_EVENT_DISCONNECTED:
Logger.Info("MQTT event MQTT_EVENT_DISCONNECTED");
break;
case MQTT_EVENT_SUBSCRIBED:
Logger.Info("MQTT event MQTT_EVENT_SUBSCRIBED");
break;
case MQTT_EVENT_UNSUBSCRIBED:
Logger.Info("MQTT event MQTT_EVENT_UNSUBSCRIBED");
break;
case MQTT_EVENT_PUBLISHED:
Logger.Info("MQTT event MQTT_EVENT_PUBLISHED");
break;
case MQTT_EVENT_DATA:
Logger.Info("MQTT event MQTT_EVENT_DATA");
for (i = 0; i < (INCOMING_DATA_BUFFER_SIZE - 1) && i < event->topic_len; i++)
{
incoming_data[i] = event->topic[i];
}
incoming_data[i] = '\0';
Logger.Info("Topic: " + String(incoming_data));
for (i = 0; i < (INCOMING_DATA_BUFFER_SIZE - 1) && i < event->data_len; i++)
{
incoming_data[i] = event->data[i];
}
incoming_data[i] = '\0';
if (String(incoming_data) == "GETWEIGHT")
{
Logger.Info("Send Data To The Cloud ");
sendTelemetry();
}
else
{
Logger.Info("Data: " + String(incoming_data));
}
break;
case MQTT_EVENT_BEFORE_CONNECT:
Logger.Info("MQTT event MQTT_EVENT_BEFORE_CONNECT");
break;
default:
Logger.Error("MQTT event UNKNOWN");
break;
}
return ESP_OK;
}
static void initializeIoTHubClient()
{
az_iot_hub_client_options options = az_iot_hub_client_options_default();
options.user_agent = AZ_SPAN_FROM_STR(AZURE_SDK_CLIENT_USER_AGENT);
if (az_result_failed(az_iot_hub_client_init(
&client,
az_span_create((uint8_t*)host, strlen(host)),
az_span_create((uint8_t*)device_id, strlen(device_id)),
&options)))
{
Logger.Error("Failed initializing Azure IoT Hub client");
return;
}
size_t client_id_length;
if (az_result_failed(az_iot_hub_client_get_client_id(
&client, mqtt_client_id, sizeof(mqtt_client_id) - 1, &client_id_length)))
{
Logger.Error("Failed getting client id");
return;
}
if (az_result_failed(az_iot_hub_client_get_user_name(
&client, mqtt_username, sizeofarray(mqtt_username), NULL)))
{
Logger.Error("Failed to get MQTT clientId, return code");
return;
}
Logger.Info("Client ID: " + String(mqtt_client_id));
Logger.Info("Username: " + String(mqtt_username));
}
static int initializeMqttClient()
{
#ifndef IOT_CONFIG_USE_X509_CERT
if (sasToken.Generate(SAS_TOKEN_DURATION_IN_MINUTES) != 0)
{
Logger.Error("Failed generating SAS token");
return 1;
}
#endif
esp_mqtt_client_config_t mqtt_config;
memset(&mqtt_config, 0, sizeof(mqtt_config));
mqtt_config.uri = mqtt_broker_uri;
mqtt_config.port = mqtt_port;
mqtt_config.client_id = mqtt_client_id;
mqtt_config.username = mqtt_username;
#ifdef IOT_CONFIG_USE_X509_CERT
Logger.Info("MQTT client using X509 Certificate authentication");
mqtt_config.client_cert_pem = IOT_CONFIG_DEVICE_CERT;
mqtt_config.client_key_pem = IOT_CONFIG_DEVICE_CERT_PRIVATE_KEY;
#else // Using SAS key
mqtt_config.password = (const char*)az_span_ptr(sasToken.Get());
#endif
mqtt_config.keepalive = 30;
mqtt_config.disable_clean_session = 0;
mqtt_config.disable_auto_reconnect = false;
mqtt_config.event_handle = mqtt_event_handler;
mqtt_config.user_context = NULL;
mqtt_config.cert_pem = (const char*)ca_pem;
mqtt_client = esp_mqtt_client_init(&mqtt_config);
if (mqtt_client == NULL)
{
Logger.Error("Failed creating mqtt client");
return 1;
}
esp_err_t start_result = esp_mqtt_client_start(mqtt_client);
if (start_result != ESP_OK)
{
Logger.Error("Could not start mqtt client; error code:" + start_result);
return 1;
}
else
{
Logger.Info("MQTT client started");
return 0;
}
}
/*
#brief Gets the number of seconds since UNIX epoch until now.
#return uint32_t Number of seconds.
*/
static uint32_t getEpochTimeInSecs()
{
return (uint32_t)time(NULL);
}
static void establishConnection()
{
connectToWiFi();
initializeTime();
initializeIoTHubClient();
(void)initializeMqttClient();
}
static void getTelemetryPayload(az_span payload, az_span* out_payload)
{
az_span original_payload = payload;
payload = az_span_copy(
payload, AZ_SPAN_FROM_STR("{ \"deviceId\": "));
payload = az_span_copy(payload, AZ_SPAN_FROM_STR( IOT_CONFIG_DEVICE_ID ));
payload = az_span_copy(payload, AZ_SPAN_FROM_STR( "," ));
payload = az_span_copy(payload, AZ_SPAN_FROM_STR( "\" weight\": "));
(void)az_span_u32toa(payload, weight , &payload);
payload = az_span_copy(payload, AZ_SPAN_FROM_STR(" }"));
payload = az_span_copy_u8(payload, '\0');
*out_payload = az_span_slice(original_payload, 0, az_span_size(original_payload) - az_span_size(payload) - 1);
}
static void sendTelemetry()
{
az_span telemetry = AZ_SPAN_FROM_BUFFER(telemetry_payload);
Logger.Info("Sending telemetry ...");
// The topic could be obtained just once during setup,
// however if properties are used the topic need to be generated again to reflect the
// current values of the properties.
if (az_result_failed(az_iot_hub_client_telemetry_get_publish_topic(
&client, NULL, telemetry_topic, sizeof(telemetry_topic), NULL)))
{
Logger.Error("Failed az_iot_hub_client_telemetry_get_publish_topic");
return;
}
getTelemetryPayload(telemetry, &telemetry);
if (esp_mqtt_client_publish(
mqtt_client,
telemetry_topic,
(const char*)az_span_ptr(telemetry),
az_span_size(telemetry),
MQTT_QOS1,
DO_NOT_RETAIN_MSG)
== 0)
{
Logger.Error("Failed publishing");
}
else
{
Logger.Info("Message published successfully");
}
}
// Arduino setup and loop main functions.
void setup()
{
establishConnection();
pinMode(PushButton, INPUT);
}
void loop()
{
if (WiFi.status() != WL_CONNECTED)
{
connectToWiFi();
}
#ifndef IOT_CONFIG_USE_X509_CERT
else if (sasToken.IsExpired())
{
Logger.Info("SAS token expired; reconnecting with a new one.");
(void)esp_mqtt_client_destroy(mqtt_client);
initializeMqttClient();
}
#endif
int Push_button_state = digitalRead(PushButton);
// if condition checks if push button is pressed
if ( Push_button_state == HIGH )
{
Serial.println("De Button Is ingedrukt");
sendTelemetry();
delay(500);
}
}
The idea is that when I send a Direct Method "GETWEIGHT" I get a json value back.
In your initializeMqttClient method, you can add the following line.
mqtt_client.setCallback(receivedCallback);
Your receivedCallback method can have the following definition (code from a Microsoft sample)
void receivedCallback(char* topic, byte* payload, unsigned int length)
{
Logger.Info("Received [");
Logger.Info(topic);
Logger.Info("]: ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println("");
}
You mentioned you want to retrieve data from the device, so you probably want to respond to the message. This is done by sending a message on the right topic. You need to include the status (for instance a 200 indicating 'OK') and the ID of the direct method. This id is included when you receive the direct method. For instance, if you receive a direct method with ID 42, you can respond to it by publishing:
void RespondToDirectMethod()
{
mqtt_client.publish("$iothub/methods/res/200/?$rid=42", "", false);
}

Why have I connection failed when I try to connect to my localhost?

I have an esp32 with one sensor(BMP280) connected and one database where I want to storage three parameters: temperature, atmospheric pressure and altitude. The database is on localhost with 8080 port. I cannot to connect at my localhost and I have connection failed. I have tried to put at host the ip address 0.0.0.0 or localhost:8080 and it doesn't work. What is the problem?
I attach my code below:
#include <BMP280_DEV.h>
#include <WiFi.h>
float temperature, pressure, altitude;
BMP280_DEV bmp280;
const char * ssid = "*******";
const char * password = "*********";
const char * host = "127.0.0.1";
const int port = 8080;
const int watchdog = 5000;
unsigned long previousMillis = millis();
void init_wifi() {
//We start by connecting to a Wi-Fi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
bmp280.begin(BMP280_I2C_ALT_ADDR);
//bmp280.setPresOversampling(OVERSAMPLING_X4);
//bmp280.setTempOversampling(OVERSAMPLING_X1);
//bmp280.setIIRFilter(IIR_FILTER_4);
bmp280.setTimeStandby(TIME_STANDBY_2000MS);
bmp280.startNormalConversion();
init_wifi();
}
void loop() {
if (bmp280.getMeasurements(temperature, pressure, altitude)) {
Serial.print(temperature);
Serial.print(F("*C "));
Serial.print(pressure);
Serial.print(F("hPa "));
Serial.print(altitude);
Serial.println(F("m"));
delay(20000);
}
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > watchdog) {
previousMillis = currentMillis;
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection Failed");
return;
}
String url = "/test_bmp280/index.php?temp=";
url += temperature;
url += "&pres=";
url += pressure;
url += "&alt=";
url += altitude;
client.print(String("GET ") + url + "HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>>Client Timeout !");
client.stop();
return;
}
}
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
}
}

esp8266 NodeMCU client cant connect to esp8266 NodeMCU server with static ip

Hello...
My code is working perfect with using dynamic IP's, the LED is connected to server and a push button is connected to client, it work perfect with dynamic IP's addresses of both devices. But when i make static IP addresses, the client can not connect to server, and it always says connection failed.
Client code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_61(192,168,100,59);
//IPAddress gateway612_61(192,168,100,1);
//IPAddress subnet612_61(255,255,255,0);
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char * host = "192.168.100.23"; // IP Server
const int httpPort = 80;
const char* Commands; // The command variable that is sent to the server
int button = 5; // push button is connected
bool btn_press = true; // The variable to detect the button has been pressed
int con = 0; // Variables for mode
void setup() {
// put your setup code here, to run once:
pinMode(button, INPUT_PULLUP); // initialize the pushbutton pin as an input:
Serial.begin(115200); // initialize serial:
Serial.println("");
Serial.println("Client-------------------------------");
Serial.print("Connecting to Network");
WiFi.mode(WIFI_STA); // Mode Station
WiFi.begin(ssid, password); // Matching the SSID and Password
delay(1000);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("Successfully Connecting");
Serial.println("Status : Connected");
//WiFi.config(staticIP612_61, gateway612_61, subnet612_61);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(button) == LOW) {
Serial.println("Client-------------------------------");
Serial.print("Send Command = ");
if (btn_press == true){
if (con >= 2) {
con=0;
}
con++;
switch (con){
case 1:
Commands="LED_On";
Serial.println(Commands);
send_commands();
break;
case 2:
Commands="LED_Off";
Serial.println(Commands);
send_commands();
break;
}
btn_press = false;
}
}
else {
btn_press = true;
}
delay(100);
}
void send_commands(){
Serial.println("Sending command...");
Serial.println("Don't press the button for now...");
Serial.println("");
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, httpPort)) {
Serial.println("Connection failed");
return;
}
// We now create a URI for the request
Serial.print("Requesting URL : ");
Serial.println(Commands);
// This will send the request to the server
client.print(String("GET ") + Commands + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: Close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
Serial.print("Server Reply = ");
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println("Now you can press the button ...");
Serial.println("-------------------------------------");
Serial.println("");
}
Server code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_60(192,168,100,60);
//IPAddress gateway612_60(192,168,100,1);
//IPAddress subnet612_60(255,255,255,0);
int led = 5; // the pin the LED is connected to
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char* Commands_Reply; // The command variable that is sent to the client
const char * host = "192.168.100.21"; // IP Client
WiFiServer server(80);
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT); // Declare the LED as an output
Serial.begin(115200); // initialize serial:
delay(10);
Serial.println("");
Serial.println("Server-------------------------------");
Serial.print("Configuring access point");
WiFi.begin(ssid, password);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// WiFi.config(staticIP612_60, gateway612_60, subnet612_60);
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("Server-------------------------------");
Serial.println("New client");
Serial.print("From client = ");
while(!client.available()){
delay(1);
}
// Read the first line of the request -------------------------------------
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
//Command LED -------------------------------------------------------------
if (req.indexOf("LED_On") != -1){
Commands_Reply = "LED Status : On";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, HIGH);
}
else if (req.indexOf("LED_Off") != -1){
Commands_Reply = "LED Status : Off";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, LOW);
}
else {
Serial.println("invalid request");
client.stop();
return;
}
client.flush();
Serial.println("Client disonnected");
Serial.println("-------------------------------------");
Serial.println("");
}
NOTE I have commented all the static IP lines, when i comment them and using dynamic ips, client connect to server perfectly and when i use static ips instead of dynamic ips client fails to connect with server. any help will be appreciated.

Arduino web socket autoreconnect

I am using 2 esp8266, both connected to same network. Esp1 send some data to esp2 using websocket. So basically esp2 connect to esp1 websocket and read data.
My problem is that if esp1 is restarted, after is up again, esp2 does not connect anymore to it and needs restart to connect
This is code I am using on esp2
#include <ESP8266WiFi.h>
#include <WebSocketsClient.h>
#include <ESP8266WebServer.h>
#include <SoftwareSerial.h>
#define USE_SERIAL Serial
#define LEDS 0 //Status led
WebSocketsClient webSocket;
SoftwareSerial COM(5, 4);
long previousMillis = 0;
long interval = 50;
String data;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
yield();
break;
case WStype_CONNECTED: {
webSocket.sendTXT("Connected");
}
yield();
break;
case WStype_TEXT:
if(payload[0] == '#') {
uint32_t dataz = (uint32_t) strtol((const char *) &payload[1], NULL, 10);
if (dataz < 99911) {
data = "0" + String(dataz);
}
else {
data = String(dataz);
}
}
yield();
if (data.length() == 6 ) {
COM.print('<'); // start marker
COM.print(data);
COM.println('>'); // end marker
}
break;
}
}
void setup() {
pinMode(LEDS, OUTPUT);
digitalWrite(LEDS, LOW);
for(uint8_t t = 4; t > 0; t--) {
delay(1000);
}
WiFi.mode(WIFI_STA);
WiFi.begin("xxx", "xxx");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
// server address, port and URL
webSocket.begin("192.168.0.30", 81, "/");
// event handler
webSocket.onEvent(webSocketEvent);
// use HTTP Basic Authorization this is optional remove if not needed
//webSocket.setAuthorization("user", "Password");
// try ever 5000 again if connection has failed
webSocket.setReconnectInterval(5000);
digitalWrite(LEDS, HIGH);
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
webSocket.loop();
}
}
I would need some help to make it reconnect when the esp1 is available again after was disconnected
Thank you very much
webSocket.loop(); should be outside of if statement.

NodeMCU Get data from webswerver and update value

I am using Nodenmcu with arduino IDE . I have used DHT11 IC to read temperature and humidity. Now i would like to add parameter in web page called set_temp . When Set_temp value being set to value the value should get updated when change icon has been pressed. Here is my code. My code is working till to enter the text from web but it wont update set_temp value
#include <ESP8266WiFi.h>
#include "DHT.h"
static float Set_Temp;
DHT dht;
int value = LOW;
const char* ssid = "esp8266";
const char* password = "Test123456";
int ledPin = 13; // GPIO13
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
dht.setup(D3); /* D1 is used for data communication */
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// New code has been added
delay(dht.getMinimumSamplingPeriod()); /* Delay of amount equal to sampling period */
float humidity = dht.getHumidity(); /* Get humidity value */
float temperature = dht.getTemperature(); /* Get temperature value */
// Serial.print(dht.getStatusString()); /* Print status of communication */
if(temperature>=Set_Temp)
{
digitalWrite(ledPin, HIGH);
value = HIGH;
}else
{
digitalWrite(ledPin, LOW);
value = LOW;
}
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
/* if (request.indexOf("/LED=ON") != -1) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
value = LOW;
}*/
// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("Relay_Turn_On_Status: ");
if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
// client.println("<br><br>");
// client.println("<button>Turn On </button>");
// client.println("<button>Turn Off </button><br />");
// client.println("</html>");
client.print("</html>");
client.print("<head>");
client.print("<title>My Page</title>");
client.print("</head>");
client.print("<body>");
client.print("<br><br>");
client.print("Set_Temp: ");
client.println("<input type=text name=textbox size=5 value=Enter_Temp_Here");
client.println("<br><input type=submit value=Change ><br>");
client.println("</div>");
client.println("</body>");
client.println("</html>");
Set_Temp:"<br><input type=submit value=Change ><br>";
//Set_Temp:"<input type=text name=textbox size=5 value=Enter_Temp_Here>";
Serial.println(Set_Temp);
client.println("<br><br>");
client.println("DHT11_HumidityReading: ");
client.println(humidity,1);
client.println("<br><br>");
client.println("DHT11_Temprature Reading: ");
client.println(temperature,1);
client.println("<br><br>");
client.println("Set_Temp: ");
client.println(Set_Temp);
client.println("<br><br>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
My main doubt in this part of code where once i read it wont update.
Set_Temp:"<br><input type=submit value=Change ><br>";
//Set_Temp:"<input type=text name=textbox size=5 value=Enter_Temp_Here>";
Serial.println(Set_Temp);
If i use like this. it will display -1
Set_Temp=readString.indexOf(2);
I followed the method of get & post from HTTP https://www.w3schools.com/htmL/[Serial Out Here][web page]
How can i change my Set_Temp value from text box.
Take a look to this article, I follow it to turn on and turn off a light in NodeMCU with Arduino IDE. The client in the web is written on PHP.
https://blog.nyl.io/esp8266-led-arduino/
<?php
$light = $_GET['light'];
if($light == "on") {
$file = fopen("light.json", "w") or die("can't open file");
fwrite($file, '{"light": "on"}');
fclose($file);
}
else if ($light == "off") {
$file = fopen("light.json", "w") or die("can't open file");
fwrite($file, '{"light": "off"}');
fclose($file);
}
?>
I hope this help you.
Regards

Resources