#include <ESP8266WiFi.h>
#include "HTTPSRedirect.h"
#include <DNSServer.h>
#include <espnow.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <AsyncElegantOTA.h>
#include "DebugMacros.h"
//#include<SoftwareSerial.h>
#include <ESPAsyncWiFiManager.h>
#include <EEPROM.h>
#include <ArduinoJson.h> // https://arduinojson.org/ or install via Arduino library manager
#include "file.h"
//callback notifying us of the need to save config
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;
}
void wifiSetup (void){
AsyncWebServer webServer(80);
DNSServer dnsServer;
//read configuration from FS json
Serial.println("mounting FS...");
if (SPIFFS.begin()) {
Serial.println("mounted file system");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument jsonBuffer(1024);
JsonObject json = jsonBuffer.as<JsonObject>();
serializeJson(json, Serial);
//json.printTo(Serial);
if (!json.isNull()) {
Serial.println("\nparsed json");
strcpy(userkey, json["userkey"]);
/*
strcpy(device1, json["device1"]);
strcpy(device2, json["device2"]);
strcpy(device3, json["device3"]);
strcpy(device4, json["device4"]);
strcpy(device5, json["device5"]);
strcpy(device6, json["device6"]);
strcpy(device7, json["device7"]);
strcpy(device8, json["device8"]);
strcpy(device9, json["device9"]);
strcpy(device10, json["device10"]);
strcpy(device11, json["device11"]);
strcpy(device12, json["device12"]);
strcpy(device13, json["device13"]);
strcpy(device14, json["device14"]);
strcpy(device15, json["device15"]);
*/
} else {
Serial.println("failed to load json config");
}
}
} else {
uint32_t start_time1 = millis();
Serial.println("delay started ");
Serial.println("failed to mount FS");
while((millis()-start_time1) < 70000)//sample for 1000ms
{
Serial.println(".");
};
}
//end read
// The extra parameters to be configured (can be either global or just in the setup)
// After connecting, parameter.getValue() will get you the configured value
// id/name placeholder/prompt default length
AsyncWiFiManagerParameter custom_userkey("userkey", "Mobile APP UserKey", userkey, 40);
/*
AsyncWiFiManagerParameter custom_device1("device1", "Device 1", device1, 40);
AsyncWiFiManagerParameter custom_device2("device2", "Device 2", device2, 40);
AsyncWiFiManagerParameter custom_device3("device3", "Device 3", device3, 40);
AsyncWiFiManagerParameter custom_device4("device4", "Device 4", device4, 40);
AsyncWiFiManagerParameter custom_device5("device5", "Device 5", device5, 40);
AsyncWiFiManagerParameter custom_device6("device6", "Device 6", device6, 40);
AsyncWiFiManagerParameter custom_device7("device7", "Device 7", device7, 40);
AsyncWiFiManagerParameter custom_device8("device8", "Device 8", device8, 40);
AsyncWiFiManagerParameter custom_device9("device9", "Device 9", device9, 40);
AsyncWiFiManagerParameter custom_device10("device10", "Device 10", device10, 40);
AsyncWiFiManagerParameter custom_device11("device11", "Device 11", device11, 40);
AsyncWiFiManagerParameter custom_device12("device12", "Device 12", device12, 40);
AsyncWiFiManagerParameter custom_device13("device13", "Device 13", device13, 40);
AsyncWiFiManagerParameter custom_device14("device14", "Device 14", device14, 40);
AsyncWiFiManagerParameter custom_device15("device15", "Device 15", device15, 40);
*/
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
AsyncWiFiManager wifiManager(&webServer,&dnsServer);
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
//set static ip
//wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//add all your parameters here
wifiManager.addParameter(&custom_userkey);
/*
wifiManager.addParameter(&custom_device1);
wifiManager.addParameter(&custom_device2);
wifiManager.addParameter(&custom_device3);
wifiManager.addParameter(&custom_device4);
wifiManager.addParameter(&custom_device5);
wifiManager.addParameter(&custom_device6);
wifiManager.addParameter(&custom_device7);
wifiManager.addParameter(&custom_device8);
wifiManager.addParameter(&custom_device9);
wifiManager.addParameter(&custom_device10);
wifiManager.addParameter(&custom_device11);
wifiManager.addParameter(&custom_device12);
wifiManager.addParameter(&custom_device13);
wifiManager.addParameter(&custom_device14);
wifiManager.addParameter(&custom_device15);
*/
//reset settings - for testing
//wifiManager.resetSettings();
//set minimu quality of signal so it ignores AP's under that quality
//defaults to 8%
//wifiManager.setMinimumSignalQuality();
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
//wifiManager.setTimeout(120);
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("xxxxxxxxxxx", "xxxxxx")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}else{
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
//read updated parameters
strcpy(userkey, custom_userkey.getValue());
/*
strcpy(device1, custom_device1.getValue());
strcpy(device2, custom_device2.getValue());
strcpy(device3, custom_device3.getValue());
strcpy(device4, custom_device4.getValue());
strcpy(device5, custom_device5.getValue());
strcpy(device6, custom_device6.getValue());
strcpy(device7, custom_device7.getValue());
strcpy(device8, custom_device8.getValue());
strcpy(device9, custom_device9.getValue());
strcpy(device10, custom_device10.getValue());
strcpy(device11, custom_device11.getValue());
strcpy(device12, custom_device12.getValue());
strcpy(device13, custom_device13.getValue());
strcpy(device14, custom_device14.getValue());
strcpy(device15, custom_device15.getValue());
*/
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonDocument jsonBuffer(1024);
JsonObject json = jsonBuffer.to<JsonObject>();
json["userkey"] = userkey;
/*
json["device1"] = device1;
json["device2"] = device2;
json["device3"] = device3;
json["device4"] = device4;
json["device5"] = device5;
json["device6"] = device6;
json["device7"] = device7;
json["device8"] = device8;
json["device9"] = device9;
json["device10"] = device10;
json["device11"] = device11;
json["device12"] = device12;
json["device13"] = device13;
json["device14"] = device14;
json["device15"] = device15;
*/
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
//json.printTo(Serial);
serializeJson(jsonBuffer, Serial);
serializeJson(jsonBuffer, configFile);
//json.printTo(configFile);
configFile.close();
//end save
/*
String wifiSSID = "";
String wifiPASSWORD = "";
wifiPASSWORD = WiFi.psk();
wifiSSID = String(WiFi.SSID());
Serial.println(wifiPASSWORD);
Serial.println(wifiSSID);
Serial.println(wifiPASSWORD);
Serial.println(wifiSSID);
Serial.println(wifiPASSWORD);
Serial.println(wifiSSID);
EEPROM.write(119, user_id.length() + 1);
EEPROM.commit();
EEPROM.write(319, wifiPASSWORD.length() + 1);
EEPROM.commit();
wifiPASSWORD.toCharArray(wifiSETUP.wifiPASSWORD5,40);
for( int i=0 ; i<=user_id.length() + 1 ; i++)
{
delay(100);
EEPROM.write(320+i, wifiSETUP.wifiPASSWORD5[i] );
}
EEPROM.commit();
EEPROM.write(419, wifiSSID.length() + 1);
EEPROM.commit();
wifiSSID.toCharArray(wifiSETUP.wifiSSID5,40);
for( int i=0 ; i<=user_id.length() + 1 ; i++)
{
delay(100);
EEPROM.write(420+i, wifiSETUP.wifiSSID5[i] );
}
EEPROM.commit();
*/
}
webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/html", myESP8266page); });
webServer.onNotFound([](AsyncWebServerRequest *request)
{ request->send(404, "text/html", myNotFoundPage); });
AsyncElegantOTA.begin(&webServer); // Start ElegantOTA
webServer.begin();
Serial.println("FOTA server ready!");
Serial.println("local ip");
Serial.println(WiFi.localIP());
loopEnable = true;
}
}
void feedbackSensorReadings(void){
float sensor_max1;
sensor_max1 = getMaxValue1();
if (sensor_max1<=10)
{
sensor_max1 = 0;
}else if (sensor_max1>10)
{
sensor_max1 = 1;
}
RGBpower1f = String(sensor_max1);
Serial.print("RGBpower1f = ");
Serial.println(RGBpower1f);
}
int getMaxValue1()
{
float sensorValue1; //value read from the sensor
float sensorMax1 = 0;
uint32_t start_time1 = millis();
while((millis()-start_time1) < 250)//sample for 1000ms
{
sensorValue1 = analogRead(FEEDBACKSENSOR1);
if (sensorValue1 > sensorMax1)
{
sensorMax1 = sensorValue1;
}
}
return sensorMax1;
}
String IpAddressToString(const IPAddress& ipAddress) {
return String(ipAddress[0]) + String(".") +\
String(ipAddress[1]) + String(".") +\
String(ipAddress[2]) + String(".") +\
String(ipAddress[3]) ;
}
void setup() {
Serial.begin(9600);
/*
uint32_t start_time1 = millis();
while((millis()-start_time1) < 90000)//sample for 1000ms
{
Serial.print(".");
}// init_espNow();
*/
pinMode(D4, OUTPUT);
pinMode(green, OUTPUT);
pinMode(D4, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(switchButton, OUTPUT);
analogWrite(red, EEPROM.read(151));
analogWrite(green, EEPROM.read(152));
analogWrite(blue, EEPROM.read(153));
digitalWrite(switchButton, EEPROM.read(154));
Serial.println(EEPROM.read(150));
Serial.println(EEPROM.read(151));
Serial.println(EEPROM.read(152));
Serial.println(EEPROM.read(153));
Serial.println(EEPROM.read(154));
//delay(90000);
wifiSetup();
pinMode(Led, OUTPUT);
digitalWrite(Led, LOW);
//Serial.println("delay started");
// delay (10000);
// mySerial.begin(9600);
// Serial.println("delay Finished");
Serial.println();
// flush() is needed to print the above (connecting...) message reliably,
// in case the wireless connection doesn't go through
/*
//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());
*/
//client2.setInsecure();
//client2.connect(host, httpsPort);
/*
webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/html", myESP8266page); });
webServer.onNotFound([](AsyncWebServerRequest *request)
{ request->send(404, "text/html", myNotFoundPage); });
AsyncElegantOTA.begin(&webServer); // Start ElegantOTA
webServer.begin();
Serial.println("FOTA server ready!");
*/
ip = IpAddressToString( WiFi.localIP() );
macAddress = String(WiFi.macAddress());
counter = 0;
}
void loop() {
String payload_base = "{\"command\": \"append_row\", \"sheet_name\": \"rgbDevice\", \"values\": ";
String redValue = "";
String blueValue = "";
String greenValue = "";
String RGBpower1 = "";
if (loopEnable == true)
{
digitalWrite(D4,HIGH);
// delay(1000);
/*
if (RGBpower1 == "1")
{
digitalWrite(switchButton, HIGH);
Serial.println("RGB SWITCH on");
analogWrite(red,redValue.toInt());
analogWrite(green,greenValue.toInt());
analogWrite(blue,blueValue.toInt());
Serial.print("red value = ");
Serial.println(redValue);
Serial.print("green value = ");
Serial.println(greenValue);
Serial.print("blue value = ");
Serial.println(blueValue);
}else if (RGBpower1 == "0")
{
digitalWrite(switchButton, LOW);
Serial.println("RGB SWITCH oFF");
// ESP.reset();
}
*/
fullData.toCharArray(fullDataArr,14);
dot = 0;
redValue = "";
greenValue = "";
blueValue = "";
RGBpower1 = "";
for( int i=0 ; i<=fullData.length() ; i++)
{
/* if (fullData.getSubString(i , i+1) == ".")
{
dot = dot + 1;
}
*/
if (String(fullDataArr[i]) == ".")
{
dot = dot + 1;
}
else if ( fullDataArr[i] >= 0 || fullDataArr[i] <= 255 ){
if (dot == 0)
{
redValue += String(fullDataArr[i]);
}else if (dot == 1)
{
greenValue += String(fullDataArr[i]);
}else if (dot == 2)
{
blueValue += String(fullDataArr[i]);
}else if (dot == 3)
{
RGBpower1 += String(fullDataArr[i]);
}
}
}
if (RGBpower1 == "1")
{
digitalWrite(switchButton, HIGH);
Serial.println("RGB SWITCH on");
}else if (RGBpower1 == "0")
{
digitalWrite(switchButton, LOW);
Serial.println("RGB SWITCH oFF");
}
EEPROM.write(151, redValue.toInt());
// EEPROM.commit();
analogWrite(red,redValue.toInt());
Serial.print("red value = ");
Serial.println(redValue.toInt());
analogWrite(green,greenValue.toInt());
Serial.print("green value = ");
Serial.println(greenValue.toInt());
EEPROM.write(152, greenValue.toInt());
// EEPROM.commit();
EEPROM.write(153, blueValue.toInt());
// EEPROM.commit();
analogWrite(blue,blueValue.toInt());
Serial.print("blue value = ");
Serial.println(blueValue.toInt());
EEPROM.write(154, RGBpower1.toInt());
EEPROM.commit();
Serial.print("RGBpower value = ");
Serial.println(RGBpower1.toInt());
counter = counter + 1;
// counter++;
Serial.print("COUNTER = ");
Serial.println(counter);
if (counter == 100)
{
loopCounter = loopCounter + 1;
counter = 0;
}
feedbackSensorReadings();
// Serial.println("loopCounter= " + loopCounter);
// payload = payload_base + "\"" + value0 + "," + value1 + "," + value2 + "\"}";
// payload = payload_base + "\"" +floorValue + "," + room + "," + deviceType + "," + macAddress + "," + ip + "," + userSerial + "," + clientName + "," + serial + "," + RGBpower1f + "\"}";
payload = payload_base + "\"" + String(ESP.getFreeHeap()) + "," + String(ESP.getFreeContStack()) + "," + counter + "," + String(ESP.getMaxFreeBlockSize()) + "," + ip + "," + String(ESP.getHeapFragmentation()) + "," + loopCounter + "," + serialNumber + "," + RGBpower1f + "\"}";
if (RGBpower1fDash == RGBpower1f)
{
postData = false;
}else{
postData = true;
}
RGBpower1fDash = RGBpower1f;
digitalWrite(D4,LOW);
//delay(1000);
//sendData(serialNumber, RGBpower1f); //--> Calls the sendData Subroutine
//delay(2000);
readingData2();
}
}
void readingData2(void)
{
const char *cellAddress5 = "J"; // to set temperature value
const char *cellAddress6 = "P"; // to set temperature value
int i = 2 ;
const char* host = "script.google.com";
// Replace with your own script id to make server side changes
const char *GScriptId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Receiving data from google script address
const int httpsPort = 443;
String payload5 = "";
String payload6 = "";
static int error_count = 0;
static int connect_count = 0;
const unsigned int MAX_CONNECT = 20;
static bool flag = false;
String GAS_ID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //--> spreadsheet script ID
String url = String("/macros/s/") + GAS_ID+ "/exec";
String url5 = String("/macros/s/") + GScriptId + "/exec?read=" + cellAddress5;
String url6 = String("/macros/s/") + GScriptId + "/exec?read=" + cellAddress6;
//digitalWrite(D0,HIGH);
if (!flag){
client = new HTTPSRedirect(httpsPort);
client->setInsecure();
flag = true;
client->setPrintResponseBody(true);
client->setContentTypeHeader("application/json");
}
if (client != nullptr){
if (!client->connected()){
client->connect(host, httpsPort);
//flag = false;
}
}
else{
DPRINTLN("Error creating client object!");
error_count = 5;
}
if (connect_count > MAX_CONNECT){
//error_count = 5;
connect_count = 0;
flag = false;
delete client;
return;
}
if (!(client->reConnectFinalEndpoint())){
++error_count;
DPRINT("Error-count while connecting: ");
DPRINTLN(error_count);
}
else
{
Serial.println("reconecteeeeeeeeeeeeeeeeeeeeeeed");
error_count = 0;
}
if (rowID == 0)
{
Serial.print("GET Google sheet Row ID: ");
payload5 = "";
while(String(payload5) != serialNumber)
{
Serial.println(cellAddress5 + String(i) );
if (client->GET(url5 + String(i), host)){
//get the value of the cell
payload5 = client->getResponseBody();
payload5.trim(); /// temperature value
Serial.println(payload5);
//++connect_count;
if (String(payload5) == serialNumber)
{
rowID = i;
}
else{
i++;
}
}
};
}
if (client->GET(url6 + String(rowID), host)){
//get the value of the cell
payload6 = client->getResponseBody();
payload6.trim(); /// temperature value
//Serial.println(payload2);
fullData = payload6;
Serial.print("fullDataValue = ");
Serial.println(fullData);
++connect_count;
}
if (postData == true)
{
// Publish data to Google Sheets
Serial.println("Publishing data...");
Serial.println(payload);
if(client->POST(url, host, payload)){
}
else{
// do stuff here if publish was not successful
Serial.println("Error while connecting");
}
}
if (error_count > 3){
Serial.println("Halting processor...");
delete client;
client = nullptr;
Serial.printf("Final free heap: %u\n", ESP.getFreeHeap());
Serial.printf("Final stack: %u\n", ESP.getFreeContStack());
// Serial.flush();
ESP.reset();
}
// delay(4000);
client->stopAll();
}
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.