Prvni ulozeni z chegewara githubu

This commit is contained in:
2023-02-25 16:13:53 +01:00
commit 01eb80dfe2
3279 changed files with 638407 additions and 0 deletions

View File

@ -0,0 +1,90 @@
/* Wi-Fi FTM Initiator Arduino Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include "WiFi.h"
/*
THIS FEATURE IS SUPPORTED ONLY BY ESP32-S2 AND ESP32-C3
*/
// Change the SSID and PASSWORD here if needed
const char * WIFI_FTM_SSID = "WiFi_FTM_Responder"; // SSID of AP that has FTM Enabled
const char * WIFI_FTM_PASS = "ftm_responder"; // STA Password
// FTM settings
// Number of FTM frames requested in terms of 4 or 8 bursts (allowed values - 0 (No pref), 16, 24, 32, 64)
const uint8_t FTM_FRAME_COUNT = 16;
// Requested time period between consecutive FTM bursts in 100s of milliseconds (allowed values - 0 (No pref) or 2-255)
const uint16_t FTM_BURST_PERIOD = 2;
// Semaphore to signal when FTM Report has been received
xSemaphoreHandle ftmSemaphore;
// Status of the received FTM Report
bool ftmSuccess = true;
// FTM report handler with the calculated data from the round trip
void onFtmReport(arduino_event_t *event) {
const char * status_str[5] = {"SUCCESS", "UNSUPPORTED", "CONF_REJECTED", "NO_RESPONSE", "FAIL"};
wifi_event_ftm_report_t * report = &event->event_info.wifi_ftm_report;
// Set the global report status
ftmSuccess = report->status == FTM_STATUS_SUCCESS;
if (ftmSuccess) {
// The estimated distance in meters may vary depending on some factors (see README file)
Serial.printf("FTM Estimate: Distance: %.2f m, Return Time: %u ns\n", (float)report->dist_est / 100.0, report->rtt_est);
// Pointer to FTM Report with multiple entries, should be freed after use
free(report->ftm_report_data);
} else {
Serial.print("FTM Error: ");
Serial.println(status_str[report->status]);
}
// Signal that report is received
xSemaphoreGive(ftmSemaphore);
}
// Initiate FTM Session and wait for FTM Report
bool getFtmReport(){
if(!WiFi.initiateFTM(FTM_FRAME_COUNT, FTM_BURST_PERIOD)){
Serial.println("FTM Error: Initiate Session Failed");
return false;
}
// Wait for signal that report is received and return true if status was success
return xSemaphoreTake(ftmSemaphore, portMAX_DELAY) == pdPASS && ftmSuccess;
}
void setup() {
Serial.begin(115200);
// Create binary semaphore (initialized taken and can be taken/given from any thread/ISR)
ftmSemaphore = xSemaphoreCreateBinary();
// Listen for FTM Report events
WiFi.onEvent(onFtmReport, ARDUINO_EVENT_WIFI_FTM_REPORT);
// Connect to AP that has FTM Enabled
Serial.println("Connecting to FTM Responder");
WiFi.begin(WIFI_FTM_SSID, WIFI_FTM_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected");
Serial.print("Initiating FTM session with Frame Count ");
Serial.print(FTM_FRAME_COUNT);
Serial.print(" and Burst Period ");
Serial.print(FTM_BURST_PERIOD * 100);
Serial.println(" ms");
// Request FTM reports until one fails
while(getFtmReport());
}
void loop() {
delay(1000);
}

View File

@ -0,0 +1,110 @@
# Wi-Fi FTM Initiator Arduino Example
This example demonstrates how to use the Fine Timing Measurement (FTM) to calculate the distace from the Access Point and the device. This is calculated by the Wi-Fi Round Trip Time (Wi-Fi RTT) introduced on the [IEEE Std 802.11-2016](https://en.wikipedia.org/wiki/IEEE_802.11mc) standard.
This example was based on the [ESP-IDF FTM](https://github.com/espressif/esp-idf/tree/master/examples/wifi/ftm). See the README file for more details about on how to use this feature.
Some usages for this feature includes:
* Indoor positioning systems.
* Navigation.
* Device Location.
* Smart Devices.
* Alarms.
# Supported Targets
Currently, this example supports the following targets:
| Supported Targets | ESP32-S2 | ESP32-C3 |
| ----------------- | -------- | -------- |
## How to Use Example
In order to use the FTM, you will need a Responder or Wi-Fi router with FTM capabilities. If you don't own one, you can use a second ESP32-S2 or ESP32-C3 to simulate one.
See the **Responder** example to prepare the environment.
* How to install the Arduino IDE: [Install Arduino IDE](https://github.com/espressif/arduino-esp32/tree/master/docs/arduino-ide).
### Configure the Project
To configure this project, you can change the following configuration related to FTM feature:
```c
// Change the SSID and PASSWORD here if needed
const char * WIFI_FTM_SSID = "WiFi_FTM_Responder"; // SSID of AP that has FTM Enabled
const char * WIFI_FTM_PASS = "ftm_responder"; // STA Password
// FTM settings
// Number of FTM frames requested in terms of 4 or 8 bursts (allowed values - 0 (No pref), 16, 24, 32, 64)
const uint8_t FTM_FRAME_COUNT = 16;
// Requested time period between consecutive FTM bursts in 100s of milliseconds (allowed values - 0 (No pref) or 2-255)
const uint16_t FTM_BURST_PERIOD = 2;
```
* Change the Wi-Fi `SSID` and `PASSWORD` as the same as the Responder/Router.
* Change `FTM_FRAME_COUNT` with the number of frames requested to the Responder.
* Change `FTM_BURST_PERIOD` with the time between each FTM burst.
To see more details about FTM, please see the [ESP-IDF docs](https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/network/esp_wifi.html).
#### Using Arduino IDE
To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).
* Before Compile/Verify, select the correct board: `Tools -> Board`.
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
#### Using Platform IO
* Select the COM port: `Devices` or setting the `upload_port` option on the `platformio.ini` file.
## Log Output
Expected log output:
```
ESP-ROM:esp32s2-rc4-20191025
Build:Oct 25 2019
rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x3ffe6100,len:0x4b0
load:0x4004c000,len:0xa6c
load:0x40050000,len:0x25c4
entry 0x4004c198
Connecting to FTM Responder
.....
WiFi Connected
Initiating FTM session with Frame Count 16 and Burst Period 200 ms
FTM Estimate: Distance: 0.13 m, Return Time: 0 ns
FTM Estimate: Distance: 0.13 m, Return Time: 0 ns
FTM Estimate: Distance: 0.13 m, Return Time: 0 ns
FTM Estimate: Distance: 0.00 m, Return Time: 0 ns
...
```
## Troubleshooting
***Important: Make sure you are using a good quality USB cable and that you have a reliable power source.***
* **Programming Fail:** If the programming/flash procedure fails, try reducing the serial connection speed.
* **COM port not detected:** Check the USB cable and the USB to Serial driver installation.
If the error persist, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
## Contribute
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome!
Before creating a new issue, be sure to try the Troubleshooting and to check if the same issue was already created by someone else.
## Resources
* Official ESP32 Forum: [Link](https://esp32.com)
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf)
* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf)
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)

View File

@ -0,0 +1,23 @@
/* Wi-Fi FTM Responder Arduino Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include "WiFi.h"
// Change the SSID and PASSWORD here if needed
const char * WIFI_FTM_SSID = "WiFi_FTM_Responder";
const char * WIFI_FTM_PASS = "ftm_responder";
void setup() {
Serial.begin(115200);
Serial.println("Starting SoftAP with FTM Responder support");
// Enable AP with FTM support (last argument is 'true')
WiFi.softAP(WIFI_FTM_SSID, WIFI_FTM_PASS, 1, 0, 4, true);
}
void loop() {
delay(1000);
}

View File

@ -0,0 +1,94 @@
# Wi-Fi FTM Responder Arduino Example
This example demonstrates how to use the Fine Timing Measurement (FTM) to calculate the distace from the Access Point and the device. This is calculated by the Wi-Fi Round Trip Time (Wi-Fi RTT) introduced on the [IEEE Std 802.11-2016](https://en.wikipedia.org/wiki/IEEE_802.11mc) standard.
This example will simulate the Router with FTM capability.
This example was based on the [ESP-IDF FTM](https://github.com/espressif/esp-idf/tree/master/examples/wifi/ftm). See the README file for more details about on how to use this feature.
Some usages for this feature includes:
* Indoor positioning systems.
* Navigation.
* Device Location.
* Smart Devices.
* Alarms.
# Supported Targets
Currently, this example supports the following targets:
| Supported Targets | ESP32-S2 | ESP32-C3 |
| ----------------- | -------- | -------- |
## How to Use Example
See the **Initiator** example to prepare the environment.
* How to install the Arduino IDE: [Install Arduino IDE](https://github.com/espressif/arduino-esp32/tree/master/docs/arduino-ide).
### Configure the Project
To configure this project, you can change the following configuration related to STA:
```c
// Change the SSID and PASSWORD here if needed
const char * WIFI_FTM_SSID = "WiFi_FTM_Responder";
const char * WIFI_FTM_PASS = "ftm_responder";
```
* Change the Wi-Fi `SSID` and `PASSWORD` as the same as the Initiator.
To see more details about FTM, please see the [ESP-IDF docs](https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/network/esp_wifi.html).
#### Using Arduino IDE
To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).
* Before Compile/Verify, select the correct board: `Tools -> Board`.
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
#### Using Platform IO
* Select the COM port: `Devices` or setting the `upload_port` option on the `platformio.ini` file.
## Log Output
Expected log output:
```
Build:Oct 25 2019
rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x3ffe6100,len:0x4b0
load:0x4004c000,len:0xa6c
load:0x40050000,len:0x25c4
entry 0x4004c198
Starting SoftAP with FTM Responder support
```
## Troubleshooting
***Important: Make sure you are using a good quality USB cable and that you have a reliable power source.***
* **Programming Fail:** If the programming/flash procedure fails, try reducing the serial connection speed.
* **COM port not detected:** Check the USB cable and the USB to Serial driver installation.
If the error persist, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
## Contribute
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome!
Before creating a new issue, be sure to try the Troubleshooting and to check if the same issue was already created by someone else.
## Resources
* Official ESP32 Forum: [Link](https://esp32.com)
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf)
* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf)
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)

View File

@ -0,0 +1,116 @@
/*
WiFi Web Server LED Blink
A simple web server that lets you blink an LED via the web.
This sketch will print the IP address of your WiFi Shield (once connected)
to the Serial monitor. From there, you can open that address in a web browser
to turn on and off the LED on pin 5.
If the IP address of your shield is yourAddress:
http://yourAddress/H turns the LED on
http://yourAddress/L turns it off
This example is written for a network using WPA2 encryption. For insecure
WEP or WPA, change the Wifi.begin() call and use Wifi.setMinSecurity() accordingly.
Circuit:
* WiFi shield attached
* LED attached to pin 5
created for arduino 25 Nov 2012
by Tom Igoe
ported for sparkfun esp32
31.01.2017 by Jan Hendrik Berlin
*/
#include <WiFi.h>
const char* ssid = "yourssid";
const char* password = "yourpasswd";
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
pinMode(5, OUTPUT); // set the LED pin mode
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
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());
server.begin();
}
int value = 0;
void loop(){
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("New Client."); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("Click <a href=\"/H\">here</a> to turn the LED on pin 5 on.<br>");
client.print("Click <a href=\"/L\">here</a> to turn the LED on pin 5 off.<br>");
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
} else { // if you got a newline, then clear currentLine:
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
digitalWrite(5, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
digitalWrite(5, LOW); // GET /L turns the LED off
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}

View File

@ -0,0 +1,104 @@
Example Serial Logs For Various Cases
======================================
For WPS Push Button method,after the ESP32 boots up and prints that WPS has started, press the button that looks something like [this](https://www.verizon.com/supportresources/images/fqgrouter-frontview-wps-button.png) on your router. In case you dont find anything similar, check your router specs if it does really support WPS Push functionality.
As for WPS Pin Mode, it will output a 8 digit Pin on the Serial Monitor that will change every 2 minutes if it hasn't connected. You need to log in to your router (generally reaching 192.168.0.1) and enter the pin shown in Serial Monitor in the WPS Settings of your router.
#### WPS Push Button Failure
```
ets Jun 8 2016 00:22:57
rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0010,len:4
load:0x3fff0014,len:732
load:0x40078000,len:0
load:0x40078000,len:11572
entry 0x40078a14
Starting WPS
Station Mode Started
WPS Timedout, retrying
WPS Timedout, retrying
```
#### WPS Push Button Successfull
```
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
ets Jun 8 2016 00:22:57
rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0010,len:4
load:0x3fff0014,len:732
load:0x40078000,len:0
load:0x40078000,len:11572
entry 0x40078a14
Starting WPS
Station Mode Started
WPS Successfull, stopping WPS and connecting to: < Your Router SSID >
Disconnected from station, attempting reconnection
Connected to : < Your Router SSID >
Got IP: 192.168.1.100
```
#### WPS PIN Failure
```
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
ets Jun 8 2016 00:22:57
rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0010,len:4
load:0x3fff0014,len:732
load:0x40078000,len:0
load:0x40078000,len:11572
entry 0x40078a14
Starting WPS
Station Mode Started
WPS_PIN = 94842104
WPS Timedout, retrying
WPS_PIN = 55814171
WPS Timedout, retrying
WPS_PIN = 71321622
```
#### WPS PIN Successfull
```
ets Jun 8 2016 00:22:57
rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0010,len:4
load:0x3fff0014,len:732
load:0x40078000,len:0
load:0x40078000,len:11572
entry 0x40078a14
Starting WPS
Station Mode Started
WPS_PIN = 36807581
WPS Successfull, stopping WPS and connecting to: <Your Router SSID>
Disconnected from station, attempting reconnection
Connected to :<Your Router SSID>
Got IP: 192.168.1.100
```

View File

@ -0,0 +1,115 @@
/*
Example Code To Get ESP32 To Connect To A Router Using WPS
===========================================================
This example code provides both Push Button method and Pin
based WPS entry to get your ESP connected to your WiFi router.
Hardware Requirements
========================
ESP32 and a Router having WPS functionality
This code is under Public Domain License.
Author:
Pranav Cherukupalli <cherukupallip@gmail.com>
*/
#include "WiFi.h"
#include "esp_wps.h"
/*
Change the definition of the WPS mode
from WPS_TYPE_PBC to WPS_TYPE_PIN in
the case that you are using pin type
WPS
*/
#define ESP_WPS_MODE WPS_TYPE_PBC
#define ESP_MANUFACTURER "ESPRESSIF"
#define ESP_MODEL_NUMBER "ESP32"
#define ESP_MODEL_NAME "ESPRESSIF IOT"
#define ESP_DEVICE_NAME "ESP STATION"
static esp_wps_config_t config;
void wpsInitConfig(){
config.wps_type = ESP_WPS_MODE;
strcpy(config.factory_info.manufacturer, ESP_MANUFACTURER);
strcpy(config.factory_info.model_number, ESP_MODEL_NUMBER);
strcpy(config.factory_info.model_name, ESP_MODEL_NAME);
strcpy(config.factory_info.device_name, ESP_DEVICE_NAME);
}
void wpsStart(){
if(esp_wifi_wps_enable(&config)){
Serial.println("WPS Enable Failed");
} else if(esp_wifi_wps_start(0)){
Serial.println("WPS Start Failed");
}
}
void wpsStop(){
if(esp_wifi_wps_disable()){
Serial.println("WPS Disable Failed");
}
}
String wpspin2string(uint8_t a[]){
char wps_pin[9];
for(int i=0;i<8;i++){
wps_pin[i] = a[i];
}
wps_pin[8] = '\0';
return (String)wps_pin;
}
void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info){
switch(event){
case ARDUINO_EVENT_WIFI_STA_START:
Serial.println("Station Mode Started");
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.println("Connected to :" + String(WiFi.SSID()));
Serial.print("Got IP: ");
Serial.println(WiFi.localIP());
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("Disconnected from station, attempting reconnection");
WiFi.reconnect();
break;
case ARDUINO_EVENT_WPS_ER_SUCCESS:
Serial.println("WPS Successfull, stopping WPS and connecting to: " + String(WiFi.SSID()));
wpsStop();
delay(10);
WiFi.begin();
break;
case ARDUINO_EVENT_WPS_ER_FAILED:
Serial.println("WPS Failed, retrying");
wpsStop();
wpsStart();
break;
case ARDUINO_EVENT_WPS_ER_TIMEOUT:
Serial.println("WPS Timedout, retrying");
wpsStop();
wpsStart();
break;
case ARDUINO_EVENT_WPS_ER_PIN:
Serial.println("WPS_PIN = " + wpspin2string(info.wps_er_pin.pin_code));
break;
default:
break;
}
}
void setup(){
Serial.begin(115200);
delay(10);
Serial.println();
WiFi.onEvent(WiFiEvent);
WiFi.mode(WIFI_MODE_STA);
Serial.println("Starting WPS");
wpsInitConfig();
wpsStart();
}
void loop(){
//nothing to do here
}

View File

@ -0,0 +1,93 @@
/*
WiFiAccessPoint.ino creates a WiFi access point and provides a web server on it.
Steps:
1. Connect to the access point "yourAp"
2. Point your web browser to http://192.168.4.1/H to turn the LED on or http://192.168.4.1/L to turn it off
OR
Run raw TCP "GET /H" and "GET /L" on PuTTY terminal with 192.168.4.1 as IP address and 80 as port
Created for arduino-esp32 on 04 July, 2018
by Elochukwu Ifediora (fedy0)
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#define LED_BUILTIN 2 // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED
// Set these to your desired credentials.
const char *ssid = "yourAP";
const char *password = "yourPassword";
WiFiServer server(80);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
Serial.println();
Serial.println("Configuring access point...");
// You can remove the password parameter if you want the AP to be open.
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("New Client."); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("Click <a href=\"/H\">here</a> to turn ON the LED.<br>");
client.print("Click <a href=\"/L\">here</a> to turn OFF the LED.<br>");
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
} else { // if you got a newline, then clear currentLine:
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
digitalWrite(LED_BUILTIN, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
digitalWrite(LED_BUILTIN, LOW); // GET /L turns the LED off
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}

View File

@ -0,0 +1,128 @@
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Sketch shows how to switch between WiFi and BlueTooth or use both
// Button is attached between GPIO 0 and GND and modes are switched with each press
#include "WiFi.h"
#define STA_SSID "your-ssid"
#define STA_PASS "your-pass"
#define AP_SSID "esp32"
enum { STEP_BTON, STEP_BTOFF, STEP_STA, STEP_AP, STEP_AP_STA, STEP_OFF, STEP_BT_STA, STEP_END };
void onButton(){
static uint32_t step = STEP_BTON;
switch(step){
case STEP_BTON://BT Only
Serial.println("** Starting BT");
btStart();
break;
case STEP_BTOFF://All Off
Serial.println("** Stopping BT");
btStop();
break;
case STEP_STA://STA Only
Serial.println("** Starting STA");
WiFi.begin(STA_SSID, STA_PASS);
break;
case STEP_AP://AP Only
Serial.println("** Stopping STA");
WiFi.mode(WIFI_AP);
Serial.println("** Starting AP");
WiFi.softAP(AP_SSID);
break;
case STEP_AP_STA://AP+STA
Serial.println("** Starting STA");
WiFi.begin(STA_SSID, STA_PASS);
break;
case STEP_OFF://All Off
Serial.println("** Stopping WiFi");
WiFi.mode(WIFI_OFF);
break;
case STEP_BT_STA://BT+STA
Serial.println("** Starting STA+BT");
WiFi.begin(STA_SSID, STA_PASS);
btStart();
break;
case STEP_END://All Off
Serial.println("** Stopping WiFi+BT");
WiFi.mode(WIFI_OFF);
btStop();
break;
default:
break;
}
if(step == STEP_END){
step = STEP_BTON;
} else {
step++;
}
//little debounce
delay(100);
}
void WiFiEvent(WiFiEvent_t event){
switch(event) {
case ARDUINO_EVENT_WIFI_AP_START:
Serial.println("AP Started");
WiFi.softAPsetHostname(AP_SSID);
break;
case ARDUINO_EVENT_WIFI_AP_STOP:
Serial.println("AP Stopped");
break;
case ARDUINO_EVENT_WIFI_STA_START:
Serial.println("STA Started");
WiFi.setHostname(AP_SSID);
break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
Serial.println("STA Connected");
WiFi.enableIpV6();
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
Serial.print("STA IPv6: ");
Serial.println(WiFi.localIPv6());
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.print("STA IPv4: ");
Serial.println(WiFi.localIP());
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("STA Disconnected");
break;
case ARDUINO_EVENT_WIFI_STA_STOP:
Serial.println("STA Stopped");
break;
default:
break;
}
}
void setup() {
Serial.begin(115200);
pinMode(0, INPUT_PULLUP);
WiFi.onEvent(WiFiEvent);
Serial.print("ESP32 SDK: ");
Serial.println(ESP.getSdkVersion());
Serial.println("Press the button to select the next mode");
}
void loop() {
static uint8_t lastPinState = 1;
uint8_t pinState = digitalRead(0);
if(!pinState && lastPinState){
onButton();
}
lastPinState = pinState;
}

View File

@ -0,0 +1,94 @@
/*
* This sketch sends data via HTTP GET requests to data.sparkfun.com service.
*
* You need to get streamId and privateKey at data.sparkfun.com and paste them
* below. Or just customize this script to talk to other HTTP servers.
*
*/
#include <WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
const char* host = "data.sparkfun.com";
const char* streamId = "....................";
const char* privateKey = "....................";
void setup()
{
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
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());
}
int value = 0;
void loop()
{
delay(5000);
++value;
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/input/";
url += streamId;
url += "?private_key=";
url += privateKey;
url += "&value=";
url += value;
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while(client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}

View File

@ -0,0 +1,87 @@
/*
* This sketch sends a message to a TCP server
*
*/
#include <WiFi.h>
#include <WiFiMulti.h>
WiFiMulti WiFiMulti;
void setup()
{
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
WiFiMulti.addAP("SSID", "passpasspass");
Serial.println();
Serial.println();
Serial.print("Waiting for WiFi... ");
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
void loop()
{
// const uint16_t port = 80;
// const char * host = "192.168.1.1"; // ip or dns
const uint16_t port = 1337;
const char * host = "192.168.1.10"; // ip or dns
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection failed.");
Serial.println("Waiting 5 seconds before retrying...");
delay(5000);
return;
}
// This will send a request to the server
//uncomment this line to send an arbitrary string to the server
//client.print("Send this data to the server");
//uncomment this line to send a basic document request to the server
client.print("GET /index.html HTTP/1.1\n\n");
int maxloops = 0;
//wait for the server's reply to become available
while (!client.available() && maxloops < 1000)
{
maxloops++;
delay(1); //delay 1 msec
}
if (client.available() > 0)
{
//read back one line from the server
String line = client.readStringUntil('\r');
Serial.println(line);
}
else
{
Serial.println("client.available() timed out ");
}
Serial.println("Closing connection.");
client.stop();
Serial.println("Waiting 5 seconds before restarting...");
delay(5000);
}

View File

@ -0,0 +1,43 @@
# ESP32-Eduroam
* Eduroam wifi connection with university login identity
* Working under Eduroam networks worldwide
* Methods: PEAP + MsCHAPv2
# Format
* IDENTITY = youridentity --> if connecting from different university, use youridentity@youruniversity.domain format
* PASSWORD = yourpassword
# Usage
* Change IDENTITY
* Change password
* Upload sketch and enjoy!
* After sucessful assign of IP address, board will connect to HTTP page on internet to verify your authentification
* Board will auto reconnect to Eduroam if it lost connection
# Tested locations
|University|Board|Method|Result|
|-------------|-------------| -----|------|
|Technical University in Košice (Slovakia)|ESP32 Devkit v1|PEAP + MsCHAPv2|Working|
|Technical University in Košice (Slovakia)|ESP32 Devmodule v4|PEAP + MsCHAPv2|Working on 6th attempt in loop|
|Slovak Technical University in Bratislava (Slovakia)|ESP32 Devkit v1|PEAP + MsCHAPv2|Working|
|University of Antwerp (Belgium)|Lolin32|PEAP + MsCHAPv2|Working|
|UPV Universitat Politècnica de València (Spain)|ESP32 Devmodule v4|PEAP + MsCHAPv2|Working|
|Local Zeroshell powered network|ESP32 Devkit v1|PEAP + MsCHAPv2|*Not working*|
|Hasselt University (Belgium)|xxx|PEAP + MsCHAPv2|Working with fix sketch|
|Universidad de Granada (Spain)|Lolin D32 Pro|PEAP + MsCHAPv2|Working|
|Universidad de Granada (Spain)|Lolin D32|PEAP + MsCHAPv2|Working|
|Universidade Federal de Santa Catarina (Brazil)|xxx|EAP-TTLS + MsCHAPv2|Working|
|University of Central Florida (Orlando, Florida)|ESP32 Built-in OLED Heltec WiFi Kit 32|PEAP + MsCHAPv2|Working|
|Université de Montpellier (France)|NodeMCU-32S|PEAP + MsCHAPv2|Working|
# Common errors - Switch to Debug mode for Serial monitor prints
|Error|Appearance|Solution|
|-------------|-------------|-------------|
|wifi: Set status to INIT|Frequent|Hold EN button for few seconds|
|HANDSHAKE_TIMEOUT|Rare|Bug was found under Zeroshell RADIUS authentization - Unsucessful connection|
|AUTH_EXPIRE|Common|In the case of weak wifi network signal, this error is quite common, bring your device closer to AP|
|ASSOC_EXPIRE|Rare|-|
# Sucessful connection example
![alt text](https://i.nahraj.to/f/24Kc.png)
# Unsucessful connection example
![alt text](https://camo.githubusercontent.com/87e47d1b27f4e8ace87423e40e8edbce7983bafa/68747470733a2f2f692e6e616872616a2e746f2f662f323435572e504e47)

View File

@ -0,0 +1,86 @@
#include <WiFi.h> //Wifi library
#include "esp_wpa2.h" //wpa2 library for connections to Enterprise networks
#define EAP_IDENTITY "login" //if connecting from another corporation, use identity@organisation.domain in Eduroam
#define EAP_USERNAME "login" //oftentimes just a repeat of the identity
#define EAP_PASSWORD "password" //your Eduroam password
const char* ssid = "eduroam"; // Eduroam SSID
const char* host = "arduino.php5.sk"; //external server domain for HTTP connection after authentification
int counter = 0;
// NOTE: For some systems, various certification keys are required to connect to the wifi system.
// Usually you are provided these by the IT department of your organization when certs are required
// and you can't connect with just an identity and password.
// Most eduroam setups we have seen do not require this level of authentication, but you should contact
// your IT department to verify.
// You should uncomment these and populate with the contents of the files if this is required for your scenario (See Example 2 and Example 3 below).
//const char *ca_pem = "insert your CA cert from your .pem file here";
//const char *client_cert = "insert your client cert from your .crt file here";
//const char *client_key = "insert your client key from your .key file here";
void setup() {
Serial.begin(115200);
delay(10);
Serial.println();
Serial.print("Connecting to network: ");
Serial.println(ssid);
WiFi.disconnect(true); //disconnect form wifi to set new wifi connection
WiFi.mode(WIFI_STA); //init wifi mode
// Example1 (most common): a cert-file-free eduroam with PEAP (or TTLS)
WiFi.begin(ssid, WPA2_AUTH_PEAP, EAP_IDENTITY, EAP_USERNAME, EAP_PASSWORD);
// Example 2: a cert-file WPA2 Enterprise with PEAP
//WiFi.begin(ssid, WPA2_AUTH_PEAP, EAP_IDENTITY, EAP_USERNAME, EAP_PASSWORD, ca_pem, client_cert, client_key);
// Example 3: TLS with cert-files and no password
//WiFi.begin(ssid, WPA2_AUTH_TLS, EAP_IDENTITY, NULL, NULL, ca_pem, client_cert, client_key);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
counter++;
if(counter>=60){ //after 30 seconds timeout - reset board
ESP.restart();
}
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address set: ");
Serial.println(WiFi.localIP()); //print LAN IP
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { //if we are connected to Eduroam network
counter = 0; //reset counter
Serial.println("Wifi is still connected with IP: ");
Serial.println(WiFi.localIP()); //inform user about his IP address
}else if (WiFi.status() != WL_CONNECTED) { //if we lost connection, retry
WiFi.begin(ssid);
}
while (WiFi.status() != WL_CONNECTED) { //during lost connection, print dots
delay(500);
Serial.print(".");
counter++;
if(counter>=60){ //30 seconds timeout - reset board
ESP.restart();
}
}
Serial.print("Connecting to website: ");
Serial.println(host);
WiFiClient client;
if (client.connect(host, 80)) {
String url = "/rele/rele1.txt";
client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "User-Agent: ESP32\r\n" + "Connection: close\r\n\r\n");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
break;
}
}
String line = client.readStringUntil('\n');
Serial.println(line);
}else{
Serial.println("Connection unsucessful");
}
}

View File

@ -0,0 +1,174 @@
/*
* This sketch shows the WiFi event usage
*
*/
/*
* 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>
const char* ssid = "your-ssid";
const char* password = "your-password";
void WiFiEvent(WiFiEvent_t event)
{
Serial.printf("[WiFi-event] event: %d\n", event);
switch (event) {
case ARDUINO_EVENT_WIFI_READY:
Serial.println("WiFi interface ready");
break;
case ARDUINO_EVENT_WIFI_SCAN_DONE:
Serial.println("Completed scan for access points");
break;
case ARDUINO_EVENT_WIFI_STA_START:
Serial.println("WiFi client started");
break;
case ARDUINO_EVENT_WIFI_STA_STOP:
Serial.println("WiFi clients stopped");
break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
Serial.println("Connected to access point");
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("Disconnected from WiFi access point");
break;
case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE:
Serial.println("Authentication mode of access point has changed");
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.print("Obtained IP address: ");
Serial.println(WiFi.localIP());
break;
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
Serial.println("Lost IP address and IP address is reset to 0");
break;
case ARDUINO_EVENT_WPS_ER_SUCCESS:
Serial.println("WiFi Protected Setup (WPS): succeeded in enrollee mode");
break;
case ARDUINO_EVENT_WPS_ER_FAILED:
Serial.println("WiFi Protected Setup (WPS): failed in enrollee mode");
break;
case ARDUINO_EVENT_WPS_ER_TIMEOUT:
Serial.println("WiFi Protected Setup (WPS): timeout in enrollee mode");
break;
case ARDUINO_EVENT_WPS_ER_PIN:
Serial.println("WiFi Protected Setup (WPS): pin code in enrollee mode");
break;
case ARDUINO_EVENT_WIFI_AP_START:
Serial.println("WiFi access point started");
break;
case ARDUINO_EVENT_WIFI_AP_STOP:
Serial.println("WiFi access point stopped");
break;
case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
Serial.println("Client connected");
break;
case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
Serial.println("Client disconnected");
break;
case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
Serial.println("Assigned IP address to client");
break;
case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED:
Serial.println("Received probe request");
break;
case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
Serial.println("AP IPv6 is preferred");
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
Serial.println("STA IPv6 is preferred");
break;
case ARDUINO_EVENT_ETH_GOT_IP6:
Serial.println("Ethernet IPv6 is preferred");
break;
case ARDUINO_EVENT_ETH_START:
Serial.println("Ethernet started");
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("Ethernet stopped");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("Ethernet connected");
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("Ethernet disconnected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("Obtained IP address");
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);
// 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: ");
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);
Serial.println();
Serial.println();
Serial.println("Wait for WiFi... ");
}
void loop()
{
delay(1000);
}

View File

@ -0,0 +1,92 @@
/*
Example of connection using Static IP
by Evandro Luis Copercini
Public domain - 2017
*/
#include <WiFi.h>
const char* ssid = "your_network_name";
const char* password = "your_network_password";
const char* host = "example.com";
const char* url = "/index.html";
IPAddress local_IP(192, 168, 31, 115);
IPAddress gateway(192, 168, 31, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8); //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional
void setup()
{
Serial.begin(115200);
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("STA Failed to configure");
}
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("ESP Mac Address: ");
Serial.println(WiFi.macAddress());
Serial.print("Subnet Mask: ");
Serial.println(WiFi.subnetMask());
Serial.print("Gateway IP: ");
Serial.println(WiFi.gatewayIP());
Serial.print("DNS: ");
Serial.println(WiFi.dnsIP());
}
void loop()
{
delay(5000);
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}

View File

@ -0,0 +1,120 @@
#include "WiFi.h"
#define STA_SSID "**********"
#define STA_PASS "**********"
#define AP_SSID "esp32-v6"
static volatile bool wifi_connected = false;
WiFiUDP ntpClient;
void wifiOnConnect(){
Serial.println("STA Connected");
Serial.print("STA IPv4: ");
Serial.println(WiFi.localIP());
ntpClient.begin(2390);
}
void wifiOnDisconnect(){
Serial.println("STA Disconnected");
delay(1000);
WiFi.begin(STA_SSID, STA_PASS);
}
void wifiConnectedLoop(){
//lets check the time
const int NTP_PACKET_SIZE = 48;
byte ntpPacketBuffer[NTP_PACKET_SIZE];
IPAddress address;
WiFi.hostByName("time.nist.gov", address);
memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE);
ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode
ntpPacketBuffer[1] = 0; // Stratum, or type of clock
ntpPacketBuffer[2] = 6; // Polling Interval
ntpPacketBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
ntpPacketBuffer[12] = 49;
ntpPacketBuffer[13] = 0x4E;
ntpPacketBuffer[14] = 49;
ntpPacketBuffer[15] = 52;
ntpClient.beginPacket(address, 123); //NTP requests are to port 123
ntpClient.write(ntpPacketBuffer, NTP_PACKET_SIZE);
ntpClient.endPacket();
delay(1000);
int packetLength = ntpClient.parsePacket();
if (packetLength){
if(packetLength >= NTP_PACKET_SIZE){
ntpClient.read(ntpPacketBuffer, NTP_PACKET_SIZE);
}
ntpClient.flush();
uint32_t secsSince1900 = (uint32_t)ntpPacketBuffer[40] << 24 | (uint32_t)ntpPacketBuffer[41] << 16 | (uint32_t)ntpPacketBuffer[42] << 8 | ntpPacketBuffer[43];
//Serial.printf("Seconds since Jan 1 1900: %u\n", secsSince1900);
uint32_t epoch = secsSince1900 - 2208988800UL;
//Serial.printf("EPOCH: %u\n", epoch);
uint8_t h = (epoch % 86400L) / 3600;
uint8_t m = (epoch % 3600) / 60;
uint8_t s = (epoch % 60);
Serial.printf("UTC: %02u:%02u:%02u (GMT)\n", h, m, s);
}
delay(9000);
}
void WiFiEvent(WiFiEvent_t event){
switch(event) {
case ARDUINO_EVENT_WIFI_AP_START:
//can set ap hostname here
WiFi.softAPsetHostname(AP_SSID);
//enable ap ipv6 here
WiFi.softAPenableIpV6();
break;
case ARDUINO_EVENT_WIFI_STA_START:
//set sta hostname here
WiFi.setHostname(AP_SSID);
break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
//enable sta ipv6 here
WiFi.enableIpV6();
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
Serial.print("STA IPv6: ");
Serial.println(WiFi.localIPv6());
break;
case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
Serial.print("AP IPv6: ");
Serial.println(WiFi.softAPIPv6());
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
wifiOnConnect();
wifi_connected = true;
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
wifi_connected = false;
wifiOnDisconnect();
break;
default:
break;
}
}
void setup(){
Serial.begin(115200);
WiFi.disconnect(true);
WiFi.onEvent(WiFiEvent);
WiFi.mode(WIFI_MODE_APSTA);
WiFi.softAP(AP_SSID);
WiFi.begin(STA_SSID, STA_PASS);
}
void loop(){
if(wifi_connected){
wifiConnectedLoop();
}
while(Serial.available()) Serial.write(Serial.read());
}

View File

@ -0,0 +1,35 @@
/*
* This sketch trys to Connect to the best AP based on a given list
*
*/
#include <WiFi.h>
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
void setup()
{
Serial.begin(115200);
delay(10);
wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");
Serial.println("Connecting Wifi...");
if(wifiMulti.run() == WL_CONNECTED) {
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
}
void loop()
{
if(wifiMulti.run() != WL_CONNECTED) {
Serial.println("WiFi not connected!");
delay(1000);
}
}

View File

@ -0,0 +1,73 @@
# WiFiScan Example
This example demonstrates how to use the WiFi library to scan available WiFi networks and print the results.
# Supported Targets
Currently this example supports the following targets.
| Supported Targets | ESP32 | ESP32-S2 | ESP32-C3 |
| ----------------- | ----- | -------- | -------- |
## How to Use Example
* How to install the Arduino IDE: [Install Arduino IDE](https://github.com/espressif/arduino-esp32/tree/master/docs/arduino-ide).
#### Using Arduino IDE
* Before Compile/Verify, select the correct board: `Tools -> Board`.
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
#### Using Platform IO
* Select the COM port: `Devices` or setting the `upload_port` option on the `platformio.ini` file.
## Example/Log Output
```
ets Jul 29 2019 12:21:46
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1412
load:0x40078000,len:13400
load:0x40080400,len:3672
entry 0x400805f8
Setup done
scan start
scan done
17 networks found
1: IoTNetwork (-62)*
2: WiFiSSID (-62)*
3: B3A7992 (-63)*
4: WiFi (-63)
5: IoTNetwork2 (-64)*
...
```
## Troubleshooting
***Important: Be sure you're using a good quality USB cable and you have enought power source for your project.***
* **Programming Fail:** If the programming/flash procedure fails, try to reduce the serial connection speed.
* **COM port not detected:** Check the USB cable connection and the USB to Serial driver installation.
If the error persist, you can ask help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
## Contribute
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome!
Before creating a new issue, be sure to try the Troubleshooting and to check if the same issue was already created by someone else.
## Resources
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf)
* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf)
* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf)
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)

View File

@ -0,0 +1,48 @@
/*
* This sketch demonstrates how to scan WiFi networks.
* The API is almost the same as with the WiFi Shield library,
* the most obvious difference being the different file you need to include:
*/
#include "WiFi.h"
void setup()
{
Serial.begin(115200);
// Set WiFi to station mode and disconnect from an AP if it was previously connected
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("Setup done");
}
void loop()
{
Serial.println("scan start");
// WiFi.scanNetworks will return the number of networks found
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0) {
Serial.println("no networks found");
} else {
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i) {
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?" ":"*");
delay(10);
}
}
Serial.println("");
// Wait a bit before scanning again
delay(5000);
}

View File

@ -0,0 +1,70 @@
# WiFiScan Example
This example demonstrates how to use the WiFi library to scan available WiFi networks and print the results.
This example shows the basic functionality of the dual antenna capability.
# Supported Targets
This example is compatible with the ESP32-WROOM-DA.
## How to Use Example
* How to install the Arduino IDE: [Install Arduino IDE](https://github.com/espressif/arduino-esp32/tree/master/docs/arduino-ide).
#### Using Arduino IDE
* Before Compile/Verify, select the correct board: `Tools -> Board`.
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
#### Using Platform IO
* Select the COM port: `Devices` or set the `upload_port` option on the `platformio.ini` file.
## Example/Log Output
```
ets Jul 29 2019 12:21:46
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1412
load:0x40078000,len:13400
load:0x40080400,len:3672
entry 0x400805f8
Setup done
scan start
scan done
17 networks found
1: IoTNetwork (-62)*
2: WiFiSSID (-62)*
3: B3A7992 (-63)*
4: WiFi (-63)
5: IoTNetwork2 (-64)*
...
```
## Troubleshooting
***Important: Be sure you're using a good quality USB cable and you have enough power source for your project.***
* **Programming Fail:** If the programming/flash procedure fails, try to reduce the serial connection speed.
* **COM port not detected:** Check the USB cable connection and the USB to Serial driver installation.
If the error persists, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
## Contribute
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome!
Before creating a new issue, be sure to try the Troubleshooting and to check if the same issue was already created by someone else.
## Resources
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf)
* ESP32-WROOM-DA Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-wroom-da_datasheet_en.pdf)

View File

@ -0,0 +1,79 @@
/*
* This sketch demonstrates how to scan WiFi networks.
* The API is almost the same as with the WiFi Shield library,
* the most obvious difference being the different file you need to include:
*/
#include "WiFi.h"
/* These are the GPIOs connected to the antenna switch on the ESP32-WROOM-DA.
* Both GPIOs are not exposed to the module pins and cannot be used except to
* control the antnnas switch.
*
* For more details, see the datashhet at:
* https://www.espressif.com/sites/default/files/documentation/esp32-wroom-da_datasheet_en.pdf
*/
#define GPIO_ANT1 2 // GPIO for antenna 1
#define GPIO_ANT2 25 // GPIO for antenna 2 (default)
void setup()
{
bool err = false;
Serial.begin(115200);
// Set WiFi to station mode and disconnect from an AP if it was previously connected
WiFi.mode(WIFI_STA);
/* Attention: This is the manual prodecure for the dual antenna configuration.
* If you choose the ESP32-WROOM-DA module from the Tools -> Board, this configuration
* is not necessary!
*
* Set WiFi dual antenna configuration by passing the GPIO and antenna mode for RX ant TX
*/
err = WiFi.setDualAntennaConfig(GPIO_ANT1, GPIO_ANT2, WIFI_RX_ANT_AUTO, WIFI_TX_ANT_AUTO);
/* For more details on how to use this feature, see our docs:
* https://docs.espressif.com/projects/arduino-esp32/en/latest/api/wifi.html
*/
if(err == false) {
Serial.println("Dual Antenna configuration failed!");
} else {
Serial.println("Dual Antenna configuration successfuly done!");
}
WiFi.disconnect();
delay(100);
Serial.println("Setup done");
}
void loop()
{
Serial.println("scan start");
// WiFi.scanNetworks will return the number of networks found
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0) {
Serial.println("no networks found");
} else {
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i) {
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?" ":"*");
delay(10);
}
}
Serial.println("");
// Wait a bit before scanning again
delay(5000);
}

View File

@ -0,0 +1,36 @@
#include "WiFi.h"
void setup() {
Serial.begin(115200);
//Init WiFi as Station, start SmartConfig
WiFi.mode(WIFI_AP_STA);
WiFi.beginSmartConfig();
//Wait for SmartConfig packet from mobile
Serial.println("Waiting for SmartConfig.");
while (!WiFi.smartConfigDone()) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("SmartConfig received.");
//Wait for WiFi to connect to AP
Serial.println("Waiting for WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi Connected.");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// put your main code here, to run repeatedly:
}

View File

@ -0,0 +1,129 @@
/*
WiFiTelnetToSerial - Example Transparent UART to Telnet Server for ESP32
Copyright (c) 2017 Hristo Gochkov. All rights reserved.
This file is part of the ESP32 WiFi library for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <WiFi.h>
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
//how many clients should be able to telnet to this ESP32
#define MAX_SRV_CLIENTS 1
const char* ssid = "**********";
const char* password = "**********";
WiFiServer server(23);
WiFiClient serverClients[MAX_SRV_CLIENTS];
void setup() {
Serial.begin(115200);
Serial.println("\nConnecting");
wifiMulti.addAP(ssid, password);
wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");
Serial.println("Connecting Wifi ");
for (int loops = 10; loops > 0; loops--) {
if (wifiMulti.run() == WL_CONNECTED) {
Serial.println("");
Serial.print("WiFi connected ");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
break;
}
else {
Serial.println(loops);
delay(1000);
}
}
if (wifiMulti.run() != WL_CONNECTED) {
Serial.println("WiFi connect failed");
delay(1000);
ESP.restart();
}
//start UART and the server
Serial1.begin(9600);
server.begin();
server.setNoDelay(true);
Serial.print("Ready! Use 'telnet ");
Serial.print(WiFi.localIP());
Serial.println(" 23' to connect");
}
void loop() {
uint8_t i;
if (wifiMulti.run() == WL_CONNECTED) {
//check if there are any new clients
if (server.hasClient()){
for(i = 0; i < MAX_SRV_CLIENTS; i++){
//find free/disconnected spot
if (!serverClients[i] || !serverClients[i].connected()){
if(serverClients[i]) serverClients[i].stop();
serverClients[i] = server.available();
if (!serverClients[i]) Serial.println("available broken");
Serial.print("New client: ");
Serial.print(i); Serial.print(' ');
Serial.println(serverClients[i].remoteIP());
break;
}
}
if (i >= MAX_SRV_CLIENTS) {
//no free/disconnected spot so reject
server.available().stop();
}
}
//check clients for data
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
if(serverClients[i].available()){
//get data from the telnet client and push it to the UART
while(serverClients[i].available()) Serial1.write(serverClients[i].read());
}
}
else {
if (serverClients[i]) {
serverClients[i].stop();
}
}
}
//check UART for data
if(Serial1.available()){
size_t len = Serial1.available();
uint8_t sbuf[len];
Serial1.readBytes(sbuf, len);
//push UART data to all connected telnet clients
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
serverClients[i].write(sbuf, len);
delay(1);
}
}
}
}
else {
Serial.println("WiFi not connected!");
for(i = 0; i < MAX_SRV_CLIENTS; i++) {
if (serverClients[i]) serverClients[i].stop();
}
delay(1000);
}
}

View File

@ -0,0 +1,76 @@
/*
* This sketch sends random data over UDP on a ESP32 device
*
*/
#include <WiFi.h>
#include <WiFiUdp.h>
// WiFi network name and password:
const char * networkName = "your-ssid";
const char * networkPswd = "your-password";
//IP address to send UDP data to:
// either use the ip address of the server or
// a network broadcast address
const char * udpAddress = "192.168.0.255";
const int udpPort = 3333;
//Are we currently connected?
boolean connected = false;
//The udp library class
WiFiUDP udp;
void setup(){
// Initilize hardware serial:
Serial.begin(115200);
//Connect to the WiFi network
connectToWiFi(networkName, networkPswd);
}
void loop(){
//only send data when connected
if(connected){
//Send a packet
udp.beginPacket(udpAddress,udpPort);
udp.printf("Seconds since boot: %lu", millis()/1000);
udp.endPacket();
}
//Wait for 1 second
delay(1000);
}
void connectToWiFi(const char * ssid, const char * pwd){
Serial.println("Connecting to WiFi network: " + String(ssid));
// delete old config
WiFi.disconnect(true);
//register event handler
WiFi.onEvent(WiFiEvent);
//Initiate connection
WiFi.begin(ssid, pwd);
Serial.println("Waiting for WIFI connection...");
}
//wifi event handler
void WiFiEvent(WiFiEvent_t event){
switch(event) {
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
//When connected set
Serial.print("WiFi connected! IP address: ");
Serial.println(WiFi.localIP());
//initializes the UDP state
//This initializes the transfer buffer
udp.begin(WiFi.localIP(),udpPort);
connected = true;
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
connected = false;
break;
default: break;
}
}

View File

@ -0,0 +1,30 @@
# This python script listens on UDP port 3333
# for messages from the ESP32 board and prints them
import socket
import sys
try :
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error, msg :
print 'Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
try:
s.bind(('', 3333))
except socket.error , msg:
print 'Bind failed. Error: ' + str(msg[0]) + ': ' + msg[1]
sys.exit()
print 'Server listening'
while 1:
d = s.recvfrom(1024)
data = d[0]
if not data:
break
print data.strip()
s.close()

View File

@ -0,0 +1,16 @@
# This ruby script listens on UDP port 3333
# for messages from the ESP32 board and prints them
require 'socket'
include Socket::Constants
udp_socket = UDPSocket.new(AF_INET)
#bind
udp_socket.bind("", 3333)
puts 'Server listening'
while true do
message, sender = udp_socket.recvfrom(1024)
puts message
end

View File

@ -0,0 +1,68 @@
#######################################
# Syntax Coloring Map For WiFi
#######################################
#######################################
# Library (KEYWORD3)
#######################################
WiFi KEYWORD3
#######################################
# Datatypes (KEYWORD1)
#######################################
WiFi KEYWORD1
WiFiClient KEYWORD1
WiFiServer KEYWORD1
WiFiUDP KEYWORD1
WiFiClientSecure KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
status KEYWORD2
mode KEYWORD2
connect KEYWORD2
write KEYWORD2
available KEYWORD2
config KEYWORD2
setDNS KEYWORD2
read KEYWORD2
flush KEYWORD2
stop KEYWORD2
connected KEYWORD2
begin KEYWORD2
beginMulticast KEYWORD2
disconnect KEYWORD2
macAddress KEYWORD2
localIP KEYWORD2
subnetMask KEYWORD2
gatewayIP KEYWORD2
SSID KEYWORD2
psk KEYWORD2
BSSID KEYWORD2
RSSI KEYWORD2
encryptionType KEYWORD2
beginPacket KEYWORD2
beginPacketMulticast KEYWORD2
endPacket KEYWORD2
parsePacket KEYWORD2
destinationIP KEYWORD2
remoteIP KEYWORD2
remotePort KEYWORD2
softAP KEYWORD2
softAPIP KEYWORD2
softAPmacAddress KEYWORD2
softAPConfig KEYWORD2
printDiag KEYWORD2
hostByName KEYWORD2
scanNetworks KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
WIFI_AP LITERAL1
WIFI_STA LITERAL1
WIFI_AP_STA LITERAL1

View File

@ -0,0 +1,9 @@
name=WiFi
version=2.0.0
author=Hristo Gochkov
maintainer=Hristo Gochkov <hristo@espressif.com>
sentence=Enables network connection (local and Internet) using the ESP32 built-in WiFi.
paragraph=With this library you can instantiate Servers, Clients and send/receive UDP packets through WiFi. The shield can connect either to open or encrypted networks. The IP address can be assigned statically or through a DHCP. The library can also manage DNS.
category=Communication
url=
architectures=esp32

101
libraries/WiFi/src/WiFi.cpp Normal file
View File

@ -0,0 +1,101 @@
/*
ESP8266WiFi.cpp - WiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "WiFi.h"
extern "C" {
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <esp_err.h>
#include <esp_wifi.h>
#include <esp_event.h>
}
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------- Debug ------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
/**
* Output WiFi settings to an object derived from Print interface (like Serial).
* @param p Print interface
*/
void WiFiClass::printDiag(Print& p)
{
const char* modes[] = { "NULL", "STA", "AP", "STA+AP" };
wifi_mode_t mode;
esp_wifi_get_mode(&mode);
uint8_t primaryChan;
wifi_second_chan_t secondChan;
esp_wifi_get_channel(&primaryChan, &secondChan);
p.print("Mode: ");
p.println(modes[mode]);
p.print("Channel: ");
p.println(primaryChan);
/*
p.print("AP id: ");
p.println(wifi_station_get_current_ap_id());
p.print("Status: ");
p.println(wifi_station_get_connect_status());
*/
wifi_config_t conf;
esp_wifi_get_config((wifi_interface_t)WIFI_IF_STA, &conf);
const char* ssid = reinterpret_cast<const char*>(conf.sta.ssid);
p.print("SSID (");
p.print(strlen(ssid));
p.print("): ");
p.println(ssid);
const char* passphrase = reinterpret_cast<const char*>(conf.sta.password);
p.print("Passphrase (");
p.print(strlen(passphrase));
p.print("): ");
p.println(passphrase);
p.print("BSSID set: ");
p.println(conf.sta.bssid_set);
}
void WiFiClass::enableProv(bool status)
{
prov_enable = status;
}
bool WiFiClass::isProvEnabled()
{
return prov_enable;
}
WiFiClass WiFi;

75
libraries/WiFi/src/WiFi.h Normal file
View File

