Skip to content

Instantly share code, notes, and snippets.

@Tech500
Last active October 13, 2022 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tech500/1522efa4a5754d35d902c2a100f6466d to your computer and use it in GitHub Desktop.
Save Tech500/1522efa4a5754d35d902c2a100f6466d to your computer and use it in GitHub Desktop.
WifiClientEvent based library example; for logging to LittleFS, four WIFI events.
/*
* This sketch shows the WiFi event usage
* Based on ESP32 Core 2.0.4, WiFi library example for WiFiClientEvents.
* Logs five WIFI events Watchdog events, Webserver starts, Brownout, WIFI Connect, and Disconnect.
* Modified by William Lucid 07/27/2022 @ 08:00 EDT
*/
/*
* WiFi Events
0 ARDUINO_EVENT_WIFI_READY < ESP32 WiFi ready
1 ARDUINO_EVENT_WIFI_SCAN_DONE < ESP32 finish scanning AP
2 ARDUINO_EVENT_WIFI_STA_START < ESP32 station start
3 ARDUINO_EVENT_WIFI_STA_STOP < ESP32 station stop
4 ARDUINO_EVENT_WIFI_STA_CONNECTED < ESP32 station connected to AP
5 ARDUINO_EVENT_WIFI_STA_DISCONNECTED < ESP32 station disconnected from AP
6 ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE < the auth mode of AP connected by ESP32 station changed
7 ARDUINO_EVENT_WIFI_STA_GOT_IP < ESP32 station got IP from connected AP
8 ARDUINO_EVENT_WIFI_STA_LOST_IP < ESP32 station lost IP and the IP is reset to 0
9 ARDUINO_EVENT_WPS_ER_SUCCESS < ESP32 station wps succeeds in enrollee mode
10 ARDUINO_EVENT_WPS_ER_FAILED < ESP32 station wps fails in enrollee mode
11 ARDUINO_EVENT_WPS_ER_TIMEOUT < ESP32 station wps timeout in enrollee mode
12 ARDUINO_EVENT_WPS_ER_PIN < ESP32 station wps pin code in enrollee mode
13 ARDUINO_EVENT_WIFI_AP_START < ESP32 soft-AP start
14 ARDUINO_EVENT_WIFI_AP_STOP < ESP32 soft-AP stop
15 ARDUINO_EVENT_WIFI_AP_STACONNECTED < a station connected to ESP32 soft-AP
16 ARDUINO_EVENT_WIFI_AP_STADISCONNECTED < a station disconnected from ESP32 soft-AP
17 ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED < ESP32 soft-AP assign an IP to a connected station
18 ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED < Receive probe request packet in soft-AP interface
19 ARDUINO_EVENT_WIFI_AP_GOT_IP6 < ESP32 ap interface v6IP addr is preferred
19 ARDUINO_EVENT_WIFI_STA_GOT_IP6 < ESP32 station interface v6IP addr is preferred
20 ARDUINO_EVENT_ETH_START < ESP32 ethernet start
21 ARDUINO_EVENT_ETH_STOP < ESP32 ethernet stop
22 ARDUINO_EVENT_ETH_CONNECTED < ESP32 ethernet phy link up
23 ARDUINO_EVENT_ETH_DISCONNECTED < ESP32 ethernet phy link down
24 ARDUINO_EVENT_ETH_GOT_IP < ESP32 ethernet got IP from connected AP
19 ARDUINO_EVENT_ETH_GOT_IP6 < ESP32 ethernet interface v6IP addr is preferred
25 ARDUINO_EVENT_MAX
*/
#include <WiFi.h>
#include <WiFiUdp.h>
#include <LittleFS.h>
#include <FTPServer.h> //https://github.com/dplasa/FTPClientServer
#include <Ticker.h>
#include <rom/rtc.h
const char* ssid = "Your SSID";
const char* password = "Your WiFi PASSWORD";
//Server settings
#define ipaddress {10,0,0,110}
#define subnet {255,255,255,0}
#define gateway {10,0,0,1}
#define dns {10,0,0,1}
WiFiUDP udp;
// local port to listen for UDP packets
const int udpPort = 123;
char incomingPacket[255];
char replyPacket[] = "Hi there! Got the message :-)";
const char * udpAddress1 = "us.pool.ntp.org";
const char * udpAddress2 = "time.nist.gov";
#define TZ "EST+5EDT,M3.2.0/2,M11.1.0/2"
int DOW, MONTH, DATE, YEAR, HOUR, MINUTE, SECOND;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
char strftime_buf[64];
String dtStamp(strftime_buf);
int lc = 0;
time_t tnow = 0;
FTPServer ftpSrv(LittleFS);
Ticker secondTick;
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
volatile int watchdogCounter;
volatile int watchDog = 0;
void IRAM_ATTR ISRwatchdog()
{
portENTER_CRITICAL_ISR(&mux);
watchdogCounter++;
if (watchdogCounter >= 75)
{
watchDog = 1;
}
portEXIT_CRITICAL_ISR(&mux);
}
int connect = 0;
int disconnect = 0;
int count = 1;
int brownout;
int softReset;
int powerOn;
int counter;
void WiFiEvent(WiFiEvent_t event) {
//Serial.printf("[WiFi-event] event: %d\n", event);
switch (event) {
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
//Serial.println("Connected to access point");
connect = 1;
disconnect = 0;
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
//Serial.println("Disconnected from WiFi access point");
disconnect = 1;
if(event == 7){ //ARDUINO_EVENT_WIFI_STA_GOT_IP
disconnect = 0;
}
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.print("\nObtained IP address: ");
Serial.println(WiFi.localIP());
break;
default: break;
}
}
void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info) {
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(IPAddress(info.got_ip.ip_info.ip.addr));
}
void setup() {
Serial.begin(115200);
if (rtc_get_reset_reason(0) == 1) //VBAT_RESET --brownout restart
{
brownout = 1;
Serial.println("Brownout reset previous boot");
}
if (rtc_get_reset_reason(0) == 12) //SOFTWARE_RESET --watchdog restart
{
softReset = 1;
Serial.println("Software reset previous boot");
}
// delete old config
WiFi.disconnect(true);
delay(1000);
// Examples of different ways to register wifi events
WiFi.onEvent(WiFiEvent);
WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
WiFiEventId_t eventID = WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){
//Serial.print("WiFi lost connection. Reason: \n");
//Serial.println(info.wifi_sta_disconnected.reason);
}, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
// Remove WiFi event
//Serial.print("WiFi Event ID: ");
////Serial.println(eventID);
//WiFi.removeEvent(eventID);
WiFi.begin(ssid, password);
//setting the addresses
IPAddress ipaddress;
IPAddress gateway;
IPAddress subnet;
IPAddress dns;
WiFi.config(ipaddress, gateway, subnet, dns);
Serial.println("Wait for WiFi Connection...");
secondTick.attach(1, ISRwatchdog); //watchdog ISR increase watchdogCounter by 1 every 1 second
if(LittleFS.begin(true))
{
Serial.println("LittleFS opened!");
Serial.println("");
ftpSrv.begin("admin", "admin"); //username, password for ftp. set ports in ESP8266FtpServer.h (default 21, 50009 for PASV)
}
powerOn = 1;
}
void loop() {
if ((brownout == 1) || (softReset == 1))
{
watchdogCounter = 0; //Resets the watchdogCounter
getDateTime();
//Open a "WIFI.TXT" for appended writing. Client access ip address logged.
File logFile =LittleFS.open("/WIFI.TXT", "a");
if (!logFile)
{
Serial.println("File: '/WIFI.TXT' failed to open");
}
if((brownout == 1) && (powerOn != 1))
{
logFile.println("ESP32 Restart caused by Brownout Detection...");
Serial.println("ESP32 Restart caused by Brownout Detection...");
brownout = 0;
connect = 1;
}
if((brownout == 1) && (powerOn == 1))
{
logFile.println("ESP32 Webserver Started...");
Serial.println("ESP32 Webserver Started...");
brownout = 0;
powerOn = 0;
}
if (softReset == 1)
{
logFile.println("ESP32 Restart caused by Watchdog Event...");
Serial.println("ESP32 Restart caused by Watchdog Event...");
softReset = 0;
}
logFile.close();
}
if(WiFi.status() == WL_NO_SSID_AVAIL ) //Prevent watchdog triggering if no wifi
{
watchdogCounter = 0;
}
if (connect == 1)
{
configTime();
//Open a "WIFI.TXT" for appended writing.
File logFile = LittleFS.open("/WIFI.TXT", "a");
if (!logFile)
{
Serial.println("File: '/WIFI.TXT' failed to open");
}
logFile.print("WiFi Connected: ");
logFile.print(dtStamp);
logFile.printf(" Connection result: %d\n", WiFi.waitForConnectResult());
logFile.println("");
logFile.close();
Serial.println("Logged WiFi connection, timestamp\n");
Serial.println("Ready...\n");
watchdogCounter = 0; //Resets the watchdogCounter
connect = 0;
counter = 1;
}
if((disconnect == 1) && (counter == 1))
{
watchdogCounter = 0; //Resets the watchdogCounter
//Open "WIFI.TXT" for appended writing. Client access ip address logged.
File logFile = LittleFS.open("/WIFI.TXT", "a");
if (!logFile)
{
Serial.println("File: '/WIFI.TXT' failed to open");
}
getDateTime();
logFile.print("WiFi Disconnected: ");
logFile.print(dtStamp);
logFile.print(" Connection result: ");
logFile.println(WiFi.waitForConnectResult());
logFile.close();
Serial.println("\nLogged WiFi disconnection, timestamp\n");
watchdogCounter = 0;
disconnect = 0;
counter = 0;
}
for (int x = 1; x < 5000; x++)
{
ftpSrv.handleFTP();
}
if (watchDog == 1)
{
portENTER_CRITICAL(&mux);
watchdogCounter--;
portEXIT_CRITICAL(&mux);
getDateTime();
logWatchdog();
}
watchdogCounter = 0;
}
void configTime()
{
configTime(0, 0, udpAddress1, udpAddress2);
setenv("TZ", "EST+5EDT,M3.2.0/2,M11.1.0/2", 3); // this sets TZ to Indianapolis, Indiana
tzset();
Serial.print("wait for first valid timestamp");
while (time(nullptr) < 100000ul)
{
Serial.print(".");
delay(5000);
}
Serial.println("\nSystem Time set\n");
getDateTime();
Serial.println(dtStamp);
}
String getDateTime()
{
struct tm *ti;
tnow = time(nullptr) + 1;
//strftime(strftime_buf, sizeof(strftime_buf), "%c", localtime(&tnow));
ti = localtime(&tnow);
DOW = ti->tm_wday;
YEAR = ti->tm_year + 1900;
MONTH = ti->tm_mon + 1;
DATE = ti->tm_mday;
HOUR = ti->tm_hour;
MINUTE = ti->tm_min;
SECOND = ti->tm_sec;
strftime(strftime_buf, sizeof(strftime_buf), "%a , %m/%d/%Y , %H:%M:%S %Z", localtime(&tnow));
dtStamp = strftime_buf;
return (dtStamp);
}
void logWatchdog()
{
Serial.println("");
Serial.println("Watchdog event triggered.");
Serial.println("Watchdog Restart " + dtStamp);
ESP.restart();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment