pin versions

This commit is contained in:
2025-08-14 21:21:39 +02:00
parent 1aa90acee4
commit afd867d393
79 changed files with 20 additions and 7833 deletions

5
.gitignore vendored
View File

@@ -74,5 +74,6 @@ dist/
/firmware /firmware
.clang_complete .clang_complete
.gcc-flags.json .gcc-flags.json
.pioenvs .pioenvs
.piolibdeps .piolibdeps
.pio

View File

@@ -1,4 +1,4 @@
image: python:2.7-stretch image: python:3.12.10
stages: stages:
- build - build
@@ -8,7 +8,7 @@ before_script:
examples: examples:
stage: build stage: build
image: python:2.7-stretch image: python:3.12.10
script: script:
- pio run -t clean - pio run --target clean
- pio run - pio run

Submodule lib/a21 deleted from 9db8a9b4b1

View File

@@ -1,57 +0,0 @@
/*
LEDC Software Fade
This example shows how to software fade LED
using the ledcWrite function.
Code adapted from original Arduino Fade example:
https://www.arduino.cc/en/Tutorial/Fade
This example code is in the public domain.
*/
// use first channel of 16 channels (started from zero)
#define LEDC_CHANNEL_0 0
// use 13 bit precission for LEDC timer
#define LEDC_TIMER_13_BIT 13
// use 5000 Hz as a LEDC base frequency
#define LEDC_BASE_FREQ 5000
// fade LED PIN (replace with LED_BUILTIN constant for built-in LED)
#define LED_PIN 5
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// Arduino like analogWrite
// value has to be between 0 and valueMax
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 255) {
// calculate duty
uint32_t duty = (LEDC_BASE_FREQ / valueMax) * min(value, valueMax);
// write duty to LEDC
ledcWrite(channel, duty);
}
void setup() {
// Setup timer and attach timer to a led pin
ledcSetup(LEDC_CHANNEL_0, LEDC_BASE_FREQ, LEDC_TIMER_13_BIT);
ledcAttachPin(LED_PIN, LEDC_CHANNEL_0);
}
void loop() {
// set the brightness on LEDC channel 0
ledcAnalogWrite(LEDC_CHANNEL_0, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

View File

@@ -1,18 +0,0 @@
void setup()
{
//setup channel 0 with frequency 312500 Hz
sigmaDeltaSetup(0, 312500);
//attach pin 18 to channel 0
sigmaDeltaAttachPin(18,0);
//initialize channel 0 to off
sigmaDeltaWrite(0, 0);
}
void loop()
{
//slowly ramp-up the value
//will overflow at 256
static uint8_t i = 0;
sigmaDeltaWrite(0, i++);
delay(100);
}

View File

@@ -1,60 +0,0 @@
/*
Repeat timer example
This example shows how to use hardware timer in ESP32. The timer calls onTimer
function every second. The timer can be stopped with button attached to PIN 0
(IO0).
This example code is in the public domain.
*/
// Stop button is attached to PIN 0 (IO0)
#define BTN_STOP_ALARM 0
hw_timer_t * timer = NULL;
void onTimer(){
static unsigned int counter = 1;
Serial.print("onTimer no. ");
Serial.print(counter);
Serial.print(" at ");
Serial.print(millis());
Serial.println(" ms");
counter++;
}
void setup() {
Serial.begin(115200);
// Set BTN_STOP_ALARM to input mode
pinMode(BTN_STOP_ALARM, INPUT);
// Use 1st timer of 4 (counted from zero).
// Set 80 divider for prescaler (see ESP32 Technical Reference Manual for more
// info).
timer = timerBegin(0, 80, true);
// Attach onTimer function to our timer.
timerAttachInterrupt(timer, &onTimer, true);
// Set alarm to call onTimer function every second (value in microseconds).
// Repeat the alarm (third parameter)
timerAlarmWrite(timer, 1000000, true);
// Start an alarm
timerAlarmEnable(timer);
}
void loop() {
// If button is pressed
if (digitalRead(BTN_STOP_ALARM) == LOW) {
// If timer is still running
if (timer) {
// Stop and free timer
timerEnd(timer);
timer = NULL;
}
}
}

View File

@@ -1,35 +0,0 @@
/*
This is un example howto use Touch Intrrerupts
The bigger the threshold, the more sensible is the touch
*/
int threshold = 40;
bool touch1detected = false;
bool touch2detected = false;
void gotTouch1(){
touch1detected = true;
}
void gotTouch2(){
touch2detected = true;
}
void setup() {
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
Serial.println("ESP32 Touch Interrupt Test");
touchAttachInterrupt(T2, gotTouch1, threshold);
touchAttachInterrupt(T3, gotTouch2, threshold);
}
void loop(){
if(touch1detected){
touch1detected = false;
Serial.println("Touch 1 detected");
}
if(touch2detected){
touch2detected = false;
Serial.println("Touch 2 detected");
}
}

View File

@@ -1,15 +0,0 @@
// ESP32 Touch Test
// Just test touch pin - Touch0 is T0 which is on GPIO 4.
void setup()
{
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
Serial.println("ESP32 Touch Test");
}
void loop()
{
Serial.println(touchRead(T0)); // get value using T0
delay(1000);
}

View File

@@ -1,9 +0,0 @@
name=ESP32
version=1.0
author=Hristo Gochkov, Ivan Grokhtkov
maintainer=Hristo Gochkov <hristo@espressif.com>
sentence=ESP32 sketches examples
paragraph=
category=Other
url=
architectures=esp32

View File

@@ -1,2 +0,0 @@
// This file is here only to silence warnings from Arduino IDE
// Currently IDE doesn't support no-code libraries, like this collection of example sketches.

View File

@@ -1,29 +0,0 @@
language: generic
env:
global:
- IDE_VERSION=1.6.12
matrix:
- BOARD="arduino:avr:uno"
- BOARD="arduino:avr:micro"
- BOARD="arduino:avr:mega:cpu=atmega2560"
- BOARD="arduino:samd:arduino_zero_edbg"
- BOARD="arduino:samd:mkr1000"
before_install:
- /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16
- sleep 3
- export DISPLAY=:1.0
- wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz
- tar xf arduino-$IDE_VERSION-linux64.tar.xz
- mv arduino-$IDE_VERSION $HOME/arduino-ide
- export PATH=$PATH:$HOME/arduino-ide
- if [[ "$BOARD" =~ "arduino:samd:" ]]; then
arduino --install-boards arduino:samd &> /dev/null;
fi
- buildExampleSketch() { arduino --verbose-build --verify --board $BOARD $PWD/examples/$1/$1.ino; }
install:
- mkdir -p $HOME/Arduino/libraries
- ln -s $PWD $HOME/Arduino/libraries/LoRa
script:
- buildExampleSketch LoRaReceiver
- buildExampleSketch LoRaReceiverCallback
- buildExampleSketch LoRaSender

View File

@@ -1,315 +0,0 @@
# LoRa API
## Include Library
```arduino
#include <LoRa.h>
```
## Setup
### Begin
Initialize the library with the specified frequency.
```arduino
LoRa.begin(frequency);
```
* `frequency` - frequency in Hz (`433E6`, `866E6`, `915E6`)
Returns `1` on success, `0` on failure.
### Set pins
Override the default `NSS`, `NRESET`, and `DIO0` pins used by the library. **Must** be called before `LoRa.begin()`.
```arduino
LoRa.setPins(ss, reset, dio0);
```
* `ss` - new slave select pin to use, defaults to `10`
* `reset` - new reset pin to use, defaults to `9`
* `dio0` - new DIO0 pin to use, defaults to `2`
This call is optional and only needs to be used if you need to change the default pins used.
### Set SPI Frequency
Override the default SPI frequency of 10 MHz used by the library. **Must** be called before `LoRa.begin()`.
```arduino
LoRa.setSPIFrequency(frequency);
```
* `frequency` - new SPI frequency to use, defaults to `10E6`
This call is optional and only needs to be used if you need to change the default SPI frequency used. Some logic level converters cannot support high speeds such as 10 MHz, so a lower SPI frequency can be selected with `LoRa.setSPIFrequency(frequency)`.
### End
Stop the library
```arduino
LoRa.end()
```
## Sending data
### Begin packet
Start the sequence of sending a packet.
```arduino
LoRa.beginPacket();
LoRa.beginPacket(implicitHeader);
```
* `implicitHeader` - (optional) `true` enables implicit header mode, `false` enables explicit header mode (default)
Returns `1` on success, `0` on failure.
### Writing
Write data to the packet. Each packet can contain up to 255 bytes.
```arduino
LoRa.write(byte);
LoRa.write(buffer, length);
```
* `byte` - single byte to write to packet
or
* `buffer` - data to write to packet
* `length` - size of data to write
Returns the number of bytes written.
**Note:** Other Arduino `Print` API's can also be used to write data into the packet
### End packet
End the sequence of sending a packet.
```arduino
LoRa.endPacket()
```
Returns `1` on success, `0` on failure.
## Receiving data
### Parsing packet
Check if a packet has been received.
```arduino
int packetSize = LoRa.parsePacket();
int packetSize = LoRa.parsePacket(size);
```
* `size` - (optional) if `> 0` implicit header mode is enabled with the expected a packet of `size` bytes, default mode is explicit header mode
Returns the packet size in bytes or `0` if no packet was received.
### Continuous receive mode
#### Register callback
Register a callback function for when a packet is received.
```arduino
LoRa.onReceive(onReceive);
void onReceive(int packetSize) {
// ...
}
```
* `onReceive` - function to call when a packet is received.
#### Receive mode
Puts the radio in continuous receive mode.
```arduino
LoRa.receive();
LoRa.receive(int size);
```
* `size` - (optional) if `> 0` implicit header mode is enabled with the expected a packet of `size` bytes, default mode is explicit header mode
The `onReceive` callback will be called when a packet is received.
### Packet RSSI
```arduino
int rssi = LoRa.packetRssi();
```
Returns the RSSI of the received packet.
### Packet SNR
```arduino
float snr = LoRa.packetSnr();
```
Returns the estimated SNR of the received packet in dB.
### Available
```arduino
int availableBytes = LoRa.available()
```
Returns number of bytes available for reading.
### Peeking
Peek at the next byte in the packet.
```arduino
byte b = LoRa.peek();
```
Returns the next byte in the packet or `-1` if no bytes are available.
### Reading
Read the next byte from the packet.
```arduino
byte b = LoRa.read();
```
Returns the next byte in the packet or `-1` if no bytes are available.
**Note:** Other Arduino [`Stream` API's](https://www.arduino.cc/en/Reference/Stream) can also be used to read data from the packet
## Other radio modes
### Idle mode
Put the radio in idle (standby) mode.
```arduino
LoRa.idle();
```
### Sleep mode
Put the radio in sleep mode.
```arduino
LoRa.sleep();
```
## Radio parameters
### TX Power
Change the TX power of the radio.
```arduino
LoRa.setTxPower(txPower);
LoRa.setTxPower(txPower, outputPin);
```
* `txPower` - TX power in dB, defaults to `17`
* `outputPin` - (optional) PA output pin, supported values are `PA_OUTPUT_RFO_PIN` and `PA_OUTPUT_PA_BOOST_PIN`, defaults to `PA_OUTPUT_PA_BOOST_PIN`.
Supported values are between `2` and `17` for `PA_OUTPUT_PA_BOOST_PIN`, `0` and `14` for `PA_OUTPUT_RFO_PIN`.
Most modules have the PA output pin connected to PA BOOST,
### Frequency
Change the frequency of the radio.
```arduino
LoRa.setFrequency(frequency);
```
* `frequency` - frequency in Hz (`433E6`, `866E6`, `915E6`)
### Spreading Factor
Change the spreading factor of the radio.
```arduino
LoRa.setSpreadingFactor(spreadingFactor);
```
* `spreadingFactor` - spreading factor, defaults to `7`
Supported values are between `6` and `12`. If a spreading factor of `6` is set, implicit header mode must be used to transmit and receive packets.
### Signal Bandwidth
Change the signal bandwidth of the radio.
```arduino
LoRa.setSignalBandwidth(signalBandwidth);
```
* `signalBandwidth` - signal bandwidth in Hz, defaults to `125E3`.
Supported values are `7.8E3`, `10.4E3`, `15.6E3`, `20.8E3`, `31.25E3`, `41.7E3`, `62.5E3`, `125E3`, and `250E3`.
### Coding Rate
Change the coding rate of the radio.
```arduino
LoRa.setCodingRate4(codingRateDenominator);
```
* `codingRateDenominator` - denominator of the coding rate, defaults to `5`
Supported values are between `5` and `8`, these correspond to coding rates of `4/5` and `4/8`. The coding rate numerator is fixed at `4`.
### Preamble Length
Change the preamble length of the radio.
```arduino
LoRa.setPreambleLength(preambleLength);
```
* `preambleLength` - preamble length in symbols, defaults to `8`
Supported values are between `6` and `65535`.
### Sync Word
Change the sync word of the radio.
```arduino
LoRa.setSyncWord(syncWord);
```
* `syncWord` - byte value to use as the sync word, defaults to `0x34`
### CRC
Enable or disable CRC usage, by default a CRC is not used.
```arduino
LoRa.crc();
LoRa.noCrc();
```
## Other functions
### Random
Generate a random byte, based on the Wideband RSSI measurement.
```
byte b = LoRa.random();
```
Returns random byte.

View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2016 Sandeep Mistry
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.

View File

@@ -1,56 +0,0 @@
# Arduino LoRa
[![Build Status](https://travis-ci.org/sandeepmistry/arduino-LoRa.svg?branch=master)](https://travis-ci.org/sandeepmistry/arduino-LoRa)
An [Arduino](http://arduino.cc/) library for sending and receiving data using [LoRa](https://www.lora-alliance.org/) radios.
## Compatible Hardware
* [Semtech SX1276/77/78/79](http://www.semtech.com/apps/product.php?pn=SX1276) based boards including:
* [Dragino Lora Shield](http://www.dragino.com/products/module/item/102-lora-shield.html)
* [HopeRF](http://www.hoperf.com/rf_transceiver/lora/) [RFM95W](http://www.hoperf.com/rf_transceiver/lora/RFM95W.html), [RFM96W](http://www.hoperf.com/rf_transceiver/lora/RFM96W.html), and [RFM98W](http://www.hoperf.com/rf_transceiver/lora/RFM98W.html)
* [Modtronix](http://modtronix.com/) [inAir4](http://modtronix.com/inair4.html), [inAir9](http://modtronix.com/inair9.html), and [inAir9B](http://modtronix.com/inair9b.html)
### Semtech SX1276/77/78/79 wiring
| Semtech SX1276/77/78/79 | Arduino |
| :---------------------: | :------:|
| VCC | 3.3V |
| GND | GND |
| SCK | SCK |
| MISO | MISO |
| MOSI | MOSI |
| NSS | 10 |
| NRESET | 9 |
| DIO0 | 2 |
`NSS`, `NRESET`, and `DIO0` pins can be changed by using `LoRa.setPins(ss, reset, dio0)`. `DIO0` pin is optional, it is only needed for receive callback mode.
## Installation
### Using the Arduino IDE Library Manager
1. Choose `Sketch` -> `Include Library` -> `Manage Libraries...`
2. Type `LoRa` into the search box.
3. Click the row to select the library.
4. Click the `Install` button to install the library.
### Using Git
```sh
cd ~/Documents/Arduino/libraries/
git clone https://github.com/sandeepmistry/arduino-LoRa LoRa
```
## API
See [API.md](API.md).
## Examples
See [examples](examples) folder.
## License
This libary is [licensed](LICENSE) under the [MIT Licence](http://en.wikipedia.org/wiki/MIT_License).

View File

@@ -1,84 +0,0 @@
#include <SPI.h>
#include <LoRa.h>
#include "SSD1306.h"
SSD1306 display(0x3c, 4, 15);
//OLED pins to ESP32 GPIOs via this connection:
//OLED_SDA -- GPIO4
//OLED_SCL -- GPIO15
//OLED_RST -- GPIO16
// WIFI_LoRa_32 ports
// GPIO5 -- SX1278's SCK
// GPIO19 -- SX1278's MISO
// GPIO27 -- SX1278's MOSI
// GPIO18 -- SX1278's CS
// GPIO14 -- SX1278's RESET
// GPIO26 -- SX1278's IRQ(Interrupt Request)
#define SS 18
#define RST 14
#define DI0 26
#define BAND 433E6
void setup() {
pinMode(16,OUTPUT);
digitalWrite(16, LOW); // set GPIO16 low to reset OLED
delay(50);
digitalWrite(16, HIGH);
display.init();
display.flipScreenVertically();
display.setFont(ArialMT_Plain_10);
display.setTextAlignment(TEXT_ALIGN_LEFT);
Serial.begin(115200);
while (!Serial); //if just the the basic function, must connect to a computer
delay(1000);
Serial.println("LoRa Receiver");
display.drawString(5,5,"LoRa Receiver");
display.display();
SPI.begin(5,19,27,18);
LoRa.setPins(SS,RST,DI0);
if (!LoRa.begin(BAND)) {
display.drawString(5,25,"Starting LoRa failed!");
while (1);
}
Serial.println("LoRa Initial OK!");
display.drawString(5,25,"LoRa Initializing OK!");
display.display();
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// received a packets
Serial.print("Received packet. ");
display.clear();
display.setFont(ArialMT_Plain_16);
display.drawString(3, 0, "Received packet ");
display.display();
// read packet
while (LoRa.available()) {
String data = LoRa.readString();
Serial.print(data);
display.drawString(20,22, data);
display.display();
}
// print RSSI of packet
Serial.print(" with RSSI ");
Serial.println(LoRa.packetRssi());
display.drawString(20, 45, "RSSI: ");
display.drawString(70, 45, (String)LoRa.packetRssi());
display.display();
}
}

View File

@@ -1,54 +0,0 @@
// This example just provide basic LoRa function test;
// Not the LoRa's farthest distance or strongest interference immunity.
// For more informations, please vist www.heltec.cn or mail to support@heltec.cn
#include <SPI.h>
#include <LoRa.h>
// WIFI_LoRa_32 ports
// GPIO5 -- SX1278's SCK
// GPIO19 -- SX1278's MISO
// GPIO27 -- SX1278's MOSI
// GPIO18 -- SX1278's CS
// GPIO14 -- SX1278's RESET
// GPIO26 -- SX1278's IRQ(Interrupt Request)
#define SS 18
#define RST 14
#define DI0 26
#define BAND 433E6
void setup() {
Serial.begin(115200);
while (!Serial); //if just the the basic function, must connect to a computer
delay(1000);
Serial.println("LoRa Receiver");
SPI.begin(5,19,27,18);
LoRa.setPins(SS,RST,DI0);
if (!LoRa.begin(BAND)) {
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// received a packet
Serial.print("Received packet '");
// read packet
while (LoRa.available()) {
Serial.print((char)LoRa.read());
}
// print RSSI of packet
Serial.print("' with RSSI ");
Serial.println(LoRa.packetRssi());
}
}

View File

@@ -1,60 +0,0 @@
// This example just provide basic LoRa function test;
// Not the LoRa's farthest distance or strongest interference immunity.
// For more informations, please vist www.heltec.cn or mail to support@heltec.cn
#include <SPI.h>
#include <LoRa.h>
// WIFI_LoRa_32 ports
// GPIO5 -- SX1278's SCK
// GPIO19 -- SX1278's MISO
// GPIO27 -- SX1278's MOSI
// GPIO18 -- SX1278's CS
// GPIO14 -- SX1278's RESET
// GPIO26 -- SX1278's IRQ(Interrupt Request)
#define SS 18
#define RST 14
#define DI0 26
#define BAND 433E6
void setup() {
Serial.begin(115200);
while (!Serial); //if just the the basic function, must connect to a computer
SPI.begin(5,19,27,18);
LoRa.setPins(SS,RST,DI0);
Serial.println("LoRa Receiver Callback");
if (!LoRa.begin(BAND)) {
Serial.println("Starting LoRa failed!");
while (1);
}
// register the receive callback
LoRa.onReceive(onReceive);
// put the radio into receive mode
LoRa.receive();
}
void loop() {
// do nothing
}
void onReceive(int packetSize) {
// received a packet
Serial.print("Received packet '");
// read packet
for (int i = 0; i < packetSize; i++) {
Serial.print((char)LoRa.read());
}
// print RSSI of packet
Serial.print("' with RSSI ");
Serial.println(LoRa.packetRssi());
}

View File

@@ -1,85 +0,0 @@
#include <SPI.h>
#include <LoRa.h>
#include "SSD1306.h"
#include<Arduino.h>
//OLED pins to ESP32 GPIOs via this connecthin:
//OLED_SDA -- GPIO4
//OLED_SCL -- GPIO15
//OLED_RST -- GPIO16
SSD1306 display(0x3c, 4, 15);
// WIFI_LoRa_32 ports
// GPIO5 -- SX1278's SCK
// GPIO19 -- SX1278's MISO
// GPIO27 -- SX1278's MOSI
// GPIO18 -- SX1278's CS
// GPIO14 -- SX1278's RESET
// GPIO26 -- SX1278's IRQ(Interrupt Request)
#define SS 18
#define RST 14
#define DI0 26
#define BAND 433E6 //915E6
int counter = 0;
void setup() {
pinMode(25,OUTPUT); //Send success, LED will bright 1 second
pinMode(16,OUTPUT);
digitalWrite(16, LOW); // set GPIO16 low to reset OLED
delay(50);
digitalWrite(16, HIGH);
Serial.begin(115200);
while (!Serial); //If just the the basic function, must connect to a computer
// Initialising the UI will init the display too.
display.init();
display.flipScreenVertically();
display.setFont(ArialMT_Plain_10);
display.setTextAlignment(TEXT_ALIGN_LEFT);
display.drawString(5,5,"LoRa Sender");
display.display();
SPI.begin(5,19,27,18);
LoRa.setPins(SS,RST,DI0);
Serial.println("LoRa Sender");
if (!LoRa.begin(BAND)) {
Serial.println("Starting LoRa failed!");
while (1);
}
Serial.println("LoRa Initial OK!");
display.drawString(5,20,"LoRa Initializing OK!");
display.display();
delay(2000);
}
void loop() {
Serial.print("Sending packet: ");
Serial.println(counter);
display.clear();
display.setFont(ArialMT_Plain_16);
display.drawString(3, 5, "Sending packet ");
display.drawString(50, 30, String(counter));
display.display();
// send packet
LoRa.beginPacket();
LoRa.print("Hello..");
LoRa.print(counter);
LoRa.endPacket();
counter++;
digitalWrite(25, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(25, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
delay(3000);
}

View File

@@ -1,59 +0,0 @@
// This example just provide basic LoRa function test;
// Not the LoRa's farthest distance or strongest interference immunity.
// For more informations, please vist www.heltec.cn or mail to support@heltec.cn
#include <SPI.h>
#include <LoRa.h>
#include<Arduino.h>
// WIFI_LoRa_32 ports
// GPIO5 -- SX1278's SCK
// GPIO19 -- SX1278's MISO
// GPIO27 -- SX1278's MOSI
// GPIO18 -- SX1278's CS
// GPIO14 -- SX1278's RESET
// GPIO26 -- SX1278's IRQ(Interrupt Request)
#define SS 18
#define RST 14
#define DI0 26
#define BAND 433E6 //915E6 -- 这里的模式选择中检查一下是否可在中国实用915这个频段
int counter = 0;
void setup() {
pinMode(25,OUTPUT); //Send success, LED will bright 1 second
Serial.begin(115200);
while (!Serial); //If just the the basic function, must connect to a computer
SPI.begin(5,19,27,18);
LoRa.setPins(SS,RST,DI0);
// Serial.println("LoRa Sender");
if (!LoRa.begin(BAND)) {
Serial.println("Starting LoRa failed!");
while (1);
}
Serial.println("LoRa Initial OK!");
}
void loop() {
Serial.print("Sending packet: ");
Serial.println(counter);
// send packet
LoRa.beginPacket();
LoRa.print("hello ");
LoRa.print(counter);
LoRa.endPacket();
counter++;
digitalWrite(25, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(25, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
delay(3000);
}

View File

@@ -1,57 +0,0 @@
#######################################
# Syntax Coloring Map For LoRa
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
LoRa KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
beginPacket KEYWORD2
endPacket KEYWORD2
parsePacket KEYWORD2
packetRssi KEYWORD2
packetSnr KEYWORD2
write KEYWORD2
available KEYWORD2
read KEYWORD2
peek KEYWORD2
flush KEYWORD2
onReceive KEYWORD2
receive KEYWORD2
idle KEYWORD2
sleep KEYWORD2
setTxPower KEYWORD2
setFrequency KEYWORD2
setSpreadingFactor KEYWORD2
setSignalBandwidth KEYWORD2
setCodingRate4 KEYWORD2
setPreambleLength KEYWORD2
setSyncWord KEYWORD2
crc KEYWORD2
noCrc KEYWORD2
random KEYWORD2
setPins KEYWORD2
setSPIFrequency KEYWORD2
dumpRegisters KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
PA_OUTPUT_RFO_PIN LITERAL1
PA_OUTPUT_PA_BOOST_PIN LITERAL1

View File

@@ -1,10 +0,0 @@
name=LoRa function basic test
version=0.0.2
author=Aaron.Lee <support@heltec.cn>
maintainer=Aaron.Lee <support@heltec.cn>
sentence=An Arduino library for sending and receiving data using LoRa radios.
paragraph=Supports Semtech SX1276/77/78/79 based boards/shields.
category=Communication
url=https://heltec.cn
architectures=*
includes=LoRa.h

View File

@@ -1,518 +0,0 @@
#include <LoRa.h>
// registers
#define REG_FIFO 0x00
#define REG_OP_MODE 0x01
#define REG_FRF_MSB 0x06
#define REG_FRF_MID 0x07
#define REG_FRF_LSB 0x08
#define REG_PA_CONFIG 0x09
#define REG_LNA 0x0c
#define REG_FIFO_ADDR_PTR 0x0d
#define REG_FIFO_TX_BASE_ADDR 0x0e
#define REG_FIFO_RX_BASE_ADDR 0x0f
#define REG_FIFO_RX_CURRENT_ADDR 0x10
#define REG_IRQ_FLAGS 0x12
#define REG_RX_NB_BYTES 0x13
#define REG_PKT_RSSI_VALUE 0x1a
#define REG_PKT_SNR_VALUE 0x1b
#define REG_MODEM_CONFIG_1 0x1d
#define REG_MODEM_CONFIG_2 0x1e
#define REG_PREAMBLE_MSB 0x20
#define REG_PREAMBLE_LSB 0x21
#define REG_PAYLOAD_LENGTH 0x22
#define REG_MODEM_CONFIG_3 0x26
#define REG_RSSI_WIDEBAND 0x2c
#define REG_DETECTION_OPTIMIZE 0x31
#define REG_DETECTION_THRESHOLD 0x37
#define REG_SYNC_WORD 0x39
#define REG_DIO_MAPPING_1 0x40
#define REG_VERSION 0x42
// modes
#define MODE_LONG_RANGE_MODE 0x80
#define MODE_SLEEP 0x00
#define MODE_STDBY 0x01
#define MODE_TX 0x03
#define MODE_RX_CONTINUOUS 0x05
#define MODE_RX_SINGLE 0x06
// PA config
#define PA_BOOST 0x80
// IRQ masks
#define IRQ_TX_DONE_MASK 0x08
#define IRQ_PAYLOAD_CRC_ERROR_MASK 0x20
#define IRQ_RX_DONE_MASK 0x40
#define MAX_PKT_LENGTH 255
LoRaClass::LoRaClass() :
_spiSettings(10E6, MSBFIRST, SPI_MODE0),
_ss(LORA_DEFAULT_SS_PIN), _reset(LORA_DEFAULT_RESET_PIN), _dio0(LORA_DEFAULT_DIO0_PIN),
_frequency(0),
_packetIndex(0),
_implicitHeaderMode(0),
_onReceive(NULL)
{
}
int LoRaClass::begin(long frequency)
{
// setup pins
pinMode(_ss, OUTPUT);
pinMode(_reset, OUTPUT);
// perform reset
digitalWrite(_reset, LOW);
delay(20);
digitalWrite(_reset, HIGH);
delay(50);
// set SS high
digitalWrite(_ss, HIGH);
// start SPI
SPI.begin();
// check version
uint8_t version = readRegister(REG_VERSION);
if (version != 0x12) {
//return 0;
}
// put in sleep mode
sleep();
// set frequency
setFrequency(frequency);
// set base addresses
writeRegister(REG_FIFO_TX_BASE_ADDR, 0);
writeRegister(REG_FIFO_RX_BASE_ADDR, 0);
// set LNA boost
writeRegister(REG_LNA, readRegister(REG_LNA) | 0x03);
// set auto AGC
writeRegister(REG_MODEM_CONFIG_3, 0x04);
// set output power to 17 dBm
setTxPower(17);
// put in standby mode
idle();
return 1;
}
void LoRaClass::end()
{
// put in sleep mode
sleep();
// stop SPI
SPI.end();
}
int LoRaClass::beginPacket(int implicitHeader)
{
// put in standby mode
idle();
if (implicitHeader) {
implicitHeaderMode();
} else {
explicitHeaderMode();
}
// reset FIFO address and paload length
writeRegister(REG_FIFO_ADDR_PTR, 0);
writeRegister(REG_PAYLOAD_LENGTH, 0);
return 1;
}
int LoRaClass::endPacket()
{
// put in TX mode
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_TX);
// wait for TX done
while((readRegister(REG_IRQ_FLAGS) & IRQ_TX_DONE_MASK) == 0);
// clear IRQ's
writeRegister(REG_IRQ_FLAGS, IRQ_TX_DONE_MASK);
return 1;
}
int LoRaClass::parsePacket(int size)
{
int packetLength = 0;
int irqFlags = readRegister(REG_IRQ_FLAGS);
if (size > 0) {
implicitHeaderMode();
writeRegister(REG_PAYLOAD_LENGTH, size & 0xff);
} else {
explicitHeaderMode();
}
// clear IRQ's
writeRegister(REG_IRQ_FLAGS, irqFlags);
if ((irqFlags & IRQ_RX_DONE_MASK) && (irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) {
// received a packet
_packetIndex = 0;
// read packet length
if (_implicitHeaderMode) {
packetLength = readRegister(REG_PAYLOAD_LENGTH);
} else {
packetLength = readRegister(REG_RX_NB_BYTES);
}
// set FIFO address to current RX address
writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR));
// put in standby mode
idle();
} else if (readRegister(REG_OP_MODE) != (MODE_LONG_RANGE_MODE | MODE_RX_SINGLE)) {
// not currently in RX mode
// reset FIFO address
writeRegister(REG_FIFO_ADDR_PTR, 0);
// put in single RX mode
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_SINGLE);
}
return packetLength;
}
int LoRaClass::packetRssi()
{
return (readRegister(REG_PKT_RSSI_VALUE) - (_frequency < 868E6 ? 164 : 157));
}
float LoRaClass::packetSnr()
{
return ((int8_t)readRegister(REG_PKT_SNR_VALUE)) * 0.25;
}
size_t LoRaClass::write(uint8_t byte)
{
return write(&byte, sizeof(byte));
}
size_t LoRaClass::write(const uint8_t *buffer, size_t size)
{
int currentLength = readRegister(REG_PAYLOAD_LENGTH);
// check size
if ((currentLength + size) > MAX_PKT_LENGTH) {
size = MAX_PKT_LENGTH - currentLength;
}
// write data
for (size_t i = 0; i < size; i++) {
writeRegister(REG_FIFO, buffer[i]);
}
// update length
writeRegister(REG_PAYLOAD_LENGTH, currentLength + size);
return size;
}
int LoRaClass::available()
{
return (readRegister(REG_RX_NB_BYTES) - _packetIndex);
}
int LoRaClass::read()
{
if (!available()) {
return -1;
}
_packetIndex++;
return readRegister(REG_FIFO);
}
int LoRaClass::peek()
{
if (!available()) {
return -1;
}
// store current FIFO address
int currentAddress = readRegister(REG_FIFO_ADDR_PTR);
// read
uint8_t b = readRegister(REG_FIFO);
// restore FIFO address
writeRegister(REG_FIFO_ADDR_PTR, currentAddress);
return b;
}
void LoRaClass::flush()
{
}
void LoRaClass::onReceive(void(*callback)(int))
{
_onReceive = callback;
if (callback) {
writeRegister(REG_DIO_MAPPING_1, 0x00);
attachInterrupt(digitalPinToInterrupt(_dio0), LoRaClass::onDio0Rise, RISING);
} else {
detachInterrupt(digitalPinToInterrupt(_dio0));
}
}
void LoRaClass::receive(int size)
{
if (size > 0) {
implicitHeaderMode();
writeRegister(REG_PAYLOAD_LENGTH, size & 0xff);
} else {
explicitHeaderMode();
}
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_CONTINUOUS);
}
void LoRaClass::idle()
{
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_STDBY);
}
void LoRaClass::sleep()
{
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_SLEEP);
}
void LoRaClass::setTxPower(int level, int outputPin)
{
if (PA_OUTPUT_RFO_PIN == outputPin) {
// RFO
if (level < 0) {
level = 0;
} else if (level > 14) {
level = 14;
}
writeRegister(REG_PA_CONFIG, 0x70 | level);
} else {
// PA BOOST
if (level < 2) {
level = 2;
} else if (level > 17) {
level = 17;
}
writeRegister(REG_PA_CONFIG, PA_BOOST | (level - 2));
}
}
void LoRaClass::setFrequency(long frequency)
{
_frequency = frequency;
uint64_t frf = ((uint64_t)frequency << 19) / 32000000;
writeRegister(REG_FRF_MSB, (uint8_t)(frf >> 16));
writeRegister(REG_FRF_MID, (uint8_t)(frf >> 8));
writeRegister(REG_FRF_LSB, (uint8_t)(frf >> 0));
}
void LoRaClass::setSpreadingFactor(int sf)
{
if (sf < 6) {
sf = 6;
} else if (sf > 12) {
sf = 12;
}
if (sf == 6) {
writeRegister(REG_DETECTION_OPTIMIZE, 0xc5);
writeRegister(REG_DETECTION_THRESHOLD, 0x0c);
} else {
writeRegister(REG_DETECTION_OPTIMIZE, 0xc3);
writeRegister(REG_DETECTION_THRESHOLD, 0x0a);
}
writeRegister(REG_MODEM_CONFIG_2, (readRegister(REG_MODEM_CONFIG_2) & 0x0f) | ((sf << 4) & 0xf0));
}
void LoRaClass::setSignalBandwidth(long sbw)
{
int bw;
if (sbw <= 7.8E3) {
bw = 0;
} else if (sbw <= 10.4E3) {
bw = 1;
} else if (sbw <= 15.6E3) {
bw = 2;
} else if (sbw <= 20.8E3) {
bw = 3;
} else if (sbw <= 31.25E3) {
bw = 4;
} else if (sbw <= 41.7E3) {
bw = 5;
} else if (sbw <= 62.5E3) {
bw = 6;
} else if (sbw <= 125E3) {
bw = 7;
} else if (sbw <= 250E3) {
bw = 8;
} else /*if (sbw <= 250E3)*/ {
bw = 9;
}
writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0x0f) | (bw << 4));
}
void LoRaClass::setCodingRate4(int denominator)
{
if (denominator < 5) {
denominator = 5;
} else if (denominator > 8) {
denominator = 8;
}
int cr = denominator - 4;
writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0xf1) | (cr << 1));
}
void LoRaClass::setPreambleLength(long length)
{
writeRegister(REG_PREAMBLE_MSB, (uint8_t)(length >> 8));
writeRegister(REG_PREAMBLE_LSB, (uint8_t)(length >> 0));
}
void LoRaClass::setSyncWord(int sw)
{
writeRegister(REG_SYNC_WORD, sw);
}
void LoRaClass::crc()
{
writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) | 0x04);
}
void LoRaClass::noCrc()
{
writeRegister(REG_MODEM_CONFIG_2, readRegister(REG_MODEM_CONFIG_2) & 0xfb);
}
byte LoRaClass::random()
{
return readRegister(REG_RSSI_WIDEBAND);
}
void LoRaClass::setPins(int ss, int reset, int dio0)
{
_ss = ss;
_reset = reset;
_dio0 = dio0;
}
void LoRaClass::setSPIFrequency(uint32_t frequency)
{
_spiSettings = SPISettings(frequency, MSBFIRST, SPI_MODE0);
}
void LoRaClass::dumpRegisters(Stream& out)
{
for (int i = 0; i < 128; i++) {
out.print("0x");
out.print(i, HEX);
out.print(": 0x");
out.println(readRegister(i), HEX);
}
}
void LoRaClass::explicitHeaderMode()
{
_implicitHeaderMode = 0;
writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) & 0xfe);
}
void LoRaClass::implicitHeaderMode()
{
_implicitHeaderMode = 1;
writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) | 0x01);
}
void LoRaClass::handleDio0Rise()
{
int irqFlags = readRegister(REG_IRQ_FLAGS);
// clear IRQ's
writeRegister(REG_IRQ_FLAGS, irqFlags);
if ((irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) {
// received a packet
_packetIndex = 0;
// read packet length
int packetLength = _implicitHeaderMode ? readRegister(REG_PAYLOAD_LENGTH) : readRegister(REG_RX_NB_BYTES);
// set FIFO address to current RX address
writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR));
if (_onReceive) {
_onReceive(packetLength);
}
// reset FIFO address
writeRegister(REG_FIFO_ADDR_PTR, 0);
}
}
uint8_t LoRaClass::readRegister(uint8_t address)
{
return singleTransfer(address & 0x7f, 0x00);
}
void LoRaClass::writeRegister(uint8_t address, uint8_t value)
{
singleTransfer(address | 0x80, value);
}
uint8_t LoRaClass::singleTransfer(uint8_t address, uint8_t value)
{
uint8_t response;
digitalWrite(_ss, LOW);
SPI.beginTransaction(_spiSettings);
SPI.transfer(address);
response = SPI.transfer(value);
SPI.endTransaction();
digitalWrite(_ss, HIGH);
return response;
}
void LoRaClass::onDio0Rise()
{
LoRa.handleDio0Rise();
}
LoRaClass LoRa;

View File

@@ -1,86 +0,0 @@
#ifndef LORA_H
#define LORA_H
#include <Arduino.h>
#include <SPI.h>
#define LORA_DEFAULT_SS_PIN 18
#define LORA_DEFAULT_RESET_PIN 14
#define LORA_DEFAULT_DIO0_PIN 26
#define PA_OUTPUT_RFO_PIN 0
#define PA_OUTPUT_PA_BOOST_PIN 1
class LoRaClass : public Stream {
public:
LoRaClass();
int begin(long frequency);
void end();
int beginPacket(int implicitHeader = false);
int endPacket();
int parsePacket(int size = 0);
int packetRssi();
float packetSnr();
// from Print
virtual size_t write(uint8_t byte);
virtual size_t write(const uint8_t *buffer, size_t size);
// from Stream
virtual int available();
virtual int read();
virtual int peek();
virtual void flush();
void onReceive(void(*callback)(int));
void receive(int size = 0);
void idle();
void sleep();
void setTxPower(int level, int outputPin = PA_OUTPUT_PA_BOOST_PIN);
void setFrequency(long frequency);
void setSpreadingFactor(int sf);
void setSignalBandwidth(long sbw);
void setCodingRate4(int denominator);
void setPreambleLength(long length);
void setSyncWord(int sw);
void crc();
void noCrc();
byte random();
void setPins(int ss = LORA_DEFAULT_SS_PIN, int reset = LORA_DEFAULT_RESET_PIN, int dio0 = LORA_DEFAULT_DIO0_PIN);
void setSPIFrequency(uint32_t frequency);
void dumpRegisters(Stream& out);
//private:
void explicitHeaderMode();
void implicitHeaderMode();
void handleDio0Rise();
uint8_t readRegister(uint8_t address);
void writeRegister(uint8_t address, uint8_t value);
uint8_t singleTransfer(uint8_t address, uint8_t value);
static void onDio0Rise();
private:
SPISettings _spiSettings;
int _ss;
int _reset;
int _dio0;
int _frequency;
int _packetIndex;
int _implicitHeaderMode;
void (*_onReceive)(int);
};
extern LoRaClass LoRa;
#endif

View File

@@ -1,56 +0,0 @@
/*
ESP32 start counter example with Preferences library
This simple example demonstrate using Preferences library to store how many times
was ESP32 module started. Preferences library is wrapper around Non-volatile
storage on ESP32 processor.
created for arduino-esp32 09 Feb 2017
by Martin Sloup (Arcao)
*/
#include <Preferences.h>
Preferences preferences;
void setup() {
Serial.begin(115200);
Serial.println();
// Open Preferences with my-app namespace. Each application module, library, etc.
// has to use namespace name to prevent key name collisions. We will open storage in
// RW-mode (second parameter has to be false).
// Note: Namespace name is limited to 15 chars
preferences.begin("my-app", false);
// Remove all preferences under opened namespace
//preferences.clear();
// Or remove the counter key only
//preferences.remove("counter");
// Get a counter value, if key is not exist return default value 0
// Note: Key name is limited to 15 chars too
unsigned int counter = preferences.getUInt("counter", 0);
// Increase counter
counter++;
// Print counter to a Serial
Serial.printf("Current counter value: %u\n", counter);
// Store counter to the Preferences
preferences.putUInt("counter", counter);
// Close the Preferences
preferences.end();
// Wait 10 seconds
Serial.println("Restarting in 10 seconds...");
delay(10000);
// Restart ESP
ESP.restart();
}
void loop() {}

View File

@@ -1,54 +0,0 @@
#######################################
# Syntax Coloring Map NVS
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
Preferences KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
clear KEYWORD2
delete KEYWORD2
putChar KEYWORD2
putUChar KEYWORD2
putShort KEYWORD2
putUShort KEYWORD2
putInt KEYWORD2
putUInt KEYWORD2
putLong KEYWORD2
putULong KEYWORD2
putLong64 KEYWORD2
putULong64 KEYWORD2
putFloat KEYWORD2
putDouble KEYWORD2
putBool KEYWORD2
putString KEYWORD2
putBytes KEYWORD2
getChar KEYWORD2
getUChar KEYWORD2
getShort KEYWORD2
getUShort KEYWORD2
getInt KEYWORD2
getUInt KEYWORD2
getLong KEYWORD2
getULong KEYWORD2
getLong64 KEYWORD2
getULong64 KEYWORD2
getFloat KEYWORD2
getDouble KEYWORD2
getBool KEYWORD2
getString KEYWORD2
getBytes KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@@ -1,9 +0,0 @@
name=Preferences
version=1.0
author=Hristo Gochkov
maintainer=Hristo Gochkov <hristo@espressif.com>
sentence=Provides friendly access to ESP32's Non-Volatile Storage
paragraph=
category=Data Storage
url=
architectures=esp32

View File

