Skip to content

Instantly share code, notes, and snippets.

@imojams
Created April 30, 2021 16:45
Show Gist options
  • Save imojams/3cab65e97fa1f1f0d4c4d65bf082e0c4 to your computer and use it in GitHub Desktop.
Save imojams/3cab65e97fa1f1f0d4c4d65bf082e0c4 to your computer and use it in GitHub Desktop.
#include <ESPAsyncWebServer.h>
AsyncWebServer webServer(80);
AsyncWebSocket webSocket("/ws");
struct MY_WIFI_CONFIG
{
char ssid[20];
char password[20];
bool multiple_ap; //if multiple access ponts exist with same ssid, then connect to strongest one
const uint8_t conn_timeout;
};
MY_WIFI_CONFIG WIFI_CONFIG = {
"My Wifi sid",
"mywifistrongpassword",
false,
10 //conn timeout in sec
};
#define PIN_BTN1 (gpio_num_t)34 // Onboard button for ESP POE ISO
volatile bool btn1_interrupted = false;
portMUX_TYPE myMutex = portMUX_INITIALIZER_UNLOCKED;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
#ifdef PIN_BTN1
configureEspGPIO();
#endif
WiFi.onEvent(WiFiEvent);
WiFiOn();
}
void loop() {
// put your main code here, to run repeatedly:
if (btn1_interrupted)
{
if (WiFi.status() == WL_CONNECTED)
{
WiFi.disconnect(true);
}
WiFi.mode(WIFI_OFF);
delay(1000);
WiFiOn();
taskENTER_CRITICAL(&myMutex);
btn1_interrupted = false;
gpio_set_intr_type(PIN_BTN1, GPIO_INTR_NEGEDGE);
taskEXIT_CRITICAL(&myMutex);
}
}
void WiFiEvent(WiFiEvent_t event)
{
switch (event) {
case SYSTEM_EVENT_STA_DISCONNECTED: //ESP32 station disconnected from AP
Serial.println("WiFiEvent() WiFi disconnected");
break;
case SYSTEM_EVENT_STA_LOST_IP: //ESP32 station lost IP and the IP is reset to 0
Serial.println("WiFiEvent() WiFi lost IP");
break;
case SYSTEM_EVENT_STA_GOT_IP:
Serial.print("WiFiEvent() WiFi got IP. WiFi MAC: "); Serial.print(WiFi.macAddress());
Serial.print(", IPv4: "); Serial.print(WiFi.localIP());
Serial.print(", GW: "); Serial.print(WiFi.gatewayIP());
Serial.print("\n");
setupWebServer();
break;
}
}
void setupWebServer()
{
Serial.println("setupWebServer()");
webServer.reset();
webServer.on("/", HTTP_GET, handleRootAsync);
webServer.onNotFound(onNotFoundAsync);
webServer.on("/webmonitor", HTTP_GET, handleWebMonitorAsync);
webSocket.onEvent(onWebSocketEvent);
webServer.addHandler(&webSocket);
webServer.begin();
}
void handleRootAsync(AsyncWebServerRequest *request)
{
AsyncResponseStream *response = request->beginResponseStream("text/plain");
response->printf("Millis: %ul", millis());
request->send(response);
}
void onNotFoundAsync(AsyncWebServerRequest *request)
{
request->send(404, "text/html", "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p></body></html>");
}
void handleWebMonitorAsync(AsyncWebServerRequest *request)
{
/* gziped content */
//AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", ws_web_console_gz, ws_web_console_gz_len);
//response->addHeader("Content-Encoding", "gzip");
//request->send(response);
request->send(200, "text/plain", "WS web app are here!");
}
void onWebSocketEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
switch (type)
{
case WS_EVT_DISCONNECT:
Serial.printf("[%d] Disconnected!\n", client->id() );
break;
case WS_EVT_DATA:
//you have received a message from a WebSocket Client
Serial.printf("Got data from WS client (WS_EVT_DATA) with len=%d\n", len);
//for(size_t i=0; i < len; i++){
// Serial.write(data[i]);
//}
break;
case WS_EVT_CONNECT:
{
Serial.printf("WS client [%d] connected from %s\n", client->id(), client->remoteIP() );
// send message to client
//webSocket.textAll("Connected to Serial on " + WiFi.localIP().toString() + "\n");
}
break;
default:
Serial.printf("Websocket event unknown type: %d\n", type);
}//switch
} // onWebSocketEvent
void WiFiOn()
{
Serial.println("WiFi on()");
if (WiFi.status() == WL_CONNECTED)
{
Serial.println("Already connected to network...");
return;
}
WiFi.begin(WIFI_CONFIG.ssid, WIFI_CONFIG.password);
unsigned long wifiConnStarted = millis();
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
Serial.print(".");
//Serial.print(WiFi.status());
if (WiFi.status() == WL_NO_SSID_AVAIL)
{
Serial.println("\nWiFiOn(): WiFi SSID not available!");
break;
}
if (millis() - wifiConnStarted > WIFI_CONFIG.conn_timeout * 1000) /* WifiConnTimeout is in seconds */
{
Serial.println("\nWiFiOn(): Timeout while connecting to WiFi!");
break;
}
}
}
#ifdef PIN_BTN1
void IRAM_ATTR button_isr_handler(void* arg)
{
taskENTER_CRITICAL(&myMutex);
gpio_set_intr_type(PIN_BTN1, GPIO_INTR_DISABLE);
taskEXIT_CRITICAL(&myMutex);
btn1_interrupted = true;
}
void configureEspGPIO()
{
gpio_config_t io_conf;
io_conf.pin_bit_mask = ( (1ULL<<PIN_BTN1) ); //GPIO pin: set with bit mask, each bit maps to a GPIO
io_conf.mode = GPIO_MODE_INPUT; // gpio_mode_t GPIO mode
io_conf.pull_up_en = GPIO_PULLUP_ENABLE; // gpio_pullup_t
io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
io_conf.intr_type = GPIO_INTR_NEGEDGE; //falling //GPIO_INTR_LOW_LEVEL; // when level is low
esp_err_t s = gpio_config(&io_conf);
if (s == ESP_OK)
{
Serial.print("GPIO button pins configured!\n");
}else
{
Serial.printf("Failed to configure pins. Error code: %d [%s]\n", s, esp_err_to_name(s) );
}
//install gpio isr service
s = gpio_install_isr_service(0); //Flags used to allocate the interrupt. One or multiple (ORred)
if(s != ESP_OK)
{
Serial.printf("error, gpio_install_isr_service failed. Error code: %d [%s]\n", s, esp_err_to_name(s));
}else
{
//hook isr handler for specific gpio pin
s = gpio_isr_handler_add(PIN_BTN1, button_isr_handler, 0);
if(s != ESP_OK)
{
Serial.printf("error, gpio_isr_handler_add failed for ACK button. Error code: %d [%s]\n", s, esp_err_to_name(s) );
}else { Serial.print("Btn interrupt installed!\n"); }
}
}//configureEspGPIO
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment