initial import

This commit is contained in:
me-no-dev 2016-10-06 14:21:30 +03:00 committed by Ivan Grokhotkov
parent 668acc2c08
commit 5f3a205955
657 changed files with 170176 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
tools/xtensa-esp32-elf

42
boards.txt Normal file
View File

@ -0,0 +1,42 @@
menu.UploadSpeed=Upload Speed
menu.FlashFreq=Flash Frequency
##############################################################
esp32.name=ESP32 Dev Module
esp32.upload.tool=esptool
esp32.upload.maximum_size=1044464
esp32.upload.maximum_data_size=114688
esp32.upload.wait_for_upload_port=true
esp32.serial.disableDTR=true
esp32.serial.disableRTS=true
esp32.build.mcu=esp32
esp32.build.core=esp32
esp32.build.variant=esp32
esp32.build.board=ESP32_DEV
esp32.build.f_cpu=160000000L
esp32.build.flash_mode=dio
esp32.build.flash_size=4MB
esp32.menu.FlashFreq.80=80MHz
esp32.menu.FlashFreq.80.build.flash_freq=80m
esp32.menu.FlashFreq.40=40MHz
esp32.menu.FlashFreq.40.build.flash_freq=40m
esp32.menu.UploadSpeed.921600=921600
esp32.menu.UploadSpeed.921600.upload.speed=921600
esp32.menu.UploadSpeed.115200=115200
esp32.menu.UploadSpeed.115200.upload.speed=115200
esp32.menu.UploadSpeed.256000.windows=256000
esp32.menu.UploadSpeed.256000.upload.speed=256000
esp32.menu.UploadSpeed.230400.windows.upload.speed=256000
esp32.menu.UploadSpeed.230400=230400
esp32.menu.UploadSpeed.230400.upload.speed=230400
esp32.menu.UploadSpeed.460800.linux=460800
esp32.menu.UploadSpeed.460800.macosx=460800
esp32.menu.UploadSpeed.460800.upload.speed=460800
esp32.menu.UploadSpeed.512000.windows=512000
esp32.menu.UploadSpeed.512000.upload.speed=512000

63
cores/esp32/Arduino.h Normal file
View File

@ -0,0 +1,63 @@
/*
Arduino.h - Main include file for the Arduino SDK
Copyright (c) 2005-2013 Arduino Team. 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 Arduino_h
#define Arduino_h
#ifdef __cplusplus
extern "C" {
#endif
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp32-hal.h"
#include "pins_arduino.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
typedef bool boolean;
typedef uint8_t byte;
#include "binary.h"
#ifdef __cplusplus
}
#endif
#include "WCharacter.h"
#include "WString.h"
#include "Stream.h"
#include "Printable.h"
#include "Print.h"
#include "IPAddress.h"
#include "Client.h"
#include "Server.h"
#include "Udp.h"
#include "HardwareSerial.h"
#include "Esp.h"
#endif /* _ESP32_CORE_ARDUINO_H_ */

48
cores/esp32/Client.h Normal file
View File

@ -0,0 +1,48 @@
/*
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 client_h
#define client_h
#include "Print.h"
#include "Stream.h"
#include "IPAddress.h"
class Client: public Stream
{
public:
virtual int connect(IPAddress ip, uint16_t port) =0;
virtual int connect(const char *host, uint16_t port) =0;
virtual size_t write(uint8_t) =0;
virtual size_t write(const uint8_t *buf, size_t size) =0;
virtual int available() = 0;
virtual int read() = 0;
virtual int read(uint8_t *buf, size_t size) = 0;
virtual int peek() = 0;
virtual void flush() = 0;
virtual void stop() = 0;
virtual uint8_t connected() = 0;
virtual operator bool() = 0;
protected:
uint8_t* rawIPAddress(IPAddress& addr)
{
return addr.raw_address();
}
};
#endif

223
cores/esp32/Esp.cpp Normal file
View File

@ -0,0 +1,223 @@
/*
Esp.cpp - ESP31B-specific APIs
Copyright (c) 2015 Ivan Grokhotkov. All rights 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 "Arduino.h"
#include "Esp.h"
#include "rom/spi_flash.h"
#include <memory>
//#define DEBUG_SERIAL Serial
/**
* User-defined Literals
* usage:
*
* uint32_t = test = 10_MHz; // --> 10000000
*/
unsigned long long operator"" _kHz(unsigned long long x)
{
return x * 1000;
}
unsigned long long operator"" _MHz(unsigned long long x)
{
return x * 1000 * 1000;
}
unsigned long long operator"" _GHz(unsigned long long x)
{
return x * 1000 * 1000 * 1000;
}
unsigned long long operator"" _kBit(unsigned long long x)
{
return x * 1024;
}
unsigned long long operator"" _MBit(unsigned long long x)
{
return x * 1024 * 1024;
}
unsigned long long operator"" _GBit(unsigned long long x)
{
return x * 1024 * 1024 * 1024;
}
unsigned long long operator"" _kB(unsigned long long x)
{
return x * 1024;
}
unsigned long long operator"" _MB(unsigned long long x)
{
return x * 1024 * 1024;
}
unsigned long long operator"" _GB(unsigned long long x)
{
return x * 1024 * 1024 * 1024;
}
EspClass ESP;
uint32_t EspClass::getCycleCount()
{
uint32_t ccount;
__asm__ __volatile__("esync; rsr %0,ccount":"=a" (ccount));
return ccount;
}
void EspClass::restart(void)
{
system_restart();
}
uint32_t EspClass::getFreeHeap(void)
{
return system_get_free_heap_size();
}
const char * EspClass::getSdkVersion(void)
{
return system_get_sdk_version();
}
uint32_t EspClass::getFlashChipSize(void)
{
uint32_t data;
uint8_t * bytes = (uint8_t *) &data;
// read first 4 byte (magic byte + flash config)
if(SPIRead(0x0000, &data, 4) == SPI_FLASH_RESULT_OK) {
return magicFlashChipSize((bytes[3] & 0xf0) >> 4);
}
return 0;
}
uint32_t EspClass::getFlashChipSpeed(void)
{
uint32_t data;
uint8_t * bytes = (uint8_t *) &data;
// read first 4 byte (magic byte + flash config)
if(SPIRead(0x0000, &data, 4) == SPI_FLASH_RESULT_OK) {
return magicFlashChipSpeed(bytes[3] & 0x0F);
}
return 0;
}
FlashMode_t EspClass::getFlashChipMode(void)
{
FlashMode_t mode = FM_UNKNOWN;
uint32_t data;
uint8_t * bytes = (uint8_t *) &data;
// read first 4 byte (magic byte + flash config)
if(SPIRead(0x0000, &data, 4) == SPI_FLASH_RESULT_OK) {
mode = magicFlashChipMode(bytes[2]);
}
return mode;
}
uint32_t EspClass::magicFlashChipSize(uint8_t byte)
{
switch(byte & 0x0F) {
case 0x0: // 4 Mbit (512KB)
return (512_kB);
case 0x1: // 2 MBit (256KB)
return (256_kB);
case 0x2: // 8 MBit (1MB)
return (1_MB);
case 0x3: // 16 MBit (2MB)
return (2_MB);
case 0x4: // 32 MBit (4MB)
return (4_MB);
case 0x5: // 64 MBit (8MB)
return (8_MB);
case 0x6: // 128 MBit (16MB)
return (16_MB);
case 0x7: // 256 MBit (32MB)
return (32_MB);
default: // fail?
return 0;
}
}
uint32_t EspClass::magicFlashChipSpeed(uint8_t byte)
{
switch(byte & 0x0F) {
case 0x0: // 40 MHz
return (40_MHz);
case 0x1: // 26 MHz
return (26_MHz);
case 0x2: // 20 MHz
return (20_MHz);
case 0xf: // 80 MHz
return (80_MHz);
default: // fail?
return 0;
}
}
FlashMode_t EspClass::magicFlashChipMode(uint8_t byte)
{
FlashMode_t mode = (FlashMode_t) byte;
if(mode > FM_DOUT) {
mode = FM_UNKNOWN;
}
return mode;
}
bool EspClass::eraseConfig(void)
{
bool ret = true;
size_t cfgAddr = (getFlashChipSize() - 0x4000);
size_t cfgSize = (8*1024);
while(cfgSize) {
if(SPIEraseSector((cfgAddr / 4096)) != SPI_FLASH_RESULT_OK) {
ret = false;
}
cfgSize -= 4096;
cfgAddr += 4096;
}
return ret;
}
bool EspClass::flashEraseSector(uint32_t sector)
{
int rc = SPIEraseSector(sector);
return rc == 0;
}
bool EspClass::flashWrite(uint32_t offset, uint32_t *data, size_t size)
{
int rc = SPIWrite(offset, (uint32_t*) data, size);
return rc == 0;
}
bool EspClass::flashRead(uint32_t offset, uint32_t *data, size_t size)
{
int rc = SPIRead(offset, (uint32_t*) data, size);
return rc == 0;
}

85
cores/esp32/Esp.h Normal file
View File

@ -0,0 +1,85 @@
/*
Esp.h - ESP31B-specific APIs
Copyright (c) 2015 Ivan Grokhotkov. All rights 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 ESP_H
#define ESP_H
#include <Arduino.h>
/**
* AVR macros for WDT managment
*/
typedef enum {
WDTO_0MS = 0, //!< WDTO_0MS
WDTO_15MS = 15, //!< WDTO_15MS
WDTO_30MS = 30, //!< WDTO_30MS
WDTO_60MS = 60, //!< WDTO_60MS
WDTO_120MS = 120, //!< WDTO_120MS
WDTO_250MS = 250, //!< WDTO_250MS
WDTO_500MS = 500, //!< WDTO_500MS
WDTO_1S = 1000,//!< WDTO_1S
WDTO_2S = 2000,//!< WDTO_2S
WDTO_4S = 4000,//!< WDTO_4S
WDTO_8S = 8000 //!< WDTO_8S
} WDTO_t;
typedef enum {
FM_QIO = 0x00,
FM_QOUT = 0x01,
FM_DIO = 0x02,
FM_DOUT = 0x03,
FM_UNKNOWN = 0xff
} FlashMode_t;
class EspClass
{
public:
EspClass() {}
~EspClass() {}
void restart();
uint32_t getFreeHeap();
uint32_t getChipId();
const char * getSdkVersion();
uint8_t getCpuFreqMHz();
uint32_t getFlashChipSize();
uint32_t getFlashChipSpeed();
FlashMode_t getFlashChipMode();
uint32_t magicFlashChipSize(uint8_t byte);
uint32_t magicFlashChipSpeed(uint8_t byte);
FlashMode_t magicFlashChipMode(uint8_t byte);
bool flashEraseSector(uint32_t sector);
bool flashWrite(uint32_t offset, uint32_t *data, size_t size);
bool flashRead(uint32_t offset, uint32_t *data, size_t size);
bool eraseConfig();
uint32_t getCycleCount();
};
extern EspClass ESP;
#endif //ESP_H

View File

@ -0,0 +1,117 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "HardwareSerial.h"
HardwareSerial Serial(0);
HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _uart(NULL) {}
void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin)
{
if(_uart_nr == 0 && rxPin < 0 && txPin < 0) {
rxPin = 3;
txPin = 1;
}
_uart = uartBegin(_uart_nr, baud, config, rxPin, txPin, 256, false);
}
void HardwareSerial::end()
{
if(uartGetDebug() == _uart_nr) {
uartSetDebug(0);
}
uartEnd(_uart);
_uart = 0;
}
void HardwareSerial::setDebugOutput(bool en)
{
if(_uart == 0) {
return;
}
if(en) {
if(_uart->txEnabled) {
uartSetDebug(_uart);
} else {
uartSetDebug(0);
}
} else {
if(uartGetDebug() == _uart_nr) {
uartSetDebug(0);
}
}
}
bool HardwareSerial::isTxEnabled(void)
{
if(_uart == 0) {
return false;
}
return _uart->txEnabled;
}
bool HardwareSerial::isRxEnabled(void)
{
if(_uart == 0) {
return false;
}
return _uart->rxEnabled;
}
int HardwareSerial::available(void)
{
if (_uart && _uart->rxEnabled) {
return uartAvailable(_uart);
}
return 0;
}
int HardwareSerial::peek(void)
{
if (_uart && _uart->rxEnabled) {
return uartPeek(_uart);
}
return -1;
}
int HardwareSerial::read(void)
{
if(_uart && _uart->rxEnabled) {
return uartRead(_uart);
}
return -1;
}
void HardwareSerial::flush()
{
if(_uart == 0 || !_uart->txEnabled) {
return;
}
uartFlush(_uart);
}
size_t HardwareSerial::write(uint8_t c)
{
if(_uart == 0 || !_uart->txEnabled) {
return 0;
}
uartWrite(_uart, c);
return 1;
}
size_t HardwareSerial::write(const uint8_t *buffer, size_t size)
{
if(_uart == 0 || !_uart->txEnabled) {
return 0;
}
uartWriteBuf(_uart, buffer, size);
return size;
}
HardwareSerial::operator bool() const
{
return _uart != 0;
}

View File

@ -0,0 +1,78 @@
/*
HardwareSerial.h - Hardware serial library for 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 28 September 2010 by Mark Sproul
Modified 14 August 2012 by Alarus
Modified 3 December 2013 by Matthijs Kooijman
Modified 18 December 2014 by Ivan Grokhotkov (esp8266 platform support)
Modified 31 March 2015 by Markus Sattler (rewrite the code for UART0 + UART1 support in ESP8266)
Modified 25 April 2015 by Thomas Flayols (add configuration different from 8N1 in ESP8266)
*/
#ifndef HardwareSerial_h
#define HardwareSerial_h
#include <inttypes.h>
#include "Stream.h"
#include "esp32-hal.h"
class HardwareSerial: public Stream
{
public:
HardwareSerial(int uart_nr);
void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1);
void end();
int available(void);
int peek(void);
int read(void);
void flush(void);
size_t write(uint8_t);
size_t write(const uint8_t *buffer, size_t size);
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);
}
operator bool() const;
void setDebugOutput(bool);
bool isTxEnabled(void);
bool isRxEnabled(void);
protected:
int _uart_nr;
uart_t* _uart;
};
extern HardwareSerial Serial;
#endif

81
cores/esp32/IPAddress.cpp Normal file
View File

@ -0,0 +1,81 @@
/*
IPAddress.cpp - Base class that provides IPAddress
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
*/
#include <Wiring.h>
#include <IPAddress.h>
#include <Print.h>
IPAddress::IPAddress()
{
_address.dword = 0;
}
IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet)
{
_address.bytes[0] = first_octet;
_address.bytes[1] = second_octet;
_address.bytes[2] = third_octet;
_address.bytes[3] = fourth_octet;
}
IPAddress::IPAddress(uint32_t address)
{
_address.dword = address;
}
IPAddress::IPAddress(const uint8_t *address)
{
memcpy(_address.bytes, address, sizeof(_address.bytes));
}
IPAddress& IPAddress::operator=(const uint8_t *address)
{
memcpy(_address.bytes, address, sizeof(_address.bytes));
return *this;
}
IPAddress& IPAddress::operator=(uint32_t address)
{
_address.dword = address;
return *this;
}
bool IPAddress::operator==(const uint8_t* addr) const
{
return memcmp(addr, _address.bytes, sizeof(_address.bytes)) == 0;
}
size_t IPAddress::printTo(Print& p) const
{
size_t n = 0;
for(int i = 0; i < 3; i++) {
n += p.print(_address.bytes[i], DEC);
n += p.print('.');
}
n += p.print(_address.bytes[3], DEC);
return n;
}
String IPAddress::toString()
{
char szRet[16];
sprintf(szRet,"%u.%u.%u.%u", _address.bytes[0], _address.bytes[1], _address.bytes[2], _address.bytes[3]);
return String(szRet);
}

93
cores/esp32/IPAddress.h Normal file
View File

@ -0,0 +1,93 @@
/*
IPAddress.h - Base class that provides IPAddress
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 IPAddress_h
#define IPAddress_h
#include <stdint.h>
#include <WString.h>
#include <Printable.h>
// A class to make it easier to handle and pass around IP addresses
class IPAddress: public Printable
{
private:
union {
uint8_t bytes[4]; // IPv4 address
uint32_t dword;
} _address;
// Access the raw byte array containing the address. Because this returns a pointer
// to the internal structure rather than a copy of the address this function should only
// be used when you know that the usage of the returned uint8_t* will be transient and not
// stored.
uint8_t* raw_address()
{
return _address.bytes;
}
public:
// Constructors
IPAddress();
IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet);
IPAddress(uint32_t address);
IPAddress(const uint8_t *address);
virtual ~IPAddress() {}
// Overloaded cast operator to allow IPAddress objects to be used where a pointer
// to a four-byte uint8_t array is expected
operator uint32_t() const
{
return _address.dword;
}
bool operator==(const IPAddress& addr) const
{
return _address.dword == addr._address.dword;
}
bool operator==(const uint8_t* addr) const;
// Overloaded index operator to allow getting and setting individual octets of the address
uint8_t operator[](int index) const
{
return _address.bytes[index];
}
uint8_t& operator[](int index)
{
return _address.bytes[index];
}
// Overloaded copy operators to allow initialisation of IPAddress objects from other types
IPAddress& operator=(const uint8_t *address);
IPAddress& operator=(uint32_t address);
virtual size_t printTo(Print& p) const;
String toString();
friend class EthernetClass;
friend class UDP;
friend class Client;
friend class Server;
friend class DhcpClass;
friend class DNSClient;
};
const IPAddress INADDR_NONE(0, 0, 0, 0);
#endif

117
cores/esp32/MD5Builder.cpp Normal file
View File

@ -0,0 +1,117 @@
/*
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 <Arduino.h>
#include <MD5Builder.h>
uint8_t hex_char_to_byte(uint8_t c)
{
return (c >= 'a' && c <= 'f') ? (c - ((uint8_t)'a' - 0xa)) :
(c >= 'A' && c <= 'F') ? (c - ((uint8_t)'A' - 0xA)) :
(c >= '0' && c<= '9') ? (c - (uint8_t)'0') : 0;
}
void MD5Builder::begin(void)
{
memset(_buf, 0x00, 16);
MD5Init(&_ctx);
}
void MD5Builder::add(uint8_t * data, uint16_t len)
{
MD5Update(&_ctx, data, len);
}
void MD5Builder::addHexString(const char * data)
{
uint16_t i, len = strlen(data);
uint8_t * tmp = (uint8_t*)malloc(len/2);
if(tmp == NULL) {
return;
}
for(i=0; i<len; i+=2) {
uint8_t high = hex_char_to_byte(data[i]);
uint8_t low = hex_char_to_byte(data[i+1]);
tmp[i/2] = (high & 0x0F) << 4 | (low & 0x0F);
}
add(tmp, len/2);
free(tmp);
}
bool MD5Builder::addStream(Stream & stream, const size_t maxLen)
{
const int buf_size = 512;
int maxLengthLeft = maxLen;
uint8_t * buf = (uint8_t*) malloc(buf_size);
if(!buf) {
return false;
}
int bytesAvailable = stream.available();
while((bytesAvailable > 0) && (maxLengthLeft > 0)) {
// determine number of bytes to read
int readBytes = bytesAvailable;
if(readBytes > maxLengthLeft) {
readBytes = maxLengthLeft ; // read only until max_len
}
if(readBytes > buf_size) {
readBytes = buf_size; // not read more the buffer can handle
}
// read data and check if we got something
int numBytesRead = stream.readBytes(buf, readBytes);
if(numBytesRead< 1) {
return false;
}
// Update MD5 with buffer payload
MD5Update(&_ctx, buf, numBytesRead);
// update available number of bytes
maxLengthLeft -= numBytesRead;
bytesAvailable = stream.available();
}
free(buf);
return true;
}
void MD5Builder::calculate(void)
{
MD5Final(_buf, &_ctx);
}
void MD5Builder::getBytes(uint8_t * output)
{
memcpy(output, _buf, 16);
}
void MD5Builder::getChars(char * output)
{
for(uint8_t i = 0; i < 16; i++) {
sprintf(output + (i * 2), "%02x", _buf[i]);
}
}
String MD5Builder::toString(void)
{
char out[33];
getChars(out);
return String(out);
}

63
cores/esp32/MD5Builder.h Normal file
View File

@ -0,0 +1,63 @@
/*
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 __ESP8266_MD5_BUILDER__
#define __ESP8266_MD5_BUILDER__
#include <WString.h>
#include <Stream.h>
#include "rom/md5_hash.h"
class MD5Builder
{
private:
struct MD5Context _ctx;
uint8_t _buf[16];
public:
void begin(void);
void add(uint8_t * data, uint16_t len);
void add(const char * data)
{
add((uint8_t*)data, strlen(data));
}
void add(char * data)
{
add((const char*)data);
}
void add(String data)
{
add(data.c_str());
}
void addHexString(const char * data);
void addHexString(char * data)
{
addHexString((const char*)data);
}
void addHexString(String data)
{
addHexString(data.c_str());
}
bool addStream(Stream & stream, const size_t maxLen);
void calculate(void);
void getBytes(uint8_t * output);
void getChars(char * output);
String toString(void);
};
#endif

293
cores/esp32/Print.cpp Normal file
View File

@ -0,0 +1,293 @@
/*
Print.cpp - Base class that provides print() and println()
Copyright (c) 2008 David A. Mellis. 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 23 November 2006 by David A. Mellis
Modified December 2014 by Ivan Grokhotkov
Modified May 2015 by Michael C. Miller - ESP31B progmem support
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "Wiring.h"
#include "Print.h"
extern "C" {
//#include "esp_common.h"
}
// Public Methods //////////////////////////////////////////////////////////////
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
while(size--) {
n += write(*buffer++);
}
return n;
}
size_t Print::printf(const char *format, ...)
{
va_list arg;
va_start(arg, format);
size_t len = vsnprintf(NULL, 0, format, arg);
char temp[len+1];
uint8_t * stemp = (uint8_t*)temp;
len = vsnprintf(temp, len+1, format, arg);
write(stemp, len);
va_end(arg);
return len;
}
/*
size_t Print::print(const __FlashStringHelper *ifsh) {
PGM_P p = reinterpret_cast<PGM_P>(ifsh);
size_t n = 0;
while (1) {
uint8_t c = pgm_read_byte(p++);
if (c == 0) break;
n += write(c);
}
return n;
}
*/
size_t Print::print(const String &s)
{
return write(s.c_str(), s.length());
}
size_t Print::print(const char str[])
{
return write(str);
}
size_t Print::print(char c)
{
return write(c);
}
size_t Print::print(unsigned char b, int base)
{
return print((unsigned long) b, base);
}
size_t Print::print(int n, int base)
{
return print((long) n, base);
}
size_t Print::print(unsigned int n, int base)
{
return print((unsigned long) n, base);
}
size_t Print::print(long n, int base)
{
if(base == 0) {
return write(n);
} else if(base == 10) {
if(n < 0) {
int t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
}
size_t Print::print(unsigned long n, int base)
{
if(base == 0) {
return write(n);
} else {
return printNumber(n, base);
}
}
size_t Print::print(double n, int digits)
{
return printFloat(n, digits);
}
size_t Print::println(const __FlashStringHelper *ifsh)
{
size_t n = print(ifsh);
n += println();
return n;
}
size_t Print::print(const Printable& x)
{
return x.printTo(*this);
}
size_t Print::println(void)
{
return print("\r\n");
}
size_t Print::println(const String &s)
{
size_t n = print(s);
n += println();
return n;
}
size_t Print::println(const char c[])
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(char c)
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(unsigned char b, int base)
{
size_t n = print(b, base);
n += println();
return n;
}
size_t Print::println(int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(double num, int digits)
{
size_t n = print(num, digits);
n += println();
return n;
}
size_t Print::println(const Printable& x)
{
size_t n = print(x);
n += println();
return n;
}
// Private Methods /////////////////////////////////////////////////////////////
size_t Print::printNumber(unsigned long n, uint8_t base)
{
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
// prevent crash if called with base == 1
if(base < 2) {
base = 10;
}
do {
unsigned long m = n;
n /= base;
char c = m - base * n;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
return write(str);
}
size_t Print::printFloat(double number, uint8_t digits)
{
size_t n = 0;
if(isnan(number)) {
return print("nan");
}
if(isinf(number)) {
return print("inf");
}
if(number > 4294967040.0) {
return print("ovf"); // constant determined empirically
}
if(number < -4294967040.0) {
return print("ovf"); // constant determined empirically
}
// Handle negative numbers
if(number < 0.0) {
n += print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for(uint8_t i = 0; i < digits; ++i) {
rounding /= 10.0;
}
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long) number;
double remainder = number - (double) int_part;
n += print(int_part);
// Print the decimal point, but only if there are digits beyond
if(digits > 0) {
n += print(".");
}
// Extract digits from the remainder one at a time
while(digits-- > 0) {
remainder *= 10.0;
int toPrint = int(remainder);
n += print(toPrint);
remainder -= toPrint;
}
return n;
}

101
cores/esp32/Print.h Normal file
View File

@ -0,0 +1,101 @@
/*
Print.h - Base class that provides print() and println()
Copyright (c) 2008 David A. Mellis. 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 Print_h
#define Print_h
#include <stdint.h>
#include <stddef.h>
#include "WString.h"
#include "Printable.h"
#define DEC 10
#define HEX 16
#define OCT 8
#define BIN 2
class Print
{
private:
int write_error;
size_t printNumber(unsigned long, uint8_t);
size_t printFloat(double, uint8_t);
protected:
void setWriteError(int err = 1)
{
write_error = err;
}
public:
Print() :
write_error(0)
{
}
virtual ~Print() {}
int getWriteError()
{
return write_error;
}
void clearWriteError()
{
setWriteError(0);
}
virtual size_t write(uint8_t) = 0;
size_t write(const char *str)
{
if(str == NULL) {
return 0;
}
return write((const uint8_t *) str, strlen(str));
}
virtual size_t write(const uint8_t *buffer, size_t size);
size_t write(const char *buffer, size_t size)
{
return write((const uint8_t *) buffer, size);
}
size_t printf(const char * format, ...) __attribute__ ((format (printf, 2, 3)));
size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);
size_t println(const __FlashStringHelper *);
size_t println(const String &s);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);
};
#endif

41
cores/esp32/Printable.h Normal file
View File

@ -0,0 +1,41 @@
/*
Printable.h - Interface class that allows printing of complex types
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 Printable_h
#define Printable_h
#include <stdlib.h>
class Print;
/** The Printable class provides a way for new classes to allow themselves to be printed.
By deriving from Printable and implementing the printTo method, it will then be possible
for users to print out instances of this class by passing them into the usual
Print::print and Print::println methods.
*/
class Printable
{
public:
virtual ~Printable() {}
virtual size_t printTo(Print& p) const = 0;
};
#endif

31
cores/esp32/Server.h Normal file
View File

@ -0,0 +1,31 @@
/*
Server.h - Base class that provides Server
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 server_h
#define server_h
#include "Print.h"
class Server: public Print
{
public:
virtual void begin() =0;
};
#endif

291
cores/esp32/Stream.cpp Normal file
View File

@ -0,0 +1,291 @@
/*
Stream.cpp - adds parsing methods to Stream class
Copyright (c) 2008 David A. Mellis. 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
Created July 2011
parsing functions based on TextFinder library by Michael Margolis
*/
#include "Wiring.h"
#include "Stream.h"
#include "esp32-hal.h"
#define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait
#define NO_SKIP_CHAR 1 // a magic char not found in a valid ASCII numeric field
// private method to read stream with timeout
int Stream::timedRead()
{
int c;
_startMillis = millis();
do {
c = read();
if(c >= 0) {
return c;
}
} while(millis() - _startMillis < _timeout);
return -1; // -1 indicates timeout
}
// private method to peek stream with timeout
int Stream::timedPeek()
{
int c;
_startMillis = millis();
do {
c = peek();
if(c >= 0) {
return c;
}
} while(millis() - _startMillis < _timeout);
return -1; // -1 indicates timeout
}
// returns peek of the next digit in the stream or -1 if timeout
// discards non-numeric characters
int Stream::peekNextDigit()
{
int c;
while(1) {
c = timedPeek();
if(c < 0) {
return c; // timeout
}
if(c == '-') {
return c;
}
if(c >= '0' && c <= '9') {
return c;
}
read(); // discard non-numeric
}
}
// Public Methods
//////////////////////////////////////////////////////////////
void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait
{
_timeout = timeout;
}
// find returns true if the target string is found
bool Stream::find(const char *target)
{
return findUntil(target, (char*) "");
}
// reads data from the stream until the target string of given length is found
// returns true if target string is found, false if timed out
bool Stream::find(const char *target, size_t length)
{
return findUntil(target, length, NULL, 0);
}
// as find but search ends if the terminator string is found
bool Stream::findUntil(const char *target, const char *terminator)
{
return findUntil(target, strlen(target), terminator, strlen(terminator));
}
// reads data from the stream until the target string of the given length is found
// search terminated if the terminator string is found
// returns true if target string is found, false if terminated or timed out
bool Stream::findUntil(const char *target, size_t targetLen, const char *terminator, size_t termLen)
{
size_t index = 0; // maximum target string length is 64k bytes!
size_t termIndex = 0;
int c;
if(*target == 0) {
return true; // return true if target is a null string
}
while((c = timedRead()) > 0) {
if(c != target[index]) {
index = 0; // reset index if any char does not match
}
if(c == target[index]) {
//////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1);
if(++index >= targetLen) { // return true if all chars in the target match
return true;
}
}
if(termLen > 0 && c == terminator[termIndex]) {
if(++termIndex >= termLen) {
return false; // return false if terminate string found before target string
}
} else {
termIndex = 0;
}
}
return false;
}
// returns the first valid (long) integer value from the current position.
// initial characters that are not digits (or the minus sign) are skipped
// function is terminated by the first character that is not a digit.
long Stream::parseInt()
{
return parseInt(NO_SKIP_CHAR); // terminate on first non-digit character (or timeout)
}
// as above but a given skipChar is ignored
// this allows format characters (typically commas) in values to be ignored
long Stream::parseInt(char skipChar)
{
boolean isNegative = false;
long value = 0;
int c;
c = peekNextDigit();
// ignore non numeric leading characters
if(c < 0) {
return 0; // zero returned if timeout
}
do {
if(c == skipChar) {
} // ignore this charactor
else if(c == '-') {
isNegative = true;
} else if(c >= '0' && c <= '9') { // is c a digit?
value = value * 10 + c - '0';
}
read(); // consume the character we got with peek
c = timedPeek();
} while((c >= '0' && c <= '9') || c == skipChar);
if(isNegative) {
value = -value;
}
return value;
}
// as parseInt but returns a floating point value
float Stream::parseFloat()
{
return parseFloat(NO_SKIP_CHAR);
}
// as above but the given skipChar is ignored
// this allows format characters (typically commas) in values to be ignored
float Stream::parseFloat(char skipChar)
{
boolean isNegative = false;
boolean isFraction = false;
long value = 0;
int c;
float fraction = 1.0;
c = peekNextDigit();
// ignore non numeric leading characters
if(c < 0) {
return 0; // zero returned if timeout
}
do {
if(c == skipChar) {
} // ignore
else if(c == '-') {
isNegative = true;
} else if(c == '.') {
isFraction = true;
} else if(c >= '0' && c <= '9') { // is c a digit?
value = value * 10 + c - '0';
if(isFraction) {
fraction *= 0.1;
}
}
read(); // consume the character we got with peek
c = timedPeek();
} while((c >= '0' && c <= '9') || c == '.' || c == skipChar);
if(isNegative) {
value = -value;
}
if(isFraction) {
return value * fraction;
} else {
return value;
}
}
// read characters from stream into buffer
// terminates if length characters have been read, or timeout (see setTimeout)
// returns the number of characters placed in the buffer
// the buffer is NOT null terminated.
//
size_t Stream::readBytes(char *buffer, size_t length)
{
size_t count = 0;
while(count < length) {
int c = timedRead();
if(c < 0) {
break;
}
*buffer++ = (char) c;
count++;
}
return count;
}
// as readBytes with terminator character
// terminates if length characters have been read, timeout, or if the terminator character detected
// returns the number of characters placed in the buffer (0 means no valid data found)
size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length)
{
if(length < 1) {
return 0;
}
size_t index = 0;
while(index < length) {
int c = timedRead();
if(c < 0 || c == terminator) {
break;
}
*buffer++ = (char) c;
index++;
}
return index; // return number of characters, not including null terminator
}
String Stream::readString()
{
String ret;
int c = timedRead();
while(c >= 0) {
ret += (char) c;
c = timedRead();
}
return ret;
}
String Stream::readStringUntil(char terminator)
{
String ret;
int c = timedRead();
while(c >= 0 && c != terminator) {
ret += (char) c;
c = timedRead();
}
return ret;
}

128
cores/esp32/Stream.h Normal file
View File

@ -0,0 +1,128 @@
/*
Stream.h - base class for character-based streams.
Copyright (c) 2010 David A. Mellis. 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
parsing functions based on TextFinder library by Michael Margolis
*/
#ifndef Stream_h
#define Stream_h
#include <inttypes.h>
#include "Print.h"
// compatability macros for testing
/*
#define getInt() parseInt()
#define getInt(skipChar) parseInt(skipchar)
#define getFloat() parseFloat()
#define getFloat(skipChar) parseFloat(skipChar)
#define getString( pre_string, post_string, buffer, length)
readBytesBetween( pre_string, terminator, buffer, length)
*/
class Stream: public Print
{
protected:
unsigned long _timeout; // number of milliseconds to wait for the next char before aborting timed read
unsigned long _startMillis; // used for timeout measurement
int timedRead(); // private method to read stream with timeout
int timedPeek(); // private method to peek stream with timeout
int peekNextDigit(); // returns the next numeric digit in the stream or -1 if timeout
public:
virtual int available() = 0;
virtual int read() = 0;
virtual int peek() = 0;
virtual void flush() = 0;
Stream():_startMillis(0)
{
_timeout = 1000;
}
virtual ~Stream() {}
// parsing methods
void setTimeout(unsigned long timeout); // sets maximum milliseconds to wait for stream data, default is 1 second
bool find(const char *target); // reads data from the stream until the target string is found
bool find(uint8_t *target)
{
return find((char *) target);
}
// returns true if target string is found, false if timed out (see setTimeout)
bool find(const char *target, size_t length); // reads data from the stream until the target string of given length is found
bool find(const uint8_t *target, size_t length)
{
return find((char *) target, length);
}
// returns true if target string is found, false if timed out
bool find(char target)
{
return find (&target, 1);
}
bool findUntil(const char *target, const char *terminator); // as find but search ends if the terminator string is found
bool findUntil(const uint8_t *target, const char *terminator)
{
return findUntil((char *) target, terminator);
}
bool findUntil(const char *target, size_t targetLen, const char *terminate, size_t termLen); // as above but search ends if the terminate string is found
bool findUntil(const uint8_t *target, size_t targetLen, const char *terminate, size_t termLen)
{
return findUntil((char *) target, targetLen, terminate, termLen);
}
long parseInt(); // returns the first valid (long) integer value from the current position.
// initial characters that are not digits (or the minus sign) are skipped
// integer is terminated by the first character that is not a digit.
float parseFloat(); // float version of parseInt
size_t readBytes(char *buffer, size_t length); // read chars from stream into buffer
size_t readBytes(uint8_t *buffer, size_t length)
{
return readBytes((char *) buffer, length);
}
// terminates if length characters have been read or timeout (see setTimeout)
// returns the number of characters placed in the buffer (0 means no valid data found)
size_t readBytesUntil(char terminator, char *buffer, size_t length); // as readBytes with terminator character
size_t readBytesUntil(char terminator, uint8_t *buffer, size_t length)
{
return readBytesUntil(terminator, (char *) buffer, length);
}
// terminates if length characters have been read, timeout, or if the terminator character detected
// returns the number of characters placed in the buffer (0 means no valid data found)
// Arduino String functions to be added here
String readString();
String readStringUntil(char terminator);
protected:
long parseInt(char skipChar); // as above but the given skipChar is ignored
// as above but the given skipChar is ignored
// this allows format characters (typically commas) in values to be ignored
float parseFloat(char skipChar); // as above but the given skipChar is ignored
};
#endif

View File

@ -0,0 +1,71 @@
/**
StreamString.cpp
Copyright (c) 2015 Markus Sattler. All rights 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 <Arduino.h>
#include "StreamString.h"
size_t StreamString::write(const uint8_t *data, size_t size)
{
if(size && data) {
if(reserve(length() + size + 1)) {
memcpy((void *) (buffer + len), (const void *) data, size);
len += size;
*(buffer + len) = 0x00; // add null for string end
return size;
}
}
return 0;
}
size_t StreamString::write(uint8_t data)
{
return concat((char) data);
}
int StreamString::available()
{
return length();
}
int StreamString::read()
{
if(length()) {
char c = charAt(0);
remove(0, 1);
return c;
}
return -1;
}
int StreamString::peek()
{
if(length()) {
char c = charAt(0);
return c;
}
return -1;
}
void StreamString::flush()
{
}

View File

@ -0,0 +1,39 @@
/**
StreamString.h
Copyright (c) 2015 Markus Sattler. All rights 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 STREAMSTRING_H_
#define STREAMSTRING_H_
class StreamString: public Stream, public String
{
public:
size_t write(const uint8_t *buffer, size_t size) override;
size_t write(uint8_t data) override;
int available() override;
int read() override;
int peek() override;
void flush() override;
};
#endif /* STREAMSTRING_H_ */

92
cores/esp32/Udp.h Normal file
View File

@ -0,0 +1,92 @@
/*
* 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 udp_h
#define udp_h
#include <Stream.h>
#include <IPAddress.h>
class UDP: public Stream
{
public:
virtual uint8_t begin(uint16_t) =0; // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use
virtual void stop() =0; // Finish with the UDP socket
// Sending UDP packets
// Start building up a packet to send to the remote host specific in ip and port
// Returns 1 if successful, 0 if there was a problem with the supplied IP address or port
virtual int beginPacket(IPAddress ip, uint16_t port) =0;
// Start building up a packet to send to the remote host specific in host and port
// Returns 1 if successful, 0 if there was a problem resolving the hostname or port
virtual int beginPacket(const char *host, uint16_t port) =0;
// Finish off this packet and send it
// Returns 1 if the packet was sent successfully, 0 if there was an error
virtual int endPacket() =0;
// Write a single byte into the packet
virtual size_t write(uint8_t) =0;
// Write size bytes from buffer into the packet
virtual size_t write(const uint8_t *buffer, size_t size) =0;
// Start processing the next available incoming packet
// Returns the size of the packet in bytes, or 0 if no packets are available
virtual int parsePacket() =0;
// Number of bytes remaining in the current packet
virtual int available() =0;
// Read a single byte from the current packet
virtual int read() =0;
// Read up to len bytes from the current packet and place them into buffer
// Returns the number of bytes read, or 0 if none are available
virtual int read(unsigned char* buffer, size_t len) =0;
// Read up to len characters from the current packet and place them into buffer
// Returns the number of characters read, or 0 if none are available
virtual int read(char* buffer, size_t len) =0;
// Return the next byte from the current packet without moving on to the next byte
virtual int peek() =0;
virtual void flush() =0; // Finish reading the current packet
// Return the IP address of the host who sent the current incoming packet
virtual IPAddress remoteIP() =0;
// Return the port of the host who sent the current incoming packet
virtual uint16_t remotePort() =0;
protected:
uint8_t* rawIPAddress(IPAddress& addr)
{
return addr.raw_address();
}
};
#endif

155
cores/esp32/WCharacter.h Normal file
View File

@ -0,0 +1,155 @@
/*
WCharacter.h - Character utility functions for Wiring & Arduino
Copyright (c) 2010 Hernando Barragan. 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 Character_h
#define Character_h
#include <ctype.h>
#include "WTypes.h"
#define isascii(__c) ((unsigned)(__c)<=0177)
#define toascii(__c) ((__c)&0177)
// WCharacter.h prototypes
inline boolean isAlphaNumeric(int c) __attribute__((always_inline));
inline boolean isAlpha(int c) __attribute__((always_inline));
inline boolean isAscii(int c) __attribute__((always_inline));
inline boolean isWhitespace(int c) __attribute__((always_inline));
inline boolean isControl(int c) __attribute__((always_inline));
inline boolean isDigit(int c) __attribute__((always_inline));
inline boolean isGraph(int c) __attribute__((always_inline));
inline boolean isLowerCase(int c) __attribute__((always_inline));
inline boolean isPrintable(int c) __attribute__((always_inline));
inline boolean isPunct(int c) __attribute__((always_inline));
inline boolean isSpace(int c) __attribute__((always_inline));
inline boolean isUpperCase(int c) __attribute__((always_inline));
inline boolean isHexadecimalDigit(int c) __attribute__((always_inline));
inline int toAscii(int c) __attribute__((always_inline));
inline int toLowerCase(int c) __attribute__((always_inline));
inline int toUpperCase(int c) __attribute__((always_inline));
// Checks for an alphanumeric character.
// It is equivalent to (isalpha(c) || isdigit(c)).
inline boolean isAlphaNumeric(int c)
{
return (isalnum(c) == 0 ? false : true);
}
// Checks for an alphabetic character.
// It is equivalent to (isupper(c) || islower(c)).
inline boolean isAlpha(int c)
{
return (isalpha(c) == 0 ? false : true);
}
// Checks whether c is a 7-bit unsigned char value
// that fits into the ASCII character set.
inline boolean isAscii(int c)
{
return ( isascii (c) == 0 ? false : true);
}
// Checks for a blank character, that is, a space or a tab.
inline boolean isWhitespace(int c)
{
return (isblank(c) == 0 ? false : true);
}
// Checks for a control character.
inline boolean isControl(int c)
{
return (iscntrl(c) == 0 ? false : true);
}
// Checks for a digit (0 through 9).
inline boolean isDigit(int c)
{
return (isdigit(c) == 0 ? false : true);
}
// Checks for any printable character except space.
inline boolean isGraph(int c)
{
return (isgraph(c) == 0 ? false : true);
}
// Checks for a lower-case character.
inline boolean isLowerCase(int c)
{
return (islower(c) == 0 ? false : true);
}
// Checks for any printable character including space.
inline boolean isPrintable(int c)
{
return (isprint(c) == 0 ? false : true);
}
// Checks for any printable character which is not a space
// or an alphanumeric character.
inline boolean isPunct(int c)
{
return (ispunct(c) == 0 ? false : true);
}
// Checks for white-space characters. For the avr-libc library,
// these are: space, formfeed ('\f'), newline ('\n'), carriage
// return ('\r'), horizontal tab ('\t'), and vertical tab ('\v').
inline boolean isSpace(int c)
{
return (isspace(c) == 0 ? false : true);
}
// Checks for an uppercase letter.
inline boolean isUpperCase(int c)
{
return (isupper(c) == 0 ? false : true);
}
// Checks for a hexadecimal digits, i.e. one of 0 1 2 3 4 5 6 7
// 8 9 a b c d e f A B C D E F.
inline boolean isHexadecimalDigit(int c)
{
return (isxdigit(c) == 0 ? false : true);
}
// Converts c to a 7-bit unsigned char value that fits into the
// ASCII character set, by clearing the high-order bits.
inline int toAscii(int c)
{
return toascii(c);
}
// Warning:
// Many people will be unhappy if you use this function.
// This function will convert accented letters into random
// characters.
// Converts the letter c to lower case, if possible.
inline int toLowerCase(int c)
{
return tolower(c);
}
// Converts the letter c to upper case, if possible.
inline int toUpperCase(int c)
{
return toupper(c);
}
#endif

67
cores/esp32/WMath.cpp Normal file
View File

@ -0,0 +1,67 @@
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Wiring project - http://wiring.org.co
Copyright (c) 2004-06 Hernando Barragan
Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/
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., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
$Id$
*/
extern "C" {
#include <stdlib.h>
}
void randomSeed(unsigned long seed)
{
if(seed != 0) {
srand(seed);
}
}
long random(long howbig)
{
if(howbig == 0) {
return 0;
}
return rand() % howbig;
}
long random(long howsmall, long howbig)
{
if(howsmall >= howbig) {
return howsmall;
}
long diff = howbig - howsmall;
return random(diff) + howsmall;
}
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
unsigned int makeWord(unsigned int w)
{
return w;
}
unsigned int makeWord(unsigned char h, unsigned char l)
{
return (h << 8) | l;
}

894
cores/esp32/WString.cpp Normal file
View File

@ -0,0 +1,894 @@
/*
WString.cpp - String library for Wiring & Arduino
...mostly rewritten by Paul Stoffregen...
Copyright (c) 2009-10 Hernando Barragan. All rights reserved.
Copyright 2011, Paul Stoffregen, paul@pjrc.com
Modified by Ivan Grokhotkov, 2014 - ESP31B support
Modified by Michael C. Miller, 2015 - ESP31B progmem support
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 "WString.h"
#include "stdlib_noniso.h"
//extern "C" {
//#include "esp_common.h"
//}
/*********************************************/
/* Constructors */
/*********************************************/
String::String(const char *cstr)
{
init();
if(cstr) {
copy(cstr, strlen(cstr));
}
}
String::String(const String &value)
{
init();
*this = value;
}
/*
String::String(const __FlashStringHelper *pstr) {
init();
*this = pstr; // see operator =
}
*/
#ifdef __GXX_EXPERIMENTAL_CXX0X__
String::String(String &&rval)
{
init();
move(rval);
}
String::String(StringSumHelper &&rval)
{
init();
move(rval);
}
#endif
String::String(char c)
{
init();
char buf[2];
buf[0] = c;
buf[1] = 0;
*this = buf;
}
String::String(unsigned char value, unsigned char base)
{
init();
char buf[1 + 8 * sizeof(unsigned char)];
utoa(value, buf, base);
*this = buf;
}
String::String(int value, unsigned char base)
{
init();
char buf[2 + 8 * sizeof(int)];
itoa(value, buf, base);
*this = buf;
}
String::String(unsigned int value, unsigned char base)
{
init();
char buf[1 + 8 * sizeof(unsigned int)];
utoa(value, buf, base);
*this = buf;
}
String::String(long value, unsigned char base)
{
init();
char buf[2 + 8 * sizeof(long)];
ltoa(value, buf, base);
*this = buf;
}
String::String(unsigned long value, unsigned char base)
{
init();
char buf[1 + 8 * sizeof(unsigned long)];
ultoa(value, buf, base);
*this = buf;
}
String::String(float value, unsigned char decimalPlaces)
{
init();
char buf[33];
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
}
String::String(double value, unsigned char decimalPlaces)
{
init();
char buf[33];
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
}
String::~String()
{
if(buffer) {
free(buffer);
}
init();
}
// /*********************************************/
// /* Memory Management */
// /*********************************************/
inline void String::init(void)
{
buffer = NULL;
capacity = 0;
len = 0;
}
void String::invalidate(void)
{
if(buffer) {
free(buffer);
}
init();
}
unsigned char String::reserve(unsigned int size)
{
if(buffer && capacity >= size) {
return 1;
}
if(changeBuffer(size)) {
if(len == 0) {
buffer[0] = 0;
}
return 1;
}
return 0;
}
unsigned char String::changeBuffer(unsigned int maxStrLen)
{
size_t newSize = (maxStrLen + 16) & (~0xf);
char *newbuffer = (char *) malloc(newSize);
if(newbuffer) {
memset(newbuffer, 0, newSize);
memcpy(newbuffer, buffer, len);
if (buffer) {
free(buffer);
}
capacity = newSize - 1;
buffer = newbuffer;
return 1;
}
buffer = newbuffer;
return 0;
}
// /*********************************************/
// /* Copy and Move */
// /*********************************************/
String & String::copy(const char *cstr, unsigned int length)
{
if(!reserve(length)) {
invalidate();
return *this;
}
len = length;
strcpy(buffer, cstr);
return *this;
}
/*
String & String::copy(const __FlashStringHelper *pstr, unsigned int length) {
if (!reserve(length)) {
invalidate();
return *this;
}
len = length;
strcpy_P(buffer, (PGM_P)pstr);
return *this;
}
*/
#ifdef __GXX_EXPERIMENTAL_CXX0X__
void String::move(String &rhs)
{
if(buffer) {
if(capacity >= rhs.len) {
strcpy(buffer, rhs.buffer);
len = rhs.len;
rhs.len = 0;
return;
} else {
free(buffer);
}
}
buffer = rhs.buffer;
capacity = rhs.capacity;
len = rhs.len;
rhs.buffer = NULL;
rhs.capacity = 0;
rhs.len = 0;
}
#endif
String & String::operator =(const String &rhs)
{
if(this == &rhs) {
return *this;
}
if(rhs.buffer) {
copy(rhs.buffer, rhs.len);
} else {
invalidate();
}
return *this;
}
#ifdef __GXX_EXPERIMENTAL_CXX0X__
String & String::operator =(String &&rval)
{
if(this != &rval) {
move(rval);
}
return *this;
}
String & String::operator =(StringSumHelper &&rval)
{
if(this != &rval) {
move(rval);
}
return *this;
}
#endif
String & String::operator =(const char *cstr)
{
if(cstr) {
copy(cstr, strlen(cstr));
} else {
invalidate();
}
return *this;
}
/*
String & String::operator = (const __FlashStringHelper *pstr)
{
if (pstr) copy(pstr, strlen_P((PGM_P)pstr));
else invalidate();
return *this;
}
*/
// /*********************************************/
// /* concat */
// /*********************************************/
unsigned char String::concat(const String &s)
{
return concat(s.buffer, s.len);
}
unsigned char String::concat(const char *cstr, unsigned int length)
{
unsigned int newlen = len + length;
if(!cstr) {
return 0;
}
if(length == 0) {
return 1;
}
if(!reserve(newlen)) {
return 0;
}
strcpy(buffer + len, cstr);
len = newlen;
return 1;
}
unsigned char String::concat(const char *cstr)
{
if(!cstr) {
return 0;
}
return concat(cstr, strlen(cstr));
}
unsigned char String::concat(char c)
{
char buf[2];
buf[0] = c;
buf[1] = 0;
return concat(buf, 1);
}
unsigned char String::concat(unsigned char num)
{
char buf[1 + 3 * sizeof(unsigned char)];
itoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(int num)
{
char buf[2 + 3 * sizeof(int)];
itoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(unsigned int num)
{
char buf[1 + 3 * sizeof(unsigned int)];
utoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(long num)
{
char buf[2 + 3 * sizeof(long)];
ltoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(unsigned long num)
{
char buf[1 + 3 * sizeof(unsigned long)];
ultoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(float num)
{
char buf[20];
char* string = dtostrf(num, 4, 2, buf);
return concat(string, strlen(string));
}
unsigned char String::concat(double num)
{
char buf[20];
char* string = dtostrf(num, 4, 2, buf);
return concat(string, strlen(string));
}
/*
unsigned char String::concat(const __FlashStringHelper * str) {
if (!str) return 0;
int length = strlen_P((PGM_P)str);
if (length == 0) return 1;
unsigned int newlen = len + length;
if (!reserve(newlen)) return 0;
strcpy_P(buffer + len, (PGM_P)str);
len = newlen;
return 1;
}
*/
/*********************************************/
/* Concatenate */
/*********************************************/
StringSumHelper & operator +(const StringSumHelper &lhs, const String &rhs)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(rhs.buffer, rhs.len)) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, const char *cstr)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!cstr || !a.concat(cstr, strlen(cstr))) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, char c)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(c)) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, unsigned char num)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num)) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, int num)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num)) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, unsigned int num)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num)) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, long num)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num)) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, unsigned long num)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num)) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, float num)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num)) {
a.invalidate();
}
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, double num)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num)) {
a.invalidate();
}
return a;
}
/*
StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs)
{
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if (!a.concat(rhs)) a.invalidate();
return a;
}
*/
// /*********************************************/
// /* Comparison */
// /*********************************************/
int String::compareTo(const String &s) const
{
if(!buffer || !s.buffer) {
if(s.buffer && s.len > 0) {
return 0 - *(unsigned char *) s.buffer;
}
if(buffer && len > 0) {
return *(unsigned char *) buffer;
}
return 0;
}
return strcmp(buffer, s.buffer);
}
unsigned char String::equals(const String &s2) const
{
return (len == s2.len && compareTo(s2) == 0);
}
unsigned char String::equals(const char *cstr) const
{
if(len == 0) {
return (cstr == NULL || *cstr == 0);
}
if(cstr == NULL) {
return buffer[0] == 0;
}
return strcmp(buffer, cstr) == 0;
}
unsigned char String::operator<(const String &rhs) const
{
return compareTo(rhs) < 0;
}
unsigned char String::operator>(const String &rhs) const
{
return compareTo(rhs) > 0;
}
unsigned char String::operator<=(const String &rhs) const
{
return compareTo(rhs) <= 0;
}
unsigned char String::operator>=(const String &rhs) const
{
return compareTo(rhs) >= 0;
}
unsigned char String::equalsIgnoreCase(const String &s2) const
{
if(this == &s2) {
return 1;
}
if(len != s2.len) {
return 0;
}
if(len == 0) {
return 1;
}
const char *p1 = buffer;
const char *p2 = s2.buffer;
while(*p1) {
if(tolower(*p1++) != tolower(*p2++)) {
return 0;
}
}
return 1;
}
unsigned char String::startsWith(const String &s2) const
{
if(len < s2.len) {
return 0;
}
return startsWith(s2, 0);
}
unsigned char String::startsWith(const String &s2, unsigned int offset) const
{
if(offset > len - s2.len || !buffer || !s2.buffer) {
return 0;
}
return strncmp(&buffer[offset], s2.buffer, s2.len) == 0;
}
unsigned char String::endsWith(const String &s2) const
{
if(len < s2.len || !buffer || !s2.buffer) {
return 0;
}
return strcmp(&buffer[len - s2.len], s2.buffer) == 0;
}
// /*********************************************/
// /* Character Access */
// /*********************************************/
char String::charAt(unsigned int loc) const
{
return operator[](loc);
}
void String::setCharAt(unsigned int loc, char c)
{
if(loc < len) {
buffer[loc] = c;
}
}
char & String::operator[](unsigned int index)
{
static char dummy_writable_char;
if(index >= len || !buffer) {
dummy_writable_char = 0;
return dummy_writable_char;
}
return buffer[index];
}
char String::operator[](unsigned int index) const
{
if(index >= len || !buffer) {
return 0;
}
return buffer[index];
}
void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const
{
if(!bufsize || !buf) {
return;
}
if(index >= len) {
buf[0] = 0;
return;
}
unsigned int n = bufsize - 1;
if(n > len - index) {
n = len - index;
}
strncpy((char *) buf, buffer + index, n);
buf[n] = 0;
}
// /*********************************************/
// /* Search */
// /*********************************************/
int String::indexOf(char c) const
{
return indexOf(c, 0);
}
int String::indexOf(char ch, unsigned int fromIndex) const
{
if(fromIndex >= len) {
return -1;
}
const char* temp = strchr(buffer + fromIndex, ch);
if(temp == NULL) {
return -1;
}
return temp - buffer;
}
int String::indexOf(const String &s2) const
{
return indexOf(s2, 0);
}
int String::indexOf(const String &s2, unsigned int fromIndex) const
{
if(fromIndex >= len) {
return -1;
}
const char *found = strstr(buffer + fromIndex, s2.buffer);
if(found == NULL) {
return -1;
}
return found - buffer;
}
int String::lastIndexOf(char theChar) const
{
return lastIndexOf(theChar, len - 1);
}
int String::lastIndexOf(char ch, unsigned int fromIndex) const
{
if(fromIndex >= len) {
return -1;
}
char tempchar = buffer[fromIndex + 1];
buffer[fromIndex + 1] = '\0';
char* temp = strrchr(buffer, ch);
buffer[fromIndex + 1] = tempchar;
if(temp == NULL) {
return -1;
}
return temp - buffer;
}
int String::lastIndexOf(const String &s2) const
{
return lastIndexOf(s2, len - s2.len);
}
int String::lastIndexOf(const String &s2, unsigned int fromIndex) const
{
if(s2.len == 0 || len == 0 || s2.len > len) {
return -1;
}
if(fromIndex >= len) {
fromIndex = len - 1;
}
int found = -1;
for(char *p = buffer; p <= buffer + fromIndex; p++) {
p = strstr(p, s2.buffer);
if(!p) {
break;
}
if((unsigned int) (p - buffer) <= fromIndex) {
found = p - buffer;
}
}
return found;
}
String String::substring(unsigned int left, unsigned int right) const
{
if(left > right) {
unsigned int temp = right;
right = left;
left = temp;
}
String out;
if(left >= len) {
return out;
}
if(right > len) {
right = len;
}
char temp = buffer[right]; // save the replaced character
buffer[right] = '\0';
out = buffer + left; // pointer arithmetic
buffer[right] = temp; //restore character
return out;
}
// /*********************************************/
// /* Modification */
// /*********************************************/
void String::replace(char find, char replace)
{
if(!buffer) {
return;
}
for(char *p = buffer; *p; p++) {
if(*p == find) {
*p = replace;
}
}
}
void String::replace(const String& find, const String& replace)
{
if(len == 0 || find.len == 0) {
return;
}
int diff = replace.len - find.len;
char *readFrom = buffer;
char *foundAt;
if(diff == 0) {
while((foundAt = strstr(readFrom, find.buffer)) != NULL) {
memcpy(foundAt, replace.buffer, replace.len);
readFrom = foundAt + replace.len;
}
} else if(diff < 0) {
char *writeTo = buffer;
while((foundAt = strstr(readFrom, find.buffer)) != NULL) {
unsigned int n = foundAt - readFrom;
memcpy(writeTo, readFrom, n);
writeTo += n;
memcpy(writeTo, replace.buffer, replace.len);
writeTo += replace.len;
readFrom = foundAt + find.len;
len += diff;
}
strcpy(writeTo, readFrom);
} else {
unsigned int size = len; // compute size needed for result
while((foundAt = strstr(readFrom, find.buffer)) != NULL) {
readFrom = foundAt + find.len;
size += diff;
}
if(size == len) {
return;
}
if(size > capacity && !changeBuffer(size)) {
return; // XXX: tell user!
}
int index = len - 1;
while(index >= 0 && (index = lastIndexOf(find, index)) >= 0) {
readFrom = buffer + index + find.len;
memmove(readFrom + diff, readFrom, len - (readFrom - buffer));
len += diff;
buffer[len] = 0;
memcpy(buffer + index, replace.buffer, replace.len);
index--;
}
}
}
void String::remove(unsigned int index)
{
// Pass the biggest integer as the count. The remove method
// below will take care of truncating it at the end of the
// string.
remove(index, (unsigned int) -1);
}
void String::remove(unsigned int index, unsigned int count)
{
if(index >= len) {
return;
}
if(count <= 0) {
return;
}
if(count > len - index) {
count = len - index;
}
char *writeTo = buffer + index;
len = len - count;
strncpy(writeTo, buffer + index + count, len - index);
buffer[len] = 0;
}
void String::toLowerCase(void)
{
if(!buffer) {
return;
}
for(char *p = buffer; *p; p++) {
*p = tolower(*p);
}
}
void String::toUpperCase(void)
{
if(!buffer) {
return;
}
for(char *p = buffer; *p; p++) {
*p = toupper(*p);
}
}
void String::trim(void)
{
if(!buffer || len == 0) {
return;
}
char *begin = buffer;
while(isspace(*begin)) {
begin++;
}
char *end = buffer + len - 1;
while(isspace(*end) && end >= begin) {
end--;
}
len = end + 1 - begin;
if(begin > buffer) {
memcpy(buffer, begin, len);
}
buffer[len] = 0;
}
// /*********************************************/
// /* Parsing / Conversion */
// /*********************************************/
long String::toInt(void) const
{
if(buffer) {
return atol(buffer);
}
return 0;
}
float String::toFloat(void) const
{
if(buffer) {
return atof(buffer);
}
return 0;
}