@@ -1,470 +0,0 @@
// 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.
#include "Preferences.h"
#include "nvs.h"
const char * nvs_errors[] = { "OTHER", "NOT_INITIALIZED", "NOT_FOUND", "TYPE_MISMATCH", "READ_ONLY", "NOT_ENOUGH_SPACE", "INVALID_NAME", "INVALID_HANDLE", "REMOVE_FAILED", "KEY_TOO_LONG", "PAGE_FULL", "INVALID_STATE", "INVALID_LENGHT"};
#define nvs_error(e) (((e)>ESP_ERR_NVS_BASE)?nvs_errors[(e)&~(ESP_ERR_NVS_BASE)]:nvs_errors[0])
Preferences::Preferences()
:_handle(0)
,_started(false)
,_readOnly(false)
{}
Preferences::~Preferences(){
end();
}
bool Preferences::begin(const char * name, bool readOnly){
if(_started){
return false;
}
_readOnly = readOnly;
esp_err_t err = nvs_open(name, readOnly?NVS_READONLY:NVS_READWRITE, &_handle);
if(err){
log_e("nvs_open failed: %s", nvs_error(err));
return false;
}
_started = true;
return true;
}
void Preferences::end(){
if(!_started){
return;
}
nvs_close(_handle);
_started = false;
}
/*
* Clear all keys in opened preferences
* */
bool Preferences::clear(){
if(!_started || _readOnly){
return false;
}
esp_err_t err = nvs_erase_all(_handle);
if(err){
log_e("nvs_erase_all fail: %s", nvs_error(err));
return false;
}
return true;
}
/*
* Remove a key
* */
bool Preferences::remove(const char * key){
if(!_started || !key || _readOnly){
return false;
}
esp_err_t err = nvs_erase_key(_handle, key);
if(err){
log_e("nvs_erase_key fail: %s %s", key, nvs_error(err));
return false;
}
return true;
}
/*
* Put a key value
* */
size_t Preferences::putChar(const char* key, int8_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i8(_handle, key, value);
if(err){
log_e("nvs_set_i8 fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return 1;
}
size_t Preferences::putUChar(const char* key, uint8_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u8(_handle, key, value);
if(err){
log_e("nvs_set_u8 fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return 1;
}
size_t Preferences::putShort(const char* key, int16_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i16(_handle, key, value);
if(err){
log_e("nvs_set_i16 fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return 2;
}
size_t Preferences::putUShort(const char* key, uint16_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u16(_handle, key, value);
if(err){
log_e("nvs_set_u16 fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return 2;
}
size_t Preferences::putInt(const char* key, int32_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i32(_handle, key, value);
if(err){
log_e("nvs_set_i32 fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return 4;
}
size_t Preferences::putUInt(const char* key, uint32_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u32(_handle, key, value);
if(err){
log_e("nvs_set_u32 fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return 4;
}
size_t Preferences::putLong(const char* key, int32_t value){
return putInt(key, value);
}
size_t Preferences::putULong(const char* key, uint32_t value){
return putUInt(key, value);
}
size_t Preferences::putLong64(const char* key, int64_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i64(_handle, key, value);
if(err){
log_e("nvs_set_i64 fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return 8;
}
size_t Preferences::putULong64(const char* key, uint64_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u64(_handle, key, value);
if(err){
log_e("nvs_set_u64 fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return 8;
}
size_t Preferences::putFloat(const char* key, const float_t value){
return putBytes(key, (void*)&value, sizeof(float_t));
}
size_t Preferences::putDouble(const char* key, const double_t value){
return putBytes(key, (void*)&value, sizeof(double_t));
}
size_t Preferences::putBool(const char* key, const bool value){
return putUChar(key, (uint8_t) (value ? 1 : 0));
}
size_t Preferences::putString(const char* key, const char* value){
if(!_started || !key || !value || _readOnly){
return 0;
}
esp_err_t err = nvs_set_str(_handle, key, value);
if(err){
log_e("nvs_set_str fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return strlen(value);
}
size_t Preferences::putString(const char* key, const String value){
return putString(key, value.c_str());
}
size_t Preferences::putBytes(const char* key, const void* value, size_t len){
if(!_started || !key || !value || !len || _readOnly){
return 0;
}
esp_err_t err = nvs_set_blob(_handle, key, value, len);
if(err){
log_e("nvs_set_blob fail: %s %s", key, nvs_error(err));
return 0;
}
err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s %s", key, nvs_error(err));
return 0;
}
return len;
}
/*
* Get a key value
* */
int8_t Preferences::getChar(const char* key, const int8_t defaultValue){
int8_t value = defaultValue;
if(!_started || !key){
return value;
}
esp_err_t err = nvs_get_i8(_handle, key, &value);
if(err){
log_e("nvs_get_i8 fail: %s %s", key, nvs_error(err));
}
return value;
}
uint8_t Preferences::getUChar(const char* key, const uint8_t defaultValue){
uint8_t value = defaultValue;
if(!_started || !key){
return value;
}
esp_err_t err = nvs_get_u8(_handle, key, &value);
if(err){
log_e("nvs_get_u8 fail: %s %s", key, nvs_error(err));
}
return value;
}
int16_t Preferences::getShort(const char* key, const int16_t defaultValue){
int16_t value = defaultValue;
if(!_started || !key){
return value;
}
esp_err_t err = nvs_get_i16(_handle, key, &value);
if(err){
log_e("nvs_get_i16 fail: %s %s", key, nvs_error(err));
}
return value;
}
uint16_t Preferences::getUShort(const char* key, const uint16_t defaultValue){
uint16_t value = defaultValue;
if(!_started || !key){
return value;
}
esp_err_t err = nvs_get_u16(_handle, key, &value);
if(err){
log_e("nvs_get_u16 fail: %s %s", key, nvs_error(err));
}
return value;
}
int32_t Preferences::getInt(const char* key, const int32_t defaultValue){
int32_t value = defaultValue;
if(!_started || !key){
return value;
}
esp_err_t err = nvs_get_i32(_handle, key, &value);
if(err){
log_e("nvs_get_i32 fail: %s %s", key, nvs_error(err));
}
return value;
}
uint32_t Preferences::getUInt(const char* key, const uint32_t defaultValue){
uint32_t value = defaultValue;
if(!_started || !key){
return value;
}
esp_err_t err = nvs_get_u32(_handle, key, &value);
if(err){
log_e("nvs_get_u32 fail: %s %s", key, nvs_error(err));
}
return value;
}
int32_t Preferences::getLong(const char* key, const int32_t defaultValue){
return getInt(key, defaultValue);
}
uint32_t Preferences::getULong(const char* key, const uint32_t defaultValue){
return getUInt(key, defaultValue);
}
int64_t Preferences::getLong64(const char* key, const int64_t defaultValue){
int64_t value = defaultValue;
if(!_started || !key){
return value;
}
esp_err_t err = nvs_get_i64(_handle, key, &value);
if(err){
log_e("nvs_get_i64 fail: %s %s", key, nvs_error(err));
}
return value;
}
uint64_t Preferences::getULong64(const char* key, const uint64_t defaultValue){
uint64_t value = defaultValue;
if(!_started || !key){
return value;
}
esp_err_t err = nvs_get_u64(_handle, key, &value);
if(err){
log_e("nvs_get_u64 fail: %s %s", key, nvs_error(err));
}
return value;
}
float_t Preferences::getFloat(const char* key, const float_t defaultValue) {
float_t value = defaultValue;
getBytes(key, (void*) &value, sizeof(float_t));
return value;
}
double_t Preferences::getDouble(const char* key, const double_t defaultValue) {
double_t value = defaultValue;
getBytes(key, (void*) &value, sizeof(double_t));
return value;
}
bool Preferences::getBool(const char* key, const bool defaultValue) {
return getUChar(key, defaultValue ? 1 : 0) == 1;
}
size_t Preferences::getString(const char* key, char* value, const size_t maxLen){
size_t len = 0;
if(!_started || !key || !value || !maxLen){
return 0;
}
esp_err_t err = nvs_get_str(_handle, key, NULL, &len);
if(err){
log_e("nvs_get_str len fail: %s %s", key, nvs_error(err));
return 0;
}
if(len > maxLen){
log_e("not enough space in value: %u < %u", maxLen, len);
return 0;
}
err = nvs_get_str(_handle, key, value, &len);
if(err){
log_e("nvs_get_str fail: %s %s", key, nvs_error(err));
return 0;
}
return len;
}
String Preferences::getString(const char* key, const String defaultValue){
char * value = NULL;
size_t len = 0;
if(!_started || !key){
return String(defaultValue);
}
esp_err_t err = nvs_get_str(_handle, key, value, &len);
if(err){
log_e("nvs_get_str len fail: %s %s", key, nvs_error(err));
return String(defaultValue);
}
char buf[len];
value = buf;
err = nvs_get_str(_handle, key, value, &len);
if(err){
log_e("nvs_get_str fail: %s %s", key, nvs_error(err));
return String(defaultValue);
}
return String(buf);
}
size_t Preferences::getBytes(const char* key, void * buf, size_t maxLen){
size_t len = 0;
if(!_started || !key || !buf || !maxLen){
return 0;
}
esp_err_t err = nvs_get_blob(_handle, key, NULL, &len);
if(err){
log_e("nvs_get_blob len fail: %s %s", key, nvs_error(err));
return 0;
}
if(len > maxLen){
log_e("not enough space in buffer: %u < %u", maxLen, len);
return 0;
}
err = nvs_get_blob(_handle, key, buf, &len);
if(err){
log_e("nvs_get_blob fail: %s %s", key, nvs_error(err));
return 0;
}
return len;
}

View File

@@ -1,69 +0,0 @@
// 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.
#ifndef _PREFERENCES_H_
#define _PREFERENCES_H_
#include "Arduino.h"
class Preferences {
protected:
uint32_t _handle;
bool _started;
bool _readOnly;
public:
Preferences();
~Preferences();
bool begin(const char * name, bool readOnly=false);
void end();
bool clear();
bool remove(const char * key);
size_t putChar(const char* key, int8_t value);
size_t putUChar(const char* key, uint8_t value);
size_t putShort(const char* key, int16_t value);
size_t putUShort(const char* key, uint16_t value);
size_t putInt(const char* key, int32_t value);
size_t putUInt(const char* key, uint32_t value);
size_t putLong(const char* key, int32_t value);
size_t putULong(const char* key, uint32_t value);
size_t putLong64(const char* key, int64_t value);
size_t putULong64(const char* key, uint64_t value);
size_t putFloat(const char* key, float_t value);
size_t putDouble(const char* key, double_t value);
size_t putBool(const char* key, bool value);
size_t putString(const char* key, const char* value);
size_t putString(const char* key, String value);
size_t putBytes(const char* key, const void* value, size_t len);
int8_t getChar(const char* key, int8_t defaultValue = 0);
uint8_t getUChar(const char* key, uint8_t defaultValue = 0);
int16_t getShort(const char* key, int16_t defaultValue = 0);
uint16_t getUShort(const char* key, uint16_t defaultValue = 0);
int32_t getInt(const char* key, int32_t defaultValue = 0);
uint32_t getUInt(const char* key, uint32_t defaultValue = 0);
int32_t getLong(const char* key, int32_t defaultValue = 0);
uint32_t getULong(const char* key, uint32_t defaultValue = 0);
int64_t getLong64(const char* key, int64_t defaultValue = 0);
uint64_t getULong64(const char* key, uint64_t defaultValue = 0);
float_t getFloat(const char* key, float_t defaultValue = NAN);
double_t getDouble(const char* key, double_t defaultValue = NAN);
bool getBool(const char* key, bool defaultValue = false);
size_t getString(const char* key, char* value, size_t maxLen);
String getString(const char* key, String defaultValue = String());
size_t getBytes(const char* key, void * buf, size_t maxLen);
};
#endif

View File

@@ -1,36 +0,0 @@
#######################################
# Syntax Coloring Map SPI
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
SPI KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
transfer KEYWORD2
setBitOrder KEYWORD2
setDataMode KEYWORD2
setClockDivider KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
SPI_CLOCK_DIV4 LITERAL1
SPI_CLOCK_DIV16 LITERAL1
SPI_CLOCK_DIV64 LITERAL1
SPI_CLOCK_DIV128 LITERAL1
SPI_CLOCK_DIV2 LITERAL1
SPI_CLOCK_DIV8 LITERAL1
SPI_CLOCK_DIV32 LITERAL1
SPI_CLOCK_DIV64 LITERAL1
SPI_MODE0 LITERAL1
SPI_MODE1 LITERAL1
SPI_MODE2 LITERAL1
SPI_MODE3 LITERAL1

View File

@@ -1,9 +0,0 @@
name=SPI
version=1.0
author=Hristo Gochkov
maintainer=Hristo Gochkov <hristo@espressif.com>
sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus. For all Arduino boards, BUT Arduino DUE.
paragraph=
category=Signal Input/Output
url=http://arduino.cc/en/Reference/SPI
architectures=esp32

View File

@@ -1,277 +0,0 @@
/*
SPI.cpp - SPI library for esp8266
Copyright (c) 2015 Hristo Gochkov. 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 "SPI.h"
SPIClass::SPIClass(uint8_t spi_bus)
:_spi_num(spi_bus)
,_spi(NULL)
,_use_hw_ss(false)
,_sck(-1)
,_miso(-1)
,_mosi(-1)
,_ss(-1)
,_div(0)
,_freq(1000000)
, _inTransaction(false)
{}
void SPIClass::begin(int8_t sck, int8_t miso, int8_t mosi, int8_t ss)
{
if(_spi) {
return;
}
if(!_div) {
_div = spiFrequencyToClockDiv(_freq);
}
_spi = spiStartBus(_spi_num, _div, SPI_MODE0, SPI_MSBFIRST);
if(!_spi) {
return;
}
_sck = sck;
_miso = miso;
_mosi = mosi;
_ss = ss;
spiAttachSCK(_spi, _sck);
spiAttachMISO(_spi, _miso);
spiAttachMOSI(_spi, _mosi);
}
void SPIClass::end()
{
if(!_spi) {
return;
}
spiDetachSCK(_spi, _sck);
spiDetachMISO(_spi, _miso);
spiDetachMOSI(_spi, _mosi);
setHwCs(false);
spiStopBus(_spi);
_spi = NULL;
}
void SPIClass::setHwCs(bool use)
{
if(use && !_use_hw_ss) {
spiAttachSS(_spi, 0, _ss);
spiSSEnable(_spi);
} else if(_use_hw_ss) {
spiSSDisable(_spi);
spiDetachSS(_spi, _ss);
}
_use_hw_ss = use;
}
void SPIClass::setFrequency(uint32_t freq)
{
//check if last freq changed
uint32_t cdiv = spiGetClockDiv(_spi);
if(_freq != freq || _div != cdiv) {
_freq = freq;
_div = spiFrequencyToClockDiv(_freq);
spiSetClockDiv(_spi, _div);
}
}
void SPIClass::setClockDivider(uint32_t clockDiv)
{
_div = clockDiv;
spiSetClockDiv(_spi, _div);
}
void SPIClass::setDataMode(uint8_t dataMode)
{
spiSetDataMode(_spi, dataMode);
}
void SPIClass::setBitOrder(uint8_t bitOrder)
{
spiSetBitOrder(_spi, bitOrder);
}
void SPIClass::beginTransaction(SPISettings settings)
{
//check if last freq changed
uint32_t cdiv = spiGetClockDiv(_spi);
if(_freq != settings._clock || _div != cdiv) {
_freq = settings._clock;
_div = spiFrequencyToClockDiv(_freq);
}
spiTransaction(_spi, _div, settings._dataMode, settings._bitOrder);
_inTransaction = true;
}
void SPIClass::endTransaction()
{
if(_inTransaction){
spiEndTransaction(_spi);
_inTransaction = false;
}
}
void SPIClass::write(uint8_t data)
{
if(_inTransaction){
return spiWriteByteNL(_spi, data);
}
spiWriteByte(_spi, data);
}
uint8_t SPIClass::transfer(uint8_t data)
{
if(_inTransaction){
return spiTransferByteNL(_spi, data);
}
return spiTransferByte(_spi, data);
}
void SPIClass::write16(uint16_t data)
{
if(_inTransaction){
return spiWriteShortNL(_spi, data);
}
spiWriteWord(_spi, data);
}
uint16_t SPIClass::transfer16(uint16_t data)
{
if(_inTransaction){
return spiTransferShortNL(_spi, data);
}
return spiTransferWord(_spi, data);
}
void SPIClass::write32(uint32_t data)
{
if(_inTransaction){
return spiWriteLongNL(_spi, data);
}
spiWriteLong(_spi, data);
}
uint32_t SPIClass::transfer32(uint32_t data)
{
if(_inTransaction){
return spiTransferLongNL(_spi, data);
}
return spiTransferLong(_spi, data);
}
void SPIClass::transferBits(uint32_t data, uint32_t * out, uint8_t bits)
{
if(_inTransaction){
return spiTransferBitsNL(_spi, data, out, bits);
}
spiTransferBits(_spi, data, out, bits);
}
/**
* @param data uint8_t *
* @param size uint32_t
*/
void SPIClass::writeBytes(uint8_t * data, uint32_t size)
{
if(_inTransaction){
return spiWriteNL(_spi, data, size);
}
spiSimpleTransaction(_spi);
spiWriteNL(_spi, data, size);
spiEndTransaction(_spi);
}
/**
* @param data void *
* @param size uint32_t
*/
void SPIClass::writePixels(const void * data, uint32_t size)
{
if(_inTransaction){
return spiWritePixelsNL(_spi, data, size);
}
spiSimpleTransaction(_spi);
spiWritePixelsNL(_spi, data, size);
spiEndTransaction(_spi);
}
/**
* @param data uint8_t * data buffer. can be NULL for Read Only operation
* @param out uint8_t * output buffer. can be NULL for Write Only operation
* @param size uint32_t
*/
void SPIClass::transferBytes(uint8_t * data, uint8_t * out, uint32_t size)
{
if(_inTransaction){
return spiTransferBytesNL(_spi, data, out, size);
}
spiTransferBytes(_spi, data, out, size);
}
/**
* @param data uint8_t *
* @param size uint8_t max for size is 64Byte
* @param repeat uint32_t
*/
void SPIClass::writePattern(uint8_t * data, uint8_t size, uint32_t repeat)
{
if(size > 64) {
return; //max Hardware FIFO
}
uint32_t byte = (size * repeat);
uint8_t r = (64 / size);
while(byte) {
if(byte > 64) {
writePattern_(data, size, r);
byte -= 64;
} else {
writePattern_(data, size, (byte / size));
byte = 0;
}
}
}
void SPIClass::writePattern_(uint8_t * data, uint8_t size, uint8_t repeat)
{
uint8_t bytes = (size * repeat);
uint8_t buffer[64];
uint8_t * bufferPtr = &buffer[0];
uint8_t * dataPtr;
uint8_t dataSize = bytes;
for(uint8_t i = 0; i < repeat; i++) {
dataSize = size;
dataPtr = data;
while(dataSize--) {
*bufferPtr = *dataPtr;
dataPtr++;
bufferPtr++;
}
}
writeBytes(&buffer[0], bytes);
}
SPIClass SPI(VSPI);

View File

@@ -1,84 +0,0 @@
/*
SPI.h - SPI library for esp8266
Copyright (c) 2015 Hristo Gochkov. 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 _SPI_H_INCLUDED
#define _SPI_H_INCLUDED
#include <stdlib.h>
#include "esp32-hal-spi.h"
class SPISettings
{
public:
SPISettings() :_clock(1000000), _bitOrder(SPI_MSBFIRST), _dataMode(SPI_MODE0) {}
SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) :_clock(clock), _bitOrder(bitOrder), _dataMode(dataMode) {}
uint32_t _clock;
uint8_t _bitOrder;
uint8_t _dataMode;
};
class SPIClass
{
private:
int8_t _spi_num;
spi_t * _spi;
bool _use_hw_ss;
int8_t _sck;
int8_t _miso;
int8_t _mosi;
int8_t _ss;
uint32_t _div;
uint32_t _freq;
bool _inTransaction;
void writePattern_(uint8_t * data, uint8_t size, uint8_t repeat);
public:
SPIClass(uint8_t spi_bus=HSPI);
void begin(int8_t sck=-1, int8_t miso=-1, int8_t mosi=-1, int8_t ss=-1);
void end();
void setHwCs(bool use);
void setBitOrder(uint8_t bitOrder);
void setDataMode(uint8_t dataMode);
void setFrequency(uint32_t freq);
void setClockDivider(uint32_t clockDiv);
void beginTransaction(SPISettings settings);
void endTransaction(void);
uint8_t transfer(uint8_t data);
uint16_t transfer16(uint16_t data);
uint32_t transfer32(uint32_t data);
void transferBytes(uint8_t * data, uint8_t * out, uint32_t size);
void transferBits(uint32_t data, uint32_t * out, uint8_t bits);
void write(uint8_t data);
void write16(uint16_t data);
void write32(uint32_t data);
void writeBytes(uint8_t * data, uint32_t size);
void writePixels(const void * data, uint32_t size);//ili9341 compatible
void writePattern(uint8_t * data, uint8_t size, uint32_t repeat);
spi_t * bus(){ return _spi; }
};
extern SPIClass SPI;
#endif

View File

@@ -1,116 +0,0 @@
/*
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 WPA encryption. For
WEP or WPA, change the Wifi.begin() call 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> turn the LED on pin 5 on<br>");
client.print("Click <a href=\"/L\">here</a> 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 disonnected");
}
}

View File

@@ -1,94 +0,0 @@
/*
* 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

@@ -1,70 +0,0 @@
/*
* 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("Wait 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
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("wait 5 sec...");
delay(5000);
return;
}
// This will send the request to the server
client.print("Send this data to server");
//read back one line from server
String line = client.readStringUntil('\r');
client.println(line);
Serial.println("closing connection");
client.stop();
Serial.println("wait 5 sec...");
delay(5000);
}

View File

@@ -1,51 +0,0 @@
/*
* This sketch shows the WiFi event usage
*
*/
#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 SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
break;
}
}
void setup()
{
Serial.begin(115200);
// delete old config
WiFi.disconnect(true);
delay(1000);
WiFi.onEvent(WiFiEvent);
WiFi.begin(ssid, password);
Serial.println();
Serial.println();
Serial.println("Wait for WiFi... ");
}
void loop()
{
delay(1000);
}

View File

@@ -1,119 +0,0 @@
#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 SYSTEM_EVENT_AP_START:
//can set ap hostname here
WiFi.softAPsetHostname(AP_SSID);
//enable ap ipv6 here
WiFi.softAPenableIpV6();
break;
case SYSTEM_EVENT_STA_START:
//set sta hostname here
WiFi.setHostname(AP_SSID);
break;
case SYSTEM_EVENT_STA_CONNECTED:
//enable sta ipv6 here
WiFi.enableIpV6();
break;
case SYSTEM_EVENT_AP_STA_GOT_IP6:
//both interfaces get the same event
Serial.print("STA IPv6: ");
Serial.println(WiFi.localIPv6());
Serial.print("AP IPv6: ");
Serial.println(WiFi.softAPIPv6());
break;
case SYSTEM_EVENT_STA_GOT_IP:
wifiOnConnect();
wifi_connected = true;
break;
case SYSTEM_EVENT_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

@@ -1,35 +0,0 @@
/*
* 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

@@ -1,48 +0,0 @@
/*
* 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

@@ -1,28 +0,0 @@
#define WiFi_Logo_width 60
#define WiFi_Logo_height 36
const char WiFi_Logo_bits[] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x07, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE0, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF,
0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
0xFF, 0x03, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x07, 0xC0, 0x83, 0x01, 0x80, 0xFF, 0xFF, 0xFF,
0x01, 0x00, 0x07, 0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x0C, 0x00,
0xC0, 0xFF, 0xFF, 0x7C, 0x00, 0x60, 0x0C, 0x00, 0xC0, 0x31, 0x46, 0x7C,
0xFC, 0x77, 0x08, 0x00, 0xE0, 0x23, 0xC6, 0x3C, 0xFC, 0x67, 0x18, 0x00,
0xE0, 0x23, 0xE4, 0x3F, 0x1C, 0x00, 0x18, 0x00, 0xE0, 0x23, 0x60, 0x3C,
0x1C, 0x70, 0x18, 0x00, 0xE0, 0x03, 0x60, 0x3C, 0x1C, 0x70, 0x18, 0x00,
0xE0, 0x07, 0x60, 0x3C, 0xFC, 0x73, 0x18, 0x00, 0xE0, 0x87, 0x70, 0x3C,
0xFC, 0x73, 0x18, 0x00, 0xE0, 0x87, 0x70, 0x3C, 0x1C, 0x70, 0x18, 0x00,
0xE0, 0x87, 0x70, 0x3C, 0x1C, 0x70, 0x18, 0x00, 0xE0, 0x8F, 0x71, 0x3C,
0x1C, 0x70, 0x18, 0x00, 0xC0, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x08, 0x00,
0xC0, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x0C, 0x00, 0x80, 0xFF, 0xFF, 0x1F,
0x00, 0x00, 0x06, 0x00, 0x80, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x07, 0x00,
0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0xF8, 0xFF, 0xFF,
0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x01, 0x00, 0x00,
0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF,
0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x1F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};

View File

@@ -1,36 +0,0 @@
#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

@@ -1,75 +0,0 @@
/*
* 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: %u", 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 SYSTEM_EVENT_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 SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
connected = false;
break;
}
}

View File

@@ -1,30 +0,0 @@
# 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

@@ -1,16 +0,0 @@
# 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

@@ -1,68 +0,0 @@
#######################################
# 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

@@ -1,9 +0,0 @@
name=WiFi
version=1.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 (WEP, WPA). The IP address can be assigned statically or through a DHCP. The library can also manage DNS.
category=Communication
url=
architectures=esp32

View File

@@ -1,96 +0,0 @@
/*
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_loop.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);
bool autoConnect;
esp_wifi_get_auto_connect(&autoConnect);
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());
*/
p.print("Auto connect: ");
p.println(autoConnect);
wifi_config_t conf;
esp_wifi_get_config(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);
}
WiFiClass WiFi;

View File

@@ -1,67 +0,0 @@
/*
ESP8266WiFi.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
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
{
public:
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;
};
extern WiFiClass WiFi;
#endif

View File

@@ -1,279 +0,0 @@
/*
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_loop.h>
#include <lwip/ip_addr.h>
}
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- Private functions ------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
static bool softap_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs);
/**
* 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(strcmp(reinterpret_cast<const char*>(lhs.ap.ssid), reinterpret_cast<const char*>(rhs.ap.ssid)) != 0) {
return false;
}
if(strcmp(reinterpret_cast<const char*>(lhs.ap.password), reinterpret_cast<const char*>(rhs.ap.password)) != 0) {
return false;
}
if(lhs.ap.channel != rhs.ap.channel) {
return false;
}
if(lhs.ap.ssid_hidden != rhs.ap.ssid_hidden) {
return false;
}
return true;
}
// -----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------- 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)
*/
bool WiFiAPClass::softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden)
{
if(!WiFi.enableAP(true)) {
// enable AP failed
return false;
}
if(!ssid || *ssid == 0 || strlen(ssid) > 31) {
// fail SSID too long or missing!
return false;
}
if(passphrase && (strlen(passphrase) > 63 || strlen(passphrase) < 8)) {
// fail passphrase to long or short!
return false;
}
esp_wifi_start();
wifi_config_t conf;
strcpy(reinterpret_cast<char*>(conf.ap.ssid), ssid);
conf.ap.channel = channel;
conf.ap.ssid_len = strlen(ssid);
conf.ap.ssid_hidden = ssid_hidden;
conf.ap.max_connection = 4;
conf.ap.beacon_interval = 100;
if(!passphrase || strlen(passphrase) == 0) {
conf.ap.authmode = WIFI_AUTH_OPEN;
*conf.ap.password = 0;
} else {
conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
strcpy(reinterpret_cast<char*>(conf.ap.password), passphrase);
}
wifi_config_t conf_current;
esp_wifi_get_config(WIFI_IF_AP, &conf_current);
if(softap_config_equal(conf, conf_current)) {
//DEBUGV("softap config unchanged");
return true;
}
bool ret;
ret = esp_wifi_set_config(WIFI_IF_AP, &conf) == ESP_OK;
return ret;
}
/**
* 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)
{
if(!WiFi.enableAP(true)) {
// enable AP failed
return false;
}
tcpip_adapter_ip_info_t info;
info.ip.addr = static_cast<uint32_t>(local_ip);
info.gw.addr = static_cast<uint32_t>(gateway);
info.netmask.addr = static_cast<uint32_t>(subnet);
tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP);
if(tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_AP, &info) == ESP_OK) {
return tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP) == ESP_OK;
}
return false;
}
/**
* 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;
*conf.ap.ssid = 0;
*conf.ap.password = 0;
ret = esp_wifi_set_config(WIFI_IF_AP, &conf) == ESP_OK;
if(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(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()
{
tcpip_adapter_ip_info_t ip;
tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip);
return IPAddress(ip.ip.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)
{
esp_wifi_get_mac(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 };
esp_wifi_get_mac(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;
if(tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_AP, &hostname)) {
return NULL;
}
return hostname;
}
/**
* Set the softAP interface Host name.
* @param hostname pointer to const string
* @return true on success
*/
bool WiFiAPClass::softAPsetHostname(const char * hostname)
{
return tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_AP, hostname) == ESP_OK;
}
/**
* Enable IPv6 on the softAP interface.
* @return true on success
*/
bool WiFiAPClass::softAPenableIpV6()
{
return tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_AP) == ESP_OK;
}
/**
* Get the softAP interface IPv6 address.
* @return IPv6Address softAP IPv6
*/
IPv6Address WiFiAPClass::softAPIPv6()
{
static ip6_addr_t addr;
if(tcpip_adapter_get_ip6_linklocal(TCPIP_ADAPTER_IF_AP, &addr)) {
return IPv6Address();
}
return IPv6Address(addr.addr);
}

View File

@@ -1,61 +0,0 @@
/*
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);
bool softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet);
bool softAPdisconnect(bool wifioff = false);
uint8_t softAPgetStationNum();
IPAddress softAPIP();
bool softAPenableIpV6();
IPv6Address softAPIPv6();
const char * softAPgetHostname();
bool softAPsetHostname(const char * hostname);
uint8_t* softAPmacAddress(uint8_t* mac);
String softAPmacAddress(void);
protected:
};
#endif /* ESP32WIFIAP_H_*/

View File

@@ -1,241 +0,0 @@
/*
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 <lwip/sockets.h>
#include <lwip/netdb.h>
#include <errno.h>
#undef connect
#undef write
#undef read
WiFiClient::WiFiClient():sockfd(-1),_connected(false),next(NULL)
{
}
WiFiClient::WiFiClient(int fd):sockfd(fd),_connected(true),next(NULL)
{
}
WiFiClient::~WiFiClient()
{
stop();
}
WiFiClient & WiFiClient::operator=(const WiFiClient &other)
{
stop();
sockfd = other.sockfd;
_connected = other._connected;
return *this;
}
void WiFiClient::stop()
{
if(_connected && sockfd >= 0) {
close(sockfd);
sockfd = -1;
_connected = false;
}
}
int WiFiClient::connect(IPAddress ip, uint16_t port)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
log_e("socket: %d", errno);
return 0;
}
uint32_t ip_addr = ip;
struct sockaddr_in serveraddr;
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((const void *)(&ip_addr), (void *)&serveraddr.sin_addr.s_addr, 4);
serveraddr.sin_port = htons(port);
int res = lwip_connect_r(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
if (res < 0) {
log_e("lwip_connect_r: %d", errno);
close(sockfd);
sockfd = -1;
return 0;
}
_connected = true;
return 1;
}
int WiFiClient::connect(const char *host, uint16_t port)
{
struct hostent *server;
server = gethostbyname(host);
if (server == NULL) {
return 0;
}
IPAddress srv((const uint8_t *)(server->h_addr));
return connect(srv, port);
}
int WiFiClient::setSocketOption(int option, char* value, size_t len)
{
int res = setsockopt(sockfd, SOL_SOCKET, option, value, len);
if(res < 0) {
log_e("%d", errno);
}
return res;
}
int WiFiClient::setTimeout(uint32_t seconds)
{
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));
}
int WiFiClient::setOption(int option, int *value)
{
int res = setsockopt(sockfd, IPPROTO_TCP, option, (char *)value, sizeof(int));
if(res < 0) {
log_e("%d", errno);
}
return res;
}
int WiFiClient::getOption(int option, int *value)
{
size_t size = sizeof(int);
int res = getsockopt(sockfd, IPPROTO_TCP, option, (char *)value, &size);
if(res < 0) {
log_e("%d", 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;
}
return data;
}
size_t WiFiClient::write(const uint8_t *buf, size_t size)
{
if(!_connected) {
return 0;
}
int res = send(sockfd, (void*)buf, size, MSG_DONTWAIT);
if(res < 0) {
log_e("%d", errno);
stop();
res = 0;
}
return res;
}
int WiFiClient::read(uint8_t *buf, size_t size)
{
if(!available()) {
return -1;
}
int res = recv(sockfd, buf, size, MSG_DONTWAIT);
if(res < 0 && errno != EWOULDBLOCK) {
log_e("%d", errno);
stop();
}
return res;
}
int WiFiClient::available()
{
if(!_connected) {
return 0;
}
int count;
int res = ioctl(sockfd, FIONREAD, &count);
if(res < 0) {
log_e("%d", errno);
stop();
return 0;
}
return count;
}
uint8_t WiFiClient::connected()
{
uint8_t dummy = 0;
read(&dummy, 0);
return _connected;
}
IPAddress WiFiClient::remoteIP(int fd)
{
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)
{
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()
{
return remoteIP(sockfd);
}
uint16_t WiFiClient::remotePort()
{
return remotePort(sockfd);
}
bool WiFiClient::operator==(const WiFiClient& rhs)
{
return sockfd == rhs.sockfd && remotePort(sockfd) == remotePort(rhs.sockfd) && remoteIP(sockfd) == remoteIP(rhs.sockfd);
}

View File

@@ -1,92 +0,0 @@
/*
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"
class WiFiClient : public Client
{
protected:
int sockfd;
bool _connected;
public:
WiFiClient *next;
WiFiClient();
WiFiClient(int fd);
~WiFiClient();
int connect(IPAddress ip, uint16_t port);
int connect(const char *host, uint16_t port);
size_t write(uint8_t data);
size_t write(const uint8_t *buf, size_t size);
int available();
int read();
int read(uint8_t *buf, size_t size);
int peek()
{
return 0;
}
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()
{
return sockfd;
}
IPAddress remoteIP();
uint16_t remotePort();
int setSocketOption(int option, char* 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(int fd);
uint16_t remotePort(int fd);
//friend class WiFiServer;
using Print::write;
};
#endif /* _WIFICLIENT_H_ */

View File

@@ -1,358 +0,0 @@
/*
ESP8266WiFiGeneric.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"
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_loop.h>
#include "lwip/ip_addr.h"
#include "lwip/opt.h"
#include "lwip/err.h"
#include "lwip/dns.h"
#include "esp_ipc.h"
#include "esp32-hal-log.h"
/**
* Boot and start WiFi
* This method get's called on boot if you use any of the WiFi methods.
* If you do not link to this library, WiFi will not be started.
* */
static bool _esp_wifi_initalized = false;
extern void initWiFi()
{
#if !CONFIG_ESP32_PHY_AUTO_INIT
arduino_phy_init();
#endif
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
tcpip_adapter_init();
esp_event_loop_init(&WiFiGenericClass::_eventCallback, NULL);
esp_wifi_init(&cfg);
esp_wifi_set_storage(WIFI_STORAGE_FLASH);
_esp_wifi_initalized = true;
}
} //extern "C"
#undef min
#undef max
#include <vector>
static bool _esp_wifi_start()
{
static bool started = false;
esp_err_t err;
if(!_esp_wifi_initalized){
initWiFi();
if(!_esp_wifi_initalized){
log_w("not initialized");
return false;
}
}
if(started){
return true;
}
started = true;
err = esp_wifi_start();
if (err != ESP_OK) {
log_e("%d", err);
return false;
}
#if CONFIG_AUTOCONNECT_WIFI
wifi_mode_t mode = WIFI_MODE_NULL;
bool auto_connect = false;
err = esp_wifi_get_mode(&mode);
if (err != ESP_OK) {
log_e("esp_wifi_get_mode: %d", err);
return false;
}
err = esp_wifi_get_auto_connect(&auto_connect);
if ((mode == WIFI_MODE_STA || mode == WIFI_MODE_APSTA) && auto_connect) {
err = esp_wifi_connect();
if (err != ESP_OK) {
log_e("esp_wifi_connect: %d", err);
return false;
}
}
#endif
return true;
}
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------- Generic WiFi function -----------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// arduino dont like std::vectors move static here
static std::vector<WiFiEventCbList_t> cbEventList;
bool WiFiGenericClass::_persistent = true;
wifi_mode_t WiFiGenericClass::_forceSleepLastMode = WIFI_MODE_NULL;
WiFiGenericClass::WiFiGenericClass()
{
}
/**
* set callback function
* @param cbEvent WiFiEventCb
* @param event optional filter (WIFI_EVENT_MAX is all events)
*/
void WiFiGenericClass::onEvent(WiFiEventCb cbEvent, system_event_id_t event)
{
if(!cbEvent) {
return;
}
WiFiEventCbList_t newEventHandler;
newEventHandler.cb = cbEvent;
newEventHandler.event = event;
cbEventList.push_back(newEventHandler);
}
/**
* removes a callback form event handler
* @param cbEvent WiFiEventCb
* @param event optional filter (WIFI_EVENT_MAX is all events)
*/
void WiFiGenericClass::removeEvent(WiFiEventCb cbEvent, system_event_id_t event)
{
if(!cbEvent) {
return;
}
for(uint32_t i = 0; i < cbEventList.size(); i++) {
WiFiEventCbList_t entry = cbEventList[i];
if(entry.cb == cbEvent && entry.event == event) {
cbEventList.erase(cbEventList.begin() + i);
}
}
}
/**
* callback for WiFi events
* @param arg
*/
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
const char * system_event_names[] = { "WIFI_READY", "SCAN_DONE", "STA_START", "STA_STOP", "STA_CONNECTED", "STA_DISCONNECTED", "STA_AUTHMODE_CHANGE", "STA_GOT_IP", "STA_WPS_ER_SUCCESS", "STA_WPS_ER_FAILED", "STA_WPS_ER_TIMEOUT", "STA_WPS_ER_PIN", "AP_START", "AP_STOP", "AP_STACONNECTED", "AP_STADISCONNECTED", "AP_PROBEREQRECVED", "AP_STA_GOT_IP6", "ETH_START", "ETH_STOP", "ETH_CONNECTED", "ETH_DISCONNECTED", "ETH_GOT_IP", "MAX"};
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN
const char * system_event_reasons[] = { "UNSPECIFIED", "AUTH_EXPIRE", "AUTH_LEAVE", "ASSOC_EXPIRE", "ASSOC_TOOMANY", "NOT_AUTHED", "NOT_ASSOCED", "ASSOC_LEAVE", "ASSOC_NOT_AUTHED", "DISASSOC_PWRCAP_BAD", "DISASSOC_SUPCHAN_BAD", "IE_INVALID", "MIC_FAILURE", "4WAY_HANDSHAKE_TIMEOUT", "GROUP_KEY_UPDATE_TIMEOUT", "IE_IN_4WAY_DIFFERS", "GROUP_CIPHER_INVALID", "PAIRWISE_CIPHER_INVALID", "AKMP_INVALID", "UNSUPP_RSN_IE_VERSION", "INVALID_RSN_IE_CAP", "802_1X_AUTH_FAILED", "CIPHER_SUITE_REJECTED", "BEACON_TIMEOUT", "NO_AP_FOUND", "AUTH_FAIL", "ASSOC_FAIL", "HANDSHAKE_TIMEOUT" };
#define reason2str(r) ((r>176)?system_event_reasons[r-176]:system_event_reasons[r-1])
#endif
esp_err_t WiFiGenericClass::_eventCallback(void *arg, system_event_t *event)
{
log_d("Event: %d - %s", event->event_id, system_event_names[event->event_id]);
if(event->event_id == SYSTEM_EVENT_SCAN_DONE) {
WiFiScanClass::_scanDone();
} else if(event->event_id == SYSTEM_EVENT_STA_DISCONNECTED) {
uint8_t reason = event->event_info.disconnected.reason;
log_w("Reason: %u - %s", reason, reason2str(reason));
if(reason == WIFI_REASON_NO_AP_FOUND) {
WiFiSTAClass::_setStatus(WL_NO_SSID_AVAIL);
} else if(reason == WIFI_REASON_AUTH_FAIL || reason == WIFI_REASON_ASSOC_FAIL) {
WiFiSTAClass::_setStatus(WL_CONNECT_FAILED);
} else if(reason == WIFI_REASON_BEACON_TIMEOUT || reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
WiFiSTAClass::_setStatus(WL_CONNECTION_LOST);
} else {
WiFiSTAClass::_setStatus(WL_DISCONNECTED);
}
} else if(event->event_id == SYSTEM_EVENT_STA_START) {
WiFiSTAClass::_setStatus(WL_DISCONNECTED);
} else if(event->event_id == SYSTEM_EVENT_STA_STOP) {
WiFiSTAClass::_setStatus(WL_NO_SHIELD);
} else if(event->event_id == SYSTEM_EVENT_STA_GOT_IP) {
WiFiSTAClass::_setStatus(WL_CONNECTED);
}
for(uint32_t i = 0; i < cbEventList.size(); i++) {
WiFiEventCbList_t entry = cbEventList[i];
if(entry.cb) {
if(entry.event == (system_event_id_t) event->event_id || entry.event == SYSTEM_EVENT_MAX) {
entry.cb((system_event_id_t) event->event_id);
}
}
}
return ESP_OK;
}
/**
* Return the current channel associated with the network
* @return channel (1-13)
*/
int32_t WiFiGenericClass::channel(void)
{
uint8_t primaryChan;
wifi_second_chan_t secondChan;
esp_wifi_get_channel(&primaryChan, &secondChan);
return primaryChan;
}
/**
* store WiFi config in SDK flash area
* @param persistent
*/
void WiFiGenericClass::persistent(bool persistent)
{
_persistent = persistent;
}
/**
* set new mode
* @param m WiFiMode_t
*/
bool WiFiGenericClass::mode(wifi_mode_t m)
{
wifi_mode_t cm = getMode();
if(cm == WIFI_MODE_MAX){
return false;
}
if(cm == m) {
return true;
}
return esp_wifi_set_mode(m) == ESP_OK;
}
/**
* get WiFi mode
* @return WiFiMode
*/
wifi_mode_t WiFiGenericClass::getMode()
{
uint8_t mode;
if(!_esp_wifi_start()){
return WIFI_MODE_MAX;
}
esp_wifi_get_mode((wifi_mode_t*)&mode);
return (wifi_mode_t)mode;
}
/**
* control STA mode
* @param enable bool
* @return ok
*/
bool WiFiGenericClass::enableSTA(bool enable)
{
wifi_mode_t currentMode = getMode();
bool isEnabled = ((currentMode & WIFI_MODE_STA) != 0);
if(isEnabled != enable) {
if(enable) {
return mode((wifi_mode_t)(currentMode | WIFI_MODE_STA));
} else {
return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_STA)));
}
} else {
return true;
}
}
/**
* control AP mode
* @param enable bool
* @return ok
*/
bool WiFiGenericClass::enableAP(bool enable)
{
wifi_mode_t currentMode = getMode();
bool isEnabled = ((currentMode & WIFI_MODE_AP) != 0);
if(isEnabled != enable) {
if(enable) {
return mode((wifi_mode_t)(currentMode | WIFI_MODE_AP));
} else {
return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_AP)));
}
} else {
return true;
}
}
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------ Generic Network function ---------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
static bool _dns_busy = false;
/**
* DNS callback
* @param name
* @param ipaddr
* @param callback_arg
*/
static void wifi_dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg)
{
if(ipaddr) {
(*reinterpret_cast<IPAddress*>(callback_arg)) = ipaddr->u_addr.ip4.addr;
}
_dns_busy = false;
}
/**
* Resolve the given hostname to an IP address.
* @param aHostname Name to be resolved
* @param aResult IPAddress structure to store the returned IP address
* @return 1 if aIPAddrString was successfully converted to an IP address,
* else error code
*/
int WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult)
{
ip_addr_t addr;
aResult = static_cast<uint32_t>(0);
_dns_busy = true;
err_t err = dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult);
if(err == ERR_OK && addr.u_addr.ip4.addr) {
aResult = addr.u_addr.ip4.addr;
_dns_busy = false;
} else if(err == ERR_INPROGRESS) {
while(_dns_busy){
delay(1);
}
} else {
_dns_busy = false;
return 0;
}
return 1;
}

View File

@@ -1,73 +0,0 @@
/*
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 "WiFiType.h"
#include <esp_err.h>
#include <esp_event_loop.h>
typedef void (*WiFiEventCb)(system_event_id_t event);
typedef struct {
WiFiEventCb cb;
system_event_id_t event;
} WiFiEventCbList_t;
class WiFiGenericClass
{
public:
WiFiGenericClass();
void onEvent(WiFiEventCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX);
void removeEvent(WiFiEventCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX);
int32_t channel(void);
void persistent(bool persistent);
static bool mode(wifi_mode_t);
static wifi_mode_t getMode();
bool enableSTA(bool enable);
bool enableAP(bool enable);
static esp_err_t _eventCallback(void *arg, system_event_t *event);
protected:
static bool _persistent;
static wifi_mode_t _forceSleepLastMode;
public:
int hostByName(const char* aHostname, IPAddress& aResult);
protected:
friend class WiFiSTAClass;
friend class WiFiScanClass;
friend class WiFiAPClass;
};
#endif /* ESP32WIFIGENERIC_H_ */

View File

@@ -1,218 +0,0 @@
/**
*
* @file ESP8266WiFiMulti.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()
{
APlistClean();
}
bool WiFiMulti::addAP(const char* ssid, const char *passphrase)
{
return APlistAdd(ssid, passphrase);
}
uint8_t WiFiMulti::run(void)
{
int8_t scanResult;
uint8_t status = WiFi.status();
if(status == WL_DISCONNECTED || status == WL_NO_SSID_AVAIL || status == WL_IDLE_STATUS || status == WL_CONNECT_FAILED) {
scanResult = WiFi.scanComplete();
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;
DEBUG_WIFI_MULTI("[WIFI] scan done\n");
delay(0);
if(scanResult <= 0) {
DEBUG_WIFI_MULTI("[WIFI] no networks found\n");
} else {
DEBUG_WIFI_MULTI("[WIFI] %d networks found\n", 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 = 0; x < APlist.size(); x++) {
WifiAPlist_t entry = APlist[x];
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) {
DEBUG_WIFI_MULTI(" ---> ");
} else {
DEBUG_WIFI_MULTI(" ");
}
DEBUG_WIFI_MULTI(" %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) %c\n", 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) ? ' ' : '*');
delay(0);
}
}
// clean up ram
WiFi.scanDelete();
DEBUG_WIFI_MULTI("\n\n");
delay(0);
if(bestNetwork.ssid) {
DEBUG_WIFI_MULTI("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channal: %d (%d)\n", 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();
// wait for connection or fail
while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED) {
delay(10);
status = WiFi.status();
}
IPAddress ip;
uint8_t * mac;
switch(status) {
case 3:
ip = WiFi.localIP();
mac = WiFi.BSSID();
DEBUG_WIFI_MULTI("[WIFI] Connecting done.\n");
DEBUG_WIFI_MULTI("[WIFI] SSID: %s\n", WiFi.SSID());
DEBUG_WIFI_MULTI("[WIFI] IP: %d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
DEBUG_WIFI_MULTI("[WIFI] MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
DEBUG_WIFI_MULTI("[WIFI] Channel: %d\n", WiFi.channel());
break;
case 1:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed AP not found.\n");
break;
case 4:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed.\n");
break;
default:
DEBUG_WIFI_MULTI("[WIFI] Connecting Failed (%d).\n", status);
break;
}
} else {
DEBUG_WIFI_MULTI("[WIFI] no matching wifi found!\n");
}
} else {
// start scan
DEBUG_WIFI_MULTI("[WIFI] delete old wifi config...\n");
WiFi.disconnect();
DEBUG_WIFI_MULTI("[WIFI] start scan\n");
// scan wifi async mode
WiFi.scanNetworks(true);
}
}
return status;
}
// ##################################################################################
bool WiFiMulti::APlistAdd(const char* ssid, const char *passphrase)
{
WifiAPlist_t newAP;
if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) {
// fail SSID to long or missing!
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] no ssid or ssid to long\n");
return false;
}
if(passphrase && strlen(passphrase) > 63) {
// fail passphrase to long!
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] passphrase to long\n");
return false;
}
newAP.ssid = strdup(ssid);
if(!newAP.ssid) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.ssid == 0\n");
return false;
}
if(passphrase && *passphrase != 0x00) {
newAP.passphrase = strdup(passphrase);
if(!newAP.passphrase) {
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] fail newAP.passphrase == 0\n");
free(newAP.ssid);
return false;
}
}
APlist.push_back(newAP);
DEBUG_WIFI_MULTI("[WIFI][APlistAdd] add SSID: %s\n", newAP.ssid);
return true;
}
void WiFiMulti::APlistClean(void)
{
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();
}

View File

@@ -1,66 +0,0 @@
/**
*
* @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"
#undef min
#undef max
#include <vector>
#ifdef DEBUG_ESP_WIFI
#ifdef DEBUG_ESP_PORT
#define DEBUG_WIFI_MULTI(...) DEBUG_ESP_PORT.printf( __VA_ARGS__ )
#endif
#endif
#ifndef DEBUG_WIFI_MULTI
#define DEBUG_WIFI_MULTI(...)
#endif
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(void);
private:
std::vector<WifiAPlist_t> APlist;
bool APlistAdd(const char* ssid, const char *passphrase = NULL);
void APlistClean(void);
};
#endif /* WIFICLIENTMULTI_H_ */

View File

@@ -1,572 +0,0 @@
/*
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 "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_loop.h>
#include <esp32-hal.h>
#include <lwip/ip_addr.h>
#include "lwip/err.h"
#include "lwip/dns.h"
#include <esp_smartconfig.h>
}
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- Private functions ------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
static bool sta_config_equal(const wifi_config_t& lhs, const wifi_config_t& rhs);
/**
* 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(strcmp(reinterpret_cast<const char*>(lhs.sta.ssid), reinterpret_cast<const char*>(rhs.sta.ssid)) != 0) {
return false;
}
if(strcmp(reinterpret_cast<const char*>(lhs.sta.password), reinterpret_cast<const char*>(rhs.sta.password)) != 0) {
return false;
}
if(lhs.sta.bssid_set != rhs.sta.bssid_set) {
return false;
}
if(lhs.sta.bssid_set) {
if(memcmp(lhs.sta.bssid, rhs.sta.bssid, 6) != 0) {
return false;
}
}
return true;
}
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- STA function -----------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
bool WiFiSTAClass::_useStaticIp = false;
wl_status_t WiFiSTAClass::_status = WL_NO_SHIELD;
/**
* 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)) {
// enable STA failed
return WL_CONNECT_FAILED;
}
if(!ssid || *ssid == 0x00 || strlen(ssid) > 31) {
// fail SSID too long or missing!
return WL_CONNECT_FAILED;
}
if(passphrase && strlen(passphrase) > 63) {
// fail passphrase too long!
return WL_CONNECT_FAILED;
}
wifi_config_t conf;
strcpy(reinterpret_cast<char*>(conf.sta.ssid), ssid);
if(passphrase) {
strcpy(reinterpret_cast<char*>(conf.sta.password), passphrase);
} else {
*conf.sta.password = 0;
}
if(bssid) {
conf.sta.bssid_set = 1;
memcpy((void *) &conf.sta.bssid[0], (void *) bssid, 6);
} else {
conf.sta.bssid_set = 0;
}
wifi_config_t current_conf;
esp_wifi_get_config(WIFI_IF_STA, &current_conf);
if(!sta_config_equal(current_conf, conf)) {
esp_wifi_set_config(WIFI_IF_STA, &conf);
}
if(channel > 0 && channel <= 13) {
esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE);
}
if(connect) {
esp_wifi_connect();
}
if(!_useStaticIp) {
tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA);
} else {
tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA);
}
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)) {
// enable STA failed
return WL_CONNECT_FAILED;
}
esp_wifi_start();
esp_wifi_connect();
if(!_useStaticIp) {
tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA);
} else {
tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA);
}
return status();
}
void WiFiSTAClass::_setStatus(wl_status_t status)
{
_status = status;
//log_i("wifi status: %d", status);
}
/**
* 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)
{
if(!WiFi.enableSTA(true)) {
return false;
}
tcpip_adapter_ip_info_t info;
info.ip.addr = static_cast<uint32_t>(local_ip);
info.gw.addr = static_cast<uint32_t>(gateway);
info.netmask.addr = static_cast<uint32_t>(subnet);
tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA);
if(tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &info) == ESP_OK) {
_useStaticIp = true;
} else {
return false;
}
ip_addr_t d;
if(dns1 != (uint32_t)0x00000000) {
// Set DNS1-Server
d.u_addr.ip4.addr = static_cast<uint32_t>(dns1);
dns_setserver(0, &d);
}
if(dns2 != (uint32_t)0x00000000) {
// Set DNS2-Server
d.u_addr.ip4.addr = static_cast<uint32_t>(dns2);
dns_setserver(1, &d);
}
return true;
}
/**
* will force a disconnect an then start reconnecting to AP
* @return ok
*/
bool WiFiSTAClass::reconnect()
{
if((WiFi.getMode() & WIFI_MODE_STA) != 0) {
if(esp_wifi_disconnect() == ESP_OK) {
return esp_wifi_connect() == ESP_OK;
}
}
return false;
}
/**
* Disconnect from the network
* @param wifioff
* @return one value of wl_status_t enum
*/
bool WiFiSTAClass::disconnect(bool wifioff)
{
bool ret;
wifi_config_t conf;
*conf.sta.ssid = 0;
*conf.sta.password = 0;
esp_wifi_set_config(WIFI_IF_STA, &conf);
ret = esp_wifi_set_config(WIFI_IF_STA, &conf) == ESP_OK;
if(wifioff) {
WiFi.enableSTA(false);
}
return ret;
}
/**
* is STA interface connected?
* @return true if STA is connected to an AD
*/
bool WiFiSTAClass::isConnected()
{
return (status() == WL_CONNECTED);
}
/**
* Setting the ESP32 station to connect to the AP (which is recorded)
* automatically or not when powered on. Enable auto-connect by default.
* @param autoConnect bool
* @return if saved
*/
bool WiFiSTAClass::setAutoConnect(bool autoConnect)
{
bool ret;
ret = esp_wifi_set_auto_connect(autoConnect);
return ret;
}
/**
* Checks if ESP32 station mode will connect to AP
* automatically or not when it is powered on.
* @return auto connect
*/
bool WiFiSTAClass::getAutoConnect()
{
bool autoConnect;
esp_wifi_get_auto_connect(&autoConnect);
return autoConnect;
}
/**
* 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()
{
//1 and 3 have STA enabled
if((WiFiGenericClass::getMode() & WIFI_MODE_STA) == 0) {
return WL_DISCONNECTED;
}
int i = 0;
while(status() >= WL_DISCONNECTED && i++ < 100) {
delay(100);
}
return status();
}
/**
* Get the station interface IP address.
* @return IPAddress station IP
*/
IPAddress WiFiSTAClass::localIP()
{
tcpip_adapter_ip_info_t ip;
tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip);
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)
{
esp_wifi_get_mac(WIFI_IF_STA, mac);
return mac;
}
/**
* Get the station interface MAC address.
* @return String mac
*/
String WiFiSTAClass::macAddress(void)
{
uint8_t mac[6];
char macStr[18] = { 0 };
esp_wifi_get_mac(WIFI_IF_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()
{
tcpip_adapter_ip_info_t ip;
tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip);
return IPAddress(ip.netmask.addr);
}
/**
* Get the gateway ip address.
* @return IPAddress gatewayIP
*/
IPAddress WiFiSTAClass::gatewayIP()
{
tcpip_adapter_ip_info_t ip;
tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip);
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)
{
ip_addr_t dns_ip = dns_getserver(dns_no);
return IPAddress(dns_ip.u_addr.ip4.addr);
}
/**
* Return Connection status.
* @return one of the value defined in wl_status_t
*
*/
wl_status_t WiFiSTAClass::status()
{
return WiFiSTAClass::_status;
}
/**
* Return the current SSID associated with the network
* @return SSID
*/
String WiFiSTAClass::SSID() const
{
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
{
wifi_config_t conf;
esp_wifi_get_config(WIFI_IF_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(!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)
{
wifi_ap_record_t info;
if(!esp_wifi_sta_get_ap_info(&info)) {
return info.rssi;
}
return 0;
}
/**
* Get the station interface Host name.
* @return char array hostname
*/
const char * WiFiSTAClass::getHostname()
{
const char * hostname;
if(tcpip_adapter_get_hostname(TCPIP_ADAPTER_IF_STA, &hostname)){
return NULL;
}
return hostname;
}
/**
* Set the station interface Host name.
* @param hostname pointer to const string
* @return true on success
*/
bool WiFiSTAClass::setHostname(const char * hostname)
{
return tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, hostname) == 0;
}
/**
* Enable IPv6 on the station interface.
* @return true on success
*/
bool WiFiSTAClass::enableIpV6()
{
return tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_STA) == 0;
}
/**
* Get the station interface IPv6 address.
* @return IPv6Address
*/
IPv6Address WiFiSTAClass::localIPv6()
{
static ip6_addr_t addr;
if(tcpip_adapter_get_ip6_linklocal(TCPIP_ADAPTER_IF_STA, &addr)){
return IPv6Address();
}
return IPv6Address(addr.addr);
}
bool WiFiSTAClass::_smartConfigStarted = false;
bool WiFiSTAClass::_smartConfigDone = false;
bool WiFiSTAClass::beginSmartConfig() {
if (_smartConfigStarted) {
return false;
}
if (!WiFi.mode(WIFI_STA)) {
return false;
}
esp_err_t err;
err = esp_smartconfig_start(reinterpret_cast<sc_callback_t>(&WiFiSTAClass::_smartConfigCallback), 1);
if (err == ESP_OK) {
_smartConfigStarted = true;
_smartConfigDone = false;
return true;
}
return false;
}
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;
}
void WiFiSTAClass::_smartConfigCallback(uint32_t st, void* result) {
smartconfig_status_t status = (smartconfig_status_t) st;
if (status == SC_STATUS_LINK) {
wifi_sta_config_t *sta_conf = reinterpret_cast<wifi_sta_config_t *>(result);
esp_wifi_set_config(WIFI_IF_AP, (wifi_config_t *)sta_conf);
esp_wifi_disconnect();
esp_wifi_connect();
_smartConfigDone = true;
} else if (status == SC_STATUS_LINK_OVER) {
WiFi.stopSmartConfig();
}
}

