wifimanager code:-
#ifdef ESP32
#include <esp_wifi.h>
#include <WiFi.h>
#include <WiFiClient.h>
#define ESP_getChipId() ((uint32_t)ESP.getEfuseMac())
#define LED_ON HIGH
#define LED_OFF LOW
#else
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#define ESP_getChipId() (ESP.getChipId())
#define LED_ON LOW
#define LED_OFF HIGH
#endif
// SSID and PW for Config Portal
String ssid = "ESP_" + String(ESP_getChipId(), HEX);
const char* password = "your_password";
// SSID and PW for your Router
String Router_SSID;
String Router_Pass;
// Use false if you don't like to display Available Pages in Information Page of Config Portal
// Comment out or use true to display Available Pages in Information Page of Config Portal
// Must be placed before #include <ESP_WiFiManager.h>
#define USE_AVAILABLE_PAGES false
#include <ESP_WiFiManager.h> //https://github.com/khoih-prog/ESP_WiFiManager
// Onboard LED I/O pin on NodeMCU board
const int PIN_LED = 2; // D4 on NodeMCU and WeMos. GPIO2/ADC12 of ESP32. Controls the onboard LED.
void heartBeatPrint(void)
{
static int num = 1;
if (WiFi.status() == WL_CONNECTED)
Serial.print("H"); // H means connected to WiFi
else
Serial.print("F"); // F means not connected to WiFi
if (num == 80)
{
Serial.println();
num = 1;
}
else if (num++ % 10 == 0)
{
Serial.print(" ");
}
}
void check_status()
{
static ulong checkstatus_timeout = 0;
//KH
#define HEARTBEAT_INTERVAL 10000L
// Print hearbeat every HEARTBEAT_INTERVAL (10) seconds.
if ((millis() > checkstatus_timeout) || (checkstatus_timeout == 0))
{
heartBeatPrint();
checkstatus_timeout = millis() + HEARTBEAT_INTERVAL;
}
}
void setup()
{
// put your setup code here, to run once:
// initialize the LED digital pin as an output.
pinMode(PIN_LED, OUTPUT);
Serial.begin(115200);
Serial.println("\nStarting");
unsigned long startedAt = millis();
digitalWrite(PIN_LED, LED_ON); // turn the LED on by making the voltage LOW to tell us we are in configuration mode.
//Local intialization. Once its business is done, there is no need to keep it around
// Use this to default DHCP hostname to ESP8266-XXXXXX or ESP32-XXXXXX
ESP_WiFiManager ESP_wifiManager;
// Use this to personalize DHCP hostname (RFC952 conformed)
//ESP_WiFiManager ESP_wifiManager("ConfigOnStartup");
ESP_wifiManager.setMinimumSignalQuality(-1);
// Set static IP, Gateway, Subnetmask, DNS1 and DNS2. New in v1.0.5
ESP_wifiManager.setSTAStaticIPConfig(IPAddress(192,168,2,114), IPAddress(192,168,2,1), IPAddress(255,255,255,0),
IPAddress(192,168,2,1), IPAddress(8,8,8,8));
// We can't use WiFi.SSID() in ESP32as it's only valid after connected.
// SSID and Password stored in ESP32 wifi_ap_record_t and wifi_config_t are also cleared in reboot
// Have to create a new function to store in EEPROM/SPIFFS for this purpose
Router_SSID = ESP_wifiManager.WiFi_SSID();
Router_Pass = ESP_wifiManager.WiFi_Pass();
//Remove this line if you do not want to see WiFi password printed
Serial.println("Stored: SSID = " + Router_SSID + ", Pass = " + Router_Pass);
//Check if there is stored WiFi router/password credentials.
//If not found, device will remain in configuration mode until switched off via webserver.
Serial.print("Opening configuration portal.");
if (Router_SSID != "")
{
ESP_wifiManager.setConfigPortalTimeout(60); //If no access point name has been previously entered disable timeout.
Serial.println("Timeout 60s");
}
else
Serial.println("No timeout");
// SSID to uppercase
ssid.toUpperCase();
//it starts an access point
//and goes into a blocking loop awaiting configuration
if (!ESP_wifiManager.startConfigPortal((const char *) ssid.c_str(), password))
Serial.println("Not connected to WiFi but continuing anyway.");
else
Serial.println("WiFi connected...yeey ");
digitalWrite(PIN_LED, LED_OFF); // Turn led off as we are not in configuration mode.
// For some unknown reason webserver can only be started once per boot up
// so webserver can not be used again in the sketch.
#define WIFI_CONNECT_TIMEOUT 30000L
#define WHILE_LOOP_DELAY 200L
#define WHILE_LOOP_STEPS (WIFI_CONNECT_TIMEOUT / ( 3 * WHILE_LOOP_DELAY ))
startedAt = millis();
while ( (WiFi.status() != WL_CONNECTED) && (millis() - startedAt < WIFI_CONNECT_TIMEOUT ) )
{
#ifdef ESP32
WiFi.mode(WIFI_STA);
WiFi.persistent (true);
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(Router_SSID);
WiFi.begin(Router_SSID.c_str(), Router_Pass.c_str());
#endif
int i = 0;
while((!WiFi.status() || WiFi.status() >= WL_DISCONNECTED) && i++ < WHILE_LOOP_STEPS)
{
delay(WHILE_LOOP_DELAY);
}
}
Serial.print("After waiting ");
Serial.print((millis()- startedAt) / 1000);
Serial.print(" secs more in setup(), connection result is ");
if (WiFi.status() == WL_CONNECTED)
{
Serial.print("connected. Local IP: ");
Serial.println(WiFi.localIP());
}
//else
// Serial.println(ESP_wifiManager.getStatus(WiFi.status()));
}
void loop()
{
// put your main code here, to run repeatedly
check_status();
}
Code which i want to combine with wifimanager:-
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsClient.h>
#include <Hash.h>
// @@@@@@@@@@@@@@@ You only need to midify modify wi-fi and domain info @@@@@@@@@@@@@@@@@@@@
const char* ssid = "enter your ssid name"; //enter your ssid/ wi-fi(case sensitiv) router name - 2.4 Ghz only
const char* password = "enter ssid password"; // enter ssid password (case sensitiv)
char host[] = "espiot.herokuapp.com"; //enter your Heroku domain name like "espiot.herokuapp.com"
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
int port = 80;
char path[] = "/ws";
ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
const int relayPin = 16;
DynamicJsonBuffer jsonBuffer;
String currState;
int pingCount=0;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) { //uint8_t *
switch(type) {
case WStype_DISCONNECTED:
Serial.println("Disconnected! ");
Serial.println("Connecting...");
webSocket.begin(host, port, path);
webSocket.onEvent(webSocketEvent);
break;
case WStype_CONNECTED:
{
Serial.println("Connected! ");
// send message to server when Connected
webSocket.sendTXT("Connected");
}
break;
case WStype_TEXT:
Serial.println("Got data");
//data = (char*)payload;
processWebScoketRequest((char*)payload);
break;
case WStype_BIN:
hexdump(payload, length);
Serial.print("Got bin");
// send data to server
webSocket.sendBIN(payload, length);
break;
}
}
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
pinMode(relayPin, OUTPUT);
for(uint8_t t = 4; t > 0; t--) {
delay(1000);
}
Serial.println();
Serial.println();
Serial.print("Connecting to ");
//Serial.println(ssid);
WiFiMulti.addAP(ssid, password);
//WiFi.disconnect();
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println("Connected to wi-fi");
webSocket.begin(host, port, path);
webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop();
//If you make change to delay mak sure adjust the ping
delay(2000);
// make sure after every 40 seconds send a ping to Heroku
//so it does not terminate the websocket connection
//This is to keep the conncetion alive between ESP and Heroku
if (pingCount > 20) {
pingCount = 0;
webSocket.sendTXT("\"heartbeat\":\"keepalive\"");
}
else {
pingCount += 1;
}
}
void processWebScoketRequest(String data){
JsonObject& root = jsonBuffer.parseObject(data);
String device = (const char*)root["device"];
String location = (const char*)root["location"];
String state = (const char*)root["state"];
String query = (const char*)root["query"];
String message="";
Serial.println(data);
if(query == "cmd"){ //if query check state
Serial.println("Received command!");
if(state=="on"){
digitalWrite(relayPin, HIGH);
message = "{\"state\":\"ON\"}";
currState = "ON";
}else{
digitalWrite(relayPin, LOW);
message = "{\"state\":\"OFF\"}";
currState = "OFF";
}
}else if(query == "?"){ //if command then execute
Serial.println("Received query!");
int state = digitalRead(relayPin);
if(currState=="ON"){
message = "{\"state\":\"ON\"}";
}else{
message = "{\"state\":\"OFF\"}";
}
}else{//can not recognized the command
Serial.println("Command is not recognized!");
}
Serial.print("Sending response back");
Serial.println(message);
// send message to server
webSocket.sendTXT(message);
if(query == "cmd" || query == "?"){webSocket.sendTXT(message);}
}