327
cores/esp32/WString.h Normal file
View File

@ -0,0 +1,327 @@
/*
WString.h - String library for Wiring & Arduino
...mostly rewritten by Paul Stoffregen...
Copyright (c) 2009-10 Hernando Barragan. All right reserved.
Copyright 2011, Paul Stoffregen, paul@pjrc.com
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 String_class_h
#define String_class_h
#ifdef __cplusplus
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//#include <pgmspace.h>
// An inherited class for holding the result of a concatenation. These
// result objects are assumed to be writable by subsequent concatenations.
class StringSumHelper;
// an abstract class used as a means to proide a unique pointer type
// but really has no body
class __FlashStringHelper;
#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
#define F(string_literal) (FPSTR(PSTR(string_literal)))
// The string class
class String
{
// use a function pointer to allow for "if (s)" without the
// complications of an operator bool(). for more information, see:
// http://www.artima.com/cppsource/safebool.html
typedef void (String::*StringIfHelperType)() const;
void StringIfHelper() const
{
}
public:
// constructors
// creates a copy of the initial value.
// if the initial value is null or invalid, or if memory allocation
// fails, the string will be marked as invalid (i.e. "if (s)" will
// be false).
String(const char *cstr = "");
String(const String &str);
//String(const __FlashStringHelper *str);
#ifdef __GXX_EXPERIMENTAL_CXX0X__
String(String &&rval);
String(StringSumHelper &&rval);
#endif
explicit String(char c);
explicit String(unsigned char, unsigned char base = 10);
explicit String(int, unsigned char base = 10);
explicit String(unsigned int, unsigned char base = 10);
explicit String(long, unsigned char base = 10);
explicit String(unsigned long, unsigned char base = 10);
explicit String(float, unsigned char decimalPlaces = 2);
explicit String(double, unsigned char decimalPlaces = 2);
~String(void);
// memory management
// return true on success, false on failure (in which case, the string
// is left unchanged). reserve(0), if successful, will validate an
// invalid string (i.e., "if (s)" will be true afterwards)
unsigned char reserve(unsigned int size);
inline unsigned int length(void) const
{
if(buffer) {
return len;
} else {
return 0;
}
}
// creates a copy of the assigned value. if the value is null or
// invalid, or if the memory allocation fails, the string will be
// marked as invalid ("if (s)" will be false).
String & operator =(const String &rhs);
String & operator =(const char *cstr);
//String & operator = (const __FlashStringHelper *str);
#ifdef __GXX_EXPERIMENTAL_CXX0X__
String & operator =(String &&rval);
String & operator =(StringSumHelper &&rval);
#endif
// concatenate (works w/ built-in types)
// returns true on success, false on failure (in which case, the string
// is left unchanged). if the argument is null or invalid, the
// concatenation is considered unsucessful.
unsigned char concat(const String &str);
unsigned char concat(const char *cstr);
unsigned char concat(char c);
unsigned char concat(unsigned char c);
unsigned char concat(int num);
unsigned char concat(unsigned int num);
unsigned char concat(long num);
unsigned char concat(unsigned long num);
unsigned char concat(float num);
unsigned char concat(double num);
//unsigned char concat(const __FlashStringHelper * str);
// if there's not enough memory for the concatenated value, the string
// will be left unchanged (but this isn't signalled in any way)
String & operator +=(const String &rhs)
{
concat(rhs);
return (*this);
}
String & operator +=(const char *cstr)
{
concat(cstr);
return (*this);
}
String & operator +=(char c)
{
concat(c);
return (*this);
}
String & operator +=(unsigned char num)
{
concat(num);
return (*this);
}
String & operator +=(int num)
{
concat(num);
return (*this);
}
String & operator +=(unsigned int num)
{
concat(num);
return (*this);
}
String & operator +=(long num)
{
concat(num);
return (*this);
}
String & operator +=(unsigned long num)
{
concat(num);
return (*this);
}
String & operator +=(float num)
{
concat(num);
return (*this);
}
String & operator +=(double num)
{
concat(num);
return (*this);
}
//String & operator += (const __FlashStringHelper *str){
// concat(str);
// return (*this);
//}
friend StringSumHelper & operator +(const StringSumHelper &lhs, const String &rhs);
friend StringSumHelper & operator +(const StringSumHelper &lhs, const char *cstr);
friend StringSumHelper & operator +(const StringSumHelper &lhs, char c);
friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned char num);
friend StringSumHelper & operator +(const StringSumHelper &lhs, int num);
friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned int num);
friend StringSumHelper & operator +(const StringSumHelper &lhs, long num);
friend StringSumHelper & operator +(const StringSumHelper &lhs, unsigned long num);
friend StringSumHelper & operator +(const StringSumHelper &lhs, float num);
friend StringSumHelper & operator +(const StringSumHelper &lhs, double num);
//friend StringSumHelper & operator +(const StringSumHelper &lhs, const __FlashStringHelper *rhs);
// comparison (only works w/ Strings and "strings")
operator StringIfHelperType() const
{
return buffer ? &String::StringIfHelper : 0;
}
int compareTo(const String &s) const;
unsigned char equals(const String &s) const;
unsigned char equals(const char *cstr) const;
unsigned char operator ==(const String &rhs) const
{
return equals(rhs);
}
unsigned char operator ==(const char *cstr) const
{
return equals(cstr);
}
unsigned char operator !=(const String &rhs) const
{
return !equals(rhs);
}
unsigned char operator !=(const char *cstr) const
{
return !equals(cstr);
}
unsigned char operator <(const String &rhs) const;
unsigned char operator >(const String &rhs) const;
unsigned char operator <=(const String &rhs) const;
unsigned char operator >=(const String &rhs) const;
unsigned char equalsIgnoreCase(const String &s) const;
unsigned char startsWith(const String &prefix) const;
unsigned char startsWith(const String &prefix, unsigned int offset) const;
unsigned char endsWith(const String &suffix) const;
// character acccess
char charAt(unsigned int index) const;
void setCharAt(unsigned int index, char c);
char operator [](unsigned int index) const;
char& operator [](unsigned int index);
void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index = 0) const;
void toCharArray(char *buf, unsigned int bufsize, unsigned int index = 0) const
{
getBytes((unsigned char *) buf, bufsize, index);
}
const char * c_str() const
{
return buffer;
}
// search
int indexOf(char ch) const;
int indexOf(char ch, unsigned int fromIndex) const;
int indexOf(const String &str) const;
int indexOf(const String &str, unsigned int fromIndex) const;
int lastIndexOf(char ch) const;
int lastIndexOf(char ch, unsigned int fromIndex) const;
int lastIndexOf(const String &str) const;
int lastIndexOf(const String &str, unsigned int fromIndex) const;
String substring(unsigned int beginIndex) const
{
return substring(beginIndex, len);
}
;
String substring(unsigned int beginIndex, unsigned int endIndex) const;
// modification
void replace(char find, char replace);
void replace(const String& find, const String& replace);
void remove(unsigned int index);
void remove(unsigned int index, unsigned int count);
void toLowerCase(void);
void toUpperCase(void);
void trim(void);
// parsing/conversion
long toInt(void) const;
float toFloat(void) const;
protected:
char *buffer; // the actual char array
unsigned int capacity; // the array length minus one (for the '\0')
unsigned int len; // the String length (not counting the '\0')
protected:
void init(void);
void invalidate(void);
unsigned char changeBuffer(unsigned int maxStrLen);
unsigned char concat(const char *cstr, unsigned int length);
// copy and move
String & copy(const char *cstr, unsigned int length);
//String & copy(const __FlashStringHelper *pstr, unsigned int length);
#ifdef __GXX_EXPERIMENTAL_CXX0X__
void move(String &rhs);
#endif
};
class StringSumHelper: public String
{
public:
StringSumHelper(const String &s) :
String(s)
{
}
StringSumHelper(const char *p) :
String(p)
{
}
StringSumHelper(char c) :
String(c)
{
}
StringSumHelper(unsigned char num) :
String(num)
{
}
StringSumHelper(int num) :
String(num)
{
}
StringSumHelper(unsigned int num) :
String(num)
{
}
StringSumHelper(long num) :
String(num)
{
}
StringSumHelper(unsigned long num) :
String(num)
{
}
StringSumHelper(float num) :
String(num)
{
}
StringSumHelper(double num) :
String(num)
{
}
};
#endif // __cplusplus
#endif // String_class_h

65
cores/esp32/base64.cpp Normal file
View File

@ -0,0 +1,65 @@
/**
* base64.cpp
*
* Created on: 09.12.2015
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the ESP31B core for Arduino.
*
* 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 "Arduino.h"
extern "C" {
#include "libb64/cdecode.h"
#include "libb64/cencode.h"
}
#include "base64.h"
/**
* convert input data to base64
* @param data uint8_t *
* @param length size_t
* @return String
*/
String base64::encode(uint8_t * data, size_t length)
{
// base64 needs more size then the source data
size_t size = ((length * 1.6f) + 1);
char * buffer = (char *) malloc(size);
if(buffer) {
base64_encodestate _state;
base64_init_encodestate(&_state);
int len = base64_encode_block((const char *) &data[0], length, &buffer[0], &_state);
len = base64_encode_blockend((buffer + len), &_state);
String base64 = String(buffer);
free(buffer);
return base64;
}
return String("-FAIL-");
}
/**
* convert input data to base64
* @param text String
* @return String
*/
String base64::encode(String text)
{
return base64::encode((uint8_t *) text.c_str(), text.length());
}

13
cores/esp32/base64.h Normal file
View File

@ -0,0 +1,13 @@
#ifndef CORE_BASE64_H_
#define CORE_BASE64_H_
class base64
{
public:
static String encode(uint8_t * data, size_t length);
static String encode(String text);
private:
};
#endif /* CORE_BASE64_H_ */

534
cores/esp32/binary.h Normal file
View File

@ -0,0 +1,534 @@
/*
binary.h - Definitions for binary constants
Copyright (c) 2006 David A. Mellis. 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 Binary_h
#define Binary_h
#define B0 0
#define B00 0
#define B000 0
#define B0000 0
#define B00000 0
#define B000000 0
#define B0000000 0
#define B00000000 0
#define B1 1
#define B01 1
#define B001 1
#define B0001 1
#define B00001 1
#define B000001 1
#define B0000001 1
#define B00000001 1
#define B10 2
#define B010 2
#define B0010 2
#define B00010 2
#define B000010 2
#define B0000010 2
#define B00000010 2
#define B11 3
#define B011 3
#define B0011 3
#define B00011 3
#define B000011 3
#define B0000011 3
#define B00000011 3
#define B100 4
#define B0100 4
#define B00100 4
#define B000100 4
#define B0000100 4
#define B00000100 4
#define B101 5
#define B0101 5
#define B00101 5
#define B000101 5
#define B0000101 5
#define B00000101 5
#define B110 6
#define B0110 6
#define B00110 6
#define B000110 6
#define B0000110 6
#define B00000110 6
#define B111 7
#define B0111 7
#define B00111 7
#define B000111 7
#define B0000111 7
#define B00000111 7
#define B1000 8
#define B01000 8
#define B001000 8
#define B0001000 8
#define B00001000 8
#define B1001 9
#define B01001 9
#define B001001 9
#define B0001001 9
#define B00001001 9
#define B1010 10
#define B01010 10
#define B001010 10
#define B0001010 10
#define B00001010 10
#define B1011 11
#define B01011 11
#define B001011 11
#define B0001011 11
#define B00001011 11
#define B1100 12
#define B01100 12
#define B001100 12
#define B0001100 12
#define B00001100 12
#define B1101 13
#define B01101 13
#define B001101 13
#define B0001101 13
#define B00001101 13
#define B1110 14
#define B01110 14
#define B001110 14
#define B0001110 14
#define B00001110 14
#define B1111 15
#define B01111 15
#define B001111 15
#define B0001111 15
#define B00001111 15
#define B10000 16
#define B010000 16
#define B0010000 16
#define B00010000 16
#define B10001 17
#define B010001 17
#define B0010001 17
#define B00010001 17
#define B10010 18
#define B010010 18
#define B0010010 18
#define B00010010 18
#define B10011 19
#define B010011 19
#define B0010011 19
#define B00010011 19
#define B10100 20
#define B010100 20
#define B0010100 20
#define B00010100 20
#define B10101 21
#define B010101 21
#define B0010101 21
#define B00010101 21
#define B10110 22
#define B010110 22
#define B0010110 22
#define B00010110 22
#define B10111 23
#define B010111 23
#define B0010111 23
#define B00010111 23
#define B11000 24
#define B011000 24
#define B0011000 24
#define B00011000 24
#define B11001 25
#define B011001 25
#define B0011001 25
#define B00011001 25
#define B11010 26
#define B011010 26
#define B0011010 26
#define B00011010 26
#define B11011 27
#define B011011 27
#define B0011011 27
#define B00011011 27
#define B11100 28
#define B011100 28
#define B0011100 28
#define B00011100 28
#define B11101 29
#define B011101 29
#define B0011101 29
#define B00011101 29
#define B11110 30
#define B011110 30
#define B0011110 30
#define B00011110 30
#define B11111 31
#define B011111 31
#define B0011111 31
#define B00011111 31
#define B100000 32
#define B0100000 32
#define B00100000 32
#define B100001 33
#define B0100001 33
#define B00100001 33
#define B100010 34
#define B0100010 34
#define B00100010 34
#define B100011 35
#define B0100011 35
#define B00100011 35
#define B100100 36
#define B0100100 36
#define B00100100 36
#define B100101 37
#define B0100101 37
#define B00100101 37
#define B100110 38
#define B0100110 38
#define B00100110 38
#define B100111 39
#define B0100111 39
#define B00100111 39
#define B101000 40
#define B0101000 40
#define B00101000 40
#define B101001 41
#define B0101001 41
#define B00101001 41
#define B101010 42
#define B0101010 42
#define B00101010 42
#define B101011 43
#define B0101011 43
#define B00101011 43
#define B101100 44
#define B0101100 44
#define B00101100 44
#define B101101 45
#define B0101101 45
#define B00101101 45
#define B101110 46
#define B0101110 46
#define B00101110 46
#define B101111 47
#define B0101111 47
#define B00101111 47
#define B110000 48
#define B0110000 48
#define B00110000 48
#define B110001 49
#define B0110001 49
#define B00110001 49
#define B110010 50
#define B0110010 50
#define B00110010 50
#define B110011 51
#define B0110011 51
#define B00110011 51
#define B110100 52
#define B0110100 52
#define B00110100 52
#define B110101 53
#define B0110101 53
#define B00110101 53
#define B110110 54
#define B0110110 54
#define B00110110 54
#define B110111 55
#define B0110111 55
#define B00110111 55
#define B111000 56
#define B0111000 56
#define B00111000 56
#define B111001 57
#define B0111001 57
#define B00111001 57
#define B111010 58
#define B0111010 58
#define B00111010 58
#define B111011 59
#define B0111011 59
#define B00111011 59
#define B111100 60
#define B0111100 60
#define B00111100 60
#define B111101 61
#define B0111101 61
#define B00111101 61
#define B111110 62
#define B0111110 62
#define B00111110 62
#define B111111 63
#define B0111111 63
#define B00111111 63
#define B1000000 64
#define B01000000 64
#define B1000001 65
#define B01000001 65
#define B1000010 66
#define B01000010 66
#define B1000011 67
#define B01000011 67
#define B1000100 68
#define B01000100 68
#define B1000101 69
#define B01000101 69
#define B1000110 70
#define B01000110 70
#define B1000111 71
#define B01000111 71
#define B1001000 72
#define B01001000 72
#define B1001001 73
#define B01001001 73
#define B1001010 74
#define B01001010 74
#define B1001011 75
#define B01001011 75
#define B1001100 76
#define B01001100 76
#define B1001101 77
#define B01001101 77
#define B1001110 78
#define B01001110 78
#define B1001111 79
#define B01001111 79
#define B1010000 80
#define B01010000 80
#define B1010001 81
#define B01010001 81
#define B1010010 82
#define B01010010 82
#define B1010011 83
#define B01010011 83
#define B1010100 84
#define B01010100 84
#define B1010101 85
#define B01010101 85
#define B1010110 86
#define B01010110 86
#define B1010111 87
#define B01010111 87
#define B1011000 88
#define B01011000 88
#define B1011001 89
#define B01011001 89
#define B1011010 90
#define B01011010 90
#define B1011011 91
#define B01011011 91
#define B1011100 92
#define B01011100 92
#define B1011101 93
#define B01011101 93
#define B1011110 94
#define B01011110 94
#define B1011111 95
#define B01011111 95
#define B1100000 96
#define B01100000 96
#define B1100001 97
#define B01100001 97
#define B1100010 98
#define B01100010 98
#define B1100011 99
#define B01100011 99
#define B1100100 100
#define B01100100 100
#define B1100101 101
#define B01100101 101
#define B1100110 102
#define B01100110 102
#define B1100111 103
#define B01100111 103
#define B1101000 104
#define B01101000 104
#define B1101001 105
#define B01101001 105
#define B1101010 106
#define B01101010 106
#define B1101011 107
#define B01101011 107
#define B1101100 108
#define B01101100 108
#define B1101101 109
#define B01101101 109
#define B1101110 110
#define B01101110 110
#define B1101111 111
#define B01101111 111
#define B1110000 112
#define B01110000 112
#define B1110001 113
#define B01110001 113
#define B1110010 114
#define B01110010 114
#define B1110011 115
#define B01110011 115
#define B1110100 116
#define B01110100 116
#define B1110101 117
#define B01110101 117
#define B1110110 118
#define B01110110 118
#define B1110111 119
#define B01110111 119
#define B1111000 120
#define B01111000 120
#define B1111001 121
#define B01111001 121
#define B1111010 122
#define B01111010 122
#define B1111011 123
#define B01111011 123
#define B1111100 124
#define B01111100 124
#define B1111101 125
#define B01111101 125
#define B1111110 126
#define B01111110 126
#define B1111111 127
#define B01111111 127
#define B10000000 128
#define B10000001 129
#define B10000010 130
#define B10000011 131
#define B10000100 132
#define B10000101 133
#define B10000110 134
#define B10000111 135
#define B10001000 136
#define B10001001 137
#define B10001010 138
#define B10001011 139
#define B10001100 140
#define B10001101 141
#define B10001110 142
#define B10001111 143
#define B10010000 144
#define B10010001 145
#define B10010010 146
#define B10010011 147
#define B10010100 148
#define B10010101 149
#define B10010110 150
#define B10010111 151
#define B10011000 152
#define B10011001 153
#define B10011010 154
#define B10011011 155
#define B10011100 156
#define B10011101 157
#define B10011110 158
#define B10011111 159
#define B10100000 160
#define B10100001 161
#define B10100010 162
#define B10100011 163
#define B10100100 164
#define B10100101 165
#define B10100110 166
#define B10100111 167
#define B10101000 168
#define B10101001 169
#define B10101010 170
#define B10101011 171
#define B10101100 172
#define B10101101 173
#define B10101110 174
#define B10101111 175
#define B10110000 176
#define B10110001 177
#define B10110010 178
#define B10110011 179
#define B10110100 180
#define B10110101 181
#define B10110110 182
#define B10110111 183
#define B10111000 184
#define B10111001 185
#define B10111010 186
#define B10111011 187
#define B10111100 188
#define B10111101 189
#define B10111110 190
#define B10111111 191
#define B11000000 192
#define B11000001 193
#define B11000010 194
#define B11000011 195
#define B11000100 196
#define B11000101 197
#define B11000110 198
#define B11000111 199
#define B11001000 200
#define B11001001 201
#define B11001010 202
#define B11001011 203
#define B11001100 204
#define B11001101 205
#define B11001110 206
#define B11001111 207
#define B11010000 208
#define B11010001 209
#define B11010010 210
#define B11010011 211
#define B11010100 212
#define B11010101 213
#define B11010110 214
#define B11010111 215
#define B11011000 216
#define B11011001 217
#define B11011010 218
#define B11011011 219
#define B11011100 220
#define B11011101 221
#define B11011110 222
#define B11011111 223
#define B11100000 224
#define B11100001 225
#define B11100010 226
#define B11100011 227
#define B11100100 228
#define B11100101 229
#define B11100110 230
#define B11100111 231
#define B11101000 232
#define B11101001 233
#define B11101010 234
#define B11101011 235
#define B11101100 236
#define B11101101 237
#define B11101110 238
#define B11101111 239
#define B11110000 240
#define B11110001 241
#define B11110010 242
#define B11110011 243
#define B11110100 244
#define B11110101 245
#define B11110110 246
#define B11110111 247
#define B11111000 248
#define B11111001 249
#define B11111010 250
#define B11111011 251
#define B11111100 252
#define B11111101 253
#define B11111110 254
#define B11111111 255
#endif

196
cores/esp32/cbuf.cpp Normal file
View File

@ -0,0 +1,196 @@
/*
cbuf.cpp - Circular buffer implementation
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
*/
#include "cbuf.h"
cbuf::cbuf(size_t size) :
next(NULL), _size(size), _buf(new char[size]), _bufend(_buf + size), _begin(_buf), _end(_begin)
{
}
cbuf::~cbuf()
{
delete[] _buf;
}
size_t cbuf::resizeAdd(size_t addSize)
{
return resize(_size + addSize);
}
size_t cbuf::resize(size_t newSize)
{
size_t bytes_available = available();
// not lose any data
// if data can be lost use remove or flush before resize
if((newSize < bytes_available) || (newSize == _size)) {
return _size;
}
char *newbuf = new char[newSize];
char *oldbuf = _buf;
if(!newbuf) {
return _size;
}
if(_buf) {
read(newbuf, bytes_available);
memset((newbuf + bytes_available), 0x00, (newSize - bytes_available));
}
_begin = newbuf;
_end = newbuf + bytes_available;
_bufend = newbuf + newSize;
_size = newSize;
_buf = newbuf;
delete[] oldbuf;
return _size;
}
size_t cbuf::available() const
{
if(_end >= _begin) {
return _end - _begin;
}
return _size - (_begin - _end);
}
size_t cbuf::size()
{
return _size;
}
size_t cbuf::room() const
{
if(_end >= _begin) {
return _size - (_end - _begin) - 1;
}
return _begin - _end - 1;
}
int cbuf::peek()
{
if(empty()) {
return -1;
}
return static_cast<int>(*_begin);
}
size_t cbuf::peek(char *dst, size_t size)
{
size_t bytes_available = available();
size_t size_to_read = (size < bytes_available) ? size : bytes_available;
size_t size_read = size_to_read;
char * begin = _begin;
if(_end < _begin && size_to_read > (size_t) (_bufend - _begin)) {
size_t top_size = _bufend - _begin;
memcpy(dst, _begin, top_size);
begin = _buf;
size_to_read -= top_size;
dst += top_size;
}
memcpy(dst, begin, size_to_read);
return size_read;
}
int cbuf::read()
{
if(empty()) {
return -1;
}
char result = *_begin;
_begin = wrap_if_bufend(_begin + 1);
return static_cast<int>(result);
}
size_t cbuf::read(char* dst, size_t size)
{
size_t bytes_available = available();
size_t size_to_read = (size < bytes_available) ? size : bytes_available;
size_t size_read = size_to_read;
if(_end < _begin && size_to_read > (size_t) (_bufend - _begin)) {
size_t top_size = _bufend - _begin;
memcpy(dst, _begin, top_size);
_begin = _buf;
size_to_read -= top_size;
dst += top_size;
}
memcpy(dst, _begin, size_to_read);
_begin = wrap_if_bufend(_begin + size_to_read);
return size_read;
}
size_t cbuf::write(char c)
{
if(full()) {
return 0;
}
*_end = c;
_end = wrap_if_bufend(_end + 1);
return 1;
}
size_t cbuf::write(const char* src, size_t size)
{
size_t bytes_available = room();
size_t size_to_write = (size < bytes_available) ? size : bytes_available;
size_t size_written = size_to_write;
if(_end >= _begin && size_to_write > (size_t) (_bufend - _end)) {
size_t top_size = _bufend - _end;
memcpy(_end, src, top_size);
_end = _buf;
size_to_write -= top_size;
src += top_size;
}
memcpy(_end, src, size_to_write);
_end = wrap_if_bufend(_end + size_to_write);
return size_written;
}
void cbuf::flush()
{
_begin = _buf;
_end = _buf;
}
size_t cbuf::remove(size_t size)
{
size_t bytes_available = available();
if(size >= bytes_available) {
flush();
return 0;
}
size_t size_to_remove = (size < bytes_available) ? size : bytes_available;
if(_end < _begin && size_to_remove > (size_t) (_bufend - _begin)) {
size_t top_size = _bufend - _begin;
_begin = _buf;
size_to_remove -= top_size;
}
_begin = wrap_if_bufend(_begin + size_to_remove);
return available();
}

79
cores/esp32/cbuf.h Normal file
View File

@ -0,0 +1,79 @@
/*
cbuf.h - Circular buffer implementation
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
*/
#ifndef __cbuf_h
#define __cbuf_h
#include <stddef.h>
#include <stdint.h>
#include <string.h>
class cbuf
{
public:
cbuf(size_t size);
~cbuf();
size_t resizeAdd(size_t addSize);
size_t resize(size_t newSize);
size_t available() const;
size_t size();
size_t room() const;
inline bool empty() const
{
return _begin == _end;
}
inline bool full() const
{
return wrap_if_bufend(_end + 1) == _begin;
}
int peek();
size_t peek(char *dst, size_t size);
int read();
size_t read(char* dst, size_t size);
size_t write(char c);
size_t write(const char* src, size_t size);
void flush();
size_t remove(size_t size);
cbuf *next;
private:
inline char* wrap_if_bufend(char* ptr) const
{
return (ptr == _bufend) ? _buf : ptr;
}
size_t _size;
char* _buf;
const char* _bufend;
char* _begin;
char* _end;
};
#endif//__cbuf_h

View File