View File

@@ -1,101 +0,0 @@
/*
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"
class WiFiSTAClass
{
// ----------------------------------------------------------------------------------------------
// ---------------------------------------- STA function ----------------------------------------
// ----------------------------------------------------------------------------------------------
public:
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 isConnected();
bool setAutoConnect(bool autoConnect);
bool getAutoConnect();
bool setAutoReconnect(bool autoReconnect);
uint8_t waitForConnectResult();
// STA network info
IPAddress localIP();
uint8_t * macAddress(uint8_t* mac);
String macAddress();
IPAddress subnetMask();
IPAddress gatewayIP();
IPAddress dnsIP(uint8_t dns_no = 0);
bool enableIpV6();
IPv6Address localIPv6();
const char * getHostname();
bool setHostname(const char * hostname);
// STA WiFi info
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 wl_status_t _status;
static bool _useStaticIp;
public:
bool beginSmartConfig();
bool stopSmartConfig();
bool smartConfigDone();
protected:
static bool _smartConfigStarted;
static bool _smartConfigDone;
static void _smartConfigCallback(uint32_t status, void* result);
};
#endif /* ESP32WIFISTA_H_ */

View File

@@ -1,268 +0,0 @@
/*
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_loop.h>
#include <esp32-hal.h>
#include <lwip/ip_addr.h>
#include "lwip/err.h"
}
bool WiFiScanClass::_scanAsync = false;
bool WiFiScanClass::_scanStarted = false;
bool WiFiScanClass::_scanComplete = false;
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
*/
int8_t WiFiScanClass::scanNetworks(bool async, bool show_hidden)
{
if(WiFiScanClass::_scanStarted) {
return WIFI_SCAN_RUNNING;
}
WiFiScanClass::_scanAsync = async;
WiFi.enableSTA(true);
scanDelete();
wifi_scan_config_t config;
config.ssid = 0;
config.bssid = 0;
config.channel = 0;
config.show_hidden = show_hidden;
if(esp_wifi_scan_start(&config, WiFiScanClass::_scanAsync) == ESP_OK) {
WiFiScanClass::_scanComplete = false;
WiFiScanClass::_scanStarted = true;
if(WiFiScanClass::_scanAsync) {
return WIFI_SCAN_RUNNING;
}
while(!(WiFiScanClass::_scanComplete)) {
delay(10);
}
return WiFiScanClass::_scanCount;
} else {
return WIFI_SCAN_FAILED;
}
}
/**
* private
* scan callback
* @param result void *arg
* @param status STATUS
*/
void WiFiScanClass::_scanDone()
{
WiFiScanClass::_scanComplete = true;
WiFiScanClass::_scanStarted = false;
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);
} else {
//no memory
WiFiScanClass::_scanCount = 0;
}
}
}
/**
*
* @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
*/
int8_t WiFiScanClass::scanComplete()
{
if(_scanStarted) {
return WIFI_SCAN_RUNNING;
}
if(_scanComplete) {
return WiFiScanClass::_scanCount;
}
return WIFI_SCAN_FAILED;
}
/**
* delete last scan result from RAM
*/
void WiFiScanClass::scanDelete()
{
if(WiFiScanClass::_scanResult) {
delete[] reinterpret_cast<wifi_ap_record_t*>(WiFiScanClass::_scanResult);
WiFiScanClass::_scanResult = 0;
WiFiScanClass::_scanCount = 0;
}
_scanComplete = false;
}
/**
* 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

@@ -1,64 +0,0 @@
/*
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:
int8_t scanNetworks(bool async = false, bool show_hidden = false);
int8_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 _scanDone();
protected:
static bool _scanAsync;
static bool _scanStarted;
static bool _scanComplete;
static uint16_t _scanCount;
static void* _scanResult;
static void * _getScanInfoByIndex(int i);
};
#endif /* ESP32WIFISCAN_H_ */