@ -0,0 +1,75 @@
/*
WiFi.h - esp32 Wifi support.
Based on WiFi.h from Arduino WiFi shield library.
Copyright (c) 2011-2014 Arduino. All right reserved.
Modified by Ivan Grokhotkov, December 2014
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef WiFi_h
#define WiFi_h
#include <stdint.h>
#include "Print.h"
#include "IPAddress.h"
#include "IPv6Address.h"
#include "WiFiType.h"
#include "WiFiSTA.h"
#include "WiFiAP.h"
#include "WiFiScan.h"
#include "WiFiGeneric.h"
#include "WiFiClient.h"
#include "WiFiServer.h"
#include "WiFiUdp.h"
class WiFiClass : public WiFiGenericClass, public WiFiSTAClass, public WiFiScanClass, public WiFiAPClass
{
private:
bool prov_enable;
public:
WiFiClass()
{
prov_enable = false;
}
using WiFiGenericClass::channel;
using WiFiSTAClass::SSID;
using WiFiSTAClass::RSSI;
using WiFiSTAClass::BSSID;
using WiFiSTAClass::BSSIDstr;
using WiFiScanClass::SSID;
using WiFiScanClass::encryptionType;
using WiFiScanClass::RSSI;
using WiFiScanClass::BSSID;
using WiFiScanClass::BSSIDstr;
using WiFiScanClass::channel;
public:
void printDiag(Print& dest);
friend class WiFiClient;
friend class WiFiServer;
friend class WiFiUDP;
void enableProv(bool status);
bool isProvEnabled();
};
extern WiFiClass WiFi;
#endif

View File

@ -0,0 +1,407 @@
/*
ESP8266WiFiSTA.cpp - WiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "WiFi.h"
#include "WiFiGeneric.h"
#include "WiFiAP.h"
extern "C" {
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <esp_err.h>
#include <esp_wifi.h>
#include <esp_event.h>
#include <lwip/ip_addr.h>
#include "dhcpserver/dhcpserver_options.h"
}
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- Private functions ------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
esp_netif_t* get_esp_interface_netif(esp_interface_t interface);
esp_err_t set_esp_interface_ip(esp_interface_t interface, IPAddress local_ip=INADDR_NONE, IPAddress gateway=INADDR_NONE, IPAddress subnet=INADDR_NONE, IPAddress dhcp_lease_start=INADDR_NONE);
static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs);
static size_t _wifi_strncpy(char * dst, const char * src, size_t dst_len){
if(!dst || !src || !dst_len){
return 0;
}
size_t src_len = strlen(src);
if(src_len >= dst_len){
src_len = dst_len;
} else {
src_len += 1;
}
memcpy(dst, src, src_len);
return src_len;
}
/**
* compare two AP configurations
* @param lhs softap_config
* @param rhs softap_config
* @return equal
*/
static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs)
{
if(strncmp(reinterpret_cast<const char*>(lhs.ap.ssid), reinterpret_cast<const char*>(rhs.ap.ssid), 32) != 0) {
return false;
}
if(strncmp(reinterpret_cast<const char*>(lhs.ap.password), reinterpret_cast<const char*>(rhs.ap.password), 64) != 0) {
return false;
}
if(lhs.ap.channel != rhs.ap.channel) {
return false;
}
if(lhs.ap.authmode != rhs.ap.authmode) {
return false;
}
if(lhs.ap.ssid_hidden != rhs.ap.ssid_hidden) {
return false;
}
if(lhs.ap.max_connection != rhs.ap.max_connection) {
return false;
}
if(lhs.ap.pairwise_cipher != rhs.ap.pairwise_cipher) {
return false;
}
if(lhs.ap.ftm_responder != rhs.ap.ftm_responder) {
return false;
}
return true;
}
void wifi_softap_config(wifi_config_t *wifi_config, const char * ssid=NULL, const char * password=NULL, uint8_t channel=6, wifi_auth_mode_t authmode=WIFI_AUTH_WPA2_PSK, uint8_t ssid_hidden=0, uint8_t max_connections=4, bool ftm_responder=false, uint16_t beacon_interval=100){
wifi_config->ap.channel = channel;
wifi_config->ap.max_connection = max_connections;
wifi_config->ap.beacon_interval = beacon_interval;
wifi_config->ap.ssid_hidden = ssid_hidden;
wifi_config->ap.authmode = WIFI_AUTH_OPEN;
wifi_config->ap.ssid_len = 0;
wifi_config->ap.ssid[0] = 0;
wifi_config->ap.password[0] = 0;
wifi_config->ap.ftm_responder = ftm_responder;
if(ssid != NULL && ssid[0] != 0){
_wifi_strncpy((char*)wifi_config->ap.ssid, ssid, 32);
wifi_config->ap.ssid_len = strlen(ssid);
if(password != NULL && password[0] != 0){
wifi_config->ap.authmode = authmode;
wifi_config->ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP; // Disable by default enabled insecure TKIP and use just CCMP.
_wifi_strncpy((char*)wifi_config->ap.password, password, 64);
}
}
}
// -----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------- AP function -----------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
/**
* Set up an access point
* @param ssid Pointer to the SSID (max 63 char).
* @param passphrase (for WPA2 min 8 char, for open use NULL)
* @param channel WiFi channel number, 1 - 13.
* @param ssid_hidden Network cloaking (0 = broadcast SSID, 1 = hide SSID)
* @param max_connection Max simultaneous connected clients, 1 - 4.
*/
bool WiFiAPClass::softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection, bool ftm_responder)
{
if(!WiFi.enableAP(true)) {
// enable AP failed
log_e("enable AP first!");
return false;
}
if(!ssid || *ssid == 0) {
// fail SSID missing
log_e("SSID missing!");
return false;
}
if(passphrase && (strlen(passphrase) > 0 && strlen(passphrase) < 8)) {
// fail passphrase too short
log_e("passphrase too short!");
return false;
}
wifi_config_t conf;
wifi_config_t conf_current;
wifi_softap_config(&conf, ssid, passphrase, channel, WIFI_AUTH_WPA2_PSK, ssid_hidden, max_connection, ftm_responder);
esp_err_t err = esp_wifi_get_config((wifi_interface_t)WIFI_IF_AP, &conf_current);
if(err){
log_e("get AP config failed");
return false;
}
if(!softap_config_equal(conf, conf_current)) {
err = esp_wifi_set_config((wifi_interface_t)WIFI_IF_AP, &conf);
if(err){
log_e("set AP config failed");
return false;
}
}
return true;
}
/**
* Return the current SSID associated with the network
* @return SSID
*/
String WiFiAPClass::softAPSSID() const
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return String();
}
wifi_config_t info;
if(!esp_wifi_get_config(WIFI_IF_AP, &info)) {
return String(reinterpret_cast<char*>(info.ap.ssid));
}
return String();
}
/**
* Configure access point
* @param local_ip access point IP
* @param gateway gateway IP
* @param subnet subnet mask
*/
bool WiFiAPClass::softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dhcp_lease_start)
{
esp_err_t err = ESP_OK;
if(!WiFi.enableAP(true)) {
// enable AP failed
return false;
}
err = set_esp_interface_ip(ESP_IF_WIFI_AP, local_ip, gateway, subnet, dhcp_lease_start);
return err == ESP_OK;
}
/**
* Disconnect from the network (close AP)
* @param wifioff disable mode?
* @return one value of wl_status_t enum
*/
bool WiFiAPClass::softAPdisconnect(bool wifioff)
{
bool ret;
wifi_config_t conf;
wifi_softap_config(&conf);
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return false;
}
ret = esp_wifi_set_config((wifi_interface_t)WIFI_IF_AP, &conf) == ESP_OK;
if(ret && wifioff) {
ret = WiFi.enableAP(false) == ESP_OK;
}
return ret;
}
/**
* Get the count of the Station / client that are connected to the softAP interface
* @return Stations count
*/
uint8_t WiFiAPClass::softAPgetStationNum()
{
wifi_sta_list_t clients;
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return 0;
}
if(esp_wifi_ap_get_sta_list(&clients) == ESP_OK) {
return clients.num;
}
return 0;
}
/**
* Get the softAP interface IP address.
* @return IPAddress softAP IP
*/
IPAddress WiFiAPClass::softAPIP()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
esp_netif_ip_info_t ip;
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_AP), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return IPAddress(ip.ip.addr);
}
/**
* Get the softAP broadcast IP address.
* @return IPAddress softAP broadcastIP
*/
IPAddress WiFiAPClass::softAPBroadcastIP()
{
esp_netif_ip_info_t ip;
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_AP), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return WiFiGenericClass::calculateBroadcast(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr));
}
/**
* Get the softAP network ID.
* @return IPAddress softAP networkID
*/
IPAddress WiFiAPClass::softAPNetworkID()
{
esp_netif_ip_info_t ip;
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_AP), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return WiFiGenericClass::calculateNetworkID(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr));
}
/**
* Get the softAP subnet CIDR.
* @return uint8_t softAP subnetCIDR
*/
uint8_t WiFiAPClass::softAPSubnetCIDR()
{
esp_netif_ip_info_t ip;
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_AP), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return WiFiGenericClass::calculateSubnetCIDR(IPAddress(ip.netmask.addr));
}
/**
* Get the softAP interface MAC address.
* @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH
* @return pointer to uint8_t*
*/
uint8_t* WiFiAPClass::softAPmacAddress(uint8_t* mac)
{
if(WiFiGenericClass::getMode() != WIFI_MODE_NULL){
esp_wifi_get_mac((wifi_interface_t)WIFI_IF_AP, mac);
}
return mac;
}
/**
* Get the softAP interface MAC address.
* @return String mac
*/
String WiFiAPClass::softAPmacAddress(void)
{
uint8_t mac[6];
char macStr[18] = { 0 };
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return String();
}
esp_wifi_get_mac((wifi_interface_t)WIFI_IF_AP, mac);
sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(macStr);
}
/**
* Get the softAP interface Host name.
* @return char array hostname
*/
const char * WiFiAPClass::softAPgetHostname()
{
const char * hostname = NULL;
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return hostname;
}
if(esp_netif_get_hostname(get_esp_interface_netif(ESP_IF_WIFI_AP), &hostname) != ESP_OK){
log_e("Netif Get Hostname Failed!");
}
return hostname;
}
/**
* Set the softAP interface Host name.
* @param hostname pointer to const string
* @return true on success
*/
bool WiFiAPClass::softAPsetHostname(const char * hostname)
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return false;
}
return esp_netif_set_hostname(get_esp_interface_netif(ESP_IF_WIFI_AP), hostname) == ESP_OK;
}
/**
* Enable IPv6 on the softAP interface.
* @return true on success
*/
bool WiFiAPClass::softAPenableIpV6()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return false;
}
return esp_netif_create_ip6_linklocal(get_esp_interface_netif(ESP_IF_WIFI_AP)) == ESP_OK;
}
/**
* Get the softAP interface IPv6 address.
* @return IPv6Address softAP IPv6
*/
IPv6Address WiFiAPClass::softAPIPv6()
{
esp_ip6_addr_t addr;
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPv6Address();
}
if(esp_netif_get_ip6_linklocal(get_esp_interface_netif(ESP_IF_WIFI_AP), &addr)) {
return IPv6Address();
}
return IPv6Address(addr.addr);
}

View File

@ -0,0 +1,67 @@
/*
ESP8266WiFiAP.h - esp8266 Wifi support.
Based on WiFi.h from Arduino WiFi shield library.
Copyright (c) 2011-2014 Arduino. All right reserved.
Modified by Ivan Grokhotkov, December 2014
Reworked by Markus Sattler, December 2015
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ESP32WIFIAP_H_
#define ESP32WIFIAP_H_
#include "WiFiType.h"
#include "WiFiGeneric.h"
class WiFiAPClass
{
// ----------------------------------------------------------------------------------------------
// ----------------------------------------- AP function ----------------------------------------
// ----------------------------------------------------------------------------------------------
public:
bool softAP(const char* ssid, const char* passphrase = NULL, int channel = 1, int ssid_hidden = 0, int max_connection = 4, bool ftm_responder = false);
bool softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dhcp_lease_start = (uint32_t) 0);
bool softAPdisconnect(bool wifioff = false);
uint8_t softAPgetStationNum();
IPAddress softAPIP();
IPAddress softAPBroadcastIP();
IPAddress softAPNetworkID();
uint8_t softAPSubnetCIDR();
bool softAPenableIpV6();
IPv6Address softAPIPv6();
const char * softAPgetHostname();
bool softAPsetHostname(const char * hostname);
uint8_t* softAPmacAddress(uint8_t* mac);
String softAPmacAddress(void);
String softAPSSID(void) const;
protected:
};
#endif /* ESP32WIFIAP_H_*/

View File

