ErDFSzZn

2021-09-13 19:10

			/*
 MQTT pin json:
 PiServer/ChipID/Status:
 { 
 "internet": true,
 "inputs": {
  "light": {
   "1": 0,
   "2": 0,
   "3": 1,
   "4": 0 },
  "fan": {
   "1": 0,
   "2": 1,
   "3": 0 }
  }
}
*/

#include <WiFi.h>
#include <WiFiClient.h>
//#include <WebServer.h> //copiedota // removed from 0.4
#include <ESPmDNS.h> //copiedota

#include <PubSubClient.h>//0.4
//#include <HTTPClient.h> //0.4
#include <ArduinoJson.h> //0.4
#include<string.h> //0.4
#include<cstring> //0.4

#include <WiFiManager.h>   
#include <ArduinoJson.h>          // https://github.com/bblanchon/ArduinoJson

#include <BlynkSimpleEsp32.h>
BlynkTimer timer;

#define DEBUG_SW 1



// Pins of Fan Regulator Knob
#define s1  27
#define s2  14
#define s3  12
#define s4  13


// Pins of Switches
#define S5 32
#define S6 35
#define S7 34
#define S8 39

// Pins of Relay (Appliances Control)
#define R5 15
#define R6 2
#define R7 4
#define R8 22

// Pins of Relay (Fan Speed Control)
#define Speed1 21
#define Speed2 19
#define Speed4 18

// By default the mode is with_internet
bool OPMODE = false;
bool connected_once = false;

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "xxxx";

// Your WiFi credentials.
const char* dnshost = "shariqESP"; //copiedota
// Set password to "" for open networks.

char ssid[] = "";

char pass[] = "xxxx";

//const char* SSID = "Wifi aye bahaar aya";//ota_esp32_client_aws_json_mqtt2
//const char* PSWD = "dingding"; //ota_esp32_client_aws_json_mqtt2

bool speed1_flag = 1;
bool speed2_flag = 1;
bool speed3_flag = 1;
bool speed4_flag = 1;
bool speed0_flag = 1;

int switch_ON_Flag1_previous_I = 0;
int switch_ON_Flag2_previous_I = 0;
int switch_ON_Flag3_previous_I = 0;
int switch_ON_Flag4_previous_I = 0;

//WebServer server(80); //copiedota // commented in 0.4


// Set your Static IP address
IPAddress local_IP(192, 168, 0, 50);
// Set your Gateway IP address
IPAddress gateway(192, 168, 0, 1);

IPAddress subnet(255, 255, 0, 0);
//IPAddress primaryDNS(8, 8, 8, 8);   //optional
//IPAddress secondaryDNS(8, 8, 4, 4); //optional

//0.4
long contentLength = 0;//0.4 needed OTA
bool isValidContentType = false; //0.4 needed OTA
uint32_t chipId = 0; //for chip id
String chipIdStr ="";//for chip id

//0.4
//mqtt params
const char* mqttServer = "192.168.0.4"; //check actual config of node-red
const int mqttPort = 1881;
const char* mqttUser = "";
const char* mqttPassword = "";
String topicOTA= "ESP/OTAStatus/";
String topicStatus= "ESP/Status/";
String PiStatus= "PiServer/"; //"PiServer/97244/Status"
String PiOTAInpStatus= "PiServer/ESP/OTA/";
//String PiRestart ;//"PiServer/97244/Status/Restart"


String host = ""; //0.4 192.168.0.5
int port = 80; 
String bin = "0.4"; // /sketch_name.ino.esp32.binbin-> file name with a slash in front.

WiFiClient espClient; //0.4
PubSubClient pubsubclient(espClient);//0.4



void cloud_write(uint8_t pin,int pinValue)
{
  Serial.print(pin );
  Serial.print(" " );
  Serial.println(pinValue );
   digitalWrite(pin, pinValue);
  
  // process received value
}

void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Connected to AP successfully!");
}

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Disconnected from WiFi access point");
  Serial.print("WiFi lost connection. Reason: ");
  Serial.println(info.disconnected.reason);
  Serial.println("Trying to Reconnect");
  //WiFi.begin(ssid, password);
  WiFi.reconnect();
}


