/*
Name: GardenlightsWebServer.ino
Created: 6/6/2021 11:52:05 AM
Author: ajkes
r
example:https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/
*/
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <arduino-timer.h>
#include <ESPAsyncWebServer.h>
#include <WebSerial.h>
#define LEDC_CHANNEL_0 0
// use 13 bit precission for LEDC timer
#define LEDC_TIMER_13_BIT 13
// use 5000 Hz as a LEDC base frequency
#define LEDC_BASE_FREQ 5000
// Replace with your network credentials
const char* ssid = "****";
const char* password = "********";
const int ledPinPWM = 12;//Green
const int ledOnboard = 2;//PinD2
const int lightSensorPin = 13;
const int activityPin = 16;
volatile uint32_t LightCounter = 0;
volatile int Tocalculate;
volatile int lightValue = 0;
volatile int lightAverage = 0;
volatile int brightness;
volatile bool activityDetected = false;
bool dark = false;
int Hour = 0;
int Minute = 0;
int HourInt = 0;
int MinuteInt = 0;
int SecondsInt = 0;
int Messagedelay = 0;
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
String formattedDate;
String dayStamp;
String timeStamp;
//Timer<1, micros> timer; // create a timer with 1 task and milisecond resolution
auto timer = timer_create_default(); // create a timer with default settings
AsyncWebServer server(80);
// Set your Static IP address
IPAddress local_IP(192, 168, 178, 184);
// Set your Gateway IP address
IPAddress gateway(192,168,178,1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8); // optional
IPAddress secondaryDNS(8, 8, 4, 4); // optional
bool UpdateTime(void*)
{
UpdateTimeResult();
return true;
}
bool UpdateIntTime(void*)
{
SecondsInt++;
if (SecondsInt >= 60)
{
MinuteInt++;
SecondsInt = 0;
}
if (MinuteInt >= 60)
{
HourInt++;
MinuteInt = 0;
}
if (HourInt >= 24)
{
HourInt = 0;
}
return true;
}
void ledcAnalogWrite(uint32_t value, uint32_t valueMax = 255) {
// calculate duty, 8191 from 2 ^ 13 - 1
uint32_t duty = (8191 / valueMax) * min(value, valueMax);
// write duty to LEDC
ledcWrite(LEDC_CHANNEL_0, duty);
}
bool ReadPins(void*) {
/*Serial.print("print_message: Called at: ");
Serial.println(millis());*/
LightCounter++;
int factor = 4;
uint16_t n = analogRead(lightSensorPin);
Tocalculate += n;
lightValue = n;
activityDetected = digitalRead(activityPin);
if (LightCounter == factor)
{
Hour = timeClient.getHours();
lightAverage = (int)Tocalculate / factor;
Serial.println(Hour);
LightCounter = 0;
Tocalculate = 0;
}
else
{
lightValue = n;
}
//ledcAnalogWrite(LEDC_CHANNEL_0, brightness);
if (lightAverage < 30 && Hour < 23 && Hour > 7)
{
dark = true;
brightness = 255;
if (activityDetected)
{
brightness = 255;
}
}
if (lightAverage < 30 && Hour > 23 && Hour < 7)
{
dark = true;
brightness = 50;
if (activityDetected)
{
brightness = 255;
}
}
if (lightAverage > 30)
{
brightness = 0;
}
ledcAnalogWrite(brightness);
return true; // repeat? true
}
void UpdateTimeResult()
{
while (!timeClient.update())
{
timeClient.forceUpdate();
delay(500);
}
// The formattedDate comes with the following format:
// 2018-05-28T16:00:13Z
// We need to extract date and time
formattedDate = timeClient.getFormattedDate();
Serial.println(formattedDate);
// Extract date
int splitT = formattedDate.indexOf("T");
dayStamp = formattedDate.substring(0, splitT);
WebSerial.print("DATE: ");
WebSerial.println(dayStamp);
// Extract time
timeStamp = formattedDate.substring(splitT + 1, formattedDate.length() - 1);
WebSerial.print("HOUR: ");
WebSerial.println(timeStamp);
int seconds = timeClient.getSeconds();
Hour = timeClient.getHours();
Minute = timeClient.getMinutes();
WebSerial.println("Time updated ");
if (Hour != HourInt)
{
HourInt = Hour;
}
if (Minute!= MinuteInt)
{
MinuteInt = Minute;
}
if (seconds != SecondsInt)
{
SecondsInt = seconds;
}
}
bool CheckConnection(void*)
{
if ((WiFi.status() != WL_CONNECTED))
{
WiFi.disconnect();
WiFi.reconnect();
}
return true;
}
void UpdateWebSerialMessages(int messageType)
{
if (messageType == 2)
{
WebSerial.print("Second = ");
WebSerial.println(SecondsInt);
WebSerial.print("MinuteInt = ");
WebSerial.println(MinuteInt);
WebSerial.print("HourInt = ");
WebSerial.println(HourInt);
}
if (messageType == 1)
{
WebSerial.print("LightAverige = ");
WebSerial.println(lightAverage);
}
}
// the setup function runs once when you press reset or power the board
void setup()
{
int tr = 0;
// Initialize Serial Monitor
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
// Configures static IP address
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("STA Failed to configure");
}
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
tr++;
Serial.print(".");
if (tr == 10)
{
ESP.restart();
}
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
pinMode(ledPinPWM, OUTPUT);
pinMode(activityPin, INPUT_PULLDOWN);
ledcSetup(LEDC_CHANNEL_0, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
ledcAttachPin(ledPinPWM, LEDC_CHANNEL_0);
// Initialize a NTPClient to get time
timeClient.begin();
// Set offset time in seconds to adjust for your timezone, for example:
// GMT +1 = 3600
// GMT +8 = 28800
// GMT -1 = -3600
// GMT 0 = 0
WebSerial.begin(&server);
server.begin();
timeClient.setTimeOffset(7200);
UpdateTimeResult();
//timer.every(60000 * 60, UpdateTime);
timer.every(1000 * 60 * 60, UpdateTime);
timer.every(1000, ReadPins);
timer.every(120000, CheckConnection);
timer.every(1000, UpdateIntTime);
}
// the loop function runs over and over again until power down or reset
void loop()
{
timer.tick();
delay(50);
if (Messagedelay != 0 && (Messagedelay % 80) == 0)
{
UpdateWebSerialMessages(1);
}
if (Messagedelay > 450)
{
UpdateWebSerialMessages(2);
Messagedelay = 0;
}
Messagedelay++;
}