@ -0,0 +1,629 @@
/*
Client.h - Client class for Raspberry Pi
Copyright (c) 2016 Hristo Gochkov All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "WiFiClient.h"
#include "WiFi.h"
#include <lwip/sockets.h>
#include <lwip/netdb.h>
#include <errno.h>
#define WIFI_CLIENT_DEF_CONN_TIMEOUT_MS (3000)
#define WIFI_CLIENT_MAX_WRITE_RETRY (10)
#define WIFI_CLIENT_SELECT_TIMEOUT_US (1000000)
#define WIFI_CLIENT_FLUSH_BUFFER_SIZE (1024)
#undef connect
#undef write
#undef read
class WiFiClientRxBuffer {
private:
size_t _size;
uint8_t *_buffer;
size_t _pos;
size_t _fill;
int _fd;
bool _failed;
size_t r_available()
{
if(_fd < 0){
return 0;
}
int count;
#ifdef ESP_IDF_VERSION_MAJOR
int res = lwip_ioctl(_fd, FIONREAD, &count);
#else
int res = lwip_ioctl_r(_fd, FIONREAD, &count);
#endif
if(res < 0) {
_failed = true;
return 0;
}
return count;
}
size_t fillBuffer()
{
if(!_buffer){
_buffer = (uint8_t *)malloc(_size);
if(!_buffer) {
log_e("Not enough memory to allocate buffer");
_failed = true;
return 0;
}
}
if(_fill && _pos == _fill){
_fill = 0;
_pos = 0;
}
if(!_buffer || _size <= _fill || !r_available()) {
return 0;
}
int res = recv(_fd, _buffer + _fill, _size - _fill, MSG_DONTWAIT);
if(res < 0) {
if(errno != EWOULDBLOCK) {
_failed = true;
}
return 0;
}
_fill += res;
return res;
}
public:
WiFiClientRxBuffer(int fd, size_t size=1436)
:_size(size)
,_buffer(NULL)
,_pos(0)
,_fill(0)
,_fd(fd)
,_failed(false)
{
//_buffer = (uint8_t *)malloc(_size);
}
~WiFiClientRxBuffer()
{
free(_buffer);
}
bool failed(){
return _failed;
}
int read(uint8_t * dst, size_t len){
if(!dst || !len || (_pos == _fill && !fillBuffer())){
return _failed ? -1 : 0;
}
size_t a = _fill - _pos;
if(len <= a || ((len - a) <= (_size - _fill) && fillBuffer() >= (len - a))){
if(len == 1){
*dst = _buffer[_pos];
} else {
memcpy(dst, _buffer + _pos, len);
}
_pos += len;
return len;
}
size_t left = len;
size_t toRead = a;
uint8_t * buf = dst;
memcpy(buf, _buffer + _pos, toRead);
_pos += toRead;
left -= toRead;
buf += toRead;
while(left){
if(!fillBuffer()){
return len - left;
}
a = _fill - _pos;
toRead = (a > left)?left:a;
memcpy(buf, _buffer + _pos, toRead);
_pos += toRead;
left -= toRead;
buf += toRead;
}
return len;
}
int peek(){
if(_pos == _fill && !fillBuffer()){
return -1;
}
return _buffer[_pos];
}
size_t available(){
return _fill - _pos + r_available();
}
};
class WiFiClientSocketHandle {
private:
int sockfd;
public:
WiFiClientSocketHandle(int fd):sockfd(fd)
{
}
~WiFiClientSocketHandle()
{
close(sockfd);
}
int fd()
{
return sockfd;
}
};
WiFiClient::WiFiClient():_connected(false),_timeout(WIFI_CLIENT_DEF_CONN_TIMEOUT_MS),next(NULL)
{
}
WiFiClient::WiFiClient(int fd):_connected(true),_timeout(WIFI_CLIENT_DEF_CONN_TIMEOUT_MS),next(NULL)
{
clientSocketHandle.reset(new WiFiClientSocketHandle(fd));
_rxBuffer.reset(new WiFiClientRxBuffer(fd));
}
WiFiClient::~WiFiClient()
{
stop();
}
WiFiClient & WiFiClient::operator=(const WiFiClient &other)
{
stop();
clientSocketHandle = other.clientSocketHandle;
_rxBuffer = other._rxBuffer;
_connected = other._connected;
return *this;
}
void WiFiClient::stop()
{
clientSocketHandle = NULL;
_rxBuffer = NULL;
_connected = false;
}
int WiFiClient::connect(IPAddress ip, uint16_t port)
{
return connect(ip,port,_timeout);
}
int WiFiClient::connect(IPAddress ip, uint16_t port, int32_t timeout)
{
_timeout = timeout;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
log_e("socket: %d", errno);
return 0;
}
fcntl( sockfd, F_SETFL, fcntl( sockfd, F_GETFL, 0 ) | O_NONBLOCK );
uint32_t ip_addr = ip;
struct sockaddr_in serveraddr;
memset((char *) &serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
memcpy((void *)&serveraddr.sin_addr.s_addr, (const void *)(&ip_addr), 4);
serveraddr.sin_port = htons(port);
fd_set fdset;
struct timeval tv;
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
tv.tv_sec = _timeout / 1000;
tv.tv_usec = 0;
#ifdef ESP_IDF_VERSION_MAJOR
int res = lwip_connect(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
#else
int res = lwip_connect_r(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
#endif
if (res < 0 && errno != EINPROGRESS) {
log_e("connect on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno));
close(sockfd);
return 0;
}
res = select(sockfd + 1, nullptr, &fdset, nullptr, _timeout<0 ? nullptr : &tv);
if (res < 0) {
log_e("select on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno));
close(sockfd);
return 0;
} else if (res == 0) {
log_i("select returned due to timeout %d ms for fd %d", _timeout, sockfd);
close(sockfd);
return 0;
} else {
int sockerr;
socklen_t len = (socklen_t)sizeof(int);
res = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &sockerr, &len);
if (res < 0) {
log_e("getsockopt on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno));
close(sockfd);
return 0;
}
if (sockerr != 0) {
log_e("socket error on fd %d, errno: %d, \"%s\"", sockfd, sockerr, strerror(sockerr));
close(sockfd);
return 0;
}
}
#define ROE_WIFICLIENT(x,msg) { if (((x)<0)) { log_e("Setsockopt '" msg "'' on fd %d failed. errno: %d, \"%s\"", sockfd, errno, strerror(errno)); return 0; }}
ROE_WIFICLIENT(setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),"SO_SNDTIMEO");
ROE_WIFICLIENT(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),"SO_RCVTIMEO");
// These are also set in WiFiClientSecure, should be set here too?
//ROE_WIFICLIENT(setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable)),"TCP_NODELAY");
//ROE_WIFICLIENT (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)),"SO_KEEPALIVE");
fcntl( sockfd, F_SETFL, fcntl( sockfd, F_GETFL, 0 ) & (~O_NONBLOCK) );
clientSocketHandle.reset(new WiFiClientSocketHandle(sockfd));
_rxBuffer.reset(new WiFiClientRxBuffer(sockfd));
_connected = true;
return 1;
}
int WiFiClient::connect(const char *host, uint16_t port)
{
return connect(host,port,_timeout);
}
int WiFiClient::connect(const char *host, uint16_t port, int32_t timeout)
{
IPAddress srv((uint32_t)0);
if(!WiFiGenericClass::hostByName(host, srv)){
return 0;
}
return connect(srv, port, timeout);
}
int WiFiClient::setSocketOption(int option, char* value, size_t len)
{
return setSocketOption(SOL_SOCKET, option, (const void*)value, len);
}
int WiFiClient::setSocketOption(int level, int option, const void* value, size_t len)
{
int res = setsockopt(fd(), level, option, value, len);
if(res < 0) {
log_e("fail on %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
}
return res;
}
int WiFiClient::setTimeout(uint32_t seconds)
{
Client::setTimeout(seconds * 1000); // This should be here?
_timeout = seconds * 1000;
if(fd() >= 0) {
struct timeval tv;
tv.tv_sec = seconds;
tv.tv_usec = 0;
if(setSocketOption(SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0) {
return -1;
}
return setSocketOption(SO_SNDTIMEO, (char *)&tv, sizeof(struct timeval));
}
else {
return 0;
}
}
int WiFiClient::setOption(int option, int *value)
{
return setSocketOption(IPPROTO_TCP, option, (const void*)value, sizeof(int));
}
int WiFiClient::getOption(int option, int *value)
{
socklen_t size = sizeof(int);
int res = getsockopt(fd(), IPPROTO_TCP, option, (char *)value, &size);
if(res < 0) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
}
return res;
}
int WiFiClient::setNoDelay(bool nodelay)
{
int flag = nodelay;
return setOption(TCP_NODELAY, &flag);
}
bool WiFiClient::getNoDelay()
{
int flag = 0;
getOption(TCP_NODELAY, &flag);
return flag;
}
size_t WiFiClient::write(uint8_t data)
{
return write(&data, 1);
}
int WiFiClient::read()
{
uint8_t data = 0;
int res = read(&data, 1);
if(res < 0) {
return res;
}
if (res == 0) { // No data available.
return -1;
}
return data;
}
size_t WiFiClient::write(const uint8_t *buf, size_t size)
{
int res =0;
int retry = WIFI_CLIENT_MAX_WRITE_RETRY;
int socketFileDescriptor = fd();
size_t totalBytesSent = 0;
size_t bytesRemaining = size;
if(!_connected || (socketFileDescriptor < 0)) {
return 0;
}
while(retry) {
//use select to make sure the socket is ready for writing
fd_set set;
struct timeval tv;
FD_ZERO(&set); // empties the set
FD_SET(socketFileDescriptor, &set); // adds FD to the set
tv.tv_sec = 0;
tv.tv_usec = WIFI_CLIENT_SELECT_TIMEOUT_US;
retry--;
if(select(socketFileDescriptor + 1, NULL, &set, NULL, &tv) < 0) {
return 0;
}
if(FD_ISSET(socketFileDescriptor, &set)) {
res = send(socketFileDescriptor, (void*) buf, bytesRemaining, MSG_DONTWAIT);
if(res > 0) {
totalBytesSent += res;
if (totalBytesSent >= size) {
//completed successfully
retry = 0;
} else {
buf += res;
bytesRemaining -= res;
retry = WIFI_CLIENT_MAX_WRITE_RETRY;
}
}
else if(res < 0) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
if(errno != EAGAIN) {
//if resource was busy, can try again, otherwise give up
stop();
res = 0;
retry = 0;
}
}
else {
// Try again
}
}
}
return totalBytesSent;
}
size_t WiFiClient::write_P(PGM_P buf, size_t size)
{
return write(buf, size);
}
size_t WiFiClient::write(Stream &stream)
{
uint8_t * buf = (uint8_t *)malloc(1360);
if(!buf){
return 0;
}
size_t toRead = 0, toWrite = 0, written = 0;
size_t available = stream.available();
while(available){
toRead = (available > 1360)?1360:available;
toWrite = stream.readBytes(buf, toRead);
written += write(buf, toWrite);
available = stream.available();
}
free(buf);
return written;
}
int WiFiClient::read(uint8_t *buf, size_t size)
{
int res = -1;
if (_rxBuffer) {
res = _rxBuffer->read(buf, size);
if(_rxBuffer->failed()) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
}
}
return res;
}
int WiFiClient::peek()
{
int res = -1;
if (_rxBuffer) {
res = _rxBuffer->peek();
if(_rxBuffer->failed()) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
}
}
return res;
}
int WiFiClient::available()
{
if(!_rxBuffer)
{
return 0;
}
int res = _rxBuffer->available();
if(_rxBuffer->failed()) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
}
return res;
}
// Though flushing means to send all pending data,
// seems that in Arduino it also means to clear RX
void WiFiClient::flush() {
int res;
size_t a = available(), toRead = 0;
if(!a){
return;//nothing to flush
}
uint8_t * buf = (uint8_t *)malloc(WIFI_CLIENT_FLUSH_BUFFER_SIZE);
if(!buf){
return;//memory error
}
while(a){
toRead = (a>WIFI_CLIENT_FLUSH_BUFFER_SIZE)?WIFI_CLIENT_FLUSH_BUFFER_SIZE:a;
res = recv(fd(), buf, toRead, MSG_DONTWAIT);
if(res < 0) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
break;
}
a -= res;
}
free(buf);
}
uint8_t WiFiClient::connected()
{
if (_connected) {
uint8_t dummy;
int res = recv(fd(), &dummy, 0, MSG_DONTWAIT);
// avoid unused var warning by gcc
(void)res;
// recv only sets errno if res is <= 0
if (res <= 0){
switch (errno) {
case EWOULDBLOCK:
case ENOENT: //caused by vfs
_connected = true;
break;
case ENOTCONN:
case EPIPE:
case ECONNRESET:
case ECONNREFUSED:
case ECONNABORTED:
_connected = false;
log_d("Disconnected: RES: %d, ERR: %d", res, errno);
break;
default:
log_i("Unexpected: RES: %d, ERR: %d", res, errno);
_connected = true;
break;
}
} else {
_connected = true;
}
}
return _connected;
}
IPAddress WiFiClient::remoteIP(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getpeername(fd, (struct sockaddr*)&addr, &len);
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
return IPAddress((uint32_t)(s->sin_addr.s_addr));
}
uint16_t WiFiClient::remotePort(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getpeername(fd, (struct sockaddr*)&addr, &len);
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
return ntohs(s->sin_port);
}
IPAddress WiFiClient::remoteIP() const
{
return remoteIP(fd());
}
uint16_t WiFiClient::remotePort() const
{
return remotePort(fd());
}
IPAddress WiFiClient::localIP(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getsockname(fd, (struct sockaddr*)&addr, &len);
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
return IPAddress((uint32_t)(s->sin_addr.s_addr));
}
uint16_t WiFiClient::localPort(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getsockname(fd, (struct sockaddr*)&addr, &len);
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
return ntohs(s->sin_port);
}
IPAddress WiFiClient::localIP() const
{
return localIP(fd());
}
uint16_t WiFiClient::localPort() const
{
return localPort(fd());
}
bool WiFiClient::operator==(const WiFiClient& rhs)
{
return clientSocketHandle == rhs.clientSocketHandle && remotePort() == rhs.remotePort() && remoteIP() == rhs.remoteIP();
}
int WiFiClient::fd() const
{
if (clientSocketHandle == NULL) {
return -1;
} else {
return clientSocketHandle->fd();
}
}

View File

@ -0,0 +1,110 @@
/*
Client.h - Base class that provides Client
Copyright (c) 2011 Adrian McEwen. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _WIFICLIENT_H_
#define _WIFICLIENT_H_
#include "Arduino.h"
#include "Client.h"
#include <memory>
class WiFiClientSocketHandle;
class WiFiClientRxBuffer;
class ESPLwIPClient : public Client
{
public:
virtual int connect(IPAddress ip, uint16_t port, int32_t timeout) = 0;
virtual int connect(const char *host, uint16_t port, int32_t timeout) = 0;
virtual int setTimeout(uint32_t seconds) = 0;
};
class WiFiClient : public ESPLwIPClient
{
protected:
std::shared_ptr<WiFiClientSocketHandle> clientSocketHandle;
std::shared_ptr<WiFiClientRxBuffer> _rxBuffer;
bool _connected;
int _timeout;
public:
WiFiClient *next;
WiFiClient();
WiFiClient(int fd);
~WiFiClient();
int connect(IPAddress ip, uint16_t port);
int connect(IPAddress ip, uint16_t port, int32_t timeout);
int connect(const char *host, uint16_t port);
int connect(const char *host, uint16_t port, int32_t timeout);
size_t write(uint8_t data);
size_t write(const uint8_t *buf, size_t size);
size_t write_P(PGM_P buf, size_t size);
size_t write(Stream &stream);
int available();
int read();
int read(uint8_t *buf, size_t size);
int peek();
void flush();
void stop();
uint8_t connected();
operator bool()
{
return connected();
}
WiFiClient & operator=(const WiFiClient &other);
bool operator==(const bool value)
{
return bool() == value;
}
bool operator!=(const bool value)
{
return bool() != value;
}
bool operator==(const WiFiClient&);
bool operator!=(const WiFiClient& rhs)
{
return !this->operator==(rhs);
};
int fd() const;
int setSocketOption(int option, char* value, size_t len);
int setSocketOption(int level, int option, const void* value, size_t len);
int setOption(int option, int *value);
int getOption(int option, int *value);
int setTimeout(uint32_t seconds);
int setNoDelay(bool nodelay);
bool getNoDelay();
IPAddress remoteIP() const;
IPAddress remoteIP(int fd) const;
uint16_t remotePort() const;
uint16_t remotePort(int fd) const;
IPAddress localIP() const;
IPAddress localIP(int fd) const;
uint16_t localPort() const;
uint16_t localPort(int fd) const;
//friend class WiFiServer;
using Print::write;
};
#endif /* _WIFICLIENT_H_ */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,223 @@
/*
ESP8266WiFiGeneric.h - esp8266 Wifi support.
Based on WiFi.h from Ardiono WiFi shield library.
Copyright (c) 2011-2014 Arduino. All right reserved.
Modified by Ivan Grokhotkov, December 2014
Reworked by Markus Sattler, December 2015
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ESP32WIFIGENERIC_H_
#define ESP32WIFIGENERIC_H_
#include "esp_err.h"
#include "esp_event.h"
#include <functional>
#include "WiFiType.h"
#include "IPAddress.h"
#include "esp_smartconfig.h"
#include "wifi_provisioning/manager.h"
ESP_EVENT_DECLARE_BASE(ARDUINO_EVENTS);
typedef enum {
ARDUINO_EVENT_WIFI_READY = 0,
ARDUINO_EVENT_WIFI_SCAN_DONE,
ARDUINO_EVENT_WIFI_STA_START,
ARDUINO_EVENT_WIFI_STA_STOP,
ARDUINO_EVENT_WIFI_STA_CONNECTED,
ARDUINO_EVENT_WIFI_STA_DISCONNECTED,
ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE,
ARDUINO_EVENT_WIFI_STA_GOT_IP,
ARDUINO_EVENT_WIFI_STA_GOT_IP6,
ARDUINO_EVENT_WIFI_STA_LOST_IP,
ARDUINO_EVENT_WIFI_AP_START,
ARDUINO_EVENT_WIFI_AP_STOP,
ARDUINO_EVENT_WIFI_AP_STACONNECTED,
ARDUINO_EVENT_WIFI_AP_STADISCONNECTED,
ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED,
ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED,
ARDUINO_EVENT_WIFI_AP_GOT_IP6,
ARDUINO_EVENT_WIFI_FTM_REPORT,
ARDUINO_EVENT_ETH_START,
ARDUINO_EVENT_ETH_STOP,
ARDUINO_EVENT_ETH_CONNECTED,
ARDUINO_EVENT_ETH_DISCONNECTED,
ARDUINO_EVENT_ETH_GOT_IP,
ARDUINO_EVENT_ETH_GOT_IP6,
ARDUINO_EVENT_WPS_ER_SUCCESS,
ARDUINO_EVENT_WPS_ER_FAILED,
ARDUINO_EVENT_WPS_ER_TIMEOUT,
ARDUINO_EVENT_WPS_ER_PIN,
ARDUINO_EVENT_WPS_ER_PBC_OVERLAP,
ARDUINO_EVENT_SC_SCAN_DONE,
ARDUINO_EVENT_SC_FOUND_CHANNEL,
ARDUINO_EVENT_SC_GOT_SSID_PSWD,
ARDUINO_EVENT_SC_SEND_ACK_DONE,
ARDUINO_EVENT_PROV_INIT,
ARDUINO_EVENT_PROV_DEINIT,
ARDUINO_EVENT_PROV_START,
ARDUINO_EVENT_PROV_END,
ARDUINO_EVENT_PROV_CRED_RECV,
ARDUINO_EVENT_PROV_CRED_FAIL,
ARDUINO_EVENT_PROV_CRED_SUCCESS,
ARDUINO_EVENT_MAX
} arduino_event_id_t;
typedef union {
wifi_event_sta_scan_done_t wifi_scan_done;
wifi_event_sta_authmode_change_t wifi_sta_authmode_change;
wifi_event_sta_connected_t wifi_sta_connected;
wifi_event_sta_disconnected_t wifi_sta_disconnected;
wifi_event_sta_wps_er_pin_t wps_er_pin;
wifi_event_sta_wps_fail_reason_t wps_fail_reason;
wifi_event_ap_probe_req_rx_t wifi_ap_probereqrecved;
wifi_event_ap_staconnected_t wifi_ap_staconnected;
wifi_event_ap_stadisconnected_t wifi_ap_stadisconnected;
wifi_event_ftm_report_t wifi_ftm_report;
ip_event_ap_staipassigned_t wifi_ap_staipassigned;
ip_event_got_ip_t got_ip;
ip_event_got_ip6_t got_ip6;
smartconfig_event_got_ssid_pswd_t sc_got_ssid_pswd;
esp_eth_handle_t eth_connected;
wifi_sta_config_t prov_cred_recv;
wifi_prov_sta_fail_reason_t prov_fail_reason;
} arduino_event_info_t;
typedef struct{
arduino_event_id_t event_id;
arduino_event_info_t event_info;
} arduino_event_t;
typedef void (*WiFiEventCb)(arduino_event_id_t event);
typedef std::function<void(arduino_event_id_t event, arduino_event_info_t info)> WiFiEventFuncCb;
typedef void (*WiFiEventSysCb)(arduino_event_t *event);
typedef size_t wifi_event_id_t;
typedef enum {
WIFI_POWER_19_5dBm = 78,// 19.5dBm
WIFI_POWER_19dBm = 76,// 19dBm
WIFI_POWER_18_5dBm = 74,// 18.5dBm
WIFI_POWER_17dBm = 68,// 17dBm
WIFI_POWER_15dBm = 60,// 15dBm
WIFI_POWER_13dBm = 52,// 13dBm
WIFI_POWER_11dBm = 44,// 11dBm
WIFI_POWER_8_5dBm = 34,// 8.5dBm
WIFI_POWER_7dBm = 28,// 7dBm
WIFI_POWER_5dBm = 20,// 5dBm
WIFI_POWER_2dBm = 8,// 2dBm
WIFI_POWER_MINUS_1dBm = -4// -1dBm
} wifi_power_t;
static const int AP_STARTED_BIT = BIT0;
static const int AP_HAS_IP6_BIT = BIT1;
static const int AP_HAS_CLIENT_BIT = BIT2;
static const int STA_STARTED_BIT = BIT3;
static const int STA_CONNECTED_BIT = BIT4;
static const int STA_HAS_IP_BIT = BIT5;
static const int STA_HAS_IP6_BIT = BIT6;
static const int ETH_STARTED_BIT = BIT7;
static const int ETH_CONNECTED_BIT = BIT8;
static const int ETH_HAS_IP_BIT = BIT9;
static const int ETH_HAS_IP6_BIT = BIT10;
static const int WIFI_SCANNING_BIT = BIT11;
static const int WIFI_SCAN_DONE_BIT= BIT12;
static const int WIFI_DNS_IDLE_BIT = BIT13;
static const int WIFI_DNS_DONE_BIT = BIT14;
typedef enum {
WIFI_RX_ANT0 = 0,
WIFI_RX_ANT1,
WIFI_RX_ANT_AUTO
} wifi_rx_ant_t;
typedef enum {
WIFI_TX_ANT0 = 0,
WIFI_TX_ANT1,
WIFI_TX_ANT_AUTO
} wifi_tx_ant_t;
class WiFiGenericClass
{
public:
WiFiGenericClass();
wifi_event_id_t onEvent(WiFiEventCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
wifi_event_id_t onEvent(WiFiEventFuncCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
wifi_event_id_t onEvent(WiFiEventSysCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
void removeEvent(WiFiEventCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
void removeEvent(WiFiEventSysCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX);
void removeEvent(wifi_event_id_t id);
static int getStatusBits();
static int waitStatusBits(int bits, uint32_t timeout_ms);
int32_t channel(void);
void persistent(bool persistent);
void enableLongRange(bool enable);
static bool mode(wifi_mode_t);
static wifi_mode_t getMode();
bool enableSTA(bool enable);
bool enableAP(bool enable);
bool setSleep(bool enabled);
bool setSleep(wifi_ps_type_t sleepType);
wifi_ps_type_t getSleep();
bool setTxPower(wifi_power_t power);
wifi_power_t getTxPower();
bool initiateFTM(uint8_t frm_count=16, uint16_t burst_period=2, uint8_t channel=1, const uint8_t * mac=NULL);
static bool setDualAntennaConfig(uint8_t gpio_ant1, uint8_t gpio_ant2, wifi_rx_ant_t rx_mode, wifi_tx_ant_t tx_mode);
static const char * getHostname();
static bool setHostname(const char * hostname);
static bool hostname(const String& aHostname) { return setHostname(aHostname.c_str()); }
static esp_err_t _eventCallback(arduino_event_t *event);
static void useStaticBuffers(bool bufferMode);
static bool useStaticBuffers();
protected:
static bool _persistent;
static bool _long_range;
static wifi_mode_t _forceSleepLastMode;
static wifi_ps_type_t _sleepEnabled;
static bool _wifiUseStaticBuffers;
static int setStatusBits(int bits);
static int clearStatusBits(int bits);
public:
static int hostByName(const char *aHostname, IPAddress &aResult);
static IPAddress calculateNetworkID(IPAddress ip, IPAddress subnet);
static IPAddress calculateBroadcast(IPAddress ip, IPAddress subnet);
static uint8_t calculateSubnetCIDR(IPAddress subnetMask);
protected:
friend class WiFiSTAClass;
friend class WiFiScanClass;
friend class WiFiAPClass;
};
#endif /* ESP32WIFIGENERIC_H_ */

View File