View File

@@ -1,77 +0,0 @@
/*
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
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();
struct sockaddr_in _client;
int cs = sizeof(struct sockaddr_in);
int client_sock = accept(sockfd, (struct sockaddr *)&_client, (socklen_t*)&cs);
if(client_sock >= 0){
int val = 1;
if(setsockopt(client_sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof(int)) == ESP_OK)
return WiFiClient(client_sock);
}
return WiFiClient();
}
void WiFiServer::begin(){
if(_listening)
return;
struct sockaddr_in server;
sockfd = socket(AF_INET , SOCK_STREAM, 0);
if (sockfd < 0)
return;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
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;
}
void WiFiServer::end(){
close(sockfd);
sockfd = -1;
_listening = false;
}

View File

@@ -1,53 +0,0 @@
/*
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"
class WiFiServer : public Server {
private:
int sockfd;
uint16_t _port;
uint8_t _max_clients;
bool _listening;
public:
void listenOnLocalhost(){}
WiFiServer(uint16_t port=80, uint8_t max_clients=4):sockfd(-1),_port(port),_max_clients(max_clients),_listening(false){}
~WiFiServer(){ end();}
WiFiClient available();
WiFiClient accept(){return available();}
void begin();
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();
operator bool(){return _listening;}
int setTimeout(uint32_t seconds);
void stopAll();
};
#endif /* _WIFISERVER_H_ */

View File

@@ -1,48 +0,0 @@
/*
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_
#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 system_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

@@ -1,277 +0,0 @@
/*
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_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 = server_port;
remote_port = multicast_ip;
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);
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(){
cbuf *b = rx_buffer;
rx_buffer = 0;
delete b;
}
IPAddress WiFiUDP::remoteIP(){
return remote_ip;
}
uint16_t WiFiUDP::remotePort(){
return remote_port;
}

View File

@@ -1,77 +0,0 @@
/*
* 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_ */

View File

@@ -1,76 +0,0 @@
/*
Wifi secure connection example for ESP32
Running on TLS 1.2 using mbedTLS
Suporting the following chipersuites:
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384","TLS_DHE_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_AES_256_CCM","TLS_DHE_RSA_WITH_AES_256_CCM","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384","TLS_DHE_RSA_WITH_AES_256_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA","TLS_DHE_RSA_WITH_AES_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8","TLS_DHE_RSA_WITH_AES_256_CCM_8","TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","TLS_DHE_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CCM","TLS_DHE_RSA_WITH_AES_128_CCM","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256","TLS_DHE_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA","TLS_DHE_RSA_WITH_AES_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8","TLS_DHE_RSA_WITH_AES_128_CCM_8","TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA","TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA","TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA","TLS_DHE_PSK_WITH_AES_256_GCM_SHA384","TLS_DHE_PSK_WITH_AES_256_CCM","TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384","TLS_DHE_PSK_WITH_AES_256_CBC_SHA384","TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA","TLS_DHE_PSK_WITH_AES_256_CBC_SHA","TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_PSK_DHE_WITH_AES_256_CCM_8","TLS_DHE_PSK_WITH_AES_128_GCM_SHA256","TLS_DHE_PSK_WITH_AES_128_CCM","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256","TLS_DHE_PSK_WITH_AES_128_CBC_SHA256","TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA","TLS_DHE_PSK_WITH_AES_128_CBC_SHA","TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_PSK_DHE_WITH_AES_128_CCM_8","TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA","TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA","TLS_RSA_WITH_AES_256_GCM_SHA384","TLS_RSA_WITH_AES_256_CCM","TLS_RSA_WITH_AES_256_CBC_SHA256","TLS_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_RSA_WITH_AES_256_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384","TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA","TLS_RSA_WITH_AES_256_CCM_8","TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256","TLS_RSA_WITH_CAMELLIA_256_CBC_SHA","TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384","TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384","TLS_RSA_WITH_AES_128_GCM_SHA256","TLS_RSA_WITH_AES_128_CCM","TLS_RSA_WITH_AES_128_CBC_SHA256","TLS_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_RSA_WITH_AES_128_CBC_SHA","TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256","TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA","TLS_RSA_WITH_AES_128_CCM_8","TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_WITH_CAMELLIA_128_CBC_SHA","TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256","TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA","TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA","TLS_RSA_PSK_WITH_AES_256_GCM_SHA384","TLS_RSA_PSK_WITH_AES_256_CBC_SHA384","TLS_RSA_PSK_WITH_AES_256_CBC_SHA","TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_RSA_PSK_WITH_AES_128_GCM_SHA256","TLS_RSA_PSK_WITH_AES_128_CBC_SHA256","TLS_RSA_PSK_WITH_AES_128_CBC_SHA","TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA","TLS_PSK_WITH_AES_256_GCM_SHA384","TLS_PSK_WITH_AES_256_CCM","TLS_PSK_WITH_AES_256_CBC_SHA384","TLS_PSK_WITH_AES_256_CBC_SHA","TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384","TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384","TLS_PSK_WITH_AES_256_CCM_8","TLS_PSK_WITH_AES_128_GCM_SHA256","TLS_PSK_WITH_AES_128_CCM","TLS_PSK_WITH_AES_128_CBC_SHA256","TLS_PSK_WITH_AES_128_CBC_SHA","TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256","TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256","TLS_PSK_WITH_AES_128_CCM_8","TLS_PSK_WITH_3DES_EDE_CBC_SHA","TLS_EMPTY_RENEGOTIATION_INFO_SCSV"]
2017 - Evandro Copercini - Apache 2.0 License.
*/
#include <WiFiClientSecure.h>
char ssid[] = "your_network_name"; // your network SSID (name of wifi network)
char pass[] = "your_password"; // your network password
char server[] = "www.howsmyssl.com"; // Server URL
// You can use x.509 certificates if you want
//unsigned char test_ca_cert[] = ""; //For the usage of verifying server
//unsigned char test_client_key[] = ""; //For the usage of verifying client
//unsigned char test_client_cert[] = ""; //For the usage of verifying client
WiFiClientSecure client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
delay(100);
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
// attempt to connect to Wifi network:
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
// wait 1 second for re-trying
delay(1000);
}
Serial.print("Connected to ");
Serial.println(ssid);
Serial.println("\nStarting connection to server...");
if (client.connect(server, 443)) { //client.connect(server, 443, test_ca_cert, test_client_cert, test_client_key)
Serial.println("Connected to server!");
// Make a HTTP request:
client.println("GET https://www.howsmyssl.com/a/check HTTP/1.0");
client.println("Host: www.howsmyssl.com");
client.println("Connection: close");
client.println();
}
else
Serial.println("Connection failed!");
Serial.print("Waiting for response "); //WiFiClientSecure uses a non blocking implementation
while (!client.available()){
delay(50); //
Serial.print(".");
}
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting from server.");
client.stop();
}
}
void loop() {
// do nothing
}

View File

@@ -1,35 +0,0 @@
#######################################
# Syntax Coloring Map For WiFi
#######################################
#######################################
# Library (KEYWORD3)
#######################################
WiFiClientSecure KEYWORD3
#######################################
# Datatypes (KEYWORD1)
#######################################
WiFiClientSecure KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
connect KEYWORD2
write KEYWORD2
available KEYWORD2
config KEYWORD2
read KEYWORD2
flush KEYWORD2
stop KEYWORD2
connected KEYWORD2
setCACert KEYWORD2
setCertificate KEYWORD2
setPrivateKey KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@@ -1,9 +0,0 @@
name=WiFiClientSecure
version=1.0
author=Evandro Luis Copercini
maintainer=Github Community
sentence=Enables secure network connection (local and Internet) using the ESP32 built-in WiFi.
paragraph=With this library you can make a TLS or SSL connection to a remote server.
category=Communication
url=
architectures=esp32

View File

@@ -1,190 +0,0 @@
/*
WiFiClientSecure.cpp - Client Secure class for ESP32
Copyright (c) 2016 Hristo Gochkov All right reserved.
Additions Copyright (C) 2017 Evandro Luis Copercini.
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 "WiFiClientSecure.h"
#include <lwip/sockets.h>
#include <lwip/netdb.h>
#include <errno.h>
#undef connect
#undef write
#undef read
WiFiClientSecure::WiFiClientSecure()
{
_connected = false;
sslclient = new sslclient_context;
ssl_init(sslclient);
sslclient->socket = -1;
_CA_cert = NULL;
_cert = NULL;
_private_key = NULL;
}
WiFiClientSecure::WiFiClientSecure(int sock)
{
_connected = false;
sslclient = new sslclient_context;
ssl_init(sslclient);
sslclient->socket = sock;
if (sock >= 0) {
_connected = true;
}
_CA_cert = NULL;
_cert = NULL;
_private_key = NULL;
}
WiFiClientSecure::~WiFiClientSecure()
{
stop();
}
WiFiClientSecure &WiFiClientSecure::operator=(const WiFiClientSecure &other)
{
stop();
sslclient->socket = other.sslclient->socket;
_connected = other._connected;
return *this;
}
void WiFiClientSecure::stop()
{
if (_connected && sslclient->socket >= 0) {
stop_ssl_socket(sslclient, _CA_cert, _cert, _private_key);
sslclient->socket = -1;
_connected = false;
}
}
int WiFiClientSecure::connect(IPAddress ip, uint16_t port)
{
return connect(ip, port, _CA_cert, _cert, _private_key);
}
int WiFiClientSecure::connect(const char *host, uint16_t port)
{
return connect(host, port, _CA_cert, _cert, _private_key);
}
int WiFiClientSecure::connect(IPAddress ip, uint16_t port, unsigned char *_CA_cert, unsigned char *_cert, unsigned char *_private_key)
{
int ret = start_ssl_client(sslclient, ip, port, _CA_cert, _cert, _private_key);
if (ret < 0) {
log_e("lwip_connect_r: %d", errno);
}
_connected = true;
return 1;
}
int WiFiClientSecure::connect(const char *host, uint16_t port, unsigned char *_CA_cert, unsigned char *_cert, unsigned char *_private_key)
{
struct hostent *server;
server = gethostbyname(host);
if (server == NULL) {
return 0;
}
IPAddress srv((const uint8_t *)(server->h_addr));
return connect(srv, port, _CA_cert, _cert, _private_key);
}
size_t WiFiClientSecure::write(uint8_t data)
{
return write(&data, 1);
}
int WiFiClientSecure::read()
{
uint8_t data = 0;
int res = read(&data, 1);
if (res < 0) {
return res;
}
return data;
}
size_t WiFiClientSecure::write(const uint8_t *buf, size_t size)
{
if (!_connected) {
return 0;
}
int res = send_ssl_data(sslclient, buf, size);
if (res < 0) {
log_e("%d", errno);
stop();
res = 0;
}
return res;
}
int WiFiClientSecure::read(uint8_t *buf, size_t size)
{
if (!available()) {
return -1;
}
int res = get_ssl_receive(sslclient, buf, size);
if (res < 0 && errno != EWOULDBLOCK) {
printf("%d", errno);
stop();
}
return res;
}
int WiFiClientSecure::available()
{
if (!_connected) {
return 0;
}
int res = data_to_read(sslclient);
return res;
}
uint8_t WiFiClientSecure::connected()
{
uint8_t dummy = 0;
read(&dummy, 0);
return _connected;
}
void WiFiClientSecure::setCACert(unsigned char *rootCA)
{
_CA_cert = rootCA;
}
void WiFiClientSecure::setCertificate (unsigned char *client_ca)
{
_cert = client_ca;
}
void WiFiClientSecure::setPrivateKey (unsigned char *private_key)
{
_private_key = private_key;
}

View File

@@ -1,92 +0,0 @@
/*
WiFiClientSecure.h - Base class that provides Client SSL to ESP32
Copyright (c) 2011 Adrian McEwen. All right reserved.
Additions Copyright (C) 2017 Evandro Luis Copercini.
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 WiFiClientSecure_h
#define WiFiClientSecure_h
#include "Arduino.h"
#include "IPAddress.h"
#include <WiFi.h>
#include "ssl_client.h"
class WiFiClientSecure : public Client
{
protected:
bool _connected;
sslclient_context *sslclient;
unsigned char *_CA_cert;
unsigned char *_cert;
unsigned char *_private_key;
public:
WiFiClientSecure *next;
WiFiClientSecure();
WiFiClientSecure(int socket);
~WiFiClientSecure();
int connect(IPAddress ip, uint16_t port);
int connect(const char *host, uint16_t port);
int connect(IPAddress ip, uint16_t port, unsigned char *rootCABuff, unsigned char *cli_cert, unsigned char *cli_key);
int connect(const char *host, uint16_t port, unsigned char *rootCABuff, unsigned char *cli_cert, unsigned char *cli_key);
size_t write(uint8_t data);
size_t write(const uint8_t *buf, size_t size);
int available();
int read();
int read(uint8_t *buf, size_t size);
int peek()
{
return 0;
}
void flush() {}
void stop();
uint8_t connected();
void setCACert(unsigned char *rootCA);
void setCertificate(unsigned char *client_ca);
void setPrivateKey (unsigned char *private_key);
operator bool()
{
return connected();
}
WiFiClientSecure &operator=(const WiFiClientSecure &other);
bool operator==(const bool value)
{
return bool() == value;
}
bool operator!=(const bool value)
{
return bool() != value;
}
bool operator==(const WiFiClientSecure &);
bool operator!=(const WiFiClientSecure &rhs)
{
return !this->operator==(rhs);
};
int socket()
{
return sslclient->socket = -1;
}
//friend class WiFiServer;
using Print::write;
};
#endif /* _WIFICLIENT_H_ */

View File

@@ -1,327 +0,0 @@
/* Provide SSL/TLS functions to ESP32 with Arduino IDE
*
* Adapted from the ssl_client1 example in mbedtls.
*
* Original Copyright (C) 2006-2015, ARM Limited, All Rights Reserved, Apache 2.0 License.
* Additions Copyright (C) 2017 Evandro Luis Copercini, Apache 2.0 License.
*/
#include "Arduino.h"
#include <lwip/sockets.h>
#include <lwip/err.h>
#include <lwip/sockets.h>
#include <lwip/sys.h>
#include <lwip/netdb.h>
#include "ssl_client.h"
const char *pers = "esp32-tls";
#define DEBUG true //Set false to supress debug messages
#ifdef DEBUG
#define DEBUG_PRINT(...) printf( __VA_ARGS__ )
#else
#define DEBUG_PRINT(x)
#endif
#ifdef MBEDTLS_DEBUG_C
#define MBEDTLS_DEBUG_LEVEL 4
/* mbedtls debug function that translates mbedTLS debug output
to ESP_LOGx debug output.
MBEDTLS_DEBUG_LEVEL 4 means all mbedTLS debug output gets sent here,
and then filtered to the ESP logging mechanism.
*/
static void mbedtls_debug(void *ctx, int level,
const char *file, int line,
const char *str)
{
const char *MBTAG = "mbedtls";
char *file_sep;
/* Shorten 'file' from the whole file path to just the filename
This is a bit wasteful because the macros are compiled in with
the full _FILE_ path in each case.
*/
file_sep = rindex(file, '/');
if (file_sep) {
file = file_sep + 1;
}
switch (level) {
case 1:
printf( "%s:%d %s \n", file, line, str);
break;
case 2:
case 3:
printf( "%s:%d %s \n", file, line, str);
case 4:
printf( "%s:%d %s \n", file, line, str);
break;
default:
printf( "Unexpected log level %d: %s \n", level, str);
break;
}
}
#endif
void ssl_init(sslclient_context *ssl_client)
{
/*
* Initialize the RNG and the session data
*/
mbedtls_ssl_init(&ssl_client->ssl_ctx);
mbedtls_ssl_config_init(&ssl_client->ssl_conf);
mbedtls_ctr_drbg_init(&ssl_client->drbg_ctx);
}
int start_ssl_client(sslclient_context *ssl_client, uint32_t ipAddress, uint32_t port, unsigned char *rootCABuff, unsigned char *cli_cert, unsigned char *cli_key)
{
char buf[512];
int ret, flags, len, timeout;
int enable = 1;
DEBUG_PRINT("Free heap before TLS %u\n", xPortGetFreeHeapSize());
do {
ssl_client->socket = -1;
ssl_client->socket = lwip_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ssl_client->socket < 0) {
printf("\r\nERROR opening socket\r\n");
return ssl_client->socket;
}
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = ipAddress;
serv_addr.sin_port = htons(port);
if (lwip_connect(ssl_client->socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == 0) {
timeout = 30000;
lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
lwip_setsockopt(ssl_client->socket, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable));
lwip_setsockopt(ssl_client->socket, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable));
} else {
printf("\r\nConnect to Server failed!\r\n");
ret = -1;
break;
}
fcntl( ssl_client->socket, F_SETFL, fcntl( ssl_client->socket, F_GETFL, 0 ) | O_NONBLOCK );
DEBUG_PRINT( "Seeding the random number generator\n");
mbedtls_entropy_init(&ssl_client->entropy_ctx);
if ((ret = mbedtls_ctr_drbg_seed(&ssl_client->drbg_ctx, mbedtls_entropy_func,
&ssl_client->entropy_ctx, (const unsigned char *) pers, strlen(pers))) != 0) {
printf( "mbedtls_ctr_drbg_seed returned %d \n", ret);
break;
}
/* MBEDTLS_SSL_VERIFY_REQUIRED if a CA certificate is defined on Arduino IDE and
MBEDTLS_SSL_VERIFY_NONE if not.
*/
if (rootCABuff != NULL) {
DEBUG_PRINT( "Loading CA cert\n");
mbedtls_x509_crt_init(&ssl_client->ca_cert);
mbedtls_ssl_conf_authmode(&ssl_client->ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED);
ret = mbedtls_x509_crt_parse(&ssl_client->ca_cert, (const unsigned char *)rootCABuff, strlen((const char *)rootCABuff) + 1);
mbedtls_ssl_conf_ca_chain(&ssl_client->ssl_conf, &ssl_client->ca_cert, NULL);
//mbedtls_ssl_conf_verify(&ssl_client->ssl_ctx, my_verify, NULL );
if (ret < 0) {
printf( "CA cert: mbedtls_x509_crt_parse returned -0x%x\n\n", -ret);
break;
}
} else {
mbedtls_ssl_conf_authmode(&ssl_client->ssl_conf, MBEDTLS_SSL_VERIFY_NONE);
}
if (cli_cert != NULL && cli_key != NULL) {
mbedtls_x509_crt_init(&ssl_client->client_cert);
mbedtls_pk_init(&ssl_client->client_key);
DEBUG_PRINT( "Loading CRT cert\n");
ret = mbedtls_x509_crt_parse(&ssl_client->client_cert, (const unsigned char *)cli_cert, strlen((const char *)cli_cert) + 1);
if (ret < 0) {
printf( "CRT cert: mbedtls_x509_crt_parse returned -0x%x\n\n", -ret);
break;
}
DEBUG_PRINT( "Loading private key\n");
ret = mbedtls_pk_parse_key(&ssl_client->client_key, (const unsigned char *)cli_key, strlen((const char *)cli_key) + 1, NULL, 0);
if (ret < 0) {
printf( "PRIVATE KEY: mbedtls_x509_crt_parse returned -0x%x\n\n", -ret);
break;
}
mbedtls_ssl_conf_own_cert(&ssl_client->ssl_conf, &ssl_client->client_cert, &ssl_client->client_key);
}
/*
// TODO: implement match CN verification
DEBUG_PRINT( "Setting hostname for TLS session...\n");
// Hostname set here should match CN in server certificate
if((ret = mbedtls_ssl_set_hostname(&ssl_client->ssl_ctx, host)) != 0)
{
printf( "mbedtls_ssl_set_hostname returned -0x%x\n", -ret);
break;
}
*/
DEBUG_PRINT( "Setting up the SSL/TLS structure...\n");
if ((ret = mbedtls_ssl_config_defaults(&ssl_client->ssl_conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
printf( "mbedtls_ssl_config_defaults returned %d\n", ret);
break;
}
mbedtls_ssl_conf_rng(&ssl_client->ssl_conf, mbedtls_ctr_drbg_random, &ssl_client->drbg_ctx);
#ifdef MBEDTLS_DEBUG_C
mbedtls_debug_set_threshold(MBEDTLS_DEBUG_LEVEL);
mbedtls_ssl_conf_dbg(&ssl_client->ssl_conf, mbedtls_debug, NULL);
#endif
if ((ret = mbedtls_ssl_setup(&ssl_client->ssl_ctx, &ssl_client->ssl_conf)) != 0) {
printf( "mbedtls_ssl_setup returned -0x%x\n\n", -ret);
break;
}
mbedtls_ssl_set_bio(&ssl_client->ssl_ctx, &ssl_client->socket, mbedtls_net_send, mbedtls_net_recv, NULL );
DEBUG_PRINT( "Performing the SSL/TLS handshake...\n");
while ((ret = mbedtls_ssl_handshake(&ssl_client->ssl_ctx)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret != -76) {
printf( "mbedtls_ssl_handshake returned -0x%x\n", -ret);
break;
}
delay(10);
vPortYield();
}
if (cli_cert != NULL && cli_key != NULL) {
DEBUG_PRINT("Protocol is %s \nCiphersuite is %s\n", mbedtls_ssl_get_version(&ssl_client->ssl_ctx), mbedtls_ssl_get_ciphersuite(&ssl_client->ssl_ctx));
if ((ret = mbedtls_ssl_get_record_expansion(&ssl_client->ssl_ctx)) >= 0) {
DEBUG_PRINT("Record expansion is %d\n", ret);
} else {
DEBUG_PRINT("Record expansion is unknown (compression)\n");
}
}
DEBUG_PRINT( "Verifying peer X.509 certificate...\n");
if ((flags = mbedtls_ssl_get_verify_result(&ssl_client->ssl_ctx)) != 0) {
printf( "Failed to verify peer certificate!\n");
bzero(buf, sizeof(buf));
mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags);
printf( "verification info: %s\n", buf);
stop_ssl_socket(ssl_client, rootCABuff, cli_cert, cli_key); //It's not safe continue.
} else {
DEBUG_PRINT( "Certificate verified.\n");
}
} while (0);
DEBUG_PRINT("Free heap after TLS %u\n", xPortGetFreeHeapSize());
return ssl_client->socket;
}
void stop_ssl_socket(sslclient_context *ssl_client, unsigned char *rootCABuff, unsigned char *cli_cert, unsigned char *cli_key)
{
DEBUG_PRINT( "\nCleaning SSL connection.\n");
close(ssl_client->socket);
ssl_client->socket = -1;
mbedtls_ssl_free(&ssl_client->ssl_ctx);
mbedtls_ssl_config_free(&ssl_client->ssl_conf);
mbedtls_ctr_drbg_free(&ssl_client->drbg_ctx);
mbedtls_entropy_free(&ssl_client->entropy_ctx);
if (rootCABuff != NULL) {
mbedtls_x509_crt_free(&ssl_client->ca_cert);
}
if (cli_cert != NULL) {
mbedtls_x509_crt_free(&ssl_client->client_cert);
}
if (cli_key != NULL) {
mbedtls_pk_free(&ssl_client->client_key);
}
}
int data_to_read(sslclient_context *ssl_client)
{
int ret, res;
ret = mbedtls_ssl_read(&ssl_client->ssl_ctx, NULL, 0);
//printf("RET: %i\n",ret); //for low level debug
res = mbedtls_ssl_get_bytes_avail(&ssl_client->ssl_ctx);
//printf("RES: %i\n",res);
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret < 0 && ret != -76) {
printf("MbedTLS error %i", ret);
}
return res;
}
int send_ssl_data(sslclient_context *ssl_client, const uint8_t *data, uint16_t len)
{
//DEBUG_PRINT( "Writing HTTP request...\n"); //for low level debug
int ret = -1;
while ((ret = mbedtls_ssl_write(&ssl_client->ssl_ctx, data, len)) <= 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret != -76) {
printf( "mbedtls_ssl_write returned -0x%x\n", -ret);
break;
}
}
len = ret;
//DEBUG_PRINT( "%d bytes written\n", len); //for low level debug
return ret;
}
int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length)
{
//DEBUG_PRINT( "Reading HTTP response...\n"); //for low level debug
int ret = -1;
ret = mbedtls_ssl_read(&ssl_client->ssl_ctx, data, length);
//DEBUG_PRINT( "%d bytes readed\n", ret); //for low level debug
return ret;
}