@ -0,0 +1,217 @@
// 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 "esp32-hal-gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "rom/gpio.h"
#include "soc/gpio_reg.h"
#include "soc/io_mux_reg.h"
#include "soc/gpio_struct.h"
#define ETS_GPIO_INUM 4
const uint8_t esp32_gpioToFn[40] = {
0x44,//0
0x88,//1
0x40,//2
0x84,//3
0x48,//4
0x6c,//5
0x60,//6
0x64,//7
0x68,//8
0x54,//9
0x58,//10
0x5c,//11
0x34,//12
0x38,//13
0x30,//14
0x3c,//15
0x4c,//16
0x50,//17
0x70,//18
0x74,//19
0x78,//20
0x7c,//21
0x80,//22
0x8c,//23
0xFF,//N/A
0x24,//25
0x28,//26
0x2c,//27
0xFF,//N/A
0xFF,//N/A
0xFF,//N/A
0xFF,//N/A
0x1c,//32
0x20,//33
0x14,//34
0x18,//35
0x04,//36
0x08,//37
0x0c,//38
0x10 //39
};
typedef void (*voidFuncPtr)(void);
static voidFuncPtr __pinInterruptHandlers[GPIO_PIN_COUNT] = {0,};
extern void IRAM_ATTR __pinMode(uint8_t pin, uint8_t mode)
{
uint32_t pinFunction = 0, pinControl = 0;
if(pin > 39 || esp32_gpioToFn[pin] == 0xFF) {
return;
}
if(mode & INPUT) {
if(pin < 32) {
GPIO.enable_w1tc = ((uint32_t)1 << pin);
} else {
GPIO.enable1_w1tc.val = ((uint32_t)1 << (pin - 32));
}
if(mode & PULLUP) {
pinFunction |= FUN_PU;
} else if(mode & PULLDOWN) {
pinFunction |= FUN_PD;
}
} else if(mode & OUTPUT) {
if(pin < 32) {
GPIO.enable_w1ts = ((uint32_t)1 << pin);
} else {
GPIO.enable1_w1ts.val = ((uint32_t)1 << (pin - 32));
}
}
pinFunction |= ((uint32_t)2 << FUN_DRV_S);//what are the drivers?
pinFunction |= FUN_IE;//input enable but required for output as well?
if(mode & (INPUT | OUTPUT)) {
pinFunction |= ((uint32_t)2 << MCU_SEL_S);
} else if(mode == SPECIAL) {
pinFunction |= ((uint32_t)(((pin)==1||(pin)==3)?0:1) << MCU_SEL_S);
} else {
pinFunction |= ((uint32_t)(mode >> 5) << MCU_SEL_S);
}
if(mode & OPEN_DRAIN) {
pinControl = (1 << GPIO_PIN0_PAD_DRIVER_S);
}
ESP_REG(DR_REG_IO_MUX_BASE + esp32_gpioToFn[pin]) = pinFunction;
GPIO.pin[pin].val = pinControl;
}
extern void IRAM_ATTR __digitalWrite(uint8_t pin, uint8_t val)
{
if(pin > 39) {
return;
}
if(val) {
if(pin < 32) {
GPIO.out_w1ts = ((uint32_t)1 << pin);
} else {
GPIO.out1_w1ts.val = ((uint32_t)1 << (pin - 32));
}
} else {
if(pin < 32) {
GPIO.out_w1tc = ((uint32_t)1 << pin);
} else {
GPIO.out1_w1tc.val = ((uint32_t)1 << (pin - 32));
}
}
}
extern int IRAM_ATTR __digitalRead(uint8_t pin)
{
if(pin > 39) {
return 0;
}
if(pin < 32) {
return (GPIO.in >> pin) & 0x1;
} else {
return (GPIO.in1.val >> (pin - 32)) & 0x1;
}
}
static void IRAM_ATTR __onPinInterrupt(void *arg)
{
uint32_t gpio_intr_status_l=0;
uint32_t gpio_intr_status_h=0;
gpio_intr_status_l = GPIO.status;
gpio_intr_status_h = GPIO.status1.val;
GPIO.status_w1tc = gpio_intr_status_l;//Clear intr for gpio0-gpio31
GPIO.status1_w1tc.val = gpio_intr_status_h;//Clear intr for gpio32-39
uint8_t pin=0;
if(gpio_intr_status_l) {
do {
if(gpio_intr_status_l & ((uint32_t)1 << pin)) {
if(__pinInterruptHandlers[pin]) {
__pinInterruptHandlers[pin]();
}
}
} while(++pin<32);
}
if(gpio_intr_status_h) {
pin=32;
do {
if(gpio_intr_status_h & ((uint32_t)1 << (pin - 32))) {
if(__pinInterruptHandlers[pin]) {
__pinInterruptHandlers[pin]();
}
}
} while(++pin<GPIO_PIN_COUNT);
}
}
extern void __attachInterrupt(uint8_t pin, voidFuncPtr userFunc, int intr_type)
{
static bool interrupt_initialized = false;
if(!interrupt_initialized) {
interrupt_initialized = true;
ESP_INTR_DISABLE(ETS_GPIO_INUM);
intr_matrix_set(PRO_CPU_NUM, ETS_GPIO_INTR_SOURCE, ETS_GPIO_INUM);
xt_set_interrupt_handler(ETS_GPIO_INUM, &__onPinInterrupt, NULL);
ESP_INTR_ENABLE(ETS_GPIO_INUM);
}
__pinInterruptHandlers[pin] = userFunc;
ESP_INTR_DISABLE(ETS_GPIO_INUM);
GPIO.pin[pin].val = (GPIO.pin[pin].val & ~((GPIO_PIN0_INT_ENA << GPIO_PIN0_INT_ENA_S) | (GPIO_PIN0_INT_TYPE << GPIO_PIN0_INT_TYPE_S))) | (((uint32_t)0x4 << GPIO_PIN0_INT_ENA_S) | ((uint32_t)intr_type << GPIO_PIN0_INT_TYPE_S));
ESP_INTR_ENABLE(ETS_GPIO_INUM);
}
extern void __detachInterrupt(uint8_t pin)
{
__pinInterruptHandlers[pin] = NULL;
ESP_INTR_DISABLE(ETS_GPIO_INUM);
GPIO.pin[pin].val = (GPIO.pin[pin].val & ~((GPIO_PIN0_INT_ENA << GPIO_PIN0_INT_ENA_S) | (GPIO_PIN0_INT_TYPE << GPIO_PIN0_INT_TYPE_S)));
ESP_INTR_ENABLE(ETS_GPIO_INUM);
}
extern void pinMode(uint8_t pin, uint8_t mode) __attribute__ ((weak, alias("__pinMode")));
extern void digitalWrite(uint8_t pin, uint8_t val) __attribute__ ((weak, alias("__digitalWrite")));
extern int digitalRead(uint8_t pin) __attribute__ ((weak, alias("__digitalRead")));
extern void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode) __attribute__ ((weak, alias("__attachInterrupt")));
extern void detachInterrupt(uint8_t pin) __attribute__ ((weak, alias("__detachInterrupt")));

View File

@ -0,0 +1,69 @@
/*
Arduino.h - Main include file for the Arduino SDK
Copyright (c) 2005-2013 Arduino Team. 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 MAIN_ESP32_HAL_GPIO_H_
#define MAIN_ESP32_HAL_GPIO_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "esp32-hal.h"
#define LOW 0x0
#define HIGH 0x1
//GPIO FUNCTIONS
#define INPUT 0x01
#define OUTPUT 0x02
#define PULLUP 0x04
#define INPUT_PULLUP 0x05
#define PULLDOWN 0x08
#define INPUT_PULLDOWN 0x09
#define OPEN_DRAIN 0x10
#define OUTPUT_OPEN_DRAIN 0x12
#define SPECIAL 0xF0
#define FUNCTION_0 0x00
#define FUNCTION_1 0x20
#define FUNCTION_2 0x40
#define FUNCTION_3 0x70
#define FUNCTION_4 0x80
//Interrupt Modes
#define DISABLED 0x00
#define RISING 0x01
#define FALLING 0x02
#define CHANGE 0x03
#define ONLOW 0x04
#define ONHIGH 0x05
#define ONLOW_WE 0x0C
#define ONHIGH_WE 0x0D
void pinMode(uint8_t pin, uint8_t mode);
void digitalWrite(uint8_t pin, uint8_t val);
int digitalRead(uint8_t pin);
void attachInterrupt(uint8_t pin, void (*)(void), int mode);
void detachInterrupt(uint8_t pin);
#ifdef __cplusplus
}
#endif
#endif /* MAIN_ESP32_HAL_GPIO_H_ */

247
cores/esp32/esp32-hal-i2c.c Normal file
View File

@ -0,0 +1,247 @@
// 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 "esp32-hal-i2c.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "rom/ets_sys.h"
#include "soc/i2c_reg.h"
#include "soc/dport_reg.h"
#define I2C_DEV(i) (volatile i2c_dev_t *)((i)?DR_REG_I2C1_EXT_BASE:DR_REG_I2C_EXT_BASE)
//#define I2C_DEV(i) ((i2c_dev_t *)(REG_I2C_BASE(i)))
#define I2C_SCL_IDX(p) ((p==0)?I2CEXT0_SCL_OUT_IDX:((p==1)?I2CEXT1_SCL_OUT_IDX:0))
#define I2C_SDA_IDX(p) ((p==0)?I2CEXT0_SDA_OUT_IDX:((p==1)?I2CEXT1_SDA_OUT_IDX:0))
void i2cAttachSCL(i2c_t * i2c, int8_t scl)
{
pinMode(scl, INPUT);
pinMatrixOutAttach(scl, I2C_SCL_IDX(i2c->num), false, false);
pinMatrixInAttach(scl, I2C_SCL_IDX(i2c->num), false);
}
void i2cDetachSCL(i2c_t * i2c, int8_t scl)
{
pinMatrixOutDetach(scl, false, false);
pinMatrixInDetach(I2C_SCL_IDX(i2c->num), false, false);
pinMode(scl, INPUT);
}
void i2cAttachSDA(i2c_t * i2c, int8_t sda)
{
pinMode(sda, INPUT);
pinMatrixOutAttach(sda, I2C_SDA_IDX(i2c->num), false, false);
pinMatrixInAttach(sda, I2C_SDA_IDX(i2c->num), false);
}
void i2cDetachSDA(i2c_t * i2c, int8_t sda)
{
pinMatrixOutDetach(sda, false, false);
pinMatrixInDetach(I2C_SDA_IDX(i2c->num), false, false);
pinMode(sda, INPUT);
}
enum {
I2C_CMD_RSTART,
I2C_CMD_WRITE,
I2C_CMD_READ,
I2C_CMD_STOP,
I2C_CMD_END
};
/*
* index - command index (0 to 15)
* op_code - is the command
* ack_val - Each data byte is terminated by an ACK bit used to set the bit level.
* ack_exp - This bit is to set an expected ACK value for the transmitter.
* ack_check - This bit is to decide whether the transmitter checks ACK bit. 1 means yes and 0 means no.
* byte_num - This register is to store the amounts of data that is read and written. byte_num in RSTART, STOP, END is null.
* */
void i2cSetCmd(i2c_t * i2c, uint8_t index, uint8_t op_code, uint8_t byte_num, bool ack_val, bool ack_exp, bool ack_check)
{
i2c->dev->command[index].val = 0;
i2c->dev->command[index].ack_en = ack_check;
i2c->dev->command[index].ack_exp = ack_exp;
i2c->dev->command[index].ack_val = ack_val;
i2c->dev->command[index].byte_num = byte_num;
i2c->dev->command[index].op_code = op_code;
}
int i2cWrite(i2c_t * i2c, uint16_t address, bool addr_10bit, uint8_t * data, uint8_t len, bool sendStop)
{
uint8_t index = 0;
uint8_t dataLen = len + (addr_10bit?2:1);
address = (address << 1);
while(dataLen) {
uint8_t willSend = (dataLen > 32)?32:dataLen;
uint8_t dataSend = willSend;
i2cSetCmd(i2c, 0, I2C_CMD_RSTART, 0, false, false, false);//START
i2cSetCmd(i2c, 1, I2C_CMD_WRITE, willSend, false, false, true);
if(!index) {
i2c->dev->fifo_data.data = address & 0xFF;
dataSend--;
if(addr_10bit) {
i2c->dev->fifo_data.data = (address >> 8) & 0xFF;
dataSend--;
}
}
int i = 0;
while(i<dataSend) {
i++;
i2c->dev->fifo_data.data = data[index++];
}
dataLen -= willSend;
if(dataLen) {
i2cSetCmd(i2c, 2, I2C_CMD_END, 0, false, false, false);
} else if(sendStop) {
i2cSetCmd(i2c, 2, I2C_CMD_STOP, 0, false, false, true);
}
i2c->dev->ctr.trans_start = 1;
while(i2c->dev->ctr.trans_start || i2c->dev->status_reg.bus_busy || (!i2c->dev->int_raw.ack_err && !i2c->dev->command[2].done));
if(!i2c->dev->command[2].done) {
log_e("Ack Error");
return -1;
}
if(i2c->dev->status_reg.arb_lost || i2c->dev->status_reg.time_out) {
log_e("Bus Fail");
return -1;
}
}
return 0;
}
int i2cRead(i2c_t * i2c, uint16_t address, bool addr_10bit, uint8_t * data, uint8_t len, bool sendStop)
{
address = (address << 1) | 1;
uint8_t addrLen = (addr_10bit?2:1);
uint8_t index = 0;
uint8_t cmdIdx;
uint8_t willRead;
i2cSetCmd(i2c, 0, I2C_CMD_RSTART, 0, false, false, false);//START
i2cSetCmd(i2c, 1, I2C_CMD_WRITE, addrLen, false, false, true);
i2c->dev->fifo_data.data = address & 0xFF;
if(addr_10bit) {
i2c->dev->fifo_data.data = (address >> 8) & 0xFF;
}
while(len) {
cmdIdx = (index)?0:2;
willRead = (len > 32)?32:(len-1);
i2cSetCmd(i2c, cmdIdx++, I2C_CMD_READ, willRead, false, false, false);
if((len - willRead) > 1) {
i2cSetCmd(i2c, cmdIdx++, I2C_CMD_END, 0, false, false, false);
} else {
willRead++;
i2cSetCmd(i2c, cmdIdx++, I2C_CMD_READ, 1, true, false, false);
if(sendStop) {
i2cSetCmd(i2c, cmdIdx++, I2C_CMD_STOP, 0, false, false, false);
}
}
i2c->dev->ctr.trans_start = 1;
while(i2c->dev->ctr.trans_start || i2c->dev->status_reg.bus_busy || (!i2c->dev->int_raw.ack_err && !i2c->dev->command[cmdIdx-1].done));
if(!i2c->dev->command[cmdIdx-1].done) {
log_e("Ack Error");
return -1;
}
if(i2c->dev->status_reg.arb_lost || i2c->dev->status_reg.time_out) {
log_e("Bus Fail");
return -1;
}
int i = 0;
while(i<willRead) {
i++;
data[index++] = i2c->dev->fifo_data.data;
}
len -= willRead;
}
return 0;
}
void i2cResetFiFo(i2c_t * i2c)
{
//TX FIFO
i2c->dev->fifo_conf.tx_fifo_rst = 1;
i2c->dev->fifo_conf.tx_fifo_rst = 0;
//RX FIFO
i2c->dev->fifo_conf.rx_fifo_rst = 1;
i2c->dev->fifo_conf.rx_fifo_rst = 0;
}
void i2cSetFrequency(i2c_t * i2c, uint32_t clk_speed)
{
uint32_t period = (APB_CLK_FREQ/clk_speed) / 2;
i2c->dev->scl_low_period.scl_low_period = period;
i2c->dev->scl_high_period.period = period;
i2c->dev->scl_start_hold.time = 50;
i2c->dev->scl_rstart_setup.time = 50;
i2c->dev->scl_stop_hold.time = 50;
i2c->dev->scl_stop_setup.time = 50;
i2c->dev->sda_hold.time = 40;
i2c->dev->sda_sample.time = 40;
}
uint32_t i2cGetFrequency(i2c_t * i2c)
{
return APB_CLK_FREQ/(i2c->dev->scl_low_period.scl_low_period+i2c->dev->scl_high_period.period);
}
/*
* mode - 0 = Slave, 1 = Master
* slave_addr - I2C Address
* addr_10bit_en - enable slave 10bit address mode.
* clk_speed - SCL Frequency
* */
i2c_t * i2cInit(uint8_t i2c_num, uint16_t slave_addr, bool addr_10bit_en)
{
i2c_t* i2c = (i2c_t*) malloc(sizeof(i2c_t));
if(i2c == 0) {
return NULL;
}
i2c->num = i2c_num;
i2c->dev = I2C_DEV(i2c_num);
if(i2c->num == 0) {
SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG,DPORT_I2C_EXT0_CLK_EN);
CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT0_RST);
} else if(i2c->num == 1) {
SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG,DPORT_I2C_EXT1_CLK_EN);
CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG,DPORT_I2C_EXT1_RST);
}
i2c->dev->ctr.rx_lsb_first = 0 ;
i2c->dev->ctr.tx_lsb_first = 0 ;
i2c->dev->ctr.ms_mode = (slave_addr == 0);
i2c->dev->ctr.sda_force_out = 1 ;
i2c->dev->ctr.scl_force_out = 1 ;
i2c->dev->ctr.sample_scl_level = 0 ;
i2c->dev->timeout.tout = 2000;
i2c->dev->fifo_conf.nonfifo_en = 0;
if (slave_addr) {
i2c->dev->slave_addr.addr = slave_addr;
i2c->dev->slave_addr.en_10bit = addr_10bit_en;
}
return i2c;
}

View File

@ -0,0 +1,50 @@
// 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 _ESP32_HAL_I2C_H_
#define _ESP32_HAL_I2C_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "esp32-hal.h"
#include "soc/i2c_struct.h"
typedef struct {
i2c_dev_t * dev;
uint8_t num;
} i2c_t;
i2c_t * i2cInit(uint8_t i2c_num, uint16_t slave_addr, bool addr_10bit_en);
void i2cSetFrequency(i2c_t * i2c, uint32_t clk_speed);
uint32_t i2cGetFrequency(i2c_t * i2c);
void i2cResetFiFo(i2c_t * i2c);
void i2cAttachSCL(i2c_t * i2c, int8_t scl);
void i2cDetachSCL(i2c_t * i2c, int8_t scl);
void i2cAttachSDA(i2c_t * i2c, int8_t sda);
void i2cDetachSDA(i2c_t * i2c, int8_t sda);
int i2cWrite(i2c_t * i2c, uint16_t address, bool addr_10bit, uint8_t * data, uint8_t len, bool sendStop);
int i2cRead(i2c_t * i2c, uint16_t address, bool addr_10bit, uint8_t * data, uint8_t len, bool sendStop);
#ifdef __cplusplus
}
#endif
#endif /* _ESP32_HAL_I2C_H_ */

105
cores/esp32/esp32-hal-log.h Normal file
View File

@ -0,0 +1,105 @@
// 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 __ARDUHAL_LOG_H__
#define __ARDUHAL_LOG_H__
#ifdef __cplusplus
extern "C"
{
#endif
#include "sdkconfig.h"
#define ARDUHAL_LOG_LEVEL_NONE (0)
#define ARDUHAL_LOG_LEVEL_ERROR (1)
#define ARDUHAL_LOG_LEVEL_WARN (2)
#define ARDUHAL_LOG_LEVEL_INFO (3)
#define ARDUHAL_LOG_LEVEL_DEBUG (4)
#define ARDUHAL_LOG_LEVEL_VERBOSE (5)
#ifndef CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL
#define CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL ARDUHAL_LOG_LEVEL_NONE
#endif
#ifndef CONFIG_ARDUHAL_LOG_COLORS
#define CONFIG_ARDUHAL_LOG_COLORS 0
#endif
#if CONFIG_ARDUHAL_LOG_COLORS
#define ARDUHAL_LOG_COLOR_BLACK "30"
#define ARDUHAL_LOG_COLOR_RED "31" //ERROR
#define ARDUHAL_LOG_COLOR_GREEN "32" //INFO
#define ARDUHAL_LOG_COLOR_YELLOW "33" //WARNING
#define ARDUHAL_LOG_COLOR_BLUE "34"
#define ARDUHAL_LOG_COLOR_MAGENTA "35"
#define ARDUHAL_LOG_COLOR_CYAN "36" //DEBUG
#define ARDUHAL_LOG_COLOR_GRAY "37" //VERBOSE
#define ARDUHAL_LOG_COLOR_WHITE "38"
#define ARDUHAL_LOG_COLOR(COLOR) "\033[0;" COLOR "m"
#define ARDUHAL_LOG_BOLD(COLOR) "\033[1;" COLOR "m"
#define ARDUHAL_LOG_RESET_COLOR "\033[0m"
#define ARDUHAL_LOG_COLOR_E ARDUHAL_LOG_COLOR(ARDUHAL_LOG_COLOR_RED)
#define ARDUHAL_LOG_COLOR_W ARDUHAL_LOG_COLOR(ARDUHAL_LOG_COLOR_YELLOW)
#define ARDUHAL_LOG_COLOR_I ARDUHAL_LOG_COLOR(ARDUHAL_LOG_COLOR_GREEN)
#define ARDUHAL_LOG_COLOR_D ARDUHAL_LOG_COLOR(ARDUHAL_LOG_COLOR_CYAN)
#define ARDUHAL_LOG_COLOR_V ARDUHAL_LOG_COLOR(ARDUHAL_LOG_COLOR_GRAY)
#else
#define ARDUHAL_LOG_COLOR_E
#define ARDUHAL_LOG_COLOR_W
#define ARDUHAL_LOG_COLOR_I
#define ARDUHAL_LOG_COLOR_D
#define ARDUHAL_LOG_COLOR_V
#define ARDUHAL_LOG_RESET_COLOR
#endif
#define ARDUHAL_SHORT_LOG_FORMAT(letter, format) ARDUHAL_LOG_COLOR_ ## letter format ARDUHAL_LOG_RESET_COLOR "\r\n"
#define ARDUHAL_LOG_FORMAT(letter, format) ARDUHAL_LOG_COLOR_ ## letter "[" #letter "][%s():%d] " format ARDUHAL_LOG_RESET_COLOR "\r\n", __FUNCTION__, __LINE__
#if CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
#define log_v(format, ...) ets_printf(ARDUHAL_SHORT_LOG_FORMAT(V, format), ##__VA_ARGS__)
#else
#define log_v(format, ...)
#endif
#if CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
#define log_d(format, ...) ets_printf(ARDUHAL_SHORT_LOG_FORMAT(D, format), ##__VA_ARGS__)
#else
#define log_d(format, ...)
#endif
#if CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL >= ARDUHAL_LOG_LEVEL_INFO
#define log_i(format, ...) ets_printf(ARDUHAL_SHORT_LOG_FORMAT(I, format), ##__VA_ARGS__)
#else
#define log_i(format, ...)
#endif
#if CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL >= ARDUHAL_LOG_LEVEL_WARN
#define log_w(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(W, format), ##__VA_ARGS__)
#else
#define log_w(format, ...)
#endif
#if CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL >= ARDUHAL_LOG_LEVEL_ERROR
#define log_e(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__)
#else
#define log_e(format, ...)
#endif
#ifdef __cplusplus
}
#endif
#endif /* __ESP_LOGGING_H__ */

View File

@ -0,0 +1,47 @@
// 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 "esp32-hal-matrix.h"
#include "esp_attr.h"
#include "rom/gpio.h"
#define MATRIX_DETACH_OUT_SIG 0x100
#define MATRIX_DETACH_IN_LOW_PIN 0x30
#define MATRIX_DETACH_IN_LOW_HIGH 0x38
void IRAM_ATTR pinMatrixOutAttach(uint8_t pin, uint8_t function, bool invertOut, bool invertEnable)
{
gpio_matrix_out(pin, function, invertOut, invertEnable);
}
void IRAM_ATTR pinMatrixOutDetach(uint8_t pin, bool invertOut, bool invertEnable)
{
gpio_matrix_out(pin, MATRIX_DETACH_OUT_SIG, invertOut, invertEnable);
}
void IRAM_ATTR pinMatrixInAttach(uint8_t pin, uint8_t signal, bool inverted)
{
gpio_matrix_in(pin, signal, inverted);
}
void IRAM_ATTR pinMatrixInDetach(uint8_t signal, bool high, bool inverted)
{
gpio_matrix_in(high?MATRIX_DETACH_IN_LOW_HIGH:MATRIX_DETACH_IN_LOW_PIN, signal, inverted);
}
/*
void IRAM_ATTR intrMatrixAttach(uint32_t source, uint32_t inum){
intr_matrix_set(PRO_CPU_NUM, source, inum);
}
*/

View File

@ -0,0 +1,35 @@
// 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 _ESP32_HAL_MATRIX_H_
#define _ESP32_HAL_MATRIX_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "esp32-hal.h"
#include "soc/gpio_sig_map.h"
void pinMatrixOutAttach(uint8_t pin, uint8_t function, bool invertOut, bool invertEnable);
void pinMatrixOutDetach(uint8_t pin, bool invertOut, bool invertEnable);
void pinMatrixInAttach(uint8_t pin, uint8_t signal, bool inverted);
void pinMatrixInDetach(uint8_t signal, bool high, bool inverted);
#ifdef __cplusplus
}
#endif
#endif /* COMPONENTS_ARDUHAL_INCLUDE_ESP32_HAL_MATRIX_H_ */

View File

@ -0,0 +1,50 @@
// 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 "esp32-hal.h"
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_attr.h"
uint32_t IRAM_ATTR micros()
{
uint32_t ccount;
__asm__ __volatile__ ( "rsr %0, ccount" : "=a" (ccount) );
return ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ;
//return system_get_time();
}
uint32_t IRAM_ATTR millis()
{
return xTaskGetTickCount() * portTICK_PERIOD_MS;
}
void delay(uint32_t ms)
{
vTaskDelay(ms / portTICK_PERIOD_MS);
}
void delayMicroseconds(uint32_t us)
{
if(us) {
unsigned long endat = micros();
endat += us;
while(micros() < endat) {
NOP();
}
}
}

700
cores/esp32/esp32-hal-spi.c Normal file
View File

@ -0,0 +1,700 @@
// 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 "esp32-hal-spi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "rom/gpio.h"
#include "soc/spi_reg.h"
#include "soc/io_mux_reg.h"
#include "soc/gpio_sig_map.h"
#include "soc/dport_reg.h"
#define SPI_REG_BASE(p) ((p==0)?DR_REG_SPI0_BASE:((p==1)?DR_REG_SPI1_BASE:((p==2)?DR_REG_SPI2_BASE:((p==3)?DR_REG_SPI3_BASE:0))))
#define SPI_DEV(i) ((spi_dev_t *)(SPI_REG_BASE(i)))
#define SPI_CLK_IDX(p) ((p==0)?SPICLK_OUT_IDX:((p==1)?SPICLK_OUT_IDX:((p==2)?HSPICLK_OUT_IDX:((p==3)?VSPICLK_OUT_MUX_IDX:0))))
#define SPI_MISO_IDX(p) ((p==0)?SPIQ_OUT_IDX:((p==1)?SPIQ_OUT_IDX:((p==2)?HSPIQ_OUT_IDX:((p==3)?VSPIQ_OUT_IDX:0))))
#define SPI_MOSI_IDX(p) ((p==0)?SPID_IN_IDX:((p==1)?SPID_IN_IDX:((p==2)?HSPID_IN_IDX:((p==3)?VSPID_IN_IDX:0))))
#define SPI_SPI_SS_IDX(n) ((n==0)?SPICS0_OUT_IDX:((n==1)?SPICS1_OUT_IDX:((n==2)?SPICS2_OUT_IDX:SPICS0_OUT_IDX)))
#define SPI_HSPI_SS_IDX(n) ((n==0)?HSPICS0_OUT_IDX:((n==1)?HSPICS1_OUT_IDX:((n==2)?HSPICS2_OUT_IDX:HSPICS0_OUT_IDX)))
#define SPI_VSPI_SS_IDX(n) ((n==0)?VSPICS0_OUT_IDX:((n==1)?VSPICS1_OUT_IDX:((n==2)?VSPICS2_OUT_IDX:VSPICS0_OUT_IDX)))
#define SPI_SS_IDX(p, n) ((p==0)?SPI_SPI_SS_IDX(n):((p==1)?SPI_SPI_SS_IDX(n):((p==2)?SPI_HSPI_SS_IDX(n):((p==3)?SPI_VSPI_SS_IDX(n):0))))
#define SPI_INUM(u) (2)
#define SPI_INTR_SOURCE(u) ((u==0)?ETS_SPI0_INTR_SOURCE:((u==1)?ETS_SPI1_INTR_SOURCE:((u==2)?ETS_SPI2_INTR_SOURCE:((p==3)?ETS_SPI3_INTR_SOURCE:0))))
void spiAttachSCK(spi_t * spi, int8_t sck)
{
if(!spi) {
return;
}
if(sck < 0) {
if(spi->num == HSPI) {
sck = 14;
} else if(spi->num == VSPI) {
sck = 18;
} else {
sck = 6;
}
}
pinMode(sck, OUTPUT);
pinMatrixOutAttach(sck, SPI_CLK_IDX(spi->num), false, false);
}
void spiAttachMISO(spi_t * spi, int8_t miso)
{
if(!spi) {
return;
}
if(miso < 0) {
if(spi->num == HSPI) {
miso = 12;
} else if(spi->num == VSPI) {
miso = 19;
} else {
miso = 7;
}
}
pinMode(miso, INPUT);
pinMatrixInAttach(miso, SPI_MISO_IDX(spi->num), false);
}
void spiAttachMOSI(spi_t * spi, int8_t mosi)
{
if(!spi) {
return;
}
if(mosi < 0) {
if(spi->num == HSPI) {
mosi = 13;
} else if(spi->num == VSPI) {
mosi = 23;
} else {
mosi = 8;
}
}
pinMode(mosi, OUTPUT);
pinMatrixOutAttach(mosi, SPI_MOSI_IDX(spi->num), false, false);
}
void spiDetachSCK(spi_t * spi, int8_t sck)
{
if(!spi) {
return;
}
if(sck < 0) {
if(spi->num == HSPI) {
sck = 14;
} else if(spi->num == VSPI) {
sck = 18;
} else {
sck = 6;
}
}
pinMatrixOutDetach(sck, false, false);
pinMode(sck, INPUT);
}
void spiDetachMISO(spi_t * spi, int8_t miso)
{
if(!spi) {
return;
}
if(miso < 0) {
if(spi->num == HSPI) {
miso = 12;
} else if(spi->num == VSPI) {
miso = 19;
} else {
miso = 7;
}
}
pinMatrixInDetach(SPI_MISO_IDX(spi->num), false, false);
pinMode(miso, INPUT);
}
void spiDetachMOSI(spi_t * spi, int8_t mosi)
{
if(!spi) {
return;
}
if(mosi < 0) {
if(spi->num == HSPI) {
mosi = 13;
} else if(spi->num == VSPI) {
mosi = 23;
} else {
mosi = 8;
}
}
pinMatrixOutDetach(mosi, false, false);
pinMode(mosi, INPUT);
}
void spiAttachSS(spi_t * spi, uint8_t cs_num, int8_t ss)
{
if(!spi) {
return;
}
if(cs_num > 2) {
return;
}
if(ss < 0) {
cs_num = 0;
if(spi->num == HSPI) {
ss = 15;
} else if(spi->num == VSPI) {
ss = 5;
} else {
ss = 11;
}
}
pinMode(ss, OUTPUT);
pinMatrixOutAttach(ss, SPI_SS_IDX(spi->num, cs_num), false, false);
spiEnableSSPins(spi, (1 << cs_num));
}
void spiDetachSS(spi_t * spi, int8_t ss)
{
if(!spi) {
return;
}
if(ss < 0) {
if(spi->num == HSPI) {
ss = 15;
} else if(spi->num == VSPI) {
ss = 5;
} else {
ss = 11;
}
}
pinMatrixOutDetach(ss, false, false);
pinMode(ss, INPUT);
}
void spiEnableSSPins(spi_t * spi, uint8_t cs_mask)
{
if(!spi) {
return;
}
spi->dev->pin.val &= ~(cs_mask & SPI_CS_MASK_ALL);
}
void spiDisableSSPins(spi_t * spi, uint8_t cs_mask)
{
if(!spi) {
return;
}
spi->dev->pin.val |= (cs_mask & SPI_CS_MASK_ALL);
}
void spiSSEnable(spi_t * spi)
{
if(!spi) {
return;
}
spi->dev->user.cs_setup = 1;
spi->dev->user.cs_hold = 1;
}
void spiSSDisable(spi_t * spi)
{
if(!spi) {
return;
}
spi->dev->user.cs_setup = 0;
spi->dev->user.cs_hold = 0;
}
void spiSSSet(spi_t * spi)
{
if(!spi) {
return;
}
spi->dev->pin.cs_keep_active = 1;
}
void spiSSClear(spi_t * spi)
{
if(!spi) {
return;
}
spi->dev->pin.cs_keep_active = 0;
}
uint32_t spiGetClockDiv(spi_t * spi)
{
if(!spi) {
return 0;
}
return spi->dev->clock.val;
}
void spiSetClockDiv(spi_t * spi, uint32_t clockDiv)
{
if(!spi) {
return;
}
spi->dev->clock.val = clockDiv;
}
uint8_t spiGetDataMode(spi_t * spi)
{
if(!spi) {
return 0;
}
bool idleEdge = spi->dev->pin.ck_idle_edge;
bool outEdge = spi->dev->user.ck_out_edge;
if(idleEdge) {
if(outEdge) {
return SPI_MODE3;
}
return SPI_MODE2;
}
if(outEdge) {
return SPI_MODE1;
}
return SPI_MODE0;
}
void spiSetDataMode(spi_t * spi, uint8_t dataMode)
{
if(!spi) {
return;
}
switch (dataMode) {
case SPI_MODE1:
spi->dev->pin.ck_idle_edge = 0;
spi->dev->user.ck_out_edge = 1;
break;
case SPI_MODE2:
spi->dev->pin.ck_idle_edge = 1;
spi->dev->user.ck_out_edge = 0;
break;
case SPI_MODE3:
spi->dev->pin.ck_idle_edge = 1;
spi->dev->user.ck_out_edge = 1;
break;
case SPI_MODE0:
default:
spi->dev->pin.ck_idle_edge = 0;
spi->dev->user.ck_out_edge = 0;
break;
}
}
uint8_t spiGetBitOrder(spi_t * spi)
{
if(!spi) {
return 0;
}
return (spi->dev->ctrl.wr_bit_order | spi->dev->ctrl.rd_bit_order) == 0;
}
void spiSetBitOrder(spi_t * spi, uint8_t bitOrder)
{
if(!spi) {
return;
}
if (SPI_MSBFIRST == bitOrder) {
spi->dev->ctrl.wr_bit_order = 0;
spi->dev->ctrl.rd_bit_order = 0;
} else if (SPI_LSBFIRST == bitOrder) {
spi->dev->ctrl.wr_bit_order = 1;
spi->dev->ctrl.rd_bit_order = 1;
}
}
void spiStopBus(spi_t * spi)
{
if(!spi) {
return;
}
spi->dev->slave.trans_done = 0;
spi->dev->slave.slave_mode = 0;
spi->dev->pin.val = 0;
spi->dev->user.val = 0;
spi->dev->user1.val = 0;
spi->dev->ctrl.val = 0;
spi->dev->ctrl1.val = 0;
spi->dev->ctrl2.val = 0;
spi->dev->clock.val = 0;
}
spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_t bitOrder)
{
spi_t* spi = (spi_t*) malloc(sizeof(spi_t));
if(spi == 0) {
return NULL;
}
spi->num = spi_num;
spi->dev = (spi_dev_t *)SPI_DEV(spi_num);
if(spi_num == HSPI) {
SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN_1);
CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST_1);
} else if(spi_num == VSPI) {
SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN_2);
CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST_2);
} else {
SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN);
CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST);
}
spiStopBus(spi);
spiSetDataMode(spi, dataMode);
spiSetBitOrder(spi, bitOrder);
spiSetClockDiv(spi, clockDiv);
spi->dev->user.usr_mosi = 1;
spi->dev->user.usr_miso = 1;
spi->dev->user.doutdin = 1;
int i;
for(i=0; i<16; i++) {
spi->dev->data_buf[i] = 0x00000000;
}
return spi;
}
void spiWaitReady(spi_t * spi)
{
if(!spi) {
return;
}
while(spi->dev->cmd.usr);
}
void spiWrite(spi_t * spi, uint32_t *data, uint8_t len)
{
if(!spi) {
return;
}
int i;
if(len > 16) {
len = 16;
}
while(spi->dev->cmd.usr);
spi->dev->mosi_dlen.usr_mosi_dbitlen = (len * 32) - 1;
spi->dev->miso_dlen.usr_miso_dbitlen = (len * 32) - 1;
for(i=0; i<len; i++) {
spi->dev->data_buf[i] = data[i];
}
spi->dev->cmd.usr = 1;
}
void spiRead(spi_t * spi, uint32_t *data, uint8_t len)
{
if(!spi) {
return;
}
int i;
if(len > 16) {
len = 16;
}
while(spi->dev->cmd.usr);
for(i=0; i<len; i++) {
data[i] = spi->dev->data_buf[i];
}
}
void spiWriteByte(spi_t * spi, uint8_t data)
{
if(!spi) {
return;
}
while(spi->dev->cmd.usr);
spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
spi->dev->miso_dlen.usr_miso_dbitlen = 7;
spi->dev->data_buf[0] = data;
spi->dev->cmd.usr = 1;
}
uint8_t spiReadByte(spi_t * spi)
{
if(!spi) {
return 0;
}
while(spi->dev->cmd.usr);
return spi->dev->data_buf[0] & 0xFF;
}
uint32_t __spiTranslate16(uint16_t data, bool msb)
{
if(msb) {
return (data >> 8) | (data << 8);
} else {
return data;
}
}
uint32_t __spiTranslate24(uint32_t data, bool msb)
{
if(msb) {
union {
uint32_t l;
uint8_t b[4];
} out;
out.l = data;
return out.b[2] | (out.b[1] << 8) | (out.b[0] << 16);
} else {
return data;
}
}
uint32_t __spiTranslate32(uint32_t data, bool msb)
{
if(msb) {
union {
uint32_t l;
uint8_t b[4];
} out;
out.l = data;
return out.b[3] | (out.b[2] << 8) | (out.b[1] << 16) | (out.b[0] << 24);
} else {
return data;
}
}
void spiWriteWord(spi_t * spi, uint16_t data)
{
if(!spi) {
return;
}
while(spi->dev->cmd.usr);
spi->dev->mosi_dlen.usr_mosi_dbitlen = 15;
spi->dev->miso_dlen.usr_miso_dbitlen = 15;
spi->dev->data_buf[0] = __spiTranslate16(data, !spi->dev->ctrl.wr_bit_order);
spi->dev->cmd.usr = 1;
}
uint16_t spiReadWord(spi_t * spi)
{
if(!spi) {
return 0;
}
while(spi->dev->cmd.usr);
return __spiTranslate16(spi->dev->data_buf[0] & 0xFFFF, !spi->dev->ctrl.rd_bit_order);
}
void spiWriteLong(spi_t * spi, uint32_t data)
{
if(!spi) {
return;
}
while(spi->dev->cmd.usr);
spi->dev->mosi_dlen.usr_mosi_dbitlen = 31;
spi->dev->miso_dlen.usr_miso_dbitlen = 31;
spi->dev->data_buf[0] = __spiTranslate32(data, !spi->dev->ctrl.wr_bit_order);
spi->dev->cmd.usr = 1;
}
uint32_t spiReadLong(spi_t * spi)
{
if(!spi) {
return 0;
}
while(spi->dev->cmd.usr);
return __spiTranslate32(spi->dev->data_buf[0], !spi->dev->ctrl.rd_bit_order);
}
void spiTransferBits(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits)
{
if(!spi) {
return;
}
if(bits > 32) {
bits = 32;
}
uint32_t bytes = (bits + 7) / 8;//64 max
uint32_t mask = (((uint64_t)1 << bits) - 1) & 0xFFFFFFFF;
while(spi->dev->cmd.usr);
spi->dev->mosi_dlen.usr_mosi_dbitlen = (bits - 1);
spi->dev->miso_dlen.usr_miso_dbitlen = (bits - 1);
if(bytes == 1) {
spi->dev->data_buf[0] = data & mask;
} else if(bytes == 2) {
spi->dev->data_buf[0] = __spiTranslate16(data & mask, !spi->dev->ctrl.wr_bit_order);
} else if(bytes == 3) {
spi->dev->data_buf[0] = __spiTranslate24(data & mask, !spi->dev->ctrl.wr_bit_order);
} else {
spi->dev->data_buf[0] = __spiTranslate32(data & mask, !spi->dev->ctrl.wr_bit_order);
}
spi->dev->cmd.usr = 1;
if(out) {
while(spi->dev->cmd.usr);
if(bytes == 1) {
*out = spi->dev->data_buf[0] & mask;
} else if(bytes == 2) {
*out = __spiTranslate16(spi->dev->data_buf[0] & mask, !spi->dev->ctrl.wr_bit_order);
} else if(bytes == 3) {
*out = __spiTranslate24(spi->dev->data_buf[0] & mask, !spi->dev->ctrl.wr_bit_order);
} else {
*out = __spiTranslate32(spi->dev->data_buf[0] & mask, !spi->dev->ctrl.wr_bit_order);
}
}
}
void __spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t bytes)
{
if(!spi) {
return;
}
int i;
if(bytes > 64) {
bytes = 64;
}
uint32_t words = (bytes + 3) / 4;//16 max
uint32_t wordsBuf[16] = {0,};
uint8_t * bytesBuf = (uint8_t *) wordsBuf;
if(data) {
for(i=0; i<bytes; i++) {
bytesBuf[i] = data[i];//copy data to buffer
}
}
while(spi->dev->cmd.usr);
spi->dev->mosi_dlen.usr_mosi_dbitlen = ((bytes * 8) - 1);
spi->dev->miso_dlen.usr_miso_dbitlen = ((bytes * 8) - 1);
for(i=0; i<words; i++) {
spi->dev->data_buf[i] = wordsBuf[i]; //copy buffer to spi fifo
}
spi->dev->cmd.usr = 1;
if(out) {
while(spi->dev->cmd.usr);
for(i=0; i<words; i++) {
wordsBuf[i] = spi->dev->data_buf[i];//copy spi fifo to buffer
}
for(i=0; i<bytes; i++) {
out[i] = bytesBuf[i];//copy buffer to output
}
}
}
void spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t size)
{
if(!spi) {
return;
}
while(size) {
if(size > 64) {
__spiTransferBytes(spi, data, out, 64);
size -= 64;
if(data) {
data += 64;
}
if(out) {
out += 64;
}
} else {
__spiTransferBytes(spi, data, out, size);
size = 0;
}
}
}
typedef union {
uint32_t regValue;
struct {
unsigned regL :6;
unsigned regH :6;
unsigned regN :6;
unsigned regPre :13;
unsigned regEQU :1;
};
} spiClk_t;
#define ClkRegToFreq(reg) (CPU_CLK_FREQ / (((reg)->regPre + 1) * ((reg)->regN + 1)))
uint32_t spiClockDivToFrequency(uint32_t clockDiv)
{
spiClk_t reg = { clockDiv };
return ClkRegToFreq(&reg);
}
uint32_t spiFrequencyToClockDiv(uint32_t freq)
{
if(freq >= CPU_CLK_FREQ) {
return SPI_CLK_EQU_SYSCLK;
}
const spiClk_t minFreqReg = { 0x7FFFF000 };
uint32_t minFreq = ClkRegToFreq((spiClk_t*) &minFreqReg);
if(freq < minFreq) {
return minFreqReg.regValue;
}
uint8_t calN = 1;
spiClk_t bestReg = { 0 };
int32_t bestFreq = 0;
while(calN <= 0x3F) {
spiClk_t reg = { 0 };
int32_t calFreq;
int32_t calPre;
int8_t calPreVari = -2;
reg.regN = calN;
while(calPreVari++ <= 1) {
calPre = (((CPU_CLK_FREQ / (reg.regN + 1)) / freq) - 1) + calPreVari;
if(calPre > 0x1FFF) {
reg.regPre = 0x1FFF;
} else if(calPre <= 0) {
reg.regPre = 0;
} else {
reg.regPre = calPre;
}
reg.regL = ((reg.regN + 1) / 2);
calFreq = ClkRegToFreq(&reg);
if(calFreq == (int32_t) freq) {
memcpy(&bestReg, &reg, sizeof(bestReg));
break;
} else if(calFreq < (int32_t) freq) {
if(abs(freq - calFreq) < abs(freq - bestFreq)) {
bestFreq = calFreq;
memcpy(&bestReg, &reg, sizeof(bestReg));
}
}
}
if(calFreq == (int32_t) freq) {
break;
}
calN++;
}
return bestReg.regValue;
}

118
cores/esp32/esp32-hal-spi.h Normal file
View File

@ -0,0 +1,118 @@
// 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 MAIN_ESP32_HAL_SPI_H_
#define MAIN_ESP32_HAL_SPI_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "esp32-hal.h"
#include "soc/spi_struct.h"
#define SPI_HAS_TRANSACTION
#define FSPI 1 //SPI bus attached to the flash (can use the same data lines but different SS)
#define HSPI 2 //SPI bus normally mapped to pins 12 - 15, but can be matrixed to any pins
#define VSPI 3 //SPI bus normally attached to pins 5, 18, 19 and 23, but can be matrixed to any pins
// This defines are not representing the real Divider of the ESP32
// the Defines match to an AVR Arduino on 16MHz for better compatibility
#define SPI_CLOCK_DIV2 0x00101001 //8 MHz
#define SPI_CLOCK_DIV4 0x00241001 //4 MHz
#define SPI_CLOCK_DIV8 0x004c1001 //2 MHz
#define SPI_CLOCK_DIV16 0x009c1001 //1 MHz
#define SPI_CLOCK_DIV32 0x013c1001 //500 KHz
#define SPI_CLOCK_DIV64 0x027c1001 //250 KHz
#define SPI_CLOCK_DIV128 0x04fc1001 //125 KHz
#define SPI_MODE0 0
#define SPI_MODE1 1
#define SPI_MODE2 2
#define SPI_MODE3 3
#define SPI_CS0 0
#define SPI_CS1 1
#define SPI_CS2 2
#define SPI_CS_MASK_ALL 0x7
#define SPI_LSBFIRST 0
#define SPI_MSBFIRST 1
typedef struct {
spi_dev_t * dev;
uint8_t num;
} spi_t;
spi_t * spiStartBus(uint8_t spi_num, uint32_t freq, uint8_t dataMode, uint8_t bitOrder);
void spiStopBus(spi_t * spi);
//Attach/Detach Signal Pins
void spiAttachSCK(spi_t * spi, int8_t sck);
void spiAttachMISO(spi_t * spi, int8_t miso);
void spiAttachMOSI(spi_t * spi, int8_t mosi);
void spiDetachSCK(spi_t * spi, int8_t sck);
void spiDetachMISO(spi_t * spi, int8_t miso);
void spiDetachMOSI(spi_t * spi, int8_t mosi);
//Attach/Detach SS pin to SPI_CSx signal
void spiAttachSS(spi_t * spi, uint8_t cs_num, int8_t ss);
void spiDetachSS(spi_t * spi, int8_t ss);
//Enable/Disable SPI_CSx pins
void spiEnableSSPins(spi_t * spi, uint8_t cs_mask);
void spiDisableSSPins(spi_t * spi, uint8_t cs_mask);
//Enable/Disable hardware control of SPI_CSx pins
void spiSSEnable(spi_t * spi);
void spiSSDisable(spi_t * spi);
//Activate enabled SPI_CSx pins
void spiSSSet(spi_t * spi);
//Deactivate enabled SPI_CSx pins
void spiSSClear(spi_t * spi);
void spiWaitReady(spi_t * spi);
uint32_t spiGetClockDiv(spi_t * spi);
void spiSetClockDiv(spi_t * spi, uint32_t clockDiv);
uint8_t spiGetDataMode(spi_t * spi);
void spiSetDataMode(spi_t * spi, uint8_t dataMode);
uint8_t spiGetBitOrder(spi_t * spi);
void spiSetBitOrder(spi_t * spi, uint8_t bitOrder);
void spiWrite(spi_t * spi, uint32_t *data, uint8_t len);
void spiWriteByte(spi_t * spi, uint8_t data);
void spiWriteWord(spi_t * spi, uint16_t data);
void spiWriteLong(spi_t * spi, uint32_t data);
void spiRead(spi_t * spi, uint32_t *out, uint8_t len);
uint8_t spiReadByte(spi_t * spi);
uint16_t spiReadWord(spi_t * spi);
uint32_t spiReadLong(spi_t * spi);
void spiTransferBits(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits);
void spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t size);
uint32_t spiFrequencyToClockDiv(uint32_t freq);
uint32_t spiClockDivToFrequency(uint32_t freq);
#ifdef __cplusplus
}
#endif
#endif /* MAIN_ESP32_HAL_SPI_H_ */

View File