@ -0,0 +1,204 @@
/**
*
* @file WiFiMulti.cpp
* @date 16.05.2015
* @author Markus Sattler
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the esp8266 core for Arduino environment.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "WiFiMulti.h"
#include <limits.h>
#include <string.h>
#include <esp32-hal.h>
WiFiMulti::WiFiMulti()
{
}
WiFiMulti::~WiFiMulti()
{
for(uint32_t i = 0; i < APlist.size(); i++) {
WifiAPlist_t entry = APlist[i];
if(entry.ssid) {
free(entry.ssid);
}
if(entry.passphrase) {
free(entry.passphrase);
}
}
APlist.clear();
}
bool WiFiMulti::addAP(const char* ssid, const char *passphrase)
{
WifiAPlist_t newAP;
if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) {
// fail SSID too long or missing!
log_e("[WIFI][APlistAdd] no ssid or ssid too long");
return false;
}
if(passphrase && strlen(passphrase) > 64) {
// fail passphrase too long!
log_e("[WIFI][APlistAdd] passphrase too long");
return false;
}
newAP.ssid = strdup(ssid);
if(!newAP.ssid) {
log_e("[WIFI][APlistAdd] fail newAP.ssid == 0");
return false;
}
if(passphrase && *passphrase != 0x00) {
newAP.passphrase = strdup(passphrase);
if(!newAP.passphrase) {
log_e("[WIFI][APlistAdd] fail newAP.passphrase == 0");
free(newAP.ssid);
return false;
}
} else {
newAP.passphrase = NULL;
}
APlist.push_back(newAP);
log_i("[WIFI][APlistAdd] add SSID: %s", newAP.ssid);
return true;
}
uint8_t WiFiMulti::run(uint32_t connectTimeout)
{
int8_t scanResult;
uint8_t status = WiFi.status();
if(status == WL_CONNECTED) {
for(uint32_t x = 0; x < APlist.size(); x++) {
if(WiFi.SSID()==APlist[x].ssid) {
return status;
}
}
WiFi.disconnect(false,false);
delay(10);
status = WiFi.status();
}
scanResult = WiFi.scanNetworks();
if(scanResult == WIFI_SCAN_RUNNING) {
// scan is running
return WL_NO_SSID_AVAIL;
} else if(scanResult >= 0) {
// scan done analyze
WifiAPlist_t bestNetwork { NULL, NULL };
int bestNetworkDb = INT_MIN;
uint8_t bestBSSID[6];
int32_t bestChannel = 0;
log_i("[WIFI] scan done");
if(scanResult == 0) {
log_e("[WIFI] no networks found");
} else {
log_i("[WIFI] %d networks found", scanResult);
for(int8_t i = 0; i < scanResult; ++i) {
String ssid_scan;
int32_t rssi_scan;
uint8_t sec_scan;
uint8_t* BSSID_scan;
int32_t chan_scan;
WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan);
bool known = false;
for(uint32_t x = APlist.size() ; x > 0; x--) {
WifiAPlist_t entry = APlist[x-1];
if(ssid_scan == entry.ssid) { // SSID match
known = true;
if(rssi_scan > bestNetworkDb) { // best network
if(sec_scan == WIFI_AUTH_OPEN || entry.passphrase) { // check for passphrase if not open wlan
bestNetworkDb = rssi_scan;
bestChannel = chan_scan;
memcpy((void*) &bestNetwork, (void*) &entry, sizeof(bestNetwork));
memcpy((void*) &bestBSSID, (void*) BSSID_scan, sizeof(bestBSSID));
}
}
break;
}
}
if(known) {
log_d(" ---> %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == WIFI_AUTH_OPEN) ? ' ' : '*');
} else {
log_d(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == WIFI_AUTH_OPEN) ? ' ' : '*');
}
}
}
// clean up ram
WiFi.scanDelete();
if(bestNetwork.ssid) {
log_i("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channel: %d (%d)", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb);
WiFi.begin(bestNetwork.ssid, bestNetwork.passphrase, bestChannel, bestBSSID);
status = WiFi.status();
auto startTime = millis();
// wait for connection, fail, or timeout
while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED && (millis() - startTime) <= connectTimeout) {
delay(10);
status = WiFi.status();
}
switch(status) {
case WL_CONNECTED:
log_i("[WIFI] Connecting done.");
log_d("[WIFI] SSID: %s", WiFi.SSID().c_str());
log_d("[WIFI] IP: %s", WiFi.localIP().toString().c_str());
log_d("[WIFI] MAC: %s", WiFi.BSSIDstr().c_str());
log_d("[WIFI] Channel: %d", WiFi.channel());
break;
case WL_NO_SSID_AVAIL:
log_e("[WIFI] Connecting Failed AP not found.");
break;
case WL_CONNECT_FAILED:
log_e("[WIFI] Connecting Failed.");
break;
default:
log_e("[WIFI] Connecting Failed (%d).", status);
break;
}
} else {
log_e("[WIFI] no matching wifi found!");
}
} else {
// start scan
log_d("[WIFI] delete old wifi config...");
WiFi.disconnect();
log_d("[WIFI] start scan");
// scan wifi async mode
WiFi.scanNetworks(true);
}
return status;
}

View File

@ -0,0 +1,51 @@
/**
*
* @file ESP8266WiFiMulti.h
* @date 16.05.2015
* @author Markus Sattler
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the esp8266 core for Arduino environment.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef WIFICLIENTMULTI_H_
#define WIFICLIENTMULTI_H_
#include "WiFi.h"
#include <vector>
typedef struct {
char * ssid;
char * passphrase;
} WifiAPlist_t;
class WiFiMulti
{
public:
WiFiMulti();
~WiFiMulti();
bool addAP(const char* ssid, const char *passphrase = NULL);
uint8_t run(uint32_t connectTimeout=5000);
private:
std::vector<WifiAPlist_t> APlist;
};
#endif /* WIFICLIENTMULTI_H_ */

View File

@ -0,0 +1,815 @@
/*
WiFiSTA.cpp - WiFi library for esp32
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "WiFi.h"
#include "WiFiGeneric.h"
#include "WiFiSTA.h"
extern "C" {
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <esp_err.h>
#include <esp_wifi.h>
#include <esp_event.h>
#include <esp32-hal.h>
#include <lwip/ip_addr.h>
#include "lwip/err.h"
#include "lwip/dns.h"
#include <esp_smartconfig.h>
#include <esp_netif.h>
#include "esp_wpa2.h"
}
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- Private functions ------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
esp_netif_t* get_esp_interface_netif(esp_interface_t interface);
esp_err_t set_esp_interface_dns(esp_interface_t interface, IPAddress main_dns=IPAddress(), IPAddress backup_dns=IPAddress(), IPAddress fallback_dns=IPAddress());
esp_err_t set_esp_interface_ip(esp_interface_t interface, IPAddress local_ip=INADDR_NONE, IPAddress gateway=INADDR_NONE, IPAddress subnet=INADDR_NONE, IPAddress dhcp_lease_start=INADDR_NONE);
static bool sta_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs);
static size_t _wifi_strncpy(char * dst, const char * src, size_t dst_len){
if(!dst || !src || !dst_len){
return 0;
}
size_t src_len = strlen(src);
if(src_len >= dst_len){
src_len = dst_len;
} else {
src_len += 1;
}
memcpy(dst, src, src_len);
return src_len;
}
/**
* compare two STA configurations
* @param lhs station_config
* @param rhs station_config
* @return equal
*/
static bool sta_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs)
{
if(memcmp(&lhs, &rhs, sizeof(wifi_config_t)) != 0) {
return false;
}
return true;
}
static void wifi_sta_config(wifi_config_t * wifi_config, const char * ssid=NULL, const char * password=NULL, const uint8_t * bssid=NULL, uint8_t channel=0, wifi_auth_mode_t min_security=WIFI_AUTH_WPA2_PSK, wifi_scan_method_t scan_method=WIFI_ALL_CHANNEL_SCAN, wifi_sort_method_t sort_method=WIFI_CONNECT_AP_BY_SIGNAL, uint16_t listen_interval=0, bool pmf_required=false){
wifi_config->sta.channel = channel;
wifi_config->sta.listen_interval = listen_interval;
wifi_config->sta.scan_method = scan_method;//WIFI_ALL_CHANNEL_SCAN or WIFI_FAST_SCAN
wifi_config->sta.sort_method = sort_method;//WIFI_CONNECT_AP_BY_SIGNAL or WIFI_CONNECT_AP_BY_SECURITY
wifi_config->sta.threshold.rssi = -127;
wifi_config->sta.pmf_cfg.capable = true;
wifi_config->sta.pmf_cfg.required = pmf_required;
wifi_config->sta.bssid_set = 0;
memset(wifi_config->sta.bssid, 0, 6);
wifi_config->sta.threshold.authmode = WIFI_AUTH_OPEN;
wifi_config->sta.ssid[0] = 0;
wifi_config->sta.password[0] = 0;
if(ssid != NULL && ssid[0] != 0){
_wifi_strncpy((char*)wifi_config->sta.ssid, ssid, 32);
if(password != NULL && password[0] != 0){
wifi_config->sta.threshold.authmode = min_security;
_wifi_strncpy((char*)wifi_config->sta.password, password, 64);
}
if(bssid != NULL){
wifi_config->sta.bssid_set = 1;
memcpy(wifi_config->sta.bssid, bssid, 6);
}
}
}
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- STA function -----------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
bool WiFiSTAClass::_autoReconnect = true;
bool WiFiSTAClass::_useStaticIp = false;
wifi_auth_mode_t WiFiSTAClass::_minSecurity = WIFI_AUTH_WPA2_PSK;
wifi_scan_method_t WiFiSTAClass::_scanMethod = WIFI_FAST_SCAN;
wifi_sort_method_t WiFiSTAClass::_sortMethod = WIFI_CONNECT_AP_BY_SIGNAL;
static wl_status_t _sta_status = WL_NO_SHIELD;
static EventGroupHandle_t _sta_status_group = NULL;
void WiFiSTAClass::_setStatus(wl_status_t status)
{
if(!_sta_status_group){
_sta_status_group = xEventGroupCreate();
if(!_sta_status_group){
log_e("STA Status Group Create Failed!");
_sta_status = status;
return;
}
}
xEventGroupClearBits(_sta_status_group, 0x00FFFFFF);
xEventGroupSetBits(_sta_status_group, status);
}
/**
* Return Connection status.
* @return one of the value defined in wl_status_t
*
*/
wl_status_t WiFiSTAClass::status()
{
if(!_sta_status_group){
return _sta_status;
}
return (wl_status_t)xEventGroupClearBits(_sta_status_group, 0);
}
/**
* Start Wifi connection with a WPA2 Enterprise AP
* if passphrase is set the most secure supported mode will be automatically selected
* @param ssid const char* Pointer to the SSID string.
* @param method wpa2_method_t The authentication method of WPA2 (WPA2_AUTH_TLS, WPA2_AUTH_PEAP, WPA2_AUTH_TTLS)
* @param wpa2_identity const char* Pointer to the entity
* @param wpa2_username const char* Pointer to the username
* @param password const char * Pointer to the password.
* @param ca_pem const char* Pointer to a string with the contents of a .pem file with CA cert
* @param client_crt const char* Pointer to a string with the contents of a .crt file with client cert
* @param client_key const char* Pointer to a string with the contants of a .key file with client key
* @param bssid uint8_t[6] Optional. BSSID / MAC of AP
* @param channel Optional. Channel of AP
* @param connect Optional. call connect
* @return
*/
wl_status_t WiFiSTAClass::begin(const char* wpa2_ssid, wpa2_auth_method_t method, const char* wpa2_identity, const char* wpa2_username, const char *wpa2_password, const char* ca_pem, const char* client_crt, const char* client_key, int32_t channel, const uint8_t* bssid, bool connect)
{
if(!WiFi.enableSTA(true)) {
log_e("STA enable failed!");
return WL_CONNECT_FAILED;
}
if(!wpa2_ssid || *wpa2_ssid == 0x00 || strlen(wpa2_ssid) > 32) {
log_e("SSID too long or missing!");
return WL_CONNECT_FAILED;
}
if(wpa2_identity && strlen(wpa2_identity) > 64) {
log_e("identity too long!");
return WL_CONNECT_FAILED;
}
if(wpa2_username && strlen(wpa2_username) > 64) {
log_e("username too long!");
return WL_CONNECT_FAILED;
}
if(wpa2_password && strlen(wpa2_password) > 64) {
log_e("password too long!");
}
if(ca_pem) {
esp_wifi_sta_wpa2_ent_set_ca_cert((uint8_t *)ca_pem, strlen(ca_pem));
}
if(client_crt) {
esp_wifi_sta_wpa2_ent_set_cert_key((uint8_t *)client_crt, strlen(client_crt), (uint8_t *)client_key, strlen(client_key), NULL, 0);
}
esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)wpa2_identity, strlen(wpa2_identity));
if(method == WPA2_AUTH_PEAP || method == WPA2_AUTH_TTLS) {
esp_wifi_sta_wpa2_ent_set_username((uint8_t *)wpa2_username, strlen(wpa2_username));
esp_wifi_sta_wpa2_ent_set_password((uint8_t *)wpa2_password, strlen(wpa2_password));
}
esp_wifi_sta_wpa2_ent_enable(); //set config settings to enable function
WiFi.begin(wpa2_ssid); //connect to wifi
return status();
}
/**
* Start Wifi connection
* if passphrase is set the most secure supported mode will be automatically selected
* @param ssid const char* Pointer to the SSID string.
* @param passphrase const char * Optional. Passphrase. Valid characters in a passphrase must be between ASCII 32-126 (decimal).
* @param bssid uint8_t[6] Optional. BSSID / MAC of AP
* @param channel Optional. Channel of AP
* @param connect Optional. call connect
* @return
*/
wl_status_t WiFiSTAClass::begin(const char* ssid, const char *passphrase, int32_t channel, const uint8_t* bssid, bool connect)
{
if(!WiFi.enableSTA(true)) {
log_e("STA enable failed!");
return WL_CONNECT_FAILED;
}
if(!ssid || *ssid == 0x00 || strlen(ssid) > 32) {
log_e("SSID too long or missing!");
return WL_CONNECT_FAILED;
}
if(passphrase && strlen(passphrase) > 64) {
log_e("passphrase too long!");
return WL_CONNECT_FAILED;
}
wifi_config_t conf;
memset(&conf, 0, sizeof(wifi_config_t));
wifi_sta_config(&conf, ssid, passphrase, bssid, channel, _minSecurity, _scanMethod, _sortMethod);
wifi_config_t current_conf;
if(esp_wifi_get_config((wifi_interface_t)ESP_IF_WIFI_STA, &current_conf) != ESP_OK){
log_e("get current config failed!");
return WL_CONNECT_FAILED;
}
if(!sta_config_equal(current_conf, conf)) {
if(esp_wifi_disconnect()){
log_e("disconnect failed!");
return WL_CONNECT_FAILED;
}
if(esp_wifi_set_config((wifi_interface_t)ESP_IF_WIFI_STA, &conf) != ESP_OK){
log_e("set config failed!");
return WL_CONNECT_FAILED;
}
} else if(status() == WL_CONNECTED){
return WL_CONNECTED;
} else {
if(esp_wifi_set_config((wifi_interface_t)ESP_IF_WIFI_STA, &conf) != ESP_OK){
log_e("set config failed!");
return WL_CONNECT_FAILED;
}
}
if(!_useStaticIp){
if(set_esp_interface_ip(ESP_IF_WIFI_STA) != ESP_OK) {
return WL_CONNECT_FAILED;
}
}
if(connect){
if(esp_wifi_connect() != ESP_OK) {
log_e("connect failed!");
return WL_CONNECT_FAILED;
}
}
return status();
}
wl_status_t WiFiSTAClass::begin(char* ssid, char *passphrase, int32_t channel, const uint8_t* bssid, bool connect)
{
return begin((const char*) ssid, (const char*) passphrase, channel, bssid, connect);
}
/**
* Use to connect to SDK config.
* @return wl_status_t
*/
wl_status_t WiFiSTAClass::begin()
{
if(!WiFi.enableSTA(true)) {
log_e("STA enable failed!");
return WL_CONNECT_FAILED;
}
wifi_config_t current_conf;
if(esp_wifi_get_config((wifi_interface_t)ESP_IF_WIFI_STA, &current_conf) != ESP_OK || esp_wifi_set_config((wifi_interface_t)ESP_IF_WIFI_STA, &current_conf) != ESP_OK) {
log_e("config failed");
return WL_CONNECT_FAILED;
}
if(!_useStaticIp && set_esp_interface_ip(ESP_IF_WIFI_STA) != ESP_OK) {
log_e("set ip failed!");
return WL_CONNECT_FAILED;
}
if(status() != WL_CONNECTED){
esp_err_t err = esp_wifi_connect();
if(err){
log_e("connect failed! 0x%x", err);
return WL_CONNECT_FAILED;
}
}
return status();
}
/**
* will force a disconnect and then start reconnecting to AP
* @return true when successful
*/
bool WiFiSTAClass::reconnect()
{
if(WiFi.getMode() & WIFI_MODE_STA) {
if(esp_wifi_disconnect() == ESP_OK) {
return esp_wifi_connect() == ESP_OK;
}
}
return false;
}
/**
* Disconnect from the network.
* @param wifioff `true` to turn the Wi-Fi radio off.
* @param eraseap `true` to erase the AP configuration from the NVS memory.
* @return `true` when successful.
*/
bool WiFiSTAClass::disconnect(bool wifioff, bool eraseap)
{
wifi_config_t conf;
wifi_sta_config(&conf);
if(WiFi.getMode() & WIFI_MODE_STA){
if(eraseap){
if(esp_wifi_set_config((wifi_interface_t)ESP_IF_WIFI_STA, &conf)){
log_e("clear config failed!");
}
}
if(esp_wifi_disconnect()){
log_e("disconnect failed!");
return false;
}
if(wifioff) {
return WiFi.enableSTA(false);
}
return true;
}
return false;
}
/**
* Change IP configuration settings disabling the dhcp client
* @param local_ip Static ip configuration
* @param gateway Static gateway configuration
* @param subnet Static Subnet mask
* @param dns1 Static DNS server 1
* @param dns2 Static DNS server 2
*/
bool WiFiSTAClass::config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2)
{
esp_err_t err = ESP_OK;
if(!WiFi.enableSTA(true)) {
return false;
}
err = set_esp_interface_ip(ESP_IF_WIFI_STA, local_ip, gateway, subnet);
if(err == ESP_OK){
err = set_esp_interface_dns(ESP_IF_WIFI_STA, dns1, dns2);
}
_useStaticIp = err == ESP_OK;
return err == ESP_OK;
}
/**
* is STA interface connected?
* @return true if STA is connected to an AP
*/
bool WiFiSTAClass::isConnected()
{
return (status() == WL_CONNECTED);
}
/**
* Set the minimum security for AP to be considered connectable.
* Must be called before WiFi.begin().
* @param minSecurity wifi_auth_mode_t
*/
void WiFiSTAClass::setMinSecurity(wifi_auth_mode_t minSecurity)
{
_minSecurity = minSecurity;
}
/**
* Set the way that AP is chosen.
* First SSID match[WIFI_FAST_SCAN] or Sorted[WIFI_ALL_CHANNEL_SCAN] (RSSI or Security)
* Must be called before WiFi.begin()
* @param scanMethod wifi_scan_method_t
*/
void WiFiSTAClass::setScanMethod(wifi_scan_method_t scanMethod)
{
_scanMethod = scanMethod;
}
/**
* Set the way that AP is sorted. (requires scanMethod WIFI_ALL_CHANNEL_SCAN)
* By SSID[WIFI_CONNECT_AP_BY_SIGNAL] or Security[WIFI_CONNECT_AP_BY_SECURITY]
* Must be called before WiFi.begin()
* @param sortMethod wifi_sort_method_t
*/
void WiFiSTAClass::setSortMethod(wifi_sort_method_t sortMethod)
{
_sortMethod = sortMethod;
}
/**
* Deprecated. Setting the ESP32 station to connect to the AP (which is recorded)
* automatically or not when powered on. Enable auto-connect by default.
* @deprecated use `setAutoReconnect`
* @param autoConnect bool
* @return if saved
*/
bool WiFiSTAClass::setAutoConnect(bool autoConnect)
{
return false;//now deprecated
}
/**
* Deprecated. Checks if ESP32 station mode will connect to AP
* automatically or not when it is powered on.
* @deprecated use `getAutoReconnect`
* @return auto connect
*/
bool WiFiSTAClass::getAutoConnect()
{
return false;//now deprecated
}
/**
* Function used to set the automatic reconnection if the connection is lost.
* @param autoReconnect `true` to enable this option.
* @return true
*/
bool WiFiSTAClass::setAutoReconnect(bool autoReconnect)
{
_autoReconnect = autoReconnect;
return true;
}
/**
* Function used to get the automatic reconnection if the connection is lost.
* @return The function will return `true` if this setting is enabled.
*/
bool WiFiSTAClass::getAutoReconnect()
{
return _autoReconnect;
}
/**
* Wait for WiFi connection to reach a result
* returns the status reached or disconnect if STA is off
* @return wl_status_t
*/
uint8_t WiFiSTAClass::waitForConnectResult(unsigned long timeoutLength)
{
//1 and 3 have STA enabled
if((WiFiGenericClass::getMode() & WIFI_MODE_STA) == 0) {
return WL_DISCONNECTED;
}
unsigned long start = millis();
while((!status() || status() >= WL_DISCONNECTED) && (millis() - start) < timeoutLength) {
delay(100);
}
return status();
}
/**
* Get the station interface IP address.
* @return IPAddress station IP
*/
IPAddress WiFiSTAClass::localIP()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
esp_netif_ip_info_t ip;
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_STA), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return IPAddress(ip.ip.addr);
}
/**
* Get the station interface MAC address.
* @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH
* @return pointer to uint8_t *
*/
uint8_t* WiFiSTAClass::macAddress(uint8_t* mac)
{
if(WiFiGenericClass::getMode() != WIFI_MODE_NULL){
esp_wifi_get_mac((wifi_interface_t)ESP_IF_WIFI_STA, mac);
}
else{
esp_read_mac(mac, ESP_MAC_WIFI_STA);
}
return mac;
}
/**
* Get the station interface MAC address.
* @return String mac
*/
String WiFiSTAClass::macAddress(void)
{
uint8_t mac[6];
char macStr[18] = { 0 };
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
esp_read_mac(mac, ESP_MAC_WIFI_STA);
}
else{
esp_wifi_get_mac((wifi_interface_t)ESP_IF_WIFI_STA, mac);
}
sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(macStr);
}
/**
* Get the interface subnet mask address.
* @return IPAddress subnetMask
*/
IPAddress WiFiSTAClass::subnetMask()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
esp_netif_ip_info_t ip;
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_STA), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return IPAddress(ip.netmask.addr);
}
/**
* Get the gateway ip address.
* @return IPAddress gatewayIP
*/
IPAddress WiFiSTAClass::gatewayIP()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
esp_netif_ip_info_t ip;
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_STA), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return IPAddress(ip.gw.addr);
}
/**
* Get the DNS ip address.
* @param dns_no
* @return IPAddress DNS Server IP
*/
IPAddress WiFiSTAClass::dnsIP(uint8_t dns_no)
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
const ip_addr_t * dns_ip = dns_getserver(dns_no);
return IPAddress(dns_ip->u_addr.ip4.addr);
}
/**
* Get the broadcast ip address.
* @return IPAddress broadcastIP
*/
IPAddress WiFiSTAClass::broadcastIP()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
esp_netif_ip_info_t ip;
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_STA), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return WiFiGenericClass::calculateBroadcast(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr));
}
/**
* Get the network id.
* @return IPAddress networkID
*/
IPAddress WiFiSTAClass::networkID()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPAddress();
}
esp_netif_ip_info_t ip;
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_STA), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return WiFiGenericClass::calculateNetworkID(IPAddress(ip.gw.addr), IPAddress(ip.netmask.addr));
}
/**
* Get the subnet CIDR.
* @return uint8_t subnetCIDR
*/
uint8_t WiFiSTAClass::subnetCIDR()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return (uint8_t)0;
}
esp_netif_ip_info_t ip;
if(esp_netif_get_ip_info(get_esp_interface_netif(ESP_IF_WIFI_STA), &ip) != ESP_OK){
log_e("Netif Get IP Failed!");
return IPAddress();
}
return WiFiGenericClass::calculateSubnetCIDR(IPAddress(ip.netmask.addr));
}
/**
* Return the current SSID associated with the network
* @return SSID
*/
String WiFiSTAClass::SSID() const
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return String();
}
wifi_ap_record_t info;
if(!esp_wifi_sta_get_ap_info(&info)) {
return String(reinterpret_cast<char*>(info.ssid));
}
return String();
}
/**
* Return the current pre shared key associated with the network
* @return psk string
*/
String WiFiSTAClass::psk() const
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return String();
}
wifi_config_t conf;
esp_wifi_get_config((wifi_interface_t)ESP_IF_WIFI_STA, &conf);
return String(reinterpret_cast<char*>(conf.sta.password));
}
/**
* Return the current bssid / mac associated with the network if configured
* @return bssid uint8_t *
*/
uint8_t* WiFiSTAClass::BSSID(void)
{
static uint8_t bssid[6];
wifi_ap_record_t info;
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return NULL;
}
if(!esp_wifi_sta_get_ap_info(&info)) {
memcpy(bssid, info.bssid, 6);
return reinterpret_cast<uint8_t*>(bssid);
}
return NULL;
}
/**
* Return the current bssid / mac associated with the network if configured
* @return String bssid mac
*/
String WiFiSTAClass::BSSIDstr(void)
{
uint8_t* bssid = BSSID();
if(!bssid){
return String();
}
char mac[18] = { 0 };
sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]);
return String(mac);
}
/**
* Return the current network RSSI.
* @return RSSI value
*/
int8_t WiFiSTAClass::RSSI(void)
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return 0;
}
wifi_ap_record_t info;
if(!esp_wifi_sta_get_ap_info(&info)) {
return info.rssi;
}
return 0;
}
/**
* Enable IPv6 on the station interface.
* @return true on success
*/
bool WiFiSTAClass::enableIpV6()
{
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return false;
}
return esp_netif_create_ip6_linklocal(get_esp_interface_netif(ESP_IF_WIFI_STA)) == ESP_OK;
}
/**
* Get the station interface IPv6 address.
* @return IPv6Address
*/
IPv6Address WiFiSTAClass::localIPv6()
{
esp_ip6_addr_t addr;
if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){
return IPv6Address();
}
if(esp_netif_get_ip6_linklocal(get_esp_interface_netif(ESP_IF_WIFI_STA), &addr)) {
return IPv6Address();
}
return IPv6Address(addr.addr);
}
bool WiFiSTAClass::_smartConfigStarted = false;
bool WiFiSTAClass::_smartConfigDone = false;
/**
* @brief
*
* @param type Select type of SmartConfig. Default type is SC_TYPE_ESPTOUCH
* @param crypt_key When using type SC_TYPE_ESPTOUTCH_V2 crypt key needed, else ignored. Lenght should be 16 chars.
* @return true if configuration is successful.
* @return false if configuration fails.
*/
bool WiFiSTAClass::beginSmartConfig(smartconfig_type_t type, char* crypt_key) {
esp_err_t err;
if (_smartConfigStarted) {
return false;
}
if (!WiFi.mode(WIFI_STA)) {
return false;
}
esp_wifi_disconnect();
smartconfig_start_config_t conf = SMARTCONFIG_START_CONFIG_DEFAULT();
if (type == SC_TYPE_ESPTOUCH_V2){
conf.esp_touch_v2_enable_crypt = true;
conf.esp_touch_v2_key = crypt_key;
}
err = esp_smartconfig_set_type(type);
if (err != ESP_OK) {
log_e("SmartConfig Set Type Failed!");
return false;
}
err = esp_smartconfig_start(&conf);
if (err != ESP_OK) {
log_e("SmartConfig Start Failed!");
return false;
}
_smartConfigStarted = true;
_smartConfigDone = false;
return true;
}
bool WiFiSTAClass::stopSmartConfig() {
if (!_smartConfigStarted) {
return true;
}
if (esp_smartconfig_stop() == ESP_OK) {
_smartConfigStarted = false;
return true;
}
return false;
}
bool WiFiSTAClass::smartConfigDone() {
if (!_smartConfigStarted) {
return false;
}
return _smartConfigDone;
}

View File

@ -0,0 +1,120 @@
/*
ESP8266WiFiSTA.h - esp8266 Wifi support.
Based on WiFi.h from Ardiono WiFi shield library.
Copyright (c) 2011-2014 Arduino. All right reserved.
Modified by Ivan Grokhotkov, December 2014
Reworked by Markus Sattler, December 2015
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ESP32WIFISTA_H_
#define ESP32WIFISTA_H_
#include "WiFiType.h"
#include "WiFiGeneric.h"
#ifdef ESP_IDF_VERSION_MAJOR
#include "esp_event.h"
#endif
typedef enum {
WPA2_AUTH_TLS = 0,
WPA2_AUTH_PEAP = 1,
WPA2_AUTH_TTLS = 2
} wpa2_auth_method_t;
class WiFiSTAClass
{
// ----------------------------------------------------------------------------------------------
// ---------------------------------------- STA function ----------------------------------------
// ----------------------------------------------------------------------------------------------
public:
wl_status_t begin(const char* wpa2_ssid, wpa2_auth_method_t method, const char* wpa2_identity=NULL, const char* wpa2_username=NULL, const char *wpa2_password=NULL, const char* ca_pem=NULL, const char* client_crt=NULL, const char* client_key=NULL, int32_t channel=0, const uint8_t* bssid=0, bool connect=true);
wl_status_t begin(const char* ssid, const char *passphrase = NULL, int32_t channel = 0, const uint8_t* bssid = NULL, bool connect = true);
wl_status_t begin(char* ssid, char *passphrase = NULL, int32_t channel = 0, const uint8_t* bssid = NULL, bool connect = true);
wl_status_t begin();
bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = (uint32_t)0x00000000, IPAddress dns2 = (uint32_t)0x00000000);
bool reconnect();
bool disconnect(bool wifioff = false, bool eraseap = false);
bool isConnected();
bool setAutoConnect(bool autoConnect);
bool getAutoConnect();
bool setAutoReconnect(bool autoReconnect);
bool getAutoReconnect();
uint8_t waitForConnectResult(unsigned long timeoutLength = 60000);
// Next group functions must be called before WiFi.begin()
void setMinSecurity(wifi_auth_mode_t minSecurity);// Default is WIFI_AUTH_WPA2_PSK
void setScanMethod(wifi_scan_method_t scanMethod);// Default is WIFI_FAST_SCAN
void setSortMethod(wifi_sort_method_t sortMethod);// Default is WIFI_CONNECT_AP_BY_SIGNAL
// STA network info
IPAddress localIP();
uint8_t * macAddress(uint8_t* mac);
String macAddress();
IPAddress subnetMask();
IPAddress gatewayIP();
IPAddress dnsIP(uint8_t dns_no = 0);
IPAddress broadcastIP();
IPAddress networkID();
uint8_t subnetCIDR();
bool enableIpV6();
IPv6Address localIPv6();
// STA WiFi info
static wl_status_t status();
String SSID() const;
String psk() const;
uint8_t * BSSID();
String BSSIDstr();
int8_t RSSI();
static void _setStatus(wl_status_t status);
protected:
static bool _useStaticIp;
static bool _autoReconnect;
static wifi_auth_mode_t _minSecurity;
static wifi_scan_method_t _scanMethod;
static wifi_sort_method_t _sortMethod;
public:
bool beginSmartConfig(smartconfig_type_t type = SC_TYPE_ESPTOUCH, char* crypt_key = NULL);
bool stopSmartConfig();
bool smartConfigDone();
static bool _smartConfigDone;
protected:
static bool _smartConfigStarted;
};
#endif /* ESP32WIFISTA_H_ */

View File

@ -0,0 +1,281 @@
/*
ESP8266WiFiScan.cpp - WiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "WiFi.h"
#include "WiFiGeneric.h"
#include "WiFiScan.h"
extern "C" {
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <esp_err.h>
#include <esp_wifi.h>
#include <esp_event.h>
#include <esp32-hal.h>
#include <lwip/ip_addr.h>
#include "lwip/err.h"
}
bool WiFiScanClass::_scanAsync = false;
uint32_t WiFiScanClass::_scanStarted = 0;
uint32_t WiFiScanClass::_scanTimeout = 10000;
uint16_t WiFiScanClass::_scanCount = 0;
void* WiFiScanClass::_scanResult = 0;
/**
* Start scan WiFi networks available
* @param async run in async mode
* @param show_hidden show hidden networks
* @return Number of discovered networks
*/
int16_t WiFiScanClass::scanNetworks(bool async, bool show_hidden, bool passive, uint32_t max_ms_per_chan, uint8_t channel, const char * ssid, const uint8_t * bssid)
{
if(WiFiGenericClass::getStatusBits() & WIFI_SCANNING_BIT) {
return WIFI_SCAN_RUNNING;
}
WiFiScanClass::_scanTimeout = max_ms_per_chan * 20;
WiFiScanClass::_scanAsync = async;
WiFi.enableSTA(true);
scanDelete();
wifi_scan_config_t config;
config.ssid = (uint8_t*)ssid;
config.bssid = (uint8_t*)bssid;
config.channel = channel;
config.show_hidden = show_hidden;
if(passive){
config.scan_type = WIFI_SCAN_TYPE_PASSIVE;
config.scan_time.passive = max_ms_per_chan;
} else {
config.scan_type = WIFI_SCAN_TYPE_ACTIVE;
config.scan_time.active.min = 100;
config.scan_time.active.max = max_ms_per_chan;
}
if(esp_wifi_scan_start(&config, false) == ESP_OK) {
_scanStarted = millis();
if (!_scanStarted) { //Prevent 0 from millis overflow
++_scanStarted;
}
WiFiGenericClass::clearStatusBits(WIFI_SCAN_DONE_BIT);
WiFiGenericClass::setStatusBits(WIFI_SCANNING_BIT);
if(WiFiScanClass::_scanAsync) {
return WIFI_SCAN_RUNNING;
}
if(WiFiGenericClass::waitStatusBits(WIFI_SCAN_DONE_BIT, 10000)){
return (int16_t) WiFiScanClass::_scanCount;
}
}
return WIFI_SCAN_FAILED;
}
/**
* private
* scan callback
* @param result void *arg
* @param status STATUS
*/
void WiFiScanClass::_scanDone()
{
esp_wifi_scan_get_ap_num(&(WiFiScanClass::_scanCount));
if(WiFiScanClass::_scanCount) {
WiFiScanClass::_scanResult = new wifi_ap_record_t[WiFiScanClass::_scanCount];
if(!WiFiScanClass::_scanResult || esp_wifi_scan_get_ap_records(&(WiFiScanClass::_scanCount), (wifi_ap_record_t*)_scanResult) != ESP_OK) {
WiFiScanClass::_scanCount = 0;
}
}
WiFiScanClass::_scanStarted=0; //Reset after a scan is completed for normal behavior
WiFiGenericClass::setStatusBits(WIFI_SCAN_DONE_BIT);
WiFiGenericClass::clearStatusBits(WIFI_SCANNING_BIT);
}
/**
*
* @param i specify from which network item want to get the information
* @return bss_info *
*/
void * WiFiScanClass::_getScanInfoByIndex(int i)
{
if(!WiFiScanClass::_scanResult || (size_t) i >= WiFiScanClass::_scanCount) {
return 0;
}
return reinterpret_cast<wifi_ap_record_t*>(WiFiScanClass::_scanResult) + i;
}
/**
* called to get the scan state in Async mode
* @return scan result or status
* -1 if scan not fin
* -2 if scan not triggered
*/
int16_t WiFiScanClass::scanComplete()
{
if (WiFiScanClass::_scanStarted && (millis()-WiFiScanClass::_scanStarted) > WiFiScanClass::_scanTimeout) { //Check is scan was started and if the delay expired, return WIFI_SCAN_FAILED in this case
WiFiGenericClass::clearStatusBits(WIFI_SCANNING_BIT);
return WIFI_SCAN_FAILED;
}
if(WiFiGenericClass::getStatusBits() & WIFI_SCAN_DONE_BIT) {
return WiFiScanClass::_scanCount;
}
if(WiFiGenericClass::getStatusBits() & WIFI_SCANNING_BIT) {
return WIFI_SCAN_RUNNING;
}
return WIFI_SCAN_FAILED;
}
/**
* delete last scan result from RAM
*/
void WiFiScanClass::scanDelete()
{
WiFiGenericClass::clearStatusBits(WIFI_SCAN_DONE_BIT);
if(WiFiScanClass::_scanResult) {
delete[] reinterpret_cast<wifi_ap_record_t*>(WiFiScanClass::_scanResult);
WiFiScanClass::_scanResult = 0;
WiFiScanClass::_scanCount = 0;
}
}
/**
* loads all infos from a scanned wifi in to the ptr parameters
* @param networkItem uint8_t
* @param ssid const char**
* @param encryptionType uint8_t *
* @param RSSI int32_t *
* @param BSSID uint8_t **
* @param channel int32_t *
* @return (true if ok)
*/
bool WiFiScanClass::getNetworkInfo(uint8_t i, String &ssid, uint8_t &encType, int32_t &rssi, uint8_t* &bssid, int32_t &channel)
{
wifi_ap_record_t* it = reinterpret_cast<wifi_ap_record_t*>(_getScanInfoByIndex(i));
if(!it) {
return false;
}
ssid = (const char*) it->ssid;
encType = it->authmode;
rssi = it->rssi;
bssid = it->bssid;
channel = it->primary;
return true;
}
/**
* Return the SSID discovered during the network scan.
* @param i specify from which network item want to get the information
* @return ssid string of the specified item on the networks scanned list
*/
String WiFiScanClass::SSID(uint8_t i)
{
wifi_ap_record_t* it = reinterpret_cast<wifi_ap_record_t*>(_getScanInfoByIndex(i));
if(!it) {
return String();
}
return String(reinterpret_cast<const char*>(it->ssid));
}
/**
* Return the encryption type of the networks discovered during the scanNetworks
* @param i specify from which network item want to get the information
* @return encryption type (enum wl_enc_type) of the specified item on the networks scanned list
*/
wifi_auth_mode_t WiFiScanClass::encryptionType(uint8_t i)
{
wifi_ap_record_t* it = reinterpret_cast<wifi_ap_record_t*>(_getScanInfoByIndex(i));
if(!it) {
return WIFI_AUTH_OPEN;
}
return it->authmode;
}
/**
* Return the RSSI of the networks discovered during the scanNetworks
* @param i specify from which network item want to get the information
* @return signed value of RSSI of the specified item on the networks scanned list
*/
int32_t WiFiScanClass::RSSI(uint8_t i)
{
wifi_ap_record_t* it = reinterpret_cast<wifi_ap_record_t*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->rssi;
}
/**
* return MAC / BSSID of scanned wifi
* @param i specify from which network item want to get the information
* @return uint8_t * MAC / BSSID of scanned wifi
*/
uint8_t * WiFiScanClass::BSSID(uint8_t i)
{
wifi_ap_record_t* it = reinterpret_cast<wifi_ap_record_t*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->bssid;
}
/**
* return MAC / BSSID of scanned wifi
* @param i specify from which network item want to get the information
* @return String MAC / BSSID of scanned wifi
*/
String WiFiScanClass::BSSIDstr(uint8_t i)
{
char mac[18] = { 0 };
wifi_ap_record_t* it = reinterpret_cast<wifi_ap_record_t*>(_getScanInfoByIndex(i));
if(!it) {
return String();
}
sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]);
return String(mac);
}
int32_t WiFiScanClass::channel(uint8_t i)
{
wifi_ap_record_t* it = reinterpret_cast<wifi_ap_record_t*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->primary;
}

View File

@ -0,0 +1,66 @@
/*
ESP8266WiFiScan.h - esp8266 Wifi support.
Based on WiFi.h from Ardiono WiFi shield library.
Copyright (c) 2011-2014 Arduino. All right reserved.
Modified by Ivan Grokhotkov, December 2014
Reworked by Markus Sattler, December 2015
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ESP32WIFISCAN_H_
#define ESP32WIFISCAN_H_
#include "WiFiType.h"
#include "WiFiGeneric.h"
class WiFiScanClass
{
public:
int16_t scanNetworks(bool async = false, bool show_hidden = false, bool passive = false, uint32_t max_ms_per_chan = 300, uint8_t channel = 0, const char * ssid=nullptr, const uint8_t * bssid=nullptr);
int16_t scanComplete();
void scanDelete();
// scan result
bool getNetworkInfo(uint8_t networkItem, String &ssid, uint8_t &encryptionType, int32_t &RSSI, uint8_t* &BSSID, int32_t &channel);
String SSID(uint8_t networkItem);
wifi_auth_mode_t encryptionType(uint8_t networkItem);
int32_t RSSI(uint8_t networkItem);
uint8_t * BSSID(uint8_t networkItem);
String BSSIDstr(uint8_t networkItem);
int32_t channel(uint8_t networkItem);
static void * getScanInfoByIndex(int i) { return _getScanInfoByIndex(i); };
static void _scanDone();
protected:
static bool _scanAsync;
static uint32_t _scanStarted;
static uint32_t _scanTimeout;
static uint16_t _scanCount;
static void* _scanResult;
static void * _getScanInfoByIndex(int i);
};
#endif /* ESP32WIFISCAN_H_ */

View File

@ -0,0 +1,139 @@
/*
Server.cpp - Server class for Raspberry Pi
Copyright (c) 2016 Hristo Gochkov All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "WiFiServer.h"
#include <lwip/sockets.h>
#include <lwip/netdb.h>
#undef write
#undef close
int WiFiServer::setTimeout(uint32_t seconds){
struct timeval tv;
tv.tv_sec = seconds;
tv.tv_usec = 0;
if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0)
return -1;
return setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(struct timeval));
}
size_t WiFiServer::write(const uint8_t *data, size_t len){
return 0;
}
void WiFiServer::stopAll(){}
WiFiClient WiFiServer::available(){
if(!_listening)
return WiFiClient();
int client_sock;
if (_accepted_sockfd >= 0) {
client_sock = _accepted_sockfd;
_accepted_sockfd = -1;
}
else {
struct sockaddr_in _client;
int cs = sizeof(struct sockaddr_in);
#ifdef ESP_IDF_VERSION_MAJOR
client_sock = lwip_accept(sockfd, (struct sockaddr *)&_client, (socklen_t*)&cs);
#else
client_sock = lwip_accept_r(sockfd, (struct sockaddr *)&_client, (socklen_t*)&cs);
#endif
}
if(client_sock >= 0){
int val = 1;
if(setsockopt(client_sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof(int)) == ESP_OK) {
val = _noDelay;
if(setsockopt(client_sock, IPPROTO_TCP, TCP_NODELAY, (char*)&val, sizeof(int)) == ESP_OK)
return WiFiClient(client_sock);
}
}
return WiFiClient();
}
void WiFiServer::begin(uint16_t port){
begin(port, 1);
}
void WiFiServer::begin(uint16_t port, int enable){
if(_listening)
return;
if(port){
_port = port;
}
struct sockaddr_in server;
sockfd = socket(AF_INET , SOCK_STREAM, 0);
if (sockfd < 0)
return;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
server.sin_family = AF_INET;
server.sin_addr.s_addr = _addr;
server.sin_port = htons(_port);
if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
return;
if(listen(sockfd , _max_clients) < 0)
return;
fcntl(sockfd, F_SETFL, O_NONBLOCK);
_listening = true;
_noDelay = false;
_accepted_sockfd = -1;
}
void WiFiServer::setNoDelay(bool nodelay) {
_noDelay = nodelay;
}
bool WiFiServer::getNoDelay() {
return _noDelay;
}
bool WiFiServer::hasClient() {
if (_accepted_sockfd >= 0) {
return true;
}
struct sockaddr_in _client;
int cs = sizeof(struct sockaddr_in);
#ifdef ESP_IDF_VERSION_MAJOR
_accepted_sockfd = lwip_accept(sockfd, (struct sockaddr *)&_client, (socklen_t*)&cs);
#else
_accepted_sockfd = lwip_accept_r(sockfd, (struct sockaddr *)&_client, (socklen_t*)&cs);
#endif
if (_accepted_sockfd >= 0) {
return true;
}
return false;
}
void WiFiServer::end(){
#ifdef ESP_IDF_VERSION_MAJOR
lwip_close(sockfd);
#else
lwip_close_r(sockfd);
#endif
sockfd = -1;
_listening = false;
}
void WiFiServer::close(){
end();
}
void WiFiServer::stop(){
end();
}

View File

@ -0,0 +1,69 @@
/*
Server.h - Server class for Raspberry Pi
Copyright (c) 2016 Hristo Gochkov All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _WIFISERVER_H_
#define _WIFISERVER_H_
#include "Arduino.h"
#include "Server.h"
#include "WiFiClient.h"
#include "IPAddress.h"
class WiFiServer : public Server {
private:
int sockfd;
int _accepted_sockfd = -1;
IPAddress _addr;
uint16_t _port;
uint8_t _max_clients;
bool _listening;
bool _noDelay = false;
public:
void listenOnLocalhost(){}
// _addr(INADDR_ANY) is the same as _addr() ==> 0.0.0.0
WiFiServer(uint16_t port=80, uint8_t max_clients=4):sockfd(-1),_accepted_sockfd(-1),_addr(),_port(port),_max_clients(max_clients),_listening(false),_noDelay(false) {
log_v("WiFiServer::WiFiServer(port=%d, ...)", port);
}
WiFiServer(const IPAddress& addr, uint16_t port=80, uint8_t max_clients=4):sockfd(-1),_accepted_sockfd(-1),_addr(addr),_port(port),_max_clients(max_clients),_listening(false),_noDelay(false) {
log_v("WiFiServer::WiFiServer(addr=%s, port=%d, ...)", addr.toString().c_str(), port);
}
~WiFiServer(){ end();}
WiFiClient available();
WiFiClient accept(){return available();}
void begin(uint16_t port=0);
void begin(uint16_t port, int reuse_enable);
void setNoDelay(bool nodelay);
bool getNoDelay();
bool hasClient();
size_t write(const uint8_t *data, size_t len);
size_t write(uint8_t data){
return write(&data, 1);
}
using Print::write;
void end();
void close();
void stop();
operator bool(){return _listening;}
int setTimeout(uint32_t seconds);
void stopAll();
};
#endif /* _WIFISERVER_H_ */

View File

@ -0,0 +1,53 @@
/*
ESP8266WiFiType.h - esp8266 Wifi support.
Copyright (c) 2011-2014 Arduino. All right reserved.
Modified by Ivan Grokhotkov, December 2014
Reworked by Markus Sattler, December 2015
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ESP32WIFITYPE_H_
#define ESP32WIFITYPE_H_
#include "esp_wifi_types.h"
#define WIFI_SCAN_RUNNING (-1)
#define WIFI_SCAN_FAILED (-2)
#define WiFiMode_t wifi_mode_t
#define WIFI_OFF WIFI_MODE_NULL
#define WIFI_STA WIFI_MODE_STA
#define WIFI_AP WIFI_MODE_AP
#define WIFI_AP_STA WIFI_MODE_APSTA
#define WiFiEvent_t arduino_event_id_t
#define WiFiEventInfo_t arduino_event_info_t
#define WiFiEventId_t wifi_event_id_t
typedef enum {
WL_NO_SHIELD = 255, // for compatibility with WiFi Shield library
WL_IDLE_STATUS = 0,
WL_NO_SSID_AVAIL = 1,
WL_SCAN_COMPLETED = 2,
WL_CONNECTED = 3,
WL_CONNECT_FAILED = 4,
WL_CONNECTION_LOST = 5,
WL_DISCONNECTED = 6
} wl_status_t;
#endif /* ESP32WIFITYPE_H_ */

View File

@ -0,0 +1,281 @@
/*
Udp.cpp - UDP class for Raspberry Pi
Copyright (c) 2016 Hristo Gochkov All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "WiFiUdp.h"
#include <lwip/sockets.h>
#include <lwip/netdb.h>
#include <errno.h>
#undef write
#undef read
WiFiUDP::WiFiUDP()
: udp_server(-1)
, server_port(0)
, remote_port(0)
, tx_buffer(0)
, tx_buffer_len(0)
, rx_buffer(0)
{}
WiFiUDP::~WiFiUDP(){
stop();
}
uint8_t WiFiUDP::begin(IPAddress address, uint16_t port){
stop();
server_port = port;
tx_buffer = new char[1460];
if(!tx_buffer){
log_e("could not create tx buffer: %d", errno);
return 0;
}
if ((udp_server=socket(AF_INET, SOCK_DGRAM, 0)) == -1){
log_e("could not create socket: %d", errno);
return 0;
}
int yes = 1;
if (setsockopt(udp_server,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)) < 0) {
log_e("could not set socket option: %d", errno);
stop();
return 0;
}
struct sockaddr_in addr;
memset((char *) &addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(server_port);
addr.sin_addr.s_addr = (in_addr_t)address;
if(bind(udp_server , (struct sockaddr*)&addr, sizeof(addr)) == -1){
log_e("could not bind socket: %d", errno);
stop();
return 0;
}
fcntl(udp_server, F_SETFL, O_NONBLOCK);
return 1;
}
uint8_t WiFiUDP::begin(uint16_t p){
return begin(IPAddress(INADDR_ANY), p);
}
uint8_t WiFiUDP::beginMulticast(IPAddress a, uint16_t p){
if(begin(IPAddress(INADDR_ANY), p)){
if(a != 0){
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = (in_addr_t)a;
mreq.imr_interface.s_addr = INADDR_ANY;
if (setsockopt(udp_server, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
log_e("could not join igmp: %d", errno);
stop();
return 0;
}
multicast_ip = a;
}
return 1;
}
return 0;
}
void WiFiUDP::stop(){
if(tx_buffer){
delete[] tx_buffer;
tx_buffer = NULL;
}
tx_buffer_len = 0;
if(rx_buffer){
cbuf *b = rx_buffer;
rx_buffer = NULL;
delete b;
}
if(udp_server == -1)
return;
if(multicast_ip != 0){
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = (in_addr_t)multicast_ip;
mreq.imr_interface.s_addr = (in_addr_t)0;
setsockopt(udp_server, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
multicast_ip = IPAddress(INADDR_ANY);
}
close(udp_server);
udp_server = -1;
}
int WiFiUDP::beginMulticastPacket(){
if(!server_port || multicast_ip == IPAddress(INADDR_ANY))
return 0;
remote_ip = multicast_ip;
remote_port = server_port;
return beginPacket();
}
int WiFiUDP::beginPacket(){
if(!remote_port)
return 0;
// allocate tx_buffer if is necessary
if(!tx_buffer){
tx_buffer = new char[1460];
if(!tx_buffer){
log_e("could not create tx buffer: %d", errno);
return 0;
}
}
tx_buffer_len = 0;
// check whereas socket is already open
if (udp_server != -1)
return 1;
if ((udp_server=socket(AF_INET, SOCK_DGRAM, 0)) == -1){
log_e("could not create socket: %d", errno);
return 0;
}
fcntl(udp_server, F_SETFL, O_NONBLOCK);
return 1;
}
int WiFiUDP::beginPacket(IPAddress ip, uint16_t port){
remote_ip = ip;
remote_port = port;
return beginPacket();
}
int WiFiUDP::beginPacket(const char *host, uint16_t port){
struct hostent *server;
server = gethostbyname(host);
if (server == NULL){
log_e("could not get host from dns: %d", errno);
return 0;
}
return beginPacket(IPAddress((const uint8_t *)(server->h_addr_list[0])), port);
}
int WiFiUDP::endPacket(){
struct sockaddr_in recipient;
recipient.sin_addr.s_addr = (uint32_t)remote_ip;
recipient.sin_family = AF_INET;
recipient.sin_port = htons(remote_port);
int sent = sendto(udp_server, tx_buffer, tx_buffer_len, 0, (struct sockaddr*) &recipient, sizeof(recipient));
if(sent < 0){
log_e("could not send data: %d", errno);
return 0;
}
return 1;
}
size_t WiFiUDP::write(uint8_t data){
if(tx_buffer_len == 1460){
endPacket();
tx_buffer_len = 0;
}
tx_buffer[tx_buffer_len++] = data;
return 1;
}
size_t WiFiUDP::write(const uint8_t *buffer, size_t size){
size_t i;
for(i=0;i<size;i++)
write(buffer[i]);
return i;
}
int WiFiUDP::parsePacket(){
if(rx_buffer)
return 0;
struct sockaddr_in si_other;
int slen = sizeof(si_other) , len;
char * buf = new char[1460];
if(!buf){
return 0;
}
if ((len = recvfrom(udp_server, buf, 1460, MSG_DONTWAIT, (struct sockaddr *) &si_other, (socklen_t *)&slen)) == -1){
delete[] buf;
if(errno == EWOULDBLOCK){
return 0;
}
log_e("could not receive data: %d", errno);
return 0;
}
remote_ip = IPAddress(si_other.sin_addr.s_addr);
remote_port = ntohs(si_other.sin_port);
if (len > 0) {
rx_buffer = new cbuf(len);
rx_buffer->write(buf, len);
}
delete[] buf;
return len;
}
int WiFiUDP::available(){
if(!rx_buffer) return 0;
return rx_buffer->available();
}
int WiFiUDP::read(){
if(!rx_buffer) return -1;
int out = rx_buffer->read();
if(!rx_buffer->available()){
cbuf *b = rx_buffer;
rx_buffer = 0;
delete b;
}
return out;
}
int WiFiUDP::read(unsigned char* buffer, size_t len){
return read((char *)buffer, len);
}
int WiFiUDP::read(char* buffer, size_t len){
if(!rx_buffer) return 0;
int out = rx_buffer->read(buffer, len);
if(!rx_buffer->available()){
cbuf *b = rx_buffer;
rx_buffer = 0;
delete b;
}
return out;
}
int WiFiUDP::peek(){
if(!rx_buffer) return -1;
return rx_buffer->peek();
}
void WiFiUDP::flush(){
if(!rx_buffer) return;
cbuf *b = rx_buffer;
rx_buffer = 0;
delete b;
}
IPAddress WiFiUDP::remoteIP(){
return remote_ip;
}
uint16_t WiFiUDP::remotePort(){
return remote_port;
}

View File

@ -0,0 +1,77 @@
/*
* Udp.cpp: Library to send/receive UDP packets.
*
* NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these)
* 1) UDP does not guarantee the order in which assembled UDP packets are received. This
* might not happen often in practice, but in larger network topologies, a UDP
* packet can be received out of sequence.
* 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being
* aware of it. Again, this may not be a concern in practice on small local networks.
* For more information, see http://www.cafeaulait.org/course/week12/35.html
*
* MIT License:
* Copyright (c) 2008 Bjoern Hartmann
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* bjoern@cs.stanford.edu 12/30/2008
*/
#ifndef _WIFIUDP_H_
#define _WIFIUDP_H_
#include <Arduino.h>
#include <Udp.h>
#include <cbuf.h>
class WiFiUDP : public UDP {
private:
int udp_server;
IPAddress multicast_ip;
IPAddress remote_ip;
uint16_t server_port;
uint16_t remote_port;
char * tx_buffer;
size_t tx_buffer_len;
cbuf * rx_buffer;
public:
WiFiUDP();
~WiFiUDP();
uint8_t begin(IPAddress a, uint16_t p);
uint8_t begin(uint16_t p);
uint8_t beginMulticast(IPAddress a, uint16_t p);
void stop();
int beginMulticastPacket();
int beginPacket();
int beginPacket(IPAddress ip, uint16_t port);
int beginPacket(const char *host, uint16_t port);
int endPacket();
size_t write(uint8_t);
size_t write(const uint8_t *buffer, size_t size);
int parsePacket();
int available();
int read();
int read(unsigned char* buffer, size_t len);
int read(char* buffer, size_t len);
int peek();
void flush();
IPAddress remoteIP();
uint16_t remotePort();
};
#endif /* _WIFIUDP_H_ */