View File

@@ -1,37 +0,0 @@
/* Provide SSL/TLS functions to ESP32 with Arduino IDE
* by Evandro Copercini - 2017 - Apache 2.0 License
*/
#ifndef ARD_SSL_H
#define ARD_SSL_H
#include "mbedtls/platform.h"
#include "mbedtls/net.h"
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
typedef struct sslclient_context {
int socket;
mbedtls_net_context net_ctx;
mbedtls_ssl_context ssl_ctx;
mbedtls_ssl_config ssl_conf;
mbedtls_ctr_drbg_context drbg_ctx;
mbedtls_entropy_context entropy_ctx;
mbedtls_x509_crt ca_cert;
mbedtls_x509_crt client_cert;
mbedtls_pk_context client_key;
} sslclient_context;
void ssl_init(sslclient_context *ssl_client);
int start_ssl_client(sslclient_context *ssl_client, uint32_t ipAddress, uint32_t port, unsigned char *rootCABuff, unsigned char *cli_cert, unsigned char *cli_key);
void stop_ssl_socket(sslclient_context *ssl_client, unsigned char *rootCABuff, unsigned char *cli_cert, unsigned char *cli_key);
int data_to_read(sslclient_context *ssl_client);
int send_ssl_data(sslclient_context *ssl_client, const uint8_t *data, uint16_t len);
int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length);
#endif

View File

@@ -1,33 +0,0 @@
#######################################
# Syntax Coloring Map For Wire
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
setClock KEYWORD2
setClockStretchLimit KEYWORD2
beginTransmission KEYWORD2
endTransmission KEYWORD2
requestFrom KEYWORD2
send KEYWORD2
receive KEYWORD2
onReceive KEYWORD2
onRequest KEYWORD2
#######################################
# Instances (KEYWORD2)
#######################################
Wire KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@@ -1,9 +0,0 @@
name=Wire
version=1.0
author=Hristo Gochkov
maintainer=Hristo Gochkov <hristo@espressif.com>
sentence=Allows the communication between devices or sensors connected via Two Wire Interface Bus. For esp8266 boards.
paragraph=
category=Signal Input/Output
url=http://arduino.cc/en/Reference/Wire
architectures=esp32

View File

@@ -1,214 +0,0 @@
/*
TwoWire.cpp - TWI/I2C library for Arduino & Wiring
Copyright (c) 2006 Nicholas Zambetti. 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
Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts
Modified December 2014 by Ivan Grokhotkov (ivan@esp8266.com) - esp8266 support
Modified April 2015 by Hrsto Gochkov (ficeto@ficeto.com) - alternative esp8266 support
*/
extern "C" {
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
}
#include "esp32-hal-i2c.h"
#include "Wire.h"
#include "Arduino.h"
TwoWire::TwoWire(uint8_t bus_num)
:num(bus_num & 1)
,sda(-1)
,scl(-1)
,i2c(NULL)
,rxIndex(0)
,rxLength(0)
,txIndex(0)
,txLength(0)
,txAddress(0)
,transmitting(0)
{}
void TwoWire::begin(int sdaPin, int sclPin, uint32_t frequency)
{
if(sdaPin < 0) {
if(num == 0) {
sdaPin = SDA;
} else {
return;
}
}
if(sclPin < 0) {
if(num == 0) {
sclPin = SCL;
} else {
return;
}
}
if(i2c == NULL) {
i2c = i2cInit(num, 0, false);
if(i2c == NULL) {
return;
}
}
i2cSetFrequency(i2c, frequency);
if(sda >= 0 && sda != sdaPin) {
i2cDetachSDA(i2c, sda);
}
if(scl >= 0 && scl != sclPin) {
i2cDetachSCL(i2c, scl);
}
sda = sdaPin;
scl = sclPin;
i2cAttachSDA(i2c, sda);
i2cAttachSCL(i2c, scl);
flush();
i2cInitFix(i2c);
}
void TwoWire::setClock(uint32_t frequency)
{
i2cSetFrequency(i2c, frequency);
}
size_t TwoWire::requestFrom(uint8_t address, size_t size, bool sendStop)
{
if(size > I2C_BUFFER_LENGTH) {
size = I2C_BUFFER_LENGTH;
}
size_t read = (i2cRead(i2c, address, false, rxBuffer, size, sendStop) == 0)?size:0;
rxIndex = 0;
rxLength = read;
return read;
}
uint8_t TwoWire::endTransmission(uint8_t sendStop)
{
int8_t ret = i2cWrite(i2c, txAddress, false, txBuffer, txLength, sendStop);
txIndex = 0;
txLength = 0;
transmitting = 0;
return ret;
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
{
return requestFrom(address, static_cast<size_t>(quantity), static_cast<bool>(sendStop));
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
return requestFrom(address, static_cast<size_t>(quantity), true);
}
uint8_t TwoWire::requestFrom(int address, int quantity)
{
return requestFrom(static_cast<uint8_t>(address), static_cast<size_t>(quantity), true);
}
uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
{
return requestFrom(static_cast<uint8_t>(address), static_cast<size_t>(quantity), static_cast<bool>(sendStop));
}
void TwoWire::beginTransmission(uint8_t address)
{
transmitting = 1;
txAddress = address;
txIndex = 0;
txLength = 0;
}
void TwoWire::beginTransmission(int address)
{
beginTransmission((uint8_t)address);
}
uint8_t TwoWire::endTransmission(void)
{
return endTransmission(true);
}
size_t TwoWire::write(uint8_t data)
{
if(transmitting) {
if(txLength >= I2C_BUFFER_LENGTH) {
return 0;
}
txBuffer[txIndex] = data;
++txIndex;
txLength = txIndex;
}
return 1;
}
size_t TwoWire::write(const uint8_t *data, size_t quantity)
{
if(transmitting) {
for(size_t i = 0; i < quantity; ++i) {
if(!write(data[i])) {
return i;
}
}
}
return quantity;
}
int TwoWire::available(void)
{
int result = rxLength - rxIndex;
return result;
}
int TwoWire::read(void)
{
int value = -1;
if(rxIndex < rxLength) {
value = rxBuffer[rxIndex];
++rxIndex;
}
return value;
}
int TwoWire::peek(void)
{
int value = -1;
if(rxIndex < rxLength) {
value = rxBuffer[rxIndex];
}
return value;
}
void TwoWire::flush(void)
{
rxIndex = 0;
rxLength = 0;
txIndex = 0;
txLength = 0;
}
TwoWire Wire = TwoWire(0);

View File

@@ -1,99 +0,0 @@
/*
TwoWire.h - TWI/I2C library for Arduino & Wiring
Copyright (c) 2006 Nicholas Zambetti. 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
Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts
Modified December 2014 by Ivan Grokhotkov (ivan@esp8266.com) - esp8266 support
Modified April 2015 by Hrsto Gochkov (ficeto@ficeto.com) - alternative esp8266 support
*/
#ifndef TwoWire_h
#define TwoWire_h
#include <esp32-hal.h>
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "Stream.h"
#define I2C_BUFFER_LENGTH 128
class TwoWire: public Stream
{
protected:
uint8_t num;
int8_t sda;
int8_t scl;
i2c_t * i2c;
uint8_t rxBuffer[I2C_BUFFER_LENGTH];
uint16_t rxIndex;
uint16_t rxLength;
uint8_t txBuffer[I2C_BUFFER_LENGTH];
uint16_t txIndex;
uint16_t txLength;
uint8_t txAddress;
uint8_t transmitting;
public:
TwoWire(uint8_t bus_num);
void begin(int sda=-1, int scl=-1, uint32_t frequency=100000);
void setClock(uint32_t);
void beginTransmission(uint8_t);
void beginTransmission(int);
uint8_t endTransmission(void);
uint8_t endTransmission(uint8_t);
size_t requestFrom(uint8_t address, size_t size, bool sendStop);
uint8_t requestFrom(uint8_t, uint8_t);
uint8_t requestFrom(uint8_t, uint8_t, uint8_t);
uint8_t requestFrom(int, int);
uint8_t requestFrom(int, int, int);
size_t write(uint8_t);
size_t write(const uint8_t *, size_t);
int available(void);
int read(void);
int peek(void);
void flush(void);
inline size_t write(const char * s)
{
return write((uint8_t*) s, strlen(s));
}
inline size_t write(unsigned long n)
{
return write((uint8_t)n);
}
inline size_t write(long n)
{
return write((uint8_t)n);
}
inline size_t write(unsigned int n)
{
return write((uint8_t)n);
}
inline size_t write(int n)
{
return write((uint8_t)n);
}
};
extern TwoWire Wire;
#endif

View File

@@ -3,16 +3,14 @@
[common] [common]
framework = arduino framework = arduino
platform = espressif8266 platform = platformio/espressif8266@2.6.3
board = esp12e board = esp12e
upload_speed = 921600 upload_speed = 921600
monitor_baud = 115200 monitor_speed = 115200
lib_deps = lib_deps =
Hash arkhipenko/TaskScheduler@^3.8.5
TaskScheduler ArduinoJson@5.13.4
SPIFFS https://gitlab.com/wirelos/sprocket-lib.git#master
ArduinoJson
https://gitlab.com/wirelos/sprocket-lib.git#develop
[env:analog] [env:analog]
@@ -20,8 +18,8 @@ platform = ${common.platform}
board = ${common.board} board = ${common.board}
framework = ${common.framework} framework = ${common.framework}
upload_speed = ${common.upload_speed} upload_speed = ${common.upload_speed}
monitor_baud = ${common.monitor_baud} monitor_speed = ${common.monitor_speed}
src_filter = +<*> -<examples/> +<examples/analog/> -<inputs/> +<inputs/analog> build_src_filter = +<*> -<examples/> +<examples/analog/> -<inputs/> +<inputs/analog>
lib_deps = ${common.lib_deps} lib_deps = ${common.lib_deps}
[env:pir] [env:pir]
@@ -29,9 +27,9 @@ platform = ${common.platform}
board = ${common.board} board = ${common.board}
framework = ${common.framework} framework = ${common.framework}
upload_speed = ${common.upload_speed} upload_speed = ${common.upload_speed}
monitor_baud = ${common.monitor_baud} monitor_speed = ${common.monitor_speed}
build_flags = -DSPROCKET_PRINT=1 build_flags = -DSPROCKET_PRINT=1
src_filter = +<*> -<examples/> +<examples/pir/> -<inputs/> +<inputs/pir> +<inputs/digital> build_src_filter = +<*> -<examples/> +<examples/pir/> -<inputs/> +<inputs/pir> +<inputs/digital>
lib_deps = ${common.lib_deps} lib_deps = ${common.lib_deps}
[env:audio] [env:audio]
@@ -39,8 +37,8 @@ platform = ${common.platform}
board = ${common.board} board = ${common.board}
framework = ${common.framework} framework = ${common.framework}
upload_speed = ${common.upload_speed} upload_speed = ${common.upload_speed}
monitor_baud = ${common.monitor_baud} monitor_speed = ${common.monitor_speed}
src_filter = +<*> -<examples/> +<examples/audio/> -<inputs/> +<inputs/audio> build_src_filter = +<*> -<examples/> +<examples/audio/> -<inputs/> +<inputs/audio>
lib_deps = ${common.lib_deps} lib_deps = ${common.lib_deps}
[env:analog_esp32] [env:analog_esp32]
@@ -49,36 +47,6 @@ board = esp32dev
framework = ${common.framework} framework = ${common.framework}
build_flags = -std=c++14 build_flags = -std=c++14
upload_speed = ${common.upload_speed} upload_speed = ${common.upload_speed}
monitor_baud = ${common.monitor_baud} monitor_speed = ${common.monitor_speed}
src_filter = +<*> -<examples/> +<examples/analog/> -<inputs/> +<inputs/analog> build_src_filter = +<*> -<examples/> +<examples/analog/> -<inputs/> +<inputs/analog>
lib_deps = ${common.lib_deps} lib_deps = ${common.lib_deps}
[env:rotary_ec11]
platform = ${common.platform}
board = ${common.board}
framework = ${common.framework}
upload_speed = ${common.upload_speed}
monitor_baud = ${common.monitor_baud}
src_filter = +<*> -<examples/> +<examples/rotary/> -<inputs/> +<inputs/rotary>
lib_deps = ${common.lib_deps}
lib_ignore = Ai Esp32 Rotary Encoder
[env:rotary_esp32]
platform = espressif32
board = esp32dev
framework = ${common.framework}
build_flags = -std=c++14
upload_speed = ${common.upload_speed}
monitor_baud = ${common.monitor_baud}
src_filter = +<*> -<examples/> +<examples/rotary/> -<inputs/> +<inputs/rotary>
[env:combined_esp32]
platform = espressif32
board = esp32dev
framework = ${common.framework}
build_flags = -std=c++14
upload_speed = ${common.upload_speed}
monitor_baud = ${common.monitor_baud}
src_filter = +<*> +<inputs/analog> +<inputs/rotary> -<examples/> +<examples/combined/>
lib_deps = ${common.lib_deps}

View File

@@ -1,38 +0,0 @@
#include "RotaryPlugin.h"
RotaryPlugin::RotaryPlugin(RotaryConfig cfg)
{
config = cfg;
rotaryEncoder = new AiEsp32RotaryEncoder(config.pinA, config.pinB, config.pinButton, config.pinVcc);
rotaryEncoder->begin();
rotaryEncoder->setBoundaries(config.lowerBound, config.upperBound, config.circulateValues);
}
void RotaryPlugin::activate(Scheduler *userScheduler)
{
// add update task
inputTask.set(TASK_MILLISECOND * config.updateInterval, TASK_FOREVER, std::bind(&RotaryPlugin::checkInput, this));
userScheduler->addTask(inputTask);
inputTask.enable();
// add dummy subscription
subscribe(config.topic, [](String msg){});
subscribe(String(config.topic) + "/btn", [](String msg){});
PRINT_MSG(Serial, "PLUGIN", "RotaryPlugin activated");
}
void RotaryPlugin::checkInput()
{
rotaryEncoder->enable();
if (rotaryEncoder->encoderChanged())
{
int encReading = rotaryEncoder->readEncoder();
publish(config.topic, String(encReading));
}
ButtonState newBtnState = rotaryEncoder->currentButtonState();
if(newBtnState != btnState){
btnState = newBtnState;
publish(String(config.topic) + String("/btn"), String(btnState));
}
}

View File

@@ -1,45 +0,0 @@
#ifndef __ROTARY_PLUGIN_H__
#define __ROTARY_PLUGIN_H__
#define _TASK_SLEEP_ON_IDLE_RUN
#define _TASK_STD_FUNCTION
#include <functional>
#include <vector>
#include <FS.h>
#include <TaskSchedulerDeclarations.h>
#include <Plugin.h>
#include <utils/print.h>
#include <utils/misc.h>
#include "AiEsp32RotaryEncoder.h"
using namespace std;
using namespace std::placeholders;
struct RotaryConfig
{
int pinA;
int pinB;
int pinButton;
int pinVcc;
int updateInterval;
int lowerBound;
int upperBound;
bool circulateValues;
const char* topic;
//const char* topicButton;
};
class RotaryPlugin : public Plugin {
public:
Task inputTask;
int currentVal = 0;
ButtonState btnState = BUT_RELEASED;
AiEsp32RotaryEncoder* rotaryEncoder;
RotaryConfig config;
RotaryPlugin(RotaryConfig cfg);
void activate(Scheduler* userScheduler);
void checkInput();
};
#endif