@ -0,0 +1,270 @@
// 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 "esp32-hal-uart.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "rom/uart.h"
#include "soc/uart_reg.h"
#include "soc/io_mux_reg.h"
#include "soc/gpio_sig_map.h"
#define ETS_UART2_INUM 5
#define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:( (u==2)?DR_REG_UART2_BASE:0)))
#define UART_RXD_IDX(u) ((u==0)?U0RXD_IN_IDX:( (u==1)?U1RXD_IN_IDX:( (u==2)?U2RXD_IN_IDX:0)))
#define UART_TXD_IDX(u) ((u==0)?U0TXD_OUT_IDX:( (u==1)?U1TXD_OUT_IDX:( (u==2)?U2TXD_OUT_IDX:0)))
#define UART_INUM(u) ((u==0)?ETS_UART0_INUM:( (u==1)?ETS_UART1_INUM:( (u==2)?ETS_UART2_INUM:0)))
#define UART_INTR_SOURCE(u) ((u==0)?ETS_UART0_INTR_SOURCE:( (u==1)?ETS_UART1_INTR_SOURCE:((u==2)?ETS_UART2_INTR_SOURCE:0)))
static int s_uart_debug_nr = 0;
static void IRAM_ATTR _uart_isr(void *arg)
{
uint8_t c;
BaseType_t xHigherPriorityTaskWoken;
uart_t* uart = (uart_t*)arg;
uart->dev->int_clr.val = UART_RXFIFO_FULL_INT_ENA | UART_FRM_ERR_INT_ENA | UART_RXFIFO_TOUT_INT_ENA; //Acknowledge the interrupt
while(uart->dev->status.rxfifo_cnt) {
c = uart->dev->fifo.rw_byte;
if(!xQueueIsQueueFullFromISR(uart->queue)) {
xQueueSendFromISR(uart->queue, &c, &xHigherPriorityTaskWoken);
}
}
if (xHigherPriorityTaskWoken) {
portYIELD_FROM_ISR();
}
}
uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rxPin, int8_t txPin, uint16_t queueLen, bool inverted)
{
uint32_t conf1 = 0;
if(uart_nr > 2) {
return NULL;
}
if(rxPin == -1 && txPin == -1) {
return NULL;
}
uart_t* uart = (uart_t*) malloc(sizeof(uart_t));
if(uart == 0) {
return NULL;
}
uart->dev = (uart_dev_t *)UART_REG_BASE(uart_nr);
uart->num = uart_nr;
uart->inverted = inverted;
uart->rxPin = rxPin;
uart->txPin = txPin;
uart->rxEnabled = (uart->rxPin != -1);
uart->txEnabled = (uart->txPin != -1);
uartFlush(uart);
if(uart->rxEnabled) {
uart->queue = xQueueCreate(queueLen, sizeof(uint8_t)); //initialize the queue
if(uart->queue == NULL) {
free(uart);
return NULL;
}
pinMode(uart->rxPin, INPUT);
pinMatrixInAttach(uart->rxPin, UART_RXD_IDX(uart->num), uart->inverted);
intr_matrix_set(PRO_CPU_NUM, UART_INTR_SOURCE(uart->num), UART_INUM(uart->num));
xt_set_interrupt_handler(UART_INUM(uart->num), _uart_isr, uart);
ESP_INTR_ENABLE(UART_INUM(uart->num));
conf1 = (112 << UART_RXFIFO_FULL_THRHD_S) | (0x02 << UART_RX_TOUT_THRHD_S) | UART_RX_TOUT_EN;
uart->dev->int_ena.val = UART_RXFIFO_FULL_INT_ENA | UART_FRM_ERR_INT_ENA | UART_RXFIFO_TOUT_INT_ENA;
uart->dev->int_clr.val = 0xffff;
}
if(uart->txEnabled) {
pinMode(uart->txPin, OUTPUT);
pinMatrixOutAttach(uart->txPin, UART_TXD_IDX(uart->num), uart->inverted, false);
}
uartSetBaudRate(uart, baudrate);
uart->dev->conf0.val = config;
uart->dev->conf1.val = conf1;
return uart;
}
void uartEnd(uart_t* uart)
{
if(uart == 0) {
return;
}
if(uart->rxEnabled) {
pinMode(uart->rxPin, INPUT);
if(uart->num || uart->rxPin != 3) {
pinMatrixInDetach(UART_RXD_IDX(uart->num), uart->inverted, false);
}
ESP_INTR_DISABLE(UART_INUM(uart->num));
xt_set_interrupt_handler(UART_INUM(uart->num), NULL, NULL);
vQueueDelete(uart->queue);
}
if(uart->txEnabled) {
pinMode(uart->txPin, INPUT);
if(uart->num || uart->txPin != 1) {
pinMatrixInDetach(UART_TXD_IDX(uart->num), !uart->inverted, uart->inverted);
}
}
uart->dev->conf0.val = 0;
uart->dev->conf1.val = 0;
uart->dev->int_ena.val = 0;
uart->dev->int_clr.val = 0xffff;
free(uart);
}
uint32_t uartAvailable(uart_t* uart)
{
return uxQueueMessagesWaiting(uart->queue);
}
uint8_t uartRead(uart_t* uart)
{
uint8_t c;
if(xQueueReceive(uart->queue, &c, 0)) {
return c;
}
return 0;
}
uint8_t uartPeek(uart_t* uart)
{
uint8_t c;
if(xQueuePeek(uart->queue, &c, 0)) {
return c;
}
return 0;
}
void uartWrite(uart_t* uart, uint8_t c)
{
while(uart->dev->status.rxfifo_cnt == 0x7F);
uart->dev->fifo.rw_byte = c;
}
void uartWriteBuf(uart_t* uart, const uint8_t * data, size_t len)
{
while(len && uart->dev->status.rxfifo_cnt < 0x7F) {
uart->dev->fifo.rw_byte = *data++;
len--;
}
}
void uartFlush(uart_t* uart)
{
uint32_t tmp = 0x00000000;
if(uart == 0) {
return;
}
if(uart->rxEnabled) {
tmp |= UART_RXFIFO_RST;
}
if(uart->txEnabled) {
tmp |= UART_TXFIFO_RST;
while(uart->dev->status.txfifo_cnt);
}
uart->dev->conf0.val |= (tmp);
uart->dev->conf0.val &= ~(tmp);
}
void uartSetBaudRate(uart_t* uart, uint32_t baud_rate)
{
if(uart == 0) {
return;
}
uart->baud_rate = baud_rate;
uint32_t clk_div = ((UART_CLK_FREQ<<4)/baud_rate);
uart->dev->clk_div.div_int = clk_div>>4 ;
uart->dev->clk_div.div_frag = clk_div & 0xf;
}
uint32_t uartGetBaudRate(uart_t* uart)
{
if(uart == 0) {
return 0;
}
return uart->baud_rate;
}
static void IRAM_ATTR uart0_write_char(char c)
{
while(((ESP_REG(0x01C+DR_REG_UART_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) == 0x7F);
ESP_REG(DR_REG_UART_BASE) = c;
}
static void IRAM_ATTR uart1_write_char(char c)
{
while(((ESP_REG(0x01C+DR_REG_UART1_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) == 0x7F);
ESP_REG(DR_REG_UART1_BASE) = c;
}
static void IRAM_ATTR uart2_write_char(char c)
{
while(((ESP_REG(0x01C+DR_REG_UART2_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) == 0x7F);
ESP_REG(DR_REG_UART2_BASE) = c;
}
void uartSetDebug(uart_t* uart)
{
if(uart == NULL || uart->num > 2) {
s_uart_debug_nr = -1;
ets_install_putc1(NULL);
return;
}
if(s_uart_debug_nr == uart->num) {
return;
}
s_uart_debug_nr = uart->num;
switch(s_uart_debug_nr) {
case 0:
ets_install_putc1((void (*)(char)) &uart0_write_char);
break;
case 1:
ets_install_putc1((void (*)(char)) &uart1_write_char);
break;
case 2:
ets_install_putc1((void (*)(char)) &uart2_write_char);
break;
default:
ets_install_putc1(NULL);
break;
}
}
int uartGetDebug()
{
return s_uart_debug_nr;
}

View File

@ -0,0 +1,84 @@
// 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 MAIN_ESP32_HAL_UART_H_
#define MAIN_ESP32_HAL_UART_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "esp32-hal.h"
#include "soc/uart_struct.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#define SERIAL_5N1 0x8000010
#define SERIAL_6N1 0x8000014
#define SERIAL_7N1 0x8000018
#define SERIAL_8N1 0x800001c
#define SERIAL_5N2 0x8000030
#define SERIAL_6N2 0x8000034
#define SERIAL_7N2 0x8000038
#define SERIAL_8N2 0x800003c
#define SERIAL_5E1 0x8000012
#define SERIAL_6E1 0x8000016
#define SERIAL_7E1 0x800001a
#define SERIAL_8E1 0x800001e
#define SERIAL_5E2 0x8000032
#define SERIAL_6E2 0x8000036
#define SERIAL_7E2 0x800003a
#define SERIAL_8E2 0x800003e
#define SERIAL_5O1 0x8000013
#define SERIAL_6O1 0x8000017
#define SERIAL_7O1 0x800001b
#define SERIAL_8O1 0x800001f
#define SERIAL_5O2 0x8000033
#define SERIAL_6O2 0x8000037
#define SERIAL_7O2 0x800003b
#define SERIAL_8O2 0x800003f
typedef struct {
uart_dev_t * dev;
xQueueHandle queue;
uint32_t baud_rate;
uint8_t num;
int8_t rxPin;
int8_t txPin;
bool rxEnabled;
bool txEnabled;
bool inverted;
} uart_t;
uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rxPin, int8_t txPin, uint16_t queueLen, bool inverted);
void uartEnd(uart_t* uart);
uint32_t uartAvailable(uart_t* uart);
uint8_t uartRead(uart_t* uart);
uint8_t uartPeek(uart_t* uart);
void uartWrite(uart_t* uart, uint8_t c);
void uartWriteBuf(uart_t* uart, const uint8_t * data, size_t len);
void uartFlush(uart_t* uart);
void uartSetBaudRate(uart_t* uart, uint32_t baud_rate);
uint32_t uartGetBaudRate(uart_t* uart);
void uartSetDebug(uart_t* uart);
int uartGetDebug();
#ifdef __cplusplus
}
#endif
#endif /* MAIN_ESP32_HAL_UART_H_ */

54
cores/esp32/esp32-hal.h Normal file
View File

@ -0,0 +1,54 @@
/*
Arduino.h - Main include file for the Arduino SDK
Copyright (c) 2005-2013 Arduino Team. 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 HAL_ESP32_HAL_H_
#define HAL_ESP32_HAL_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#define ESP_REG(addr) *((volatile uint32_t *)(addr))
#define NOP() asm volatile ("nop")
#include "esp32-hal-log.h"
#include "esp32-hal-matrix.h"
#include "esp32-hal-uart.h"
#include "esp32-hal-gpio.h"
#include "esp32-hal-spi.h"
#include "esp32-hal-i2c.h"
#include "esp_system.h"
uint32_t micros();
uint32_t millis();
void delay(uint32_t);
void delayMicroseconds(uint32_t us);
#ifdef __cplusplus
}
#endif
#endif /* HAL_ESP32_HAL_H_ */

7
cores/esp32/libb64/AUTHORS Executable file
View File

@ -0,0 +1,7 @@
libb64: Base64 Encoding/Decoding Routines
======================================
Authors:
-------
Chris Venter chris.venter@gmail.com http://rocketpod.blogspot.com

29
cores/esp32/libb64/LICENSE Executable file
View File

@ -0,0 +1,29 @@
Copyright-Only Dedication (based on United States law)
or Public Domain Certification
The person or persons who have associated work with this document (the
"Dedicator" or "Certifier") hereby either (a) certifies that, to the best of
his knowledge, the work of authorship identified is in the public domain of the
country from which the work is published, or (b) hereby dedicates whatever
copyright the dedicators holds in the work of authorship identified below (the
"Work") to the public domain. A certifier, moreover, dedicates any copyright
interest he may have in the associated work, and for these purposes, is
described as a "dedicator" below.
A certifier has taken reasonable steps to verify the copyright status of this
work. Certifier recognizes that his good faith efforts may not shield him from
liability if in fact the work certified is not in the public domain.
Dedicator makes this dedication for the benefit of the public at large and to
the detriment of the Dedicator's heirs and successors. Dedicator intends this
dedication to be an overt act of relinquishment in perpetuity of all present
and future rights under copyright law, whether vested or contingent, in the
Work. Dedicator understands that such relinquishment of all rights includes
the relinquishment of all rights to enforce (by lawsuit or otherwise) those
copyrights in the Work.
Dedicator recognizes that, once placed in the public domain, the Work may be
freely reproduced, distributed, transmitted, used, modified, built upon, or
otherwise exploited by anyone for any purpose, commercial or non-commercial,
and in any way, including by methods that have not yet been invented or
conceived.

94
cores/esp32/libb64/cdecode.c Executable file
View File

@ -0,0 +1,94 @@
/*
cdecoder.c - c source to a base64 decoding algorithm implementation
This is part of the libb64 project, and has been placed in the public domain.
For details, see http://sourceforge.net/projects/libb64
*/
#include "cdecode.h"
int base64_decode_value(char value_in)
{
static const char decoding[] = {62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-2,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51};
static const char decoding_size = sizeof(decoding);
value_in -= 43;
if (value_in < 0 || value_in > decoding_size) {
return -1;
}
return decoding[(int)value_in];
}
void base64_init_decodestate(base64_decodestate* state_in)
{
state_in->step = step_a;
state_in->plainchar = 0;
}
int base64_decode_block(const char* code_in, const int length_in, char* plaintext_out, base64_decodestate* state_in)
{
const char* codechar = code_in;
char* plainchar = plaintext_out;
char fragment;
*plainchar = state_in->plainchar;
switch (state_in->step) {
while (1) {
case step_a:
do {
if (codechar == code_in+length_in) {
state_in->step = step_a;
state_in->plainchar = *plainchar;
return plainchar - plaintext_out;
}
fragment = (char)base64_decode_value(*codechar++);
} while (fragment < 0);
*plainchar = (fragment & 0x03f) << 2;
case step_b:
do {
if (codechar == code_in+length_in) {
state_in->step = step_b;
state_in->plainchar = *plainchar;
return plainchar - plaintext_out;
}
fragment = (char)base64_decode_value(*codechar++);
} while (fragment < 0);
*plainchar++ |= (fragment & 0x030) >> 4;
*plainchar = (fragment & 0x00f) << 4;
case step_c:
do {
if (codechar == code_in+length_in) {
state_in->step = step_c;
state_in->plainchar = *plainchar;
return plainchar - plaintext_out;
}
fragment = (char)base64_decode_value(*codechar++);
} while (fragment < 0);
*plainchar++ |= (fragment & 0x03c) >> 2;
*plainchar = (fragment & 0x003) << 6;
case step_d:
do {
if (codechar == code_in+length_in) {
state_in->step = step_d;
state_in->plainchar = *plainchar;
return plainchar - plaintext_out;
}
fragment = (char)base64_decode_value(*codechar++);
} while (fragment < 0);
*plainchar++ |= (fragment & 0x03f);
}
}
/* control should not reach here */
return plainchar - plaintext_out;
}
int base64_decode_chars(const char* code_in, const int length_in, char* plaintext_out)
{
base64_decodestate _state;
base64_init_decodestate(&_state);
int len = base64_decode_block(code_in, length_in, plaintext_out, &_state);
if(len > 0) {
plaintext_out[len] = 0;
}
return len;
}

38
cores/esp32/libb64/cdecode.h Executable file
View File

@ -0,0 +1,38 @@
/*
cdecode.h - c header for a base64 decoding algorithm
This is part of the libb64 project, and has been placed in the public domain.
For details, see http://sourceforge.net/projects/libb64
*/
#ifndef BASE64_CDECODE_H
#define BASE64_CDECODE_H
#define base64_decode_expected_len(n) ((n * 3) / 4)
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
step_a, step_b, step_c, step_d
} base64_decodestep;
typedef struct {
base64_decodestep step;
char plainchar;
} base64_decodestate;
void base64_init_decodestate(base64_decodestate* state_in);
int base64_decode_value(char value_in);
int base64_decode_block(const char* code_in, const int length_in, char* plaintext_out, base64_decodestate* state_in);
int base64_decode_chars(const char* code_in, const int length_in, char* plaintext_out);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* BASE64_CDECODE_H */

111
cores/esp32/libb64/cencode.c Executable file
View File

@ -0,0 +1,111 @@
/*
cencoder.c - c source to a base64 encoding algorithm implementation
This is part of the libb64 project, and has been placed in the public domain.
For details, see http://sourceforge.net/projects/libb64
*/
#include "cencode.h"
const int CHARS_PER_LINE = 72;
void base64_init_encodestate(base64_encodestate* state_in)
{
state_in->step = step_A;
state_in->result = 0;
state_in->stepcount = 0;
}
char base64_encode_value(char value_in)
{
static const char* encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
if (value_in > 63) {
return '=';
}
return encoding[(int)value_in];
}
int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in)
{
const char* plainchar = plaintext_in;
const char* const plaintextend = plaintext_in + length_in;
char* codechar = code_out;
char result;
char fragment;
result = state_in->result;
switch (state_in->step) {
while (1) {
case step_A:
if (plainchar == plaintextend) {
state_in->result = result;
state_in->step = step_A;
return codechar - code_out;
}
fragment = *plainchar++;
result = (fragment & 0x0fc) >> 2;
*codechar++ = base64_encode_value(result);
result = (fragment & 0x003) << 4;
case step_B:
if (plainchar == plaintextend) {
state_in->result = result;
state_in->step = step_B;
return codechar - code_out;
}
fragment = *plainchar++;
result |= (fragment & 0x0f0) >> 4;
*codechar++ = base64_encode_value(result);
result = (fragment & 0x00f) << 2;
case step_C:
if (plainchar == plaintextend) {
state_in->result = result;
state_in->step = step_C;
return codechar - code_out;
}
fragment = *plainchar++;
result |= (fragment & 0x0c0) >> 6;
*codechar++ = base64_encode_value(result);
result = (fragment & 0x03f) >> 0;
*codechar++ = base64_encode_value(result);
++(state_in->stepcount);
if (state_in->stepcount == CHARS_PER_LINE/4) {
*codechar++ = '\n';
state_in->stepcount = 0;
}
}
}
/* control should not reach here */
return codechar - code_out;
}
int base64_encode_blockend(char* code_out, base64_encodestate* state_in)
{
char* codechar = code_out;
switch (state_in->step) {
case step_B:
*codechar++ = base64_encode_value(state_in->result);
*codechar++ = '=';
*codechar++ = '=';
break;
case step_C:
*codechar++ = base64_encode_value(state_in->result);
*codechar++ = '=';
break;
case step_A:
break;
}
*codechar = 0x00;
return codechar - code_out;
}
int base64_encode_chars(const char* plaintext_in, int length_in, char* code_out)
{
base64_encodestate _state;
base64_init_encodestate(&_state);
int len = base64_encode_block(plaintext_in, length_in, code_out, &_state);
return len + base64_encode_blockend((code_out + len), &_state);
}

41
cores/esp32/libb64/cencode.h Executable file
View File

@ -0,0 +1,41 @@
/*
cencode.h - c header for a base64 encoding algorithm
This is part of the libb64 project, and has been placed in the public domain.
For details, see http://sourceforge.net/projects/libb64
*/
#ifndef BASE64_CENCODE_H
#define BASE64_CENCODE_H
#define base64_encode_expected_len(n) ((((4 * n) / 3) + 3) & ~3)
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
step_A, step_B, step_C
} base64_encodestep;
typedef struct {
base64_encodestep step;
char result;
int stepcount;
} base64_encodestate;
void base64_init_encodestate(base64_encodestate* state_in);
char base64_encode_value(char value_in);
int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in);
int base64_encode_blockend(char* code_out, base64_encodestate* state_in);
int base64_encode_chars(const char* plaintext_in, int length_in, char* code_out);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* BASE64_CENCODE_H */

35
cores/esp32/main.cpp Normal file
View File

@ -0,0 +1,35 @@
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
void initVariant() __attribute__((weak));
void initVariant() {}
void init() __attribute__((weak));
void init() {}
void bootWiFi() __attribute__((weak));
void bootWiFi() {}
extern void loop();
extern void setup();
void loopTask(void *pvParameters)
{
bool setup_done = false;
for(;;) {
if(!setup_done) {
bootWiFi();
setup();
setup_done = true;
}
loop();
}
}
extern "C" void app_main()
{
init();
initVariant();
xTaskCreatePinnedToCore(loopTask, "loopTask", 4096, NULL, 1, NULL, 0);
}

42
cores/esp32/pgmspace.h Normal file
View File

@ -0,0 +1,42 @@
/*
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the RaspberryPi 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 PGMSPACE_INCLUDE
#define PGMSPACE_INCLUDE
typedef char __FlashStringHelper;
#define PROGMEM
#define PSTR(s) (s)
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#define pgm_read_word(addr) (*(const unsigned short *)(addr))
#define pgm_read_dword(addr) (*(const unsigned long *)(addr))
#define pgm_read_float(addr) (*(const float *)(addr))
#define pgm_read_byte_near(addr) pgm_read_byte(addr)
#define pgm_read_word_near(addr) pgm_read_word(addr)
#define pgm_read_dword_near(addr) pgm_read_dword(addr)
#define pgm_read_float_near(addr) pgm_read_float(addr)
#define pgm_read_byte_far(addr) pgm_read_byte(addr)
#define pgm_read_word_far(addr) pgm_read_word(addr)
#define pgm_read_dword_far(addr) pgm_read_dword(addr)
#define pgm_read_float_far(addr) pgm_read_float(addr)
#define memcpy_P(to,from,len) memcpy(to,from,len)
#endif

View File

@ -0,0 +1,49 @@
/*
stdlib_noniso.h - nonstandard (but usefull) conversion functions
Copyright (c) 2014 Ivan Grokhotkov. All rights 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 STDLIB_NONISO_H
#define STDLIB_NONISO_H
#ifdef __cplusplus
extern "C" {
#endif
int atoi(const char *s);
long atol(const char* s);
double atof(const char* s);
char* itoa (int val, char *s, int radix);
char* ltoa (long val, char *s, int radix);
char* utoa (unsigned int val, char *s, int radix);
char* ultoa (unsigned long val, char *s, int radix);
char* dtostrf (double val, signed char width, unsigned char prec, char *s);
#ifdef __cplusplus
} // extern "C"
#endif
#endif

View File

@ -0,0 +1,45 @@
/*
wiring_private.h - Internal header file.
Part of Arduino - http://www.arduino.cc/
Copyright (c) 2005-2006 David A. Mellis
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., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
$Id: wiring.h 239 2007-01-12 17:58:39Z mellis $
*/
#ifndef WiringPrivate_h
#define WiringPrivate_h
#include <stdio.h>
#include <stdarg.h>
#include "arducore.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*voidFuncPtr)(void);
void initPins();
#ifdef __cplusplus
} // extern "C"
#endif
#endif

View File

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

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

232
libraries/SPI/src/SPI.cpp Normal file
View File

@ -0,0 +1,232 @@
/*
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)
{}
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::beginTransaction(SPISettings settings)
{
spiWaitReady(_spi);
setFrequency(settings._clock);
setBitOrder(settings._bitOrder);
setDataMode(settings._dataMode);
}
void SPIClass::endTransaction() {}
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::write(uint8_t data)
{
spiWriteByte(_spi, data);
}
uint8_t SPIClass::transfer(uint8_t data)
{
spiWriteByte(_spi, data);
return spiReadByte(_spi);
}
void SPIClass::write16(uint16_t data)
{
spiWriteWord(_spi, data);
}
uint16_t SPIClass::transfer16(uint16_t data)
{
spiWriteWord(_spi, data);
return spiReadWord(_spi);
}
void SPIClass::write32(uint32_t data)
{
spiWriteLong(_spi, data);
}
uint32_t SPIClass::transfer32(uint32_t data)
{
spiWriteLong(_spi, data);
return spiReadLong(_spi);
}
void SPIClass::transferBits(uint32_t data, uint32_t * out, uint8_t bits)
{
spiTransferBits(_spi, data, out, bits);
}
/**
* Note:
* data need to be aligned to 32Bit
* or you get an Fatal exception (9)
* @param data uint8_t *
* @param size uint32_t
*/
void SPIClass::writeBytes(uint8_t * data, uint32_t size)
{
spiTransferBytes(_spi, data, 0, size);
}
/**
* @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)
{
spiTransferBytes(_spi, data, out, size);
}
/**
* Note:
* data need to be aligned to 32Bit
* or you get an Fatal exception (9)
* @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);

81
libraries/SPI/src/SPI.h Normal file
View File

@ -0,0 +1,81 @@
/*
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
{
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 write16(uint16_t data, bool msb);
void write32(uint32_t data);
void write32(uint32_t data, bool msb);
void writeBytes(uint8_t * data, uint32_t size);
void writePattern(uint8_t * data, uint8_t size, uint32_t repeat);
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;
void writePattern_(uint8_t * data, uint8_t size, uint8_t repeat);
};
extern SPIClass SPI;
#endif

View File

@ -0,0 +1,90 @@
/*
* HTTP over TLS (HTTPS) example sketch
*
* This example demonstrates how to use
* WiFiClientSecure class to access HTTPS API.
* We fetch and display the status of
* esp8266/Arduino project continuous integration
* build.
*
* Created by Ivan Grokhotkov, 2015.
* This example is in public domain.
*/
#include <WiFi.h>
#include <WiFiClientSecure.h>
const char* ssid = "........";
const char* password = "........";
const char* host = "api.github.com";
const int httpsPort = 443;
// Use web browser to view and copy
// SHA1 fingerprint of the certificate
const char* fingerprint = "CF 05 98 89 CA FF 8E D8 5E 5C E0 C2 E4 F7 E6 C3 C7 50 DD 5C";
void setup()
{
Serial.begin(115200);
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());
// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;
Serial.print("connecting to ");
Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
if (client.verify(fingerprint, host)) {
Serial.println("certificate matches");
} else {
Serial.println("certificate doesn't match");
}
String url = "/repos/esp8266/Arduino/commits/master/status";
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
String line = client.readStringUntil('\n');
if (line.startsWith("{\"state\":\"success\"")) {
Serial.println("esp8266/Arduino CI successfull!");
} else {
Serial.println("esp8266/Arduino CI has failed");
}
Serial.println("reply was:");
Serial.println("==========");
Serial.println(line);
Serial.println("==========");
Serial.println("closing connection");
}
void loop()
{
}

View File

@ -0,0 +1,152 @@
/*
Udp NTP Client
Get the time from a Network Time Protocol (NTP) time server
Demonstrates use of UDP sendPacket and ReceivePacket
For more on NTP time servers and the messages needed to communicate with them,
see http://en.wikipedia.org/wiki/Network_Time_Protocol
created 4 Sep 2010
by Michael Margolis
modified 9 Apr 2012
by Tom Igoe
updated for the ESP8266 12 Apr 2015
by Ivan Grokhotkov
This code is in the public domain.
*/
#include <WiFi.h>
#include <WiFiUdp.h>
char ssid[] = "*************"; // your network SSID (name)
char pass[] = "********"; // your network password
unsigned int localPort = 2390; // local port to listen for UDP packets
/* Don't hardwire the IP address or we won't get the benefits of the pool.
* Lookup the IP address for the host name instead */
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "time.nist.gov";
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println();
// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Starting UDP");
udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(udp.localPort());
}
void loop()
{
//get a random server from the pool
WiFi.hostByName(ntpServerName, timeServerIP);
sendNTPpacket(timeServerIP); // send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);
int cb = udp.parsePacket();
if (!cb) {
Serial.println("no packet yet");
} else {
Serial.print("packet received, length=");
Serial.println(cb);
// We've received a packet, read the data from it
udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);
// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ( (epoch % 60) < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(epoch % 60); // print the second
}
// wait ten seconds before asking for the time again
delay(10000);
}
// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(IPAddress& address)
{
Serial.println("sending NTP packet...");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
udp.beginPacket(address, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
}

View File

@ -0,0 +1,71 @@
/*
* Copyright (c) 2015, Majenko Technologies
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* * Neither the name of Majenko Technologies nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Create a WiFi access point and provide a web server on it. */
#include <WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
/* Set these to your desired credentials. */
const char *ssid = "ESPap";
const char *password = "thereisnospoon";
ESP8266WebServer server(80);
/* Just a little test message. Go to http://192.168.4.1 in a web browser
* connected to this access point to see it.
*/
void handleRoot()
{
server.send(200, "text/html", "<h1>You are connected</h1>");
}
void setup()
{
delay(1000);
Serial.begin(115200);
Serial.println();
Serial.print("Configuring access point...");
/* You can remove the password parameter if you want the AP to be open. */
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on("/", handleRoot);
server.begin();
Serial.println("HTTP server started");
}
void loop()
{
server.handleClient();
}

View File

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

View File

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

@ -0,0 +1,51 @@
/*
* 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 WIFI_EVENT_STAMODE_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
break;
case WIFI_EVENT_STAMODE_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

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

View File

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

View File

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

View File

@ -0,0 +1,100 @@
/*
* This sketch demonstrates how to set up a simple HTTP-like server.
* The server will set a GPIO pin depending on the request
* http://server_ip/gpio/0 will set the GPIO2 low,
* http://server_ip/gpio/1 will set the GPIO2 high
* server_ip is the IP address of the ESP8266 module, will be
* printed to Serial when the module is connected.
*/
#include <WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
delay(10);
// prepare GPIO2
pinMode(2, OUTPUT);
digitalWrite(2, 0);
// Connect to 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");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop()
{
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()) {
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
// Match the request
int val;
if (req.indexOf("/gpio/0") != -1) {
val = 0;
} else if (req.indexOf("/gpio/1") != -1) {
val = 1;
} else {
Serial.println("invalid request");
client.stop();
return;
}
// Set GPIO2 according to the request
digitalWrite(2, val);
client.flush();
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
s += (val)?"high":"low";
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");
// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}

View File

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

View File

@ -0,0 +1,9 @@
name=WiFi
version=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

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

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

@ -0,0 +1,62 @@
/*
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 "WiFiType.h"
#include "WiFiSTA.h"
#include "WiFiAP.h"
#include "WiFiScan.h"
#include "WiFiGeneric.h"
#include "WiFiClient.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;
};
extern WiFiClass WiFi;
#endif

View File

@ -0,0 +1,234 @@
/*
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)) {
return tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP);
}
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()
{
uint16_t number;
if(esp_wifi_get_ap_num(&number) == ESP_OK) {
return number;
}
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);
}

View File

@ -0,0 +1,55 @@
/*
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();
uint8_t* softAPmacAddress(uint8_t* mac);
String softAPmacAddress(void);
protected:
};
#endif /* ESP32WIFIAP_H_*/

View File

@ -0,0 +1,250 @@
/*
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)
{
//ets_printf("WiFiClient(%d)\n", sockfd);
}
WiFiClient::WiFiClient(int fd):sockfd(fd),_connected(true),next(NULL)
{
ets_printf("WiFiClient(%d)\n", sockfd);
}
WiFiClient::~WiFiClient()
{
if(sockfd >= 0) {
ets_printf("~WiFiClient(%d)\n", sockfd);
}
//stop();
}
WiFiClient & WiFiClient::operator=(const WiFiClient &other)
{
ets_printf("WiFiClient(%d) = (%d)\n", sockfd, other.sockfd);
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("error: %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("error: %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("error: %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("error: %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("error: %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("error: %d", errno);
_connected = false;
sockfd = -1;
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("error: %d", errno);
_connected = false;
sockfd = -1;
}
return res;
}
int WiFiClient::available()
{
if(!_connected) {
return 0;
}
int count;
int res = ioctl(sockfd, FIONREAD, &count);
if(res < 0) {
log_e("error: %d", errno);
_connected = false;
sockfd = -1;
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

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

@ -0,0 +1,333 @@
/*
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 "esp32-hal-log.h"
}
//#include "WiFiClient.h"
//#include "WiFiUdp.h"
#undef min
#undef max
#include <vector>
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------- 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
*/
esp_err_t WiFiGenericClass::_eventCallback(void *arg, system_event_t *event)
{
log_d("wifi evt: %d", 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;
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);
}
log_d("wifi reason: %d", reason);
} 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)
{
if(getMode() == m) {
return true;
}
return esp_wifi_set_mode(m) == ESP_OK;
}
/**
* get WiFi mode
* @return WiFiMode
*/
wifi_mode_t WiFiGenericClass::getMode()
{
uint8_t mode;
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 ---------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
void wifi_dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg);
/**
* 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
*/
static bool _dns_busy = false;
int WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult)
{
ip_addr_t addr;
aResult = static_cast<uint32_t>(0);
err_t err = dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult);
_dns_busy = err == ERR_INPROGRESS;
while(_dns_busy);
if(err == ERR_INPROGRESS && aResult) {
//found by search
} else if(err == ERR_OK && addr.u_addr.ip4.addr) {
aResult = addr.u_addr.ip4.addr;
} else {
return 0;
}
return 1;
}
/**
* DNS callback
* @param name
* @param ipaddr
* @param callback_arg
*/
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;
}
/**
* 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.
* */
#include "nvs_flash.h"
void bootWiFi()
{
esp_err_t err;
wifi_init_config_t cfg;
wifi_mode_t mode = WIFI_MODE_NULL;
bool auto_connect = false;
err = nvs_flash_init();
if (err != ESP_OK) {
log_e("nvs_flash_init fail %d", err);
return;
}
system_init();
tcpip_adapter_init();
esp_event_loop_init(WiFiGenericClass::_eventCallback, NULL);
cfg.event_handler = &esp_event_send;
err = esp_wifi_init(&cfg);
if (err != ESP_OK) {
log_e("esp_wifi_init fail %d\n", err);
return;
}
err = esp_wifi_start();
if (err != ESP_OK) {
log_e("esp_wifi_start fail %d\n", err);
return;
}
err = esp_wifi_get_mode(&mode);
if (err != ESP_OK) {
log_e("esp_wifi_get_mode fail %d\n", err);
return;
}
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 fail %d\n", err);
}
}
}

View File

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

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

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

@ -0,0 +1,455 @@
/*
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"
}
extern "C" void esp_schedule();
extern "C" void esp_yield();
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- 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(!_useStaticIp) {
tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA);
}
if(connect) {
esp_wifi_connect();
}
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);
}
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)) {
_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_config_t conf;
esp_wifi_get_config(WIFI_IF_STA, &conf);
return String(reinterpret_cast<char*>(conf.sta.ssid));
}
/**
* 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_config_t conf;
esp_wifi_get_config(WIFI_IF_STA, &conf);
memcpy(bssid, conf.sta.bssid, 6);
return reinterpret_cast<uint8_t*>(bssid);
}
/**
* Return the current bssid / mac associated with the network if configured
* @return String bssid mac
*/
String WiFiSTAClass::BSSIDstr(void)
{
char mac[18] = { 0 };
wifi_config_t conf;
esp_wifi_get_config(WIFI_IF_STA, &conf);
sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", conf.sta.bssid[0], conf.sta.bssid[1], conf.sta.bssid[2], conf.sta.bssid[3], conf.sta.bssid[4], conf.sta.bssid[5]);
return String(mac);
}
/**
* Return the current network RSSI.
* @return RSSI value
*/
int32_t WiFiSTAClass::RSSI(void)
{
return 0;//wifi_station_get_rssi();
}

View File

@ -0,0 +1,85 @@
/*
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);
// STA WiFi info
wl_status_t status();
String SSID() const;
String psk() const;
uint8_t * BSSID();
String BSSIDstr();
int32_t RSSI();
static void _setStatus(wl_status_t status);
protected:
static wl_status_t _status;
static bool _useStaticIp;
};
#endif /* ESP32WIFISTA_H_ */

View File