void callback(char* topic, byte* payload, unsigned int length) {
 //lines removed
}

// Utility to extract header value from headers
String getHeaderValue(String header, String headerName) {
  return header.substring(strlen(headerName.c_str()));
}



void setup()
{
  // put your setup code here, to run once:
  pinMode(s1, INPUT);
  pinMode(s2, INPUT);
  pinMode(s3, INPUT_PULLUP);
  pinMode(s4, INPUT);
  pinMode(S5, INPUT);
  pinMode(S6, INPUT);
  pinMode(S7, INPUT);
  pinMode(S8, INPUT);

  pinMode(R5, OUTPUT);
  pinMode(R6, OUTPUT);
  pinMode(R7, OUTPUT);
  pinMode(R8, OUTPUT);
  pinMode(Speed1, OUTPUT);
  pinMode(Speed2, OUTPUT);
  pinMode(Speed4, OUTPUT);

  Serial.begin(115200);
  
   //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wm;

  wm.setConfigPortalTimeout(40);
  
   //wm.setDebugOutput(true);
  
Serial.printf("SSID0: %s\n", wm.getWiFiSSID().c_str());
String saved_ssid_old =wm.getWiFiSSID().c_str();

  if(!wm.autoConnect("AutoConnectAP")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    //ESP.restart();
    //delay(5000);
  } 

   String saved_ssid =WiFi.SSID().c_str();
   Serial.print("SSID1: ");
   Serial.println(saved_ssid);
   //Serial.printf("SSID1: %s\n", WiFi.SSID().c_str());
   Serial.println("SSID00: " + (String)wm.getWiFiSSID());
   Serial.println( wm.getWiFiIsSaved() );


if(WiFi.SSID().c_str() == ""){

int str_len = saved_ssid_old.length() + 1; 
char char_array[str_len];
// Copy it over 
saved_ssid_old.toCharArray(char_array, str_len);
Serial.println( ssid);

strcpy(ssid , char_array);

}
  
if(WiFi.SSID().c_str() != ""){
    Serial.println("not blank");

  //String saved_ssid =WiFi.SSID().c_str();
  //String saved_ssid_old =wm.getWiFiSSID().c_str();
  Serial.println(saved_ssid);
 
  strncpy(ssid, WiFi.SSID().c_str(), saved_ssid.length());
ssid[saved_ssid.length() ] = '\0';

        
}
Serial.print("Now printing SSID:");
  Serial.println( ssid);

wm.disconnect();
delay(1000);  


WiFi.onEvent(WiFiStationConnected, SYSTEM_EVENT_STA_CONNECTED);
WiFi.onEvent(WiFiGotIP, SYSTEM_EVENT_STA_GOT_IP);
WiFi.onEvent(WiFiStationDisconnected, SYSTEM_EVENT_STA_DISCONNECTED);

  
   WiFi.begin(ssid, pass);
    Serial.print("main begin ssid:");
    Serial.println(ssid);
    int ct= 0;
      Serial.print("before while ssid:");
    Serial.println(ssid);
    
    while(WiFi.status() != WL_CONNECTED ){
      delay(1000);
      ct=ct+1000;
      if(ct>5000){
        Serial.println("not able to connect to wifi");        
        break;
        }
      }

    Serial.print("after while bfore if ssid:");
    Serial.println(ssid);

//0.4 logic starts
    delay(10);
  for(int i=0; i<17; i=i+8) { //get chip id for esp32
    chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
    }
    
  chipIdStr= String(chipId).substring(0,5) ;
  topicOTA += chipIdStr;
  topicStatus += chipIdStr;
  PiStatus += chipIdStr+"/Status";
  //PiRestart= PiStatus+"/Restart";
  PiOTAInpStatus += chipIdStr ;
  
   //Serial.printf("ESP32 Chip model = %s Rev %d\n", ESP.getChipModel(), ESP.getChipRevision());

  Serial.print("OTA: ");
  Serial.println(topicOTA.c_str());
  Serial.print("Status: ");
  Serial.println(topicStatus.c_str());
  
  Serial.print("after2 while bfore if ssid:");
  Serial.println(ssid);
   setup_mqtt();
   //0.4 logic ends
   
   //setdns(); //custom // changed from setOTA in 0.4//removed in 0.5

 Serial.print("after ota ssid:");
    Serial.println(ssid);
 timer.setInterval(3000L, checkBlynk); // check if connected to Blynk server every 3 seconds

  Blynk.config(auth);//, ssid, pass);
   Serial.print("End ssid:");
    Serial.println(ssid);
}

//0.4 added function
void setup_mqtt(){

 Serial.print("after3a:");
  Serial.println(ssid);
   
   pubsubclient.setServer(mqttServer, mqttPort);
  pubsubclient.setCallback(callback);
  int  mqct =0;
  Serial.print("after3b:");
  Serial.println(ssid);
   
  while ( (!pubsubclient.connected()) || (mqct< 1200)) {
    Serial.print("after4:");
  Serial.println(ssid);
    Serial.println("Connecting to MQTT...");
 
//    if (pubsubclient.connect("ESP32Client", mqttUser, mqttPassword )) {
if (pubsubclient.connect( chipIdStr.c_str(), mqttUser, mqttPassword )) {

   Serial.print("after5:");
  Serial.println(ssid);
 //if (client.connect("ESP32Client")) {
      Serial.println("connected");  
      //pubsubclient.publish("ESP_Status","ESP device connected ");

      
      pubsubclient.subscribe(PiStatus.c_str());//"PiServer/97244/Status"
      //pubsubclient.subscribe(PiRestart.c_str());//"PiServer/97244/Status/Restart"
      pubsubclient.subscribe(PiOTAInpStatus.c_str());//"PiServer/ESP/OTA/97244"
      Serial.print("Trying to publish in ");
      Serial.println(topicStatus.c_str());
      pubsubclient.publish(topicStatus.c_str(),"ESP device connected ");
 
 Serial.print("after5a:");
  Serial.println(ssid);


      OPMODE =false;
      
 
    } else {

       Serial.print("after6:");
  Serial.println(ssid);
      Serial.print("failed with state ");
      Serial.println(pubsubclient.state());
       Serial.println((bool)OPMODE);
      delay(600);
       if ( !OPMODE ){
      OPMODE =true;
       }
      //port = 79;
       Serial.println((bool)OPMODE);

      Serial.print("after6.1:");
  Serial.println(ssid);
      
      mqct= mqct+600;
      if (mqct>1200) {
         Serial.print("after6a:");
  Serial.println(ssid);
        Serial.println("MQTT cannot be reached");
        break;
      }
       Serial.print("after6b:");
  Serial.println(ssid);
 
    }
     Serial.print("after7:");
  Serial.println(ssid);
  }
  Serial.print("after8:");
  Serial.println(ssid);
 
  }


void loop()
{
  //Check WiFi connection status
  Serial.print("Wifi status: ");
   Serial.print("Start ssid:");
    Serial.println(ssid);
  
  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(ssid);
    Serial.println(WiFi.SSID().c_str() );
    if (DEBUG_SW) Serial.println("Not Connected");
    
 
    
  }
  else
  {
    //0.4 logic added
    //reconnect to mqtt or process if incoming string present
    if (pubsubclient.connected()) {
    Serial.println("connected with MQTT");
    pubsubclient.loop();
 
    } else {
 
      Serial.print("Reconnect to MQTT server failed with state ");
      Serial.print(pubsubclient.state());
          
      setup_mqtt();
 
    }
    //0.4 logic ends
    delay(1000);
    digitalWrite(R6,HIGH);
    if (DEBUG_SW) Serial.println("Wifi Connected");
    Blynk.run();
    
  }
  timer.run(); // Initiates SimpleTimer
  //server.handleClient(); //custom// removed from 0.4

   delay(400); //custom
   //digitalWrite(R6,LOW);

if (OPMODE)
    without_internet();
  else
  with_internet();
    
}

void with_internet()
{
//
}


void without_internet()
{
//
}



// Fan Speed Control

void checkBlynk()
{
         Serial.println("Blynk check");

  bool isconnected = Blynk.connected();
  if (isconnected == false)
  {

    Serial.println("Blynk disconnected");

    OPMODE = true;
  }
  if (isconnected == true)
  {
    Serial.println("Blynk connected");
    OPMODE = false;
  }
}