@ -0,0 +1,268 @@
/*
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_get_ap_num(&(WiFiScanClass::_scanCount));
if(WiFiScanClass::_scanCount) {
WiFiScanClass::_scanResult = new wifi_ap_list_t[WiFiScanClass::_scanCount];
if(WiFiScanClass::_scanResult) {
esp_wifi_get_ap_list(&(WiFiScanClass::_scanCount), (wifi_ap_list_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_list_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_list_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_list_t* it = reinterpret_cast<wifi_ap_list_t*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
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_list_t* it = reinterpret_cast<wifi_ap_list_t*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
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_list_t* it = reinterpret_cast<wifi_ap_list_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_list_t* it = reinterpret_cast<wifi_ap_list_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_list_t* it = reinterpret_cast<wifi_ap_list_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_list_t* it = reinterpret_cast<wifi_ap_list_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_list_t* it = reinterpret_cast<wifi_ap_list_t*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->primary;
}

View File

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

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

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

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

211
libraries/Wire/src/Wire.cpp Normal file
View File

@ -0,0 +1,211 @@
/*
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"
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 = I2C0_DEFAULT_SDA_PIN;
} else {
return;
}
}
if(sclPin < 0) {
if(num == 0) {
sclPin = I2C0_DEFAULT_SCL_PIN;
} 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();
}
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);

97
libraries/Wire/src/Wire.h Normal file
View File

@ -0,0 +1,97 @@
/*
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"
#define I2C_BUFFER_LENGTH 128
#define I2C0_DEFAULT_SDA_PIN 21
#define I2C0_DEFAULT_SCL_PIN 22
class TwoWire
{
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(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

@ -0,0 +1,76 @@
{
"packages": [
{
"name": "esp32",
"maintainer": "Espressif Systems",
"websiteURL": "https://github.com/espressif/esp32-arduino",
"email": "hristo@espressif.com",
"help": {
"online": "http://esp32.com"
},
"platforms": [
{
"name": "esp32",
"architecture": "esp32",
"version": "",
"category": "ESP32",
"url": "",
"archiveFileName": "",
"checksum": "",
"size": "",
"help": {
"online": ""
},
"boards": [
{
"name": "ESP32 Dev Module"
}
],
"toolsDependencies": [
{
"packager": "esp32",
"name": "xtensa-esp32-elf-gcc",
"version": "1.22.0-59"
}
]
}
],
"tools": [
{
"name": "xtensa-esp32-elf-gcc",
"version": "1.22.0-59",
"systems": [
{
"host": "i686-mingw32",
"url": "https://dl.espressif.com/dl/xtensa-esp32-elf-win32-1.22.0-59.zip",
"archiveFileName": "xtensa-esp32-elf-win32-1.22.0-59.zip",
"checksum": "SHA-256:10476b9c11a7a90f40883413ddfb409f505b20692e316c4e597c4c175b4be09c",
"size": "153527527"
},
{
"host": "x86_64-apple-darwin",
"url": "https://dl.espressif.com/dl/xtensa-esp32-elf-osx-1.22.0-59.tar.gz",
"archiveFileName": "xtensa-esp32-elf-osx-1.22.0-59.tar.gz",
"checksum": "SHA-256:0cf150193997bd1355e0f49d3d49711730035257bc1aee1eaaad619e56b9e4e6",
"size": "35385382"
},
{
"host": "x86_64-pc-linux-gnu",
"url": "https://dl.espressif.com/dl/xtensa-esp32-elf-linux64-1.22.0-59.tar.gz",
"archiveFileName": "xtensa-esp32-elf-linux64-1.22.0-59.tar.gz",
"checksum": "SHA-256:46f057fbd8b320889a26167daf325038912096d09940b2a95489db92431473b7",
"size": "30262903"
},
{
"host": "i686-pc-linux-gnu",
"url": "https://dl.espressif.com/dl/xtensa-esp32-elf-linux32-1.22.0-59.tar.gz",
"archiveFileName": "xtensa-esp32-elf-linux32-1.22.0-59.tar.gz",
"checksum": "SHA-256:b24817819f0078fb05895a640e806e0aca9aa96b47b80d2390ac8e2d9ddc955a",
"size": "32734156"
}
]
}
]
}
]
}

97
platform.txt Normal file
View File

@ -0,0 +1,97 @@
name=ESP32 Arduino
version=0.0.1
runtime.tools.xtensa-esp32-elf-gcc.path={runtime.platform.path}/tools/xtensa-esp32-elf
runtime.tools.esptool.path={runtime.platform.path}/tools/esptool.py
compiler.warning_flags=-w
compiler.warning_flags.none=-w
compiler.warning_flags.default=
compiler.warning_flags.more=-Wall
compiler.warning_flags.all=-Wall -Wextra
compiler.path={runtime.tools.xtensa-esp32-elf-gcc.path}/bin/
compiler.sdk.path={runtime.platform.path}/tools/sdk
compiler.cpreprocessor.flags=-DESP_PLATFORM -DMBEDTLS_CONFIG_FILE='"mbedtls/esp_config.h"' -DHAVE_CONFIG_H "-I{compiler.sdk.path}/include/config" "-I{compiler.sdk.path}/include/bt" "-I{compiler.sdk.path}/include/driver" "-I{compiler.sdk.path}/include/esp32" "-I{compiler.sdk.path}/include/freertos" "-I{compiler.sdk.path}/include/log" "-I{compiler.sdk.path}/include/newlib" "-I{compiler.sdk.path}/include/nvs_flash" "-I{compiler.sdk.path}/include/spi_flash" "-I{compiler.sdk.path}/include/tcpip_adapter" "-I{compiler.sdk.path}/include/expat" "-I{compiler.sdk.path}/include/json" "-I{compiler.sdk.path}/include/mbedtls" "-I{compiler.sdk.path}/include/nghttp" "-I{compiler.sdk.path}/include/lwip"
compiler.c.cmd=xtensa-esp32-elf-gcc
compiler.c.flags=-c {compiler.warning_flags} -Os -g3 -Wpointer-arith -Wno-error=unused-function -Wno-error=unused-but-set-variable -Wno-error=unused-variable -ffunction-sections -fdata-sections -mlongcalls -nostdlib -MMD -std=gnu99 -fstrict-volatile-bitfields
compiler.cpp.cmd=xtensa-esp32-elf-g++
compiler.cpp.flags=-c {compiler.warning_flags} -Os -g3 -Wpointer-arith -Wno-error=unused-function -Wno-error=unused-but-set-variable -Wno-error=unused-variable -fno-rtti -ffunction-sections -fdata-sections -mlongcalls -nostdlib -MMD -std=gnu++11 -fno-exceptions -fstrict-volatile-bitfields
compiler.S.cmd=xtensa-esp32-elf-gcc
compiler.S.flags=-c -g3 -x assembler-with-cpp -MMD -mlongcalls
compiler.c.elf.cmd=xtensa-esp32-elf-gcc
compiler.c.elf.flags="-L{compiler.sdk.path}/lib" "-L{compiler.sdk.path}/ld" -nostdlib -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -u call_user_start_cpu0 -Wl,--gc-sections -Wl,-static -Wl,--undefined=uxTopUsedPriority
compiler.c.elf.libs=-lgcc -lc -lm -lhal -lcore -lnet80211 -lphy -lrtc -lpp -lwpa -lsmartconfig -lbtdm_app -lbt -ldriver -lesp32 -lcrypto -lexpat -lfreertos -ljson -llog -llwip -lmbedtls -lnghttp -lnvs_flash -lspi_flash -ltcpip_adapter
compiler.as.cmd=xtensa-esp32-elf-as
compiler.ar.cmd=xtensa-esp32-elf-ar
compiler.ar.flags=cru
compiler.elf2hex.cmd=esptool.py
compiler.elf2hex.flags=
compiler.size.cmd=xtensa-esp32-elf-size
compiler.python.cmd=python
compiler.python.cmd.windows=python.exe
# This can be overriden in boards.txt
build.extra_flags=-DESP32
# These can be overridden in platform.local.txt
compiler.c.extra_flags=
compiler.c.elf.extra_flags=
compiler.S.extra_flags=
compiler.cpp.extra_flags=
compiler.ar.extra_flags=
compiler.objcopy.eep.extra_flags=
compiler.elf2hex.extra_flags=
## Compile c files
recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.cpreprocessor.flags} {compiler.c.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Compile c++ files
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor.flags} {compiler.cpp.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Compile S files
recipe.S.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.cpreprocessor.flags} {compiler.S.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"
## Create archives
recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/arduino.ar" "{object_file}"
## Combine gc-sections, archives, and objects
recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} -Wl,--start-group {object_files} "{build.path}/arduino.ar" {compiler.c.elf.libs} -Wl,--end-group -o "{build.path}/{build.project_name}.elf"
## Create eeprom
recipe.objcopy.eep.pattern=
## Create hex
recipe.objcopy.hex.pattern="{compiler.python.cmd}" "{runtime.platform.path}/tools/esptool.py" --chip esp32 elf2image --flash_mode "{build.flash_mode}" --flash_freq "{build.flash_freq}" -o "{build.path}/{build.project_name}.bin" "{build.path}/{build.project_name}.elf"
## Save hex
recipe.output.tmp_file={build.project_name}.bin
recipe.output.save_file={build.project_name}.{build.variant}.bin
## Compute size
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=^(?:\.iram0\.text|\.dram0\.text|\.flash\.text|\.dram0\.data|\.flash\.rodata|)\s+([0-9]+).*
recipe.size.regex.data=^(?:\.dram0\.data|\.flash\.rodata|\.dram0\.bss)\s+([0-9]+).*
# ------------------------------
tools.esptool.cmd=python
tools.esptool.cmd.windows=python.exe
tools.esptool.path={runtime.platform.path}/tools/esptool.py
tools.esptool.network_cmd=python
tools.esptool.network_cmd.windows=python.exe
tools.esptool.upload.protocol=esp32
tools.esptool.upload.params.verbose=
tools.esptool.upload.params.quiet=
tools.esptool.upload.pattern="{cmd}" "{path}" --chip esp32 --port "{serial.port}" --baud {upload.speed} write_flash -z --flash_freq {build.flash_freq} --flash_mode {build.flash_mode} 0x1000 "{runtime.platform.path}/tools/sdk/bin/bootloader.bin" 0x4000 "{runtime.platform.path}/tools/sdk/bin/partitions_singleapp.bin" 0x10000 "{build.path}/{build.project_name}.bin"

0
programmers.txt Normal file
View File

1816
tools/esptool.py Executable file

File diff suppressed because it is too large Load Diff

116
tools/get.py Executable file
View File

@ -0,0 +1,116 @@
#!/usr/bin/env python
# This script will download and extract required tools into the current directory.
# Tools list is obtained from package/package_esp8266com_index.template.json file.
# Written by Ivan Grokhotkov, 2015.
#
from __future__ import print_function
import os
import shutil
import errno
import os.path
import hashlib
import json
import platform
import sys
import tarfile
import zipfile
import re
if sys.version_info[0] == 3:
from urllib.request import urlretrieve
else:
# Not Python 3 - today, it is most likely to be Python 2
from urllib import urlretrieve
dist_dir = 'dist/'
def sha256sum(filename, blocksize=65536):
hash = hashlib.sha256()
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hash.update(block)
return hash.hexdigest()
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno != errno.EEXIST or not os.path.isdir(path):
raise
def report_progress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
percent = min(100, percent)
sys.stdout.write("\r%d%%" % percent)
sys.stdout.flush()
def unpack(filename, destination):
dirname = ''
print('Extracting {0}'.format(filename))
if filename.endswith('tar.gz'):
tfile = tarfile.open(filename, 'r:gz')
tfile.extractall(destination)
dirname= tfile.getnames()[0]
elif filename.endswith('zip'):
zfile = zipfile.ZipFile(filename)
zfile.extractall(destination)
dirname = zfile.namelist()[0]
else:
raise NotImplementedError('Unsupported archive type')
# a little trick to rename tool directories so they don't contain version number
rename_to = re.match(r'^([a-z][^\-]*\-*)+', dirname).group(0).strip('-')
if rename_to != dirname:
print('Renaming {0} to {1}'.format(dirname, rename_to))
if os.path.isdir(rename_to):
shutil.rmtree(rename_to)
shutil.move(dirname, rename_to)
def get_tool(tool):
archive_name = tool['archiveFileName']
local_path = dist_dir + archive_name
url = tool['url']
#real_hash = tool['checksum'].split(':')[1]
if not os.path.isfile(local_path):
print('Downloading ' + archive_name);
urlretrieve(url, local_path, report_progress)
sys.stdout.write("\rDone\n")
sys.stdout.flush()
else:
print('Tool {0} already downloaded'.format(archive_name))
#local_hash = sha256sum(local_path)
#if local_hash != real_hash:
# print('Hash mismatch for {0}, delete the file and try again'.format(local_path))
# raise RuntimeError()
unpack(local_path, '.')
def load_tools_list(filename, platform):
tools_info = json.load(open(filename))['packages'][0]['tools']
tools_to_download = []
for t in tools_info:
tool_platform = [p for p in t['systems'] if p['host'] == platform]
if len(tool_platform) == 0:
continue
tools_to_download.append(tool_platform[0])
return tools_to_download
def identify_platform():
arduino_platform_names = {'Darwin' : {32 : 'i386-apple-darwin', 64 : 'x86_64-apple-darwin'},
'Linux' : {32 : 'i686-pc-linux-gnu', 64 : 'x86_64-pc-linux-gnu'},
'LinuxARM': {32 : 'arm-linux-gnueabihf', 64 : 'aarch64-linux-gnu'},
'Windows' : {32 : 'i686-mingw32', 64 : 'i686-mingw32'}}
bits = 32
if sys.maxsize > 2**32:
bits = 64
sys_name = platform.system()
if 'Linux' in sys_name and platform.platform().find('arm') > 0:
sys_name = 'LinuxARM'
if 'CYGWIN_NT' in sys_name:
sys_name = 'Windows'
return arduino_platform_names[sys_name][bits]
if __name__ == '__main__':
print('Platform: {0}'.format(identify_platform()))
tools_to_download = load_tools_list('../package/package_esp32_index.template.json', identify_platform())
mkdir_p(dist_dir)
for tool in tools_to_download:
get_tool(tool)

Binary file not shown.

Binary file not shown.

69
tools/sdk/include/bt/bt.h Normal file
View File

@ -0,0 +1,69 @@
// 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 __BT_H__
#define __BT_H__
#include <stdint.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Initialize BT controller
*
* This function should be called only once, before any other BT functions are called.
*/
void bt_controller_init();
/** @brief: vhci_host_callback
* used for vhci call host function to notify what host need to do
*
* notify_host_send_available: notify host can send packet to controller
* notify_host_recv: notify host that controller has packet send to host
*/
typedef struct vhci_host_callback {
void (*notify_host_send_available)(void);
int (*notify_host_recv)(uint8_t *data, uint16_t len);
} vhci_host_callback_t;
/** @brief: API_vhci_host_check_send_available
* used for check actively if the host can send packet to controller or not.
* return true for ready to send, false means cannot send packet
*/
bool API_vhci_host_check_send_available(void);
/** @brief: API_vhci_host_send_packet
* host send packet to controller
* param data is the packet point, the param len is the packet length
* return void
*/
void API_vhci_host_send_packet(uint8_t *data, uint16_t len);
/** @brief: API_vhci_host_register_callback
* register the vhci referece callback, the call back
* struct defined by vhci_host_callback structure.
* param is the vhci_host_callback type variable
*/
void API_vhci_host_register_callback(const vhci_host_callback_t *callback);
#ifdef __cplusplus
}
#endif
#endif /* __BT_H__ */

View File

@ -0,0 +1,49 @@
/*
*
* Automatically generated file; DO NOT EDIT.
* Espressif IoT Development Framework Configuration
*
*/
#define CONFIG_TRACEMEM_RESERVE_DRAM 0x0
#define CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE 1
#define CONFIG_ESPTOOLPY_FLASHFREQ "80m"
#define CONFIG_NEWLIB_STDOUT_ADDCR 1
#define CONFIG_FREERTOS_PANIC_PRINT_REBOOT 1
#define CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS 1
#define CONFIG_BT_RESERVE_DRAM 0x0
#define CONFIG_LWIP_MAX_SOCKETS 4
#define CONFIG_ESP32_DEFAULT_CPU_FREQ_160 1
#define CONFIG_ULP_COPROC_RESERVE_MEM 0
#define CONFIG_ESPTOOLPY_BAUD 921600
#define CONFIG_LOG_DEFAULT_LEVEL_WARN 1
#define CONFIG_TOOLPREFIX "xtensa-esp32-elf-"
#define CONFIG_LWIP_THREAD_LOCAL_STORAGE_INDEX 0
#define CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN 16384
#define CONFIG_ESP32_ENABLE_STACK_WIFI 1
#define CONFIG_LOG_BOOTLOADER_LEVEL_WARN 1
#define CONFIG_MAIN_TASK_STACK_SIZE 4096
#define CONFIG_ESPTOOLPY_FLASHMODE "dio"
#define CONFIG_LOG_DEFAULT_LEVEL 2
#define CONFIG_ESPTOOLPY_FLASHMODE_DIO 1
#define CONFIG_PYTHON "python"
#define CONFIG_ESPTOOLPY_COMPRESSED 1
#define CONFIG_PARTITION_TABLE_FILENAME "partitions_singleapp.csv"
#define CONFIG_PARTITION_TABLE_SINGLE_APP 1
#define CONFIG_WIFI_ENABLED 1
#define CONFIG_ESPTOOLPY_FLASHFREQ_80M 1
#define CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE 2048
#define CONFIG_PARTITION_TABLE_CUSTOM_APP_BIN_OFFSET 0x10000
#define CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ 160
#define CONFIG_FREERTOS_HZ 1000
#define CONFIG_FREERTOS_ASSERT_FAIL_ABORT 1
#define CONFIG_LOG_BOOTLOADER_LEVEL 2
#define CONFIG_ESPTOOLPY_BAUD_OTHER_VAL 115200
#define CONFIG_LWIP_SO_REUSE 1
#define CONFIG_FREERTOS_CORETIMER_0 1
#define CONFIG_PARTITION_TABLE_CUSTOM_FILENAME "partitions.csv"
#define CONFIG_FREERTOS_DEBUG_OCDAWARE 1
#define CONFIG_SYSTEM_EVENT_QUEUE_SIZE 32
#define CONFIG_ESPTOOLPY_BAUD_921600B 1
#define CONFIG_APP_OFFSET 0x10000
#define CONFIG_MEMMAP_SMP 1
#define CONFIG_ESPTOOLPY_PORT "/dev/tty.SLAB_USBtoUART"

View File

@ -0,0 +1,462 @@
// 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 _DRIVER_GPIO_H_
#define _DRIVER_GPIO_H_
#include "esp_err.h"
#include <esp_types.h>
#include "soc/gpio_reg.h"
#include "soc/gpio_struct.h"
#include "soc/rtc_io_reg.h"
#include "soc/io_mux_reg.h"
#include "rom/gpio.h"
#include "esp_attr.h"
#ifdef __cplusplus
extern "C" {
#endif
#define GPIO_SEL_0 (BIT(0)) /* Pin 0 selected */
#define GPIO_SEL_1 (BIT(1)) /* Pin 1 selected */
#define GPIO_SEL_2 (BIT(2)) /* Pin 2 selected */
#define GPIO_SEL_3 (BIT(3)) /* Pin 3 selected */
#define GPIO_SEL_4 (BIT(4)) /* Pin 4 selected */
#define GPIO_SEL_5 (BIT(5)) /* Pin 5 selected */
#define GPIO_SEL_6 (BIT(6)) /* Pin 6 selected */
#define GPIO_SEL_7 (BIT(7)) /* Pin 7 selected */
#define GPIO_SEL_8 (BIT(8)) /* Pin 8 selected */
#define GPIO_SEL_9 (BIT(9)) /* Pin 9 selected */
#define GPIO_SEL_10 (BIT(10)) /* Pin 10 selected */
#define GPIO_SEL_11 (BIT(11)) /* Pin 11 selected */
#define GPIO_SEL_12 (BIT(12)) /* Pin 12 selected */
#define GPIO_SEL_13 (BIT(13)) /* Pin 13 selected */
#define GPIO_SEL_14 (BIT(14)) /* Pin 14 selected */
#define GPIO_SEL_15 (BIT(15)) /* Pin 15 selected */
#define GPIO_SEL_16 (BIT(16)) /* Pin 16 selected */
#define GPIO_SEL_17 (BIT(17)) /* Pin 17 selected */
#define GPIO_SEL_18 (BIT(18)) /* Pin 18 selected */
#define GPIO_SEL_19 (BIT(19)) /* Pin 19 selected */
#define GPIO_SEL_21 (BIT(21)) /* Pin 21 selected */
#define GPIO_SEL_22 (BIT(22)) /* Pin 22 selected */
#define GPIO_SEL_23 (BIT(23)) /* Pin 23 selected */
#define GPIO_SEL_25 (BIT(25)) /* Pin 25 selected */
#define GPIO_SEL_26 (BIT(26)) /* Pin 26 selected */
#define GPIO_SEL_27 (BIT(27)) /* Pin 27 selected */
#define GPIO_SEL_32 ((uint64_t)(((uint64_t)1)<<32)) /* Pin 32 selected */
#define GPIO_SEL_33 ((uint64_t)(((uint64_t)1)<<33)) /* Pin 33 selected */
#define GPIO_SEL_34 ((uint64_t)(((uint64_t)1)<<34)) /* Pin 34 selected */
#define GPIO_SEL_35 ((uint64_t)(((uint64_t)1)<<35)) /* Pin 35 selected */
#define GPIO_SEL_36 ((uint64_t)(((uint64_t)1)<<36)) /* Pin 36 selected */
#define GPIO_SEL_37 ((uint64_t)(((uint64_t)1)<<37)) /* Pin 37 selected */
#define GPIO_SEL_38 ((uint64_t)(((uint64_t)1)<<38)) /* Pin 38 selected */
#define GPIO_SEL_39 ((uint64_t)(((uint64_t)1)<<39)) /* Pin 39 selected */
#define GPIO_PIN_REG_0 PERIPHS_IO_MUX_GPIO0_U
#define GPIO_PIN_REG_1 PERIPHS_IO_MUX_U0TXD_U
#define GPIO_PIN_REG_2 PERIPHS_IO_MUX_GPIO2_U
#define GPIO_PIN_REG_3 PERIPHS_IO_MUX_U0RXD_U
#define GPIO_PIN_REG_4 PERIPHS_IO_MUX_GPIO4_U
#define GPIO_PIN_REG_5 PERIPHS_IO_MUX_GPIO5_U
#define GPIO_PIN_REG_6 PERIPHS_IO_MUX_SD_CLK_U
#define GPIO_PIN_REG_7 PERIPHS_IO_MUX_SD_DATA0_U
#define GPIO_PIN_REG_8 PERIPHS_IO_MUX_SD_DATA1_U
#define GPIO_PIN_REG_9 PERIPHS_IO_MUX_SD_DATA2_U
#define GPIO_PIN_REG_10 PERIPHS_IO_MUX_SD_DATA3_U
#define GPIO_PIN_REG_11 PERIPHS_IO_MUX_SD_CMD_U
#define GPIO_PIN_REG_12 PERIPHS_IO_MUX_MTDI_U
#define GPIO_PIN_REG_13 PERIPHS_IO_MUX_MTCK_U
#define GPIO_PIN_REG_14 PERIPHS_IO_MUX_MTMS_U
#define GPIO_PIN_REG_15 PERIPHS_IO_MUX_MTDO_U
#define GPIO_PIN_REG_16 PERIPHS_IO_MUX_GPIO16_U
#define GPIO_PIN_REG_17 PERIPHS_IO_MUX_GPIO17_U
#define GPIO_PIN_REG_18 PERIPHS_IO_MUX_GPIO18_U
#define GPIO_PIN_REG_19 PERIPHS_IO_MUX_GPIO19_U
#define GPIO_PIN_REG_20 PERIPHS_IO_MUX_GPIO20_U
#define GPIO_PIN_REG_21 PERIPHS_IO_MUX_GPIO21_U
#define GPIO_PIN_REG_22 PERIPHS_IO_MUX_GPIO22_U
#define GPIO_PIN_REG_23 PERIPHS_IO_MUX_GPIO23_U
#define GPIO_PIN_REG_25 PERIPHS_IO_MUX_GPIO25_U
#define GPIO_PIN_REG_26 PERIPHS_IO_MUX_GPIO26_U
#define GPIO_PIN_REG_27 PERIPHS_IO_MUX_GPIO27_U
#define GPIO_PIN_REG_32 PERIPHS_IO_MUX_GPIO32_U
#define GPIO_PIN_REG_33 PERIPHS_IO_MUX_GPIO33_U
#define GPIO_PIN_REG_34 PERIPHS_IO_MUX_GPIO34_U
#define GPIO_PIN_REG_35 PERIPHS_IO_MUX_GPIO35_U
#define GPIO_PIN_REG_36 PERIPHS_IO_MUX_GPIO36_U
#define GPIO_PIN_REG_37 PERIPHS_IO_MUX_GPIO37_U
#define GPIO_PIN_REG_38 PERIPHS_IO_MUX_GPIO38_U
#define GPIO_PIN_REG_39 PERIPHS_IO_MUX_GPIO39_U
#define GPIO_APP_CPU_INTR_ENA (BIT(0))
#define GPIO_APP_CPU_NMI_INTR_ENA (BIT(1))
#define GPIO_PRO_CPU_INTR_ENA (BIT(2))
#define GPIO_PRO_CPU_NMI_INTR_ENA (BIT(3))
#define GPIO_SDIO_EXT_INTR_ENA (BIT(4))
#define GPIO_MODE_DEF_INPUT (BIT0)
#define GPIO_MODE_DEF_OUTPUT (BIT1)
#define GPIO_MODE_DEF_OD (BIT2)
#define GPIO_PIN_COUNT 40
extern const uint32_t GPIO_PIN_MUX_REG[GPIO_PIN_COUNT];
#define GPIO_IS_VALID_GPIO(gpio_num) ((gpio_num < GPIO_PIN_COUNT && GPIO_PIN_MUX_REG[gpio_num] != 0)) //to decide whether it is a valid GPIO number
#define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) ((GPIO_IS_VALID_GPIO(gpio_num)) && (gpio_num < 34)) //to decide whether it can be a valid GPIO number of output mode
typedef enum {
GPIO_NUM_0 = 0,
GPIO_NUM_1 = 1,
GPIO_NUM_2 = 2,
GPIO_NUM_3 = 3,
GPIO_NUM_4 = 4,
GPIO_NUM_5 = 5,
GPIO_NUM_6 = 6,
GPIO_NUM_7 = 7,
GPIO_NUM_8 = 8,
GPIO_NUM_9 = 9,
GPIO_NUM_10 = 10,
GPIO_NUM_11 = 11,
GPIO_NUM_12 = 12,
GPIO_NUM_13 = 13,
GPIO_NUM_14 = 14,
GPIO_NUM_15 = 15,
GPIO_NUM_16 = 16,
GPIO_NUM_17 = 17,
GPIO_NUM_18 = 18,
GPIO_NUM_19 = 19,
GPIO_NUM_21 = 21,
GPIO_NUM_22 = 22,
GPIO_NUM_23 = 23,
GPIO_NUM_25 = 25,
GPIO_NUM_26 = 26,
GPIO_NUM_27 = 27,
GPIO_NUM_32 = 32,
GPIO_NUM_33 = 33,
GPIO_NUM_34 = 34, /*input mode only */
GPIO_NUM_35 = 35, /*input mode only */
GPIO_NUM_36 = 36, /*input mode only */
GPIO_NUM_37 = 37, /*input mode only */
GPIO_NUM_38 = 38, /*input mode only */
GPIO_NUM_39 = 39, /*input mode only */
} gpio_num_t;
typedef enum {
GPIO_INTR_DISABLE = 0, /* disable GPIO interrupt */
GPIO_INTR_POSEDGE = 1, /* GPIO interrupt type : rising edge */
GPIO_INTR_NEGEDGE = 2, /* GPIO interrupt type : falling edge */
GPIO_INTR_ANYEDGE = 3, /* GPIO interrupt type : both rising and falling edge */
GPIO_INTR_LOW_LEVEL = 4, /* GPIO interrupt type : input low level trigger */
GPIO_INTR_HIGH_LEVEL = 5, /* GPIO interrupt type : input high level trigger */
GPIO_INTR_MAX,
} gpio_int_type_t;
typedef enum {
GPIO_MODE_INPUT = GPIO_MODE_DEF_INPUT, /* GPIO mode : input only */
GPIO_MODE_OUTPUT = GPIO_MODE_DEF_OUTPUT, /* GPIO mode : output only mode */
GPIO_MODE_OUTPUT_OD = ((GPIO_MODE_DEF_OUTPUT)|(GPIO_MODE_DEF_OD)), /* GPIO mode : output only with open-drain mode */
GPIO_MODE_INPUT_OUTPUT_OD = ((GPIO_MODE_DEF_INPUT)|(GPIO_MODE_DEF_OUTPUT)|(GPIO_MODE_DEF_OD)), /* GPIO mode : output and input with open-drain mode*/
GPIO_MODE_INPUT_OUTPUT = ((GPIO_MODE_DEF_INPUT)|(GPIO_MODE_DEF_OUTPUT)), /* GPIO mode : output and input mode */
} gpio_mode_t;
typedef enum {
GPIO_PULLUP_DISABLE = 0x0, /* disable GPIO pull-up resistor */
GPIO_PULLUP_ENABLE = 0x1, /* enable GPIO pull-up resistor */
} gpio_pullup_t;
typedef enum {
GPIO_PULLDOWN_DISABLE = 0x0, /* disable GPIO pull-down resistor */
GPIO_PULLDOWN_ENABLE = 0x1, /* enable GPIO pull-down resistor */
} gpio_pulldown_t;
typedef struct {
uint64_t pin_bit_mask; /* GPIO pin: set with bit mask, each bit maps to a GPIO */
gpio_mode_t mode; /* GPIO mode: set input/output mode */
gpio_pullup_t pull_up_en; /* GPIO pull-up */
gpio_pulldown_t pull_down_en; /* GPIO pull-down */
gpio_int_type_t intr_type; /* GPIO interrupt type */
} gpio_config_t;
typedef enum {
GPIO_LOW_LEVEL = 0,
GPIO_HIGH_LEVEL = 1,
GPIO_LEVEL_ERR,
} gpio_level_t;
typedef enum {
GPIO_PULLUP_ONLY, /* Pad pull up */
GPIO_PULLDOWN_ONLY, /* Pad pull down */
GPIO_PULLUP_PULLDOWN, /* Pad pull up + pull down*/
GPIO_FLOATING, /* Pad floating */
} gpio_pull_mode_t;
typedef void (*gpio_event_callback)(gpio_num_t gpio_intr_num);
/** \defgroup Driver_APIs Driver APIs
* @brief Driver APIs
*/
/** @addtogroup Driver_APIs
* @{
*/
/** \defgroup GPIO_Driver_APIs GPIO Driver APIs
* @brief GPIO APIs
*/
/** @addtogroup GPIO_Driver_APIs
* @{
*/
/**
* @brief GPIO common configuration
*
* Use this Function ,Configure GPIO's Mode,pull-up,PullDown,IntrType
*
* @parameter[in] pGPIOConfig
* pGPIOConfig.pin_bit_mask : Configure GPIO pins bits,set this parameter with bit mask.
* If you want to configure GPIO34 and GPIO16, pin_bit_mask=GPIO_Pin_16|GPIO_Pin_34;
* pGPIOConfig.mode : Configure GPIO mode,such as output ,input...
* pGPIOConfig.pull_up_en : Enable or Disable pull-up
* pGPIOConfig.pull_down_en : Enable or Disable pull-down
* pGPIOConfig.intr_type : Configure GPIO interrupt trigger type
* @return ESP_OK: success ;
* ESP_ERR_INVALID_ARG: parameter error
* ESP_FAIL : GPIO error
*
*/
esp_err_t gpio_config(gpio_config_t *pGPIOConfig);
/**
* @brief GPIO set interrupt trigger type
*
* @parameter[in] gpio_num : GPIO number.
* If you want to set output level of GPIO16, gpio_num should be GPIO_NUM_16 (16);
* @parameter[in] intr_type: interrupt type, select from gpio_int_type_t
*
* @return ESP_OK : success
* ESP_ERR_INVALID_ARG: parameter error
*
*/
esp_err_t gpio_set_intr_type(gpio_num_t gpio_num, gpio_int_type_t intr_type);
/**
* @brief enable GPIO module interrupt signal
*
* @parameter[in] gpio_num : GPIO number.
* If you want to set output level of GPIO16, gpio_num should be GPIO_NUM_16 (16);
*
* @return ESP_OK : success
* ESP_ERR_INVALID_ARG: parameter error
*
*/
esp_err_t gpio_intr_enable(gpio_num_t gpio_num);
/**
* @brief disable GPIO module interrupt signal
*
* @parameter[in] gpio_num : GPIO number.
* If you want to set output level of GPIO16, gpio_num should be GPIO_NUM_16 (16);
*
* @return ESP_OK : success
* ESP_ERR_INVALID_ARG: parameter error
*
*/
esp_err_t gpio_intr_disable(gpio_num_t gpio_num);
/**
* @brief GPIO set output level
*
* @parameter[in] gpio_num : GPIO number.
* If you want to set output level of GPIO16, gpio_num should be GPIO_NUM_16 (16);
* @parameter[in] level : Output level. 0: low ; 1: high
*
* @return ESP_OK : success
* ESP_FAIL : GPIO error
*
*/
esp_err_t gpio_set_level(gpio_num_t gpio_num, uint32_t level);
/**
* @brief GPIO get input level
*
* @parameter[in] gpio_num : GPIO number.
* If you want to get level of pin GPIO16, gpio_num should be GPIO_NUM_16 (16);
*
* @return 0 : the GPIO input level is 0
* 1 : the GPIO input level is 1
*
*/
int gpio_get_level(gpio_num_t gpio_num);
/**
* @brief GPIO set direction
*
* Configure GPIO direction,such as output_only,input_only,output_and_input
*
* @parameter[in] gpio_num : Configure GPIO pins number,it should be GPIO number.
* If you want to set direction of GPIO16, gpio_num should be GPIO_NUM_16 (16);
* @parameter[in] mode : Configure GPIO direction,such as output_only,input_only,...
*
* @return ESP_OK : success
* ESP_ERR_INVALID_ARG : fail
* ESP_FAIL : GPIO error
*
*/
esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode);
/**
* @brief GPIO set pull
*
* User this Function,configure GPIO pull mode,such as pull-up,pull-down
*
* @parameter[in] gpio_num : Configure GPIO pins number,it should be GPIO number.
* If you want to set pull up or down mode for GPIO16,gpio_num should be GPIO_NUM_16 (16);
* @parameter[in] pull : Configure GPIO pull up/down mode,such as pullup_only,pulldown_only,pullup_and_pulldown,...
*
* @return ESP_OK : success
* ESP_ERR_INVALID_ARG : fail
* ESP_FAIL : GPIO error
*
*/
esp_err_t gpio_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull);
/**
* @brief enable GPIO wake-up function.
*
* @param gpio_num_t gpio_num : GPIO number.
*
* @param gpio_int_type_t intr_type : only GPIO_INTR_LOLEVEL\GPIO_INTR_HILEVEL can be used
*
* @return ESP_OK: success
* ESP_ERR_INVALID_ARG: parameter error
*/
esp_err_t gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type);
/**
* @brief disable GPIO wake-up function.
*
* @param gpio_num_t gpio_num: GPIO number
*
* @return ESP_OK: success
* ESP_ERR_INVALID_ARG: parameter error
*/
esp_err_t gpio_wakeup_disable(gpio_num_t gpio_num);
/**
* @brief register GPIO interrupt handler, the handler is an ISR.
* The handler will be attached to the same CPU core that this function is running on.
* Users should know that which CPU is running and then pick a INUM that is not used by system.
* We can find the information of INUM and interrupt level in soc.h.
* TODO: to move INUM options to menu_config
* @parameter uint32_t gpio_intr_num : GPIO interrupt number,check the info in soc.h, and please see the core-isa.h for more details
* @parameter void (* fn)(void* ) : interrupt handler function.
* Note that the handler function MUST be defined with attribution of "IRAM_ATTR".
* @parameter void * arg : parameter for handler function
*
* @return ESP_OK : success ;
* ESP_FAIL: gpio error
*/
esp_err_t gpio_isr_register(uint32_t gpio_intr_num, void (*fn)(void*), void * arg);
/**
* *************** ATTENTION ********************/
/**
*
* Each GPIO has its own separate configuration register, so we do not use
* a lock to serialize access to them. This works under the assumption that
* no situation will occur where two tasks try to configure the same GPIO
* pin simultaneously. It is up to the application developer to guarantee this.
*/
/*----------EXAMPLE TO CONIFGURE GPIO AS OUTPUT ------------ */
/* gpio_config_t io_conf;
* io_conf.intr_type = GPIO_INTR_DISABLE; //disable interrupt
* io_conf.mode = GPIO_MODE_OUTPUT; //set as output mode
* io_conf.pin_bit_mask = GPIO_SEL_18 | GPIO_SEL_19; //bit mask of the pins that you want to set,e.g.GPIO18/19
* io_conf.pull_down_en = 0; //disable pull-down mode
* io_conf.pull_up_en = 0; //disable pull-up mode
* gpio_config(&io_conf); //configure GPIO with the given settings
**/
/*----------EXAMPLE TO CONIFGURE GPIO AS OUTPUT ------------ */
/* io_conf.intr_type = GPIO_INTR_POSEDGE; //set posedge interrupt
* io_conf.mode = GPIO_MODE_INPUT; //set as input
* io_conf.pin_bit_mask = GPIO_SEL_4 | GPIO_SEL_5; //bit mask of the pins that you want to set, e.g.,GPIO4/5
* io_conf.pull_down_en = 0; //disable pull-down mode
* io_conf.pull_up_en = 1; //enable pull-up mode
* gpio_config(&io_conf); //configure GPIO with the given settings
*----------EXAMPLE TO SET ISR HANDLER ----------------------*/
/* gpio_isr_register(18,gpio_intr_test,NULL); //hook the isr handler for GPIO interrupt
* //the first parameter is INUM, you can pick one form interrupt level 1/2 which is not used by the system.
* //NOTE1:user should arrange the INUMs that used, better not to use a same INUM for different interrupt.
* //NOTE2:do not pick the INUM that already occupied by the system.
* //NOTE3:refer to soc.h to check which INUMs that can be used.
*-------------EXAMPLE OF HANDLER FUNCTION-------------------*/
/*#include "esp_attr.h"
* void IRAM_ATTR gpio_intr_test(void* arg)
*{
* //GPIO intr process
* ets_printf("in gpio_intr\n");
* uint32_t gpio_num = 0;
* uint32_t gpio_intr_status = READ_PERI_REG(GPIO_STATUS_REG); //read status to get interrupt status for GPIO0-31
* uint32_t gpio_intr_status_h = READ_PERI_REG(GPIO_STATUS1_REG);//read status1 to get interrupt status for GPIO32-39
* SET_PERI_REG_MASK(GPIO_STATUS_W1TC_REG, gpio_intr_status); //Clear intr for gpio0-gpio31
* SET_PERI_REG_MASK(GPIO_STATUS1_W1TC_REG, gpio_intr_status_h); //Clear intr for gpio32-39
* do {
* if(gpio_num < 32) {
* if(gpio_intr_status & BIT(gpio_num)) { //gpio0-gpio31
* ets_printf("Intr GPIO%d ,val: %d\n",gpio_num,gpio_get_level(gpio_num));
* //This is an isr handler, you should post an event to process it in RTOS queue.
* }
* } else {
* if(gpio_intr_status_h & BIT(gpio_num - 32)) {
* ets_printf("Intr GPIO%d, val : %d\n",gpio_num,gpio_get_level(gpio_num));
* //This is an isr handler, you should post an event to process it in RTOS queue.
* }
* }
* } while(++gpio_num < GPIO_PIN_COUNT);
*}
*----EXAMPLE OF I2C CONFIG AND PICK SIGNAL FOR IO MATRIX---*/
/* gpio_config_t io_conf;
* io_conf.intr_type = GPIO_INTR_DISABLE; //disable interrupt
* io_conf.mode = GPIO_MODE_INPUT_OUTPUT_OD; //set as output mode
* io_conf.pin_bit_mask = GPIO_SEL_21 | GPIO_SEL_22; //bit mask of the pins that you want to set,e.g.GPIO21/22
* io_conf.pull_down_en = 0; //disable pull-down mode
* io_conf.pull_up_en = 1; //enable pull-up mode
* gpio_config(&io_conf); //configure GPIO with the given settings
* gpio_matrix_out(21, EXT_I2C_SCL_O_IDX, 0, 0); //set output signal for io_matrix
* gpio_matrix_out(22, EXT_I2C_SDA_O_IDX, 0, 0); //set output signal for io_matrix
* gpio_matrix_in( 22, EXT_I2C_SDA_I_IDX, 0); //set input signal for io_matrix
*
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* _DRIVER_GPIO_H_ */

View File

@ -0,0 +1,406 @@
// 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 _DRIVER_LEDC_H_
#define _DRIVER_LEDC_H_
#include "esp_err.h"
#include "soc/soc.h"
#include "soc/ledc_reg.h"
#include "soc/ledc_reg.h"
#include "soc/ledc_struct.h"
#include "driver/gpio.h"
#include "driver/periph_ctrl.h"
#ifdef __cplusplus
extern "C" {
#endif
#define LEDC_APB_CLK_HZ (APB_CLK_FREQ)
#define LEDC_REF_CLK_HZ (1*1000000)
typedef enum {
LEDC_HIGH_SPEED_MODE = 0, /*LEDC high speed speed_mode */
//in this version, we only support high speed speed_mode. We will access low speed speed_mode later
//LEDC_LOW_SPEED_MODE, /*LEDC low speed speed_mode */
LEDC_SPEED_MODE_MAX,
} ledc_mode_t;
typedef enum {
LEDC_INTR_DISABLE = 0, /*Disable LEDC interrupt */
LEDC_INTR_FADE_END, /*Enable LEDC interrupt */
} ledc_intr_type_t;
typedef enum {
LEDC_DUTY_DIR_DECREASE = 0, /*LEDC duty decrease direction */
LEDC_DUTY_DIR_INCREASE = 1, /*LEDC duty increase direction */
} ledc_duty_direction_t;
typedef enum {
LEDC_REF_TICK = 0, /*LEDC timer clock divided from reference tick(1Mhz) */
LEDC_APB_CLK, /*LEDC timer clock divided from APB clock(80Mhz)*/
} ledc_clk_src_t;
typedef enum {
LEDC_TIMER_0 = 0, /*LEDC source timer TIMER0 */
LEDC_TIMER_1, /*LEDC source timer TIMER1 */
LEDC_TIMER_2, /*LEDC source timer TIMER2 */
LEDC_TIMER_3, /*LEDC source timer TIMER3 */
} ledc_timer_t;
typedef enum {
LEDC_CHANNEL_0 = 0, /*LEDC channel 0 */
LEDC_CHANNEL_1, /*LEDC channel 1 */
LEDC_CHANNEL_2, /*LEDC channel 2 */
LEDC_CHANNEL_3, /*LEDC channel 3 */
LEDC_CHANNEL_4, /*LEDC channel 4 */
LEDC_CHANNEL_5, /*LEDC channel 5 */
LEDC_CHANNEL_6, /*LEDC channel 6 */
LEDC_CHANNEL_7, /*LEDC channel 7 */
} ledc_channel_t;
typedef enum {
LEDC_TIMER_10_BIT = 10, /*LEDC PWM depth 10Bit */
LEDC_TIMER_11_BIT = 11, /*LEDC PWM depth 11Bit */
LEDC_TIMER_12_BIT = 12, /*LEDC PWM depth 12Bit */
LEDC_TIMER_13_BIT = 13, /*LEDC PWM depth 13Bit */
LEDC_TIMER_14_BIT = 14, /*LEDC PWM depth 14Bit */
LEDC_TIMER_15_BIT = 15, /*LEDC PWM depth 15Bit */
} ledc_timer_bit_t;
typedef struct {
int gpio_num; /*the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16*/
ledc_mode_t speed_mode; /*LEDC speed speed_mode, high-speed mode or low-speed mode*/
ledc_channel_t channel; /*LEDC channel(0 - 7)*/
ledc_intr_type_t intr_type; /*configure interrupt, Fade interrupt enable or Fade interrupt disable*/
ledc_timer_t timer_sel; /*Select the timer source of channel (0 - 3)*/
uint32_t duty; /*LEDC channel duty, the duty range is [0, (2**bit_num) - 1], */
} ledc_channel_config_t;
typedef struct {
ledc_mode_t speed_mode; /*LEDC speed speed_mode, high-speed mode or low-speed mode*/
ledc_timer_bit_t bit_num; /*LEDC channel duty depth*/
ledc_timer_t timer_num; /*The timer source of channel (0 - 3)*/
uint32_t freq_hz; /*LEDC timer frequency(Hz)*/
} ledc_timer_config_t;
/**
* @brief LEDC channel configuration
*
* User this Function, configure LEDC channel with the given channel/output gpio_num/interrupt/source timer/frequency(Hz)/LEDC depth
*
* @param[in] ledc_channel_config_t
* ledc_channel_config_t.speed_mode : LEDC speed speed_mode
* ledc_channel_config_t.gpio_num : LEDC output gpio_num, if you want to use gpio16, ledc_channel_config_t.gpio_num = 16
* ledc_channel_config_t.channel : LEDC channel(0 - 7)
* ledc_channel_config_t.intr_type : configure interrupt, Fade interrupt enable or Fade interrupt disable
* ledc_channel_config_t.timer_sel : Select the timer source of channel (0 - 3), high speed channel must bind with high speed timer.
* ledc_channel_config_t.duty : LEDC channel duty, the duty range is [0, (2**timer_bit_num) - 1],
* @return ESP_OK: success
* ESP_ERR_INVALID_ARG: parameter error
*
*/
esp_err_t ledc_channel_config(ledc_channel_config_t* ledc_conf);
/**
* @brief LEDC timer configuration
*
* User this Function, configure LEDC timer with the given source timer/frequency(Hz)/bit_num
*
* @param[in] ledc_timer_config_t
* ledc_timer_config_t.speed_mode : LEDC speed speed_mode
* ledc_timer_config_t.timer_num : Select the timer source of channel (0 - 3)
* ledc_timer_config_t.freq_hz : LEDC channel frequency(Hz),
* ledc_timer_config_t.bit_num : LEDC channel duty depth
* @return ESP_OK: success
* ESP_ERR_INVALID_ARG: parameter error
* ESP_FAIL: Can not find a proper pre-divider number base on the given frequency and the current bit_num.
*
*/
esp_err_t ledc_timer_config(ledc_timer_config_t* timer_conf);
/**
* @brief LEDC update channel parameters
*
* Call this function to activate the LEDC updated parameters.
* After ledc_set_duty, ledc_set_fade, we need to call this function to update the settings.
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] channel : LEDC channel(0-7), select from ledc_channel_t
*
* @return ESP_OK: success
* ESP_ERR_INVALID_ARG: parameter error
*
*/
esp_err_t ledc_update_duty(ledc_mode_t speed_mode, ledc_channel_t channel);
/**
* @brief LEDC stop
*
* Disable LEDC output, and set idle level
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] channel : LEDC channel(0-7), select from ledc_channel_t
*
* @return ESP_OK: success
* ESP_ERR_INVALID_ARG: parameter error
*/
esp_err_t ledc_stop(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t idle_level);
/**
* @brief LEDC set channel frequency(Hz)
*
* Set LEDC frequency(Hz)
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] timer_num : LEDC timer index(0-3), select from ledc_timer_t
*
* @param[in] freq_hz : set the LEDC frequency
*
* @return ESP_OK: success
* ESP_ERR_INVALID_ARG: parameter error
* ESP_FAIL: Can not find a proper pre-divider number base on the given frequency and the current bit_num.
*/
esp_err_t ledc_set_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num, uint32_t freq_hz);
/**
* @brief LEDC get channel frequency(Hz)
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] timer_num : LEDC timer index(0-3), select from ledc_timer_t
*
* @return 0 : error
* others : current LEDC frequency
*
*/
uint32_t ledc_get_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num);
/**
* @brief LEDC set duty
*
* Set LEDC duty, After the function calls the ledc_update_duty function, the function can take effect.
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] channel : LEDC channel(0-7), select from ledc_channel_t
*
* @param[in] duty : set the LEDC duty, the duty range is [0, (2**bit_num) - 1]
*
* @return ESP_OK: success
* ESP_ERR_INVALID_ARG: parameter error
*/
esp_err_t ledc_set_duty(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty);
/**
* @brief LEDC get duty
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] channel : LEDC channel(0-7), select from ledc_channel_t
*
*
* @return -1: parameter error
* other value: current LEDC duty
*
*/
int ledc_get_duty(ledc_mode_t speed_mode, ledc_channel_t channel);
/**
* @brief LEDC set gradient
*
* Set LEDC gradient, After the function calls the ledc_update_duty function, the function can take effect.
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] channel : LEDC channel(0-7), select from ledc_channel_t
*
* @param[in] duty : set the start of the gradient duty, the duty range is [0, (2**bit_num) - 1]
*
* @param[in] gradule_direction : set the direction of the gradient
*
* @param[in] step_num : set the number of the gradient
*
* @param[in] duty_cyle_num : set how many LEDC tick each time the gradient lasts
*
* @param[in] duty_scale : set gradient change amplitude
*
* @return ESP_OK : success
* ESP_ERR_INVALID_ARG : parameter error
*/
esp_err_t ledc_set_fade(ledc_mode_t speed_mode, uint32_t channel, uint32_t duty, ledc_duty_direction_t gradule_direction,
uint32_t step_num, uint32_t duty_cyle_num, uint32_t duty_scale);
/**
* @brief register LEDC interrupt handler, the handler is an ISR.
* The handler will be attached to the same CPU core that this function is running on.
* Users should know that which CPU is running and then pick a INUM that is not used by system.
* We can find the information of INUM and interrupt level in soc.h.
* TODO: to move INUM options to menu_config
* @param[in] uint32_t ledc_intr_num : LEDC interrupt number, check the info in soc.h, and please see the core-isa.h for more details
* @param[in] void (* fn)(void* ) : interrupt handler function.
* Note that the handler function MUST be defined with attribution of "IRAM_ATTR".
* @param[in] void * arg : parameter for handler function
*
* @return ESP_OK : success ;
* ESP_ERR_INVALID_ARG : function ptr error.
*/
esp_err_t ledc_isr_register(uint32_t ledc_intr_num, void (*fn)(void*), void * arg);
/**
* @brief configure LEDC settings
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] timer_sel : timer index(0-3), there are 4 timers in LEDC module
*
* @param[in] div_num : timer clock divide number, the timer clock is divided from the selected clock source
*
* @param[in] bit_num : the count number of one period, counter range is 0 ~ ((2 ** bit_num) - 1)
*
* @param[in] clk_src : select LEDC source clock.
*
* @return -1: parameter error
* other value: current LEDC duty
*
*/
esp_err_t ledc_timer_set(ledc_mode_t speed_mode, ledc_timer_t timer_sel, uint32_t div_num, uint32_t bit_num, ledc_clk_src_t clk_src);
/**
* @brief reset LEDC timer
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] timer_sel : LEDC timer index(0-3), select from ledc_timer_t
*
*
* @return ESP_ERR_INVALID_ARG: parameter error
* ESP_OK: success
*
*/
esp_err_t ledc_timer_rst(ledc_mode_t speed_mode, uint32_t timer_sel);
/**
* @brief pause LEDC timer counter
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] timer_sel : LEDC timer index(0-3), select from ledc_timer_t
*
*
* @return ESP_ERR_INVALID_ARG: parameter error
* ESP_OK: success
*
*/
esp_err_t ledc_timer_pause(ledc_mode_t speed_mode, uint32_t timer_sel);
/**
* @brief pause LEDC timer resume
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] timer_sel : LEDC timer index(0-3), select from ledc_timer_t
*
*
* @return ESP_ERR_INVALID_ARG: parameter error
* ESP_OK: success
*
*/
esp_err_t ledc_timer_resume(ledc_mode_t speed_mode, uint32_t timer_sel);
/**
* @brief bind LEDC channel with the selected timer
*
* @param[in] speed_mode : select the LEDC speed_mode, high-speed mode and low-speed mode, now we only support high-speed mode. We will access low-speed mode in next version
*
* @param[in] channel : LEDC channel index(0-7), select from ledc_channel_t
*
* @param[in] timer_idx : LEDC timer index(0-3), select from ledc_timer_t
*
*
* @return ESP_ERR_INVALID_ARG: parameter error
* ESP_OK: success
*
*/
esp_err_t ledc_bind_channel_timer(ledc_mode_t speed_mode, uint32_t channel, uint32_t timer_idx);
/***************************EXAMPLE**********************************
*
*
* ----------------EXAMPLE OF LEDC SETTING ---------------------
* //1. enable LEDC
* periph_module_enable(PERIPH_LEDC_MODULE); //enable LEDC module, or you can not set any register of it.
*
* //2. set LEDC timer
* ledc_timer_config_t timer_conf = {
* .bit_num = LEDC_TIMER_12_BIT, //set timer counter bit number
* .freq_hz = 1000, //set frequency of pwm, here, 1000Hz
* .speed_mode = LEDC_HIGH_SPEED_MODE //timer mode,
* .timer_num = LEDC_TIMER_0, //timer number
* };
* ledc_timer_config(&timer_conf); //setup timer.
*
* //3. set LEDC channel
* ledc_channel_config_t ledc_conf = {
* .channel = LEDC_CHANNEL_0; //set LEDC channel 0
* .duty = 1000; //set the duty for initialization.(duty range is 0 ~ ((2**bit_num)-1)
* .gpio_num = 16; //GPIO number
* .intr_type = LEDC_INTR_FADE_END; //GPIO INTR TYPE, as an example, we enable fade_end interrupt here.
* .speed_mode = LEDC_HIGH_SPEED_MODE; //set LEDC mode, from ledc_mode_t
* .timer_sel = LEDC_TIMER_0; //set LEDC timer source, if different channel use one timer, the frequency and bit_num of these channels should be the same
* }
* ledc_channel_config(&ledc_conf); //setup the configuration
*
* ----------------EXAMPLE OF SETTING DUTY --- -----------------
* uint32_t ledc_channel = LEDC_CHANNEL_0; //LEDC channel(0-73)
* uint32_t duty = 2000; //duty range is 0 ~ ((2**bit_num)-1)
* LEDC_set_duty(LEDC_HIGH_SPEED_MODE, ledc_channel, duty); //set speed mode, channel, and duty.
* ledc_update_duty(LEDC_HIGH_SPEED_MODE, ledc_channel); //after set duty, we need to call ledc_update_duty to update the settings.
*
*
* ----------------EXAMPLE OF LEDC INTERRUPT ------------------
* //we have fade_end interrupt and counter overflow interrupt. we just give an example of fade_end interrupt here.
* ledc_isr_register(18, ledc_isr_handler, NULL); //hook the isr handler for LEDC interrupt
* //the first parameter is INUM, you can pick one form interrupt level 1/2 which is not used by the system.
* //NOTE1:user should arrange the INUMs that used, better not to use a same INUM for different interrupt source.
* //NOTE2:do not pick the INUM that already occupied by the system.
* //NOTE3:refer to soc.h to check which INUMs that can be used.
* ----------------EXAMPLE OF INTERRUPT HANDLER ---------------
* #include "esp_attr.h"
* void IRAM_ATTR ledc_isr_handler(void* arg) //we should add 'IRAM_ATTR' attribution when we declare the isr function
* {
* uint32_t intr_st = LEDC.int_st.val; //read LEDC interrupt status.
*
* //you will find which channels have triggered fade_end interrupt here,
* //then, you can post some event to RTOS queue to process the event.
* //later we will add a queue in the driver code.
*
* LEDC.int_clr.val = intr_st; //clear LEDC interrupt status.
* }
*
*
*--------------------------END OF EXAMPLE --------------------------
*/
#ifdef __cplusplus
}
#endif
#endif /* _DRIVER_LEDC_H_ */

View File

@ -0,0 +1,70 @@
// 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 _DRIVER_PERIPH_CTRL_H_
#define _DRIVER_PERIPH_CTRL_H_
#include "esp_err.h"
#include "soc/soc.h"
#include "soc/dport_reg.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
PERIPH_LEDC_MODULE = 0,
PERIPH_UART0_MODULE,
PERIPH_UART1_MODULE,
PERIPH_UART2_MODULE,
PERIPH_I2C0_MODULE,
PERIPH_I2C1_MODULE,
PERIPH_I2S0_MODULE,
PERIPH_I2S1_MODULE,
PERIPH_TIMG0_MODULE,
PERIPH_TIMG1_MODULE,
PERIPH_PWM0_MODULE,
PERIPH_PWM1_MODULE,
PERIPH_PWM2_MODULE,
PERIPH_PWM3_MODULE,
PERIPH_UHCI0_MODULE,
PERIPH_UHCI1_MODULE,
} periph_module_t;
/**
* @brief enable peripheral module
*
* @param[in] periph : Peripheral module name
*
*
* @return NULL
*
*/
void periph_module_enable(periph_module_t periph);
/**
* @brief disable peripheral module
*
* @param[in] periph : Peripheral module name
*
*
* @return NULL
*
*/
void periph_module_disable(periph_module_t periph);
#ifdef __cplusplus
}
#endif
#endif /* _DRIVER_PERIPH_CTRL_H_ */

Some files were not shown because too many files have changed in this diff Show More