1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-07-30 16:24:09 +03:00

Merge branch 'master' into wifi_mesh_update_2.2

This commit is contained in:
aerlon
2019-10-29 21:55:08 +01:00
committed by GitHub
192 changed files with 18054 additions and 14744 deletions

View File

@ -21,6 +21,7 @@
#include "Arduino.h"
#include "EEPROM.h"
#include "debug.h"
extern "C" {
#include "c_types.h"
@ -30,7 +31,7 @@ extern "C" {
#include "spi_flash.h"
}
extern "C" uint32_t _FS_end;
extern "C" uint32_t _EEPROM_start;
EEPROMClass::EEPROMClass(uint32_t sector)
: _sector(sector)
@ -41,7 +42,7 @@ EEPROMClass::EEPROMClass(uint32_t sector)
}
EEPROMClass::EEPROMClass(void)
: _sector((((uint32_t)&_FS_end - 0x40200000) / SPI_FLASH_SEC_SIZE))
: _sector((((uint32_t)&_EEPROM_start - 0x40200000) / SPI_FLASH_SEC_SIZE))
, _data(0)
, _size(0)
, _dirty(false)
@ -49,10 +50,14 @@ EEPROMClass::EEPROMClass(void)
}
void EEPROMClass::begin(size_t size) {
if (size <= 0)
if (size <= 0) {
DEBUGV("EEPROMClass::begin error, size == 0\n");
return;
if (size > SPI_FLASH_SEC_SIZE)
}
if (size > SPI_FLASH_SEC_SIZE) {
DEBUGV("EEPROMClass::begin error, %d > %d\n", size, SPI_FLASH_SEC_SIZE);
size = SPI_FLASH_SEC_SIZE;
}
size = (size + 3) & (~3);
@ -66,9 +71,9 @@ void EEPROMClass::begin(size_t size) {
_size = size;
noInterrupts();
spi_flash_read(_sector * SPI_FLASH_SEC_SIZE, reinterpret_cast<uint32_t*>(_data), _size);
interrupts();
if (!ESP.flashRead(_sector * SPI_FLASH_SEC_SIZE, reinterpret_cast<uint32_t*>(_data), _size)) {
DEBUGV("EEPROMClass::begin flash read failed\n");
}
_dirty = false; //make sure dirty is cleared in case begin() is called 2nd+ time
}
@ -88,19 +93,27 @@ void EEPROMClass::end() {
uint8_t EEPROMClass::read(int const address) {
if (address < 0 || (size_t)address >= _size)
if (address < 0 || (size_t)address >= _size) {
DEBUGV("EEPROMClass::read error, address %d > %d or %d < 0\n", address, _size, address);
return 0;
if(!_data)
}
if (!_data) {
DEBUGV("EEPROMClass::read without ::begin\n");
return 0;
}
return _data[address];
}
void EEPROMClass::write(int const address, uint8_t const value) {
if (address < 0 || (size_t)address >= _size)
if (address < 0 || (size_t)address >= _size) {
DEBUGV("EEPROMClass::write error, address %d > %d or %d < 0\n", address, _size, address);
return;
if(!_data)
}
if(!_data) {
DEBUGV("EEPROMClass::read without ::begin\n");
return;
}
// Optimise _dirty. Only flagged if data written is different.
uint8_t* pData = &_data[address];
@ -112,7 +125,6 @@ void EEPROMClass::write(int const address, uint8_t const value) {
}
bool EEPROMClass::commit() {
bool ret = false;
if (!_size)
return false;
if(!_dirty)
@ -120,16 +132,15 @@ bool EEPROMClass::commit() {
if(!_data)
return false;
noInterrupts();
if(spi_flash_erase_sector(_sector) == SPI_FLASH_RESULT_OK) {
if(spi_flash_write(_sector * SPI_FLASH_SEC_SIZE, reinterpret_cast<uint32_t*>(_data), _size) == SPI_FLASH_RESULT_OK) {
if (ESP.flashEraseSector(_sector)) {
if (ESP.flashWrite(_sector * SPI_FLASH_SEC_SIZE, reinterpret_cast<uint32_t*>(_data), _size)) {
_dirty = false;
ret = true;
return true;
}
}
interrupts();
return ret;
DEBUGV("EEPROMClass::commit failed\n");
return false;
}
uint8_t * EEPROMClass::getDataPtr() {

View File

@ -14,7 +14,7 @@ byte value;
void setup() {
// initialize serial and wait for port to open:
Serial.begin(9600);
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}

View File

@ -13,6 +13,7 @@
int addr = 0;
void setup() {
Serial.begin(115200);
EEPROM.begin(512);
}
@ -33,7 +34,11 @@ void loop() {
addr = addr + 1;
if (addr == 512) {
addr = 0;
EEPROM.commit();
if (EEPROM.commit()) {
Serial.println("EEPROM successfully committed");
} else {
Serial.println("ERROR! EEPROM commit failed");
}
}
delay(100);

View File

@ -113,8 +113,8 @@ protected:
* constructor
*/
HTTPClient::HTTPClient()
: _client(nullptr), _userAgent(F("ESP8266HTTPClient"))
{
_client = nullptr;
#if HTTPCLIENT_1_1_COMPATIBLE
_tcpDeprecated.reset(nullptr);
#endif
@ -536,8 +536,8 @@ void HTTPClient::setTimeout(uint16_t timeout)
bool HTTPClient::setURL(String url)
{
// if the new location is only a path then only update the URI
if (_location.startsWith("/")) {
_uri = _location;
if (url && url[0] == '/') {
_uri = url;
clear();
return true;
}
@ -1294,21 +1294,21 @@ int HTTPClient::handleHeaderResponse()
String headerValue = headerLine.substring(headerLine.indexOf(':') + 1);
headerValue.trim();
if(headerName.equalsIgnoreCase("Content-Length")) {
if(headerName.equalsIgnoreCase(F("Content-Length"))) {
_size = headerValue.toInt();
}
if(_canReuse && headerName.equalsIgnoreCase("Connection")) {
if(_canReuse && headerName.equalsIgnoreCase(F("Connection"))) {
if(headerValue.indexOf("close") >= 0 && headerValue.indexOf("keep-alive") < 0) {
_canReuse = false;
}
}
if(headerName.equalsIgnoreCase("Transfer-Encoding")) {
if(headerName.equalsIgnoreCase(F("Transfer-Encoding"))) {
transferEncoding = headerValue;
}
if(headerName.equalsIgnoreCase("Location")) {
if(headerName.equalsIgnoreCase(F("Location"))) {
_location = headerValue;
}
@ -1334,7 +1334,7 @@ int HTTPClient::handleHeaderResponse()
if(transferEncoding.length() > 0) {
DEBUG_HTTPCLIENT("[HTTP-Client][handleHeaderResponse] Transfer-Encoding: %s\n", transferEncoding.c_str());
if(transferEncoding.equalsIgnoreCase("chunked")) {
if(transferEncoding.equalsIgnoreCase(F("chunked"))) {
_transferEncoding = HTTPC_TE_CHUNKED;
} else {
return HTTPC_ERROR_ENCODING;

View File

@ -242,7 +242,7 @@ protected:
String _uri;
String _protocol;
String _headers;
String _userAgent = "ESP8266HTTPClient";
String _userAgent;
String _base64Authorization;
/// Response handling

View File

@ -1,6 +1,6 @@
name=ESP8266HTTPUpdateServer
version=1.0
author=Ivan Grokhotkov, Miguel Ángel Ajo
author=Ivan Grokhotkov, Miguel Angel Ajo
maintainer=Ivan Grokhtkov <ivan@esp8266.com>
sentence=Simple HTTP Update server based on the ESP8266WebServer
paragraph=The library accepts HTTP post requests to the /update url, and updates the ESP8266 firmware.

View File

@ -3,6 +3,9 @@
#include <WiFiServer.h>
#include <ESP8266WebServer.h>
#include <WiFiUdp.h>
#include <flash_hal.h>
#include <FS.h>
#include <LittleFS.h>
#include "StreamString.h"
#include "ESP8266HTTPUpdateServer.h"
@ -10,11 +13,25 @@ namespace esp8266httpupdateserver {
using namespace esp8266webserver;
static const char serverIndex[] PROGMEM =
R"(<html><body><form method='POST' action='' enctype='multipart/form-data'>
<input type='file' name='update'>
<input type='submit' value='Update'>
</form>
</body></html>)";
R"(<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'/>
</head>
<body>
<form method='POST' action='' enctype='multipart/form-data'>
Firmware:<br>
<input type='file' accept='.bin' name='firmware'>
<input type='submit' value='Update Firmware'>
</form>
<form method='POST' action='' enctype='multipart/form-data'>
FileSystem:<br>
<input type='file' accept='.bin' name='filesystem'>
<input type='submit' value='Update FileSystem'>
</form>
</body>
</html>)";
static const char successResponse[] PROGMEM =
"<META http-equiv=\"refresh\" content=\"15;URL=/\">Update Success! Rebooting...";
@ -75,9 +92,18 @@ void ESP8266HTTPUpdateServerTemplate<ServerType>::setup(ESP8266WebServerTemplate
WiFiUDP::stopAll();
if (_serial_output)
Serial.printf("Update: %s\n", upload.filename.c_str());
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if(!Update.begin(maxSketchSpace)){//start with max available size
_setUpdaterError();
if (upload.name == "filesystem") {
size_t fsSize = ((size_t) &_FS_end - (size_t) &_FS_start);
SPIFFS.end();
LittleFS.end();
if (!Update.begin(fsSize, U_FS)){//start with max available size
if (_serial_output) Update.printError(Serial);
}
} else {
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if (!Update.begin(maxSketchSpace, U_FLASH)){//start with max available size
_setUpdaterError();
}
}
} else if(_authenticated && upload.status == UPLOAD_FILE_WRITE && !_updaterError.length()){
if (_serial_output) Serial.printf(".");

View File

@ -238,7 +238,7 @@ bool ESP8266WebServerTemplate<ServerType>::_parseRequest(ClientType& client) {
DEBUG_OUTPUT.println(headerValue);
#endif
if (headerName.equalsIgnoreCase("Host")){
if (headerName.equalsIgnoreCase(F("Host"))){
_hostHeader = headerValue;
}
}

View File

@ -85,8 +85,9 @@ void setup() {
Serial.swap();
// Hardware serial is now on RX:GPIO13 TX:GPIO15
// use SoftwareSerial on regular RX(3)/TX(1) for logging
logger = new SoftwareSerial(3, 1);
logger->begin(BAUD_LOGGER);
logger = new SoftwareSerial();
logger->begin(BAUD_LOGGER, 3, 1);
logger->enableIntTx(false);
logger->println("\n\nUsing SoftwareSerial for logging");
#else
logger->begin(BAUD_LOGGER);

View File

@ -49,24 +49,24 @@ extern "C" {
* @param p Print interface
*/
void ESP8266WiFiClass::printDiag(Print& p) {
const char* modes[] = { "NULL", "STA", "AP", "STA+AP" };
p.print("Mode: ");
const char* const modes[] = { "NULL", "STA", "AP", "STA+AP" };
p.print(F("Mode: "));
p.println(modes[wifi_get_opmode()]);
const char* phymodes[] = { "", "B", "G", "N" };
p.print("PHY mode: ");
const char* const phymodes[] = { "", "B", "G", "N" };
p.print(F("PHY mode: "));
p.println(phymodes[(int) wifi_get_phy_mode()]);
p.print("Channel: ");
p.print(F("Channel: "));
p.println(wifi_get_channel());
p.print("AP id: ");
p.print(F("AP id: "));
p.println(wifi_station_get_current_ap_id());
p.print("Status: ");
p.print(F("Status: "));
p.println(wifi_station_get_connect_status());
p.print("Auto connect: ");
p.print(F("Auto connect: "));
p.println(wifi_station_get_auto_connect());
struct station_config conf;
@ -75,22 +75,14 @@ void ESP8266WiFiClass::printDiag(Print& p) {
char ssid[33]; //ssid can be up to 32chars, => plus null term
memcpy(ssid, conf.ssid, sizeof(conf.ssid));
ssid[32] = 0; //nullterm in case of 32 char ssid
p.print("SSID (");
p.print(strlen(ssid));
p.print("): ");
p.println(ssid);
p.printf_P(PSTR("SSID (%d): %s\n"), strlen(ssid), ssid);
char passphrase[65];
memcpy(passphrase, conf.password, sizeof(conf.password));
passphrase[64] = 0;
p.printf_P(PSTR("Passphrase (%d): %s\n"), strlen(passphrase), passphrase);
p.print("Passphrase (");
p.print(strlen(passphrase));
p.print("): ");
p.println(passphrase);
p.print("BSSID set: ");
p.print(F("BSSID set: "));
p.println(conf.bssid_set);
}

View File

@ -43,7 +43,7 @@ ESP8266HTTPUpdate::~ESP8266HTTPUpdate(void)
{
}
#ifdef HTTPUPDATE_1_2_COMPATIBLE
#if HTTPUPDATE_1_2_COMPATIBLE
HTTPUpdateResult ESP8266HTTPUpdate::update(const String& url, const String& currentVersion,
const String& httpsFingerprint, bool reboot)
{
@ -94,7 +94,7 @@ HTTPUpdateResult ESP8266HTTPUpdate::update(WiFiClient& client, const String& url
return handleUpdate(http, currentVersion, false);
}
#ifdef HTTPUPDATE_1_2_COMPATIBLE
#if HTTPUPDATE_1_2_COMPATIBLE
HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint)
{
HTTPClient http;
@ -133,7 +133,7 @@ HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(WiFiClient& client, const Strin
return handleUpdate(http, currentVersion, true);
}
#ifdef HTTPUPDATE_1_2_COMPATIBLE
#if HTTPUPDATE_1_2_COMPATIBLE
HTTPUpdateResult ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& uri, const String& currentVersion,
bool https, const String& httpsFingerprint, bool reboot)
{
@ -263,6 +263,7 @@ HTTPUpdateResult ESP8266HTTPUpdate::handleUpdate(HTTPClient& http, const String&
http.setTimeout(_httpClientTimeout);
http.setFollowRedirects(_followRedirects);
http.setUserAgent(F("ESP8266-http-Update"));
http.addHeader(F("x-ESP8266-Chip-ID"), String(ESP.getChipId()));
http.addHeader(F("x-ESP8266-STA-MAC"), WiFi.macAddress());
http.addHeader(F("x-ESP8266-AP-MAC"), WiFi.softAPmacAddress());
http.addHeader(F("x-ESP8266-free-space"), String(ESP.getFreeSketchSpace()));
@ -388,7 +389,11 @@ HTTPUpdateResult ESP8266HTTPUpdate::handleUpdate(HTTPClient& http, const String&
DEBUG_HTTP_UPDATE("[httpUpdate] Update ok\n");
http.end();
#ifdef ATOMIC_FS_UPDATE
if(_rebootOnUpdate) {
#else
if(_rebootOnUpdate && !spiffs) {
#endif
ESP.restart();
}

View File

@ -26,14 +26,16 @@
#ifndef ESP8266HTTPUPDATE_H_
#define ESP8266HTTPUPDATE_H_
#define HTTPUPDATE_1_2_COMPATIBLE
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <ESP8266HTTPClient.h>
#ifndef HTTPUPDATE_1_2_COMPATIBLE
#define HTTPUPDATE_1_2_COMPATIBLE HTTPCLIENT_1_1_COMPATIBLE
#endif
#ifdef DEBUG_ESP_HTTP_UPDATE
#ifdef DEBUG_ESP_PORT
#define DEBUG_HTTP_UPDATE(fmt, ...) DEBUG_ESP_PORT.printf_P( (PGM_P)PSTR(fmt), ## __VA_ARGS__ )
@ -85,7 +87,7 @@ public:
_ledOn = ledOn;
}
#ifdef HTTPUPDATE_1_2_COMPATIBLE
#if HTTPUPDATE_1_2_COMPATIBLE
// This function is deprecated, use rebootOnUpdate and the next one instead
t_httpUpdate_return update(const String& url, const String& currentVersion,
const String& httpsFingerprint, bool reboot) __attribute__((deprecated));
@ -97,7 +99,7 @@ public:
#endif
t_httpUpdate_return update(WiFiClient& client, const String& url, const String& currentVersion = "");
#ifdef HTTPUPDATE_1_2_COMPATIBLE
#if HTTPUPDATE_1_2_COMPATIBLE
// This function is deprecated, use one of the overloads below along with rebootOnUpdate
t_httpUpdate_return update(const String& host, uint16_t port, const String& uri, const String& currentVersion,
bool https, const String& httpsFingerprint, bool reboot) __attribute__((deprecated));
@ -112,7 +114,7 @@ public:
t_httpUpdate_return update(WiFiClient& client, const String& host, uint16_t port, const String& uri = "/",
const String& currentVersion = "");
#ifdef HTTPUPDATE_1_2_COMPATIBLE
#if HTTPUPDATE_1_2_COMPATIBLE
// This function is deprecated, use rebootOnUpdate and the next one instead
t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion,
const String& httpsFingerprint, bool reboot) __attribute__((deprecated));

View File

@ -1,10 +1,10 @@
#include <ESP8266mDNS.h>
/*
* MDNS responder global instance
*
* Class type that is instantiated depends on the type mapping in ESP8266mDNS.h
*/
MDNS responder global instance
Class type that is instantiated depends on the type mapping in ESP8266mDNS.h
*/
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_MDNS)
MDNSResponder MDNS;
#endif

View File

@ -1,44 +1,44 @@
/*
ESP8266mDNS.h - mDNSResponder for ESP8266 family
This file is part of the esp8266 core for Arduino environment.
ESP8266mDNS.h - mDNSResponder for ESP8266 family
This file is part of the esp8266 core for Arduino environment.
Legacy_ESP8266mDNS:
The well known, thouroughly tested (yet no flawless) default mDNS library for the ESP8266 family
Legacy_ESP8266mDNS:
The well known, thouroughly tested (yet no flawless) default mDNS library for the ESP8266 family
LEA_ESP8266mDNS:
An (currently) experimental mDNS implementation, that supports a lot more of mDNS features than Legacy_ESP8266mDNS, like:
- Presenting a DNS-SD service to interested observers, eg. a http server by presenting _http._tcp service
- Support for multi-level compressed names in input; in output only a very simple one-leven full-name compression is implemented
- Probing host and service domains for uniqueness in the local network
- Tiebreaking while probing is supportet in a very minimalistic way (the 'higher' IP address wins the tiebreak)
- Announcing available services after successful probing
- Using fixed service TXT items or
- Using dynamic service TXT items for presented services (via callback)
- Remove services (and un-announcing them to the observers by sending goodbye-messages)
- Static queries for DNS-SD services (creating a fixed answer set after a certain timeout period)
- Dynamic queries for DNS-SD services with cached and updated answers and user notifications
- Support for multi-homed client host domains
LEA_ESP8266mDNS:
An (currently) experimental mDNS implementation, that supports a lot more of mDNS features than Legacy_ESP8266mDNS, like:
- Presenting a DNS-SD service to interested observers, eg. a http server by presenting _http._tcp service
- Support for multi-level compressed names in input; in output only a very simple one-leven full-name compression is implemented
- Probing host and service domains for uniqueness in the local network
- Tiebreaking while probing is supportet in a very minimalistic way (the 'higher' IP address wins the tiebreak)
- Announcing available services after successful probing
- Using fixed service TXT items or
- Using dynamic service TXT items for presented services (via callback)
- Remove services (and un-announcing them to the observers by sending goodbye-messages)
- Static queries for DNS-SD services (creating a fixed answer set after a certain timeout period)
- Dynamic queries for DNS-SD services with cached and updated answers and user notifications
- Support for multi-homed client host domains
See 'LEA_ESP8266mDNS/EPS8266mDNS.h' for more implementation details and usage informations.
See 'examples/mDNS_Clock' and 'examples/mDNS_ServiceMonitor' for implementation examples of the advanced features.
See 'LEA_ESP8266mDNS/EPS8266mDNS.h' for more implementation details and usage informations.
See 'examples/mDNS_Clock' and 'examples/mDNS_ServiceMonitor' for implementation examples of the advanced features.
LEA_ESP8266mDNS is (mostly) client source code compatible to 'Legacy_ESP8266mDNS', so it could be
use as a 'drop-in' replacement in existing projects.
LEA_ESP8266mDNS is (mostly) client source code compatible to 'Legacy_ESP8266mDNS', so it could be
use as a 'drop-in' replacement in existing projects.
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 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.
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
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
*/
@ -47,10 +47,10 @@
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_MDNS)
// Maps the implementation to use to the global namespace type
//using MDNSResponder = Legacy_MDNSResponder::MDNSResponder; //legacy
using MDNSResponder = esp8266::MDNSImplementation::MDNSResponder; //new
extern MDNSResponder MDNS;
// Maps the implementation to use to the global namespace type
//using MDNSResponder = Legacy_MDNSResponder::MDNSResponder; //legacy
using MDNSResponder = esp8266::MDNSImplementation::MDNSResponder; //new
extern MDNSResponder MDNS;
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,43 +1,43 @@
/*
ESP8266 Multicast DNS (port of CC3000 Multicast DNS library)
Version 1.1
Copyright (c) 2013 Tony DiCola (tony@tonydicola.com)
ESP8266 port (c) 2015 Ivan Grokhotkov (ivan@esp8266.com)
Extended MDNS-SD support 2016 Lars Englund (lars.englund@gmail.com)
ESP8266 Multicast DNS (port of CC3000 Multicast DNS library)
Version 1.1
Copyright (c) 2013 Tony DiCola (tony@tonydicola.com)
ESP8266 port (c) 2015 Ivan Grokhotkov (ivan@esp8266.com)
Extended MDNS-SD support 2016 Lars Englund (lars.englund@gmail.com)
This is a simple implementation of multicast DNS query support for an Arduino
running on ESP8266 chip. Only support for resolving address queries is currently
implemented.
This is a simple implementation of multicast DNS query support for an Arduino
running on ESP8266 chip. Only support for resolving address queries is currently
implemented.
Requirements:
- ESP8266WiFi library
Requirements:
- ESP8266WiFi library
Usage:
- Include the ESP8266 Multicast DNS library in the sketch.
- Call the begin method in the sketch's setup and provide a domain name (without
the '.local' suffix, i.e. just provide 'foo' to resolve 'foo.local'), and the
Adafruit CC3000 class instance. Optionally provide a time to live (in seconds)
for the DNS record--the default is 1 hour.
- Call the update method in each iteration of the sketch's loop function.
Usage:
- Include the ESP8266 Multicast DNS library in the sketch.
- Call the begin method in the sketch's setup and provide a domain name (without
the '.local' suffix, i.e. just provide 'foo' to resolve 'foo.local'), and the
Adafruit CC3000 class instance. Optionally provide a time to live (in seconds)
for the DNS record--the default is 1 hour.
- Call the update method in each iteration of the sketch's loop function.
License (MIT license):
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:
License (MIT license):
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 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.
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.
*/
#ifndef ESP8266MDNS_LEGACY_H
@ -54,95 +54,108 @@ License (MIT license):
class UdpContext;
namespace Legacy_MDNSResponder {
namespace Legacy_MDNSResponder
{
struct MDNSService;
struct MDNSTxt;
struct MDNSAnswer;
class MDNSResponder {
class MDNSResponder
{
public:
MDNSResponder();
~MDNSResponder();
bool begin(const char* hostName);
bool begin(const String& hostName) {
return begin(hostName.c_str());
}
//for compatibility
bool begin(const char* hostName, IPAddress ip, uint32_t ttl=120){
(void) ip;
(void) ttl;
return begin(hostName);
}
bool begin(const String& hostName, IPAddress ip, uint32_t ttl=120) {
return begin(hostName.c_str(), ip, ttl);
}
/* Application should call this whenever AP is configured/disabled */
void notifyAPChange();
void update();
MDNSResponder();
~MDNSResponder();
bool begin(const char* hostName);
bool begin(const String& hostName)
{
return begin(hostName.c_str());
}
//for compatibility
bool begin(const char* hostName, IPAddress ip, uint32_t ttl = 120)
{
(void) ip;
(void) ttl;
return begin(hostName);
}
bool begin(const String& hostName, IPAddress ip, uint32_t ttl = 120)
{
return begin(hostName.c_str(), ip, ttl);
}
/* Application should call this whenever AP is configured/disabled */
void notifyAPChange();
void update();
void addService(char *service, char *proto, uint16_t port);
void addService(const char *service, const char *proto, uint16_t port){
addService((char *)service, (char *)proto, port);
}
void addService(const String& service, const String& proto, uint16_t port){
addService(service.c_str(), proto.c_str(), port);
}
bool addServiceTxt(char *name, char *proto, char * key, char * value);
bool addServiceTxt(const char *name, const char *proto, const char *key,const char * value){
return addServiceTxt((char *)name, (char *)proto, (char *)key, (char *)value);
}
bool addServiceTxt(const String& name, const String& proto, const String& key, const String& value){
return addServiceTxt(name.c_str(), proto.c_str(), key.c_str(), value.c_str());
}
int queryService(char *service, char *proto);
int queryService(const char *service, const char *proto){
return queryService((char *)service, (char *)proto);
}
int queryService(const String& service, const String& proto){
return queryService(service.c_str(), proto.c_str());
}
String hostname(int idx);
IPAddress IP(int idx);
uint16_t port(int idx);
void enableArduino(uint16_t port, bool auth=false);
void addService(char *service, char *proto, uint16_t port);
void addService(const char *service, const char *proto, uint16_t port)
{
addService((char *)service, (char *)proto, port);
}
void addService(const String& service, const String& proto, uint16_t port)
{
addService(service.c_str(), proto.c_str(), port);
}
void setInstanceName(String name);
void setInstanceName(const char * name){
setInstanceName(String(name));
}
void setInstanceName(char * name){
setInstanceName(String(name));
}
bool addServiceTxt(char *name, char *proto, char * key, char * value);
bool addServiceTxt(const char *name, const char *proto, const char *key, const char * value)
{
return addServiceTxt((char *)name, (char *)proto, (char *)key, (char *)value);
}
bool addServiceTxt(const String& name, const String& proto, const String& key, const String& value)
{
return addServiceTxt(name.c_str(), proto.c_str(), key.c_str(), value.c_str());
}
int queryService(char *service, char *proto);
int queryService(const char *service, const char *proto)
{
return queryService((char *)service, (char *)proto);
}
int queryService(const String& service, const String& proto)
{
return queryService(service.c_str(), proto.c_str());
}
String hostname(int idx);
IPAddress IP(int idx);
uint16_t port(int idx);
void enableArduino(uint16_t port, bool auth = false);
void setInstanceName(String name);
void setInstanceName(const char * name)
{
setInstanceName(String(name));
}
void setInstanceName(char * name)
{
setInstanceName(String(name));
}
private:
struct MDNSService * _services;
UdpContext* _conn;
String _hostName;
String _instanceName;
struct MDNSAnswer * _answers;
struct MDNSQuery * _query;
bool _newQuery;
bool _waitingForAnswers;
WiFiEventHandler _disconnectedHandler;
WiFiEventHandler _gotIPHandler;
struct MDNSService * _services;
UdpContext* _conn;
String _hostName;
String _instanceName;
struct MDNSAnswer * _answers;
struct MDNSQuery * _query;
bool _newQuery;
bool _waitingForAnswers;
WiFiEventHandler _disconnectedHandler;
WiFiEventHandler _gotIPHandler;
uint16_t _getServicePort(char *service, char *proto);
MDNSTxt * _getServiceTxt(char *name, char *proto);
uint16_t _getServiceTxtLen(char *name, char *proto);
IPAddress _getRequestMulticastInterface();
void _parsePacket();
void _replyToTypeEnumRequest(IPAddress multicastInterface);
void _replyToInstanceRequest(uint8_t questionMask, uint8_t responseMask, char * service, char *proto, uint16_t port, IPAddress multicastInterface);
MDNSAnswer* _getAnswerFromIdx(int idx);
int _getNumAnswers();
bool _listen();
void _restart();
uint16_t _getServicePort(char *service, char *proto);
MDNSTxt * _getServiceTxt(char *name, char *proto);
uint16_t _getServiceTxtLen(char *name, char *proto);
IPAddress _getRequestMulticastInterface();
void _parsePacket();
void _replyToTypeEnumRequest(IPAddress multicastInterface);
void _replyToInstanceRequest(uint8_t questionMask, uint8_t responseMask, char * service, char *proto, uint16_t port, IPAddress multicastInterface);
MDNSAnswer* _getAnswerFromIdx(int idx);
int _getNumAnswers();
bool _listen();
void _restart();
};
} // namespace Legacy_MDNSResponder

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,180 +1,182 @@
/*
* LEAmDNS_Priv.h
*
* License (MIT license):
* 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.
*
*/
#ifndef MDNS_PRIV_H
#define MDNS_PRIV_H
namespace esp8266 {
/*
* LEAmDNS
*/
namespace MDNSImplementation {
// Enable class debug functions
#define ESP_8266_MDNS_INCLUDE
//#define DEBUG_ESP_MDNS_RESPONDER
#if !defined(DEBUG_ESP_MDNS_RESPONDER) && defined(DEBUG_ESP_MDNS)
#define DEBUG_ESP_MDNS_RESPONDER
#endif
#ifndef LWIP_OPEN_SRC
#define LWIP_OPEN_SRC
#endif
//
// If ENABLE_ESP_MDNS_RESPONDER_PASSIV_MODE is defined, the mDNS responder ignores a successful probing
// This allows to drive the responder in a environment, where 'update()' isn't called in the loop
//#define ENABLE_ESP_MDNS_RESPONDER_PASSIV_MODE
// Enable/disable debug trace macros
#ifdef DEBUG_ESP_MDNS_RESPONDER
#define DEBUG_ESP_MDNS_INFO
#define DEBUG_ESP_MDNS_ERR
#define DEBUG_ESP_MDNS_TX
#define DEBUG_ESP_MDNS_RX
#endif
#ifdef DEBUG_ESP_MDNS_RESPONDER
#ifdef DEBUG_ESP_MDNS_INFO
#define DEBUG_EX_INFO(A) A
#else
#define DEBUG_EX_INFO(A) do { (void)0; } while (0)
#endif
#ifdef DEBUG_ESP_MDNS_ERR
#define DEBUG_EX_ERR(A) A
#else
#define DEBUG_EX_ERR(A) do { (void)0; } while (0)
#endif
#ifdef DEBUG_ESP_MDNS_TX
#define DEBUG_EX_TX(A) A
#else
#define DEBUG_EX_TX(A) do { (void)0; } while (0)
#endif
#ifdef DEBUG_ESP_MDNS_RX
#define DEBUG_EX_RX(A) A
#else
#define DEBUG_EX_RX(A) do { (void)0; } while (0)
#endif
#ifdef DEBUG_ESP_PORT
#define DEBUG_OUTPUT DEBUG_ESP_PORT
#else
#define DEBUG_OUTPUT Serial
#endif
#else
#define DEBUG_EX_INFO(A) do { (void)0; } while (0)
#define DEBUG_EX_ERR(A) do { (void)0; } while (0)
#define DEBUG_EX_TX(A) do { (void)0; } while (0)
#define DEBUG_EX_RX(A) do { (void)0; } while (0)
#endif
/* Replaced by 'lwip/prot/dns.h' definitions
#ifdef MDNS_IP4_SUPPORT
#define MDNS_MULTICAST_ADDR_IP4 (IPAddress(224, 0, 0, 251)) // ip_addr_t v4group = DNS_MQUERY_IPV4_GROUP_INIT
#endif
#ifdef MDNS_IP6_SUPPORT
#define MDNS_MULTICAST_ADDR_IP6 (IPAddress("FF02::FB")) // ip_addr_t v6group = DNS_MQUERY_IPV6_GROUP_INIT
#endif*/
//#define MDNS_MULTICAST_PORT 5353
/*
* This is NOT the TTL (Time-To-Live) for MDNS records, but the
* subnet level distance MDNS records should travel.
* 1 sets the subnet distance to 'local', which is default for MDNS.
* (Btw.: 255 would set it to 'as far as possible' -> internet)
*
* However, RFC 3171 seems to force 255 instead
*/
#define MDNS_MULTICAST_TTL 255/*1*/
/*
* This is the MDNS record TTL
* Host level records are set to 2min (120s)
* service level records are set to 75min (4500s)
*/
#define MDNS_HOST_TTL 120
#define MDNS_SERVICE_TTL 4500
/*
* Compressed labels are flaged by the two topmost bits of the length byte being set
*/
#define MDNS_DOMAIN_COMPRESS_MARK 0xC0
/*
* Avoid endless recursion because of malformed compressed labels
*/
#define MDNS_DOMAIN_MAX_REDIRCTION 6
/*
* Default service priority and weight in SRV answers
*/
#define MDNS_SRV_PRIORITY 0
#define MDNS_SRV_WEIGHT 0
/*
* Delay between and number of probes for host and service domains
* Delay between and number of announces for host and service domains
* Delay between and number of service queries; the delay is multiplied by the resent number in '_checkServiceQueryCache'
*/
#define MDNS_PROBE_DELAY 250
#define MDNS_PROBE_COUNT 3
#define MDNS_ANNOUNCE_DELAY 1000
#define MDNS_ANNOUNCE_COUNT 8
#define MDNS_DYNAMIC_QUERY_RESEND_COUNT 5
#define MDNS_DYNAMIC_QUERY_RESEND_DELAY 5000
/*
* Force host domain to use only lowercase letters
*/
//#define MDNS_FORCE_LOWERCASE_HOSTNAME
/*
* Enable/disable the usage of the F() macro in debug trace printf calls.
* There needs to be an PGM comptible printf function to use this.
*
* USE_PGM_PRINTF and F
*/
#define USE_PGM_PRINTF
#ifdef USE_PGM_PRINTF
#else
#ifdef F
#undef F
#endif
#define F(A) A
#endif
} // namespace MDNSImplementation
} // namespace esp8266
// Include the main header, so the submodlues only need to include this header
#include "LEAmDNS.h"
#endif // MDNS_PRIV_H
/*
LEAmDNS_Priv.h
License (MIT license):
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.
*/
#ifndef MDNS_PRIV_H
#define MDNS_PRIV_H
namespace esp8266
{
/*
LEAmDNS
*/
namespace MDNSImplementation
{
// Enable class debug functions
#define ESP_8266_MDNS_INCLUDE
//#define DEBUG_ESP_MDNS_RESPONDER
#if !defined(DEBUG_ESP_MDNS_RESPONDER) && defined(DEBUG_ESP_MDNS)
#define DEBUG_ESP_MDNS_RESPONDER
#endif
#ifndef LWIP_OPEN_SRC
#define LWIP_OPEN_SRC
#endif
//
// If ENABLE_ESP_MDNS_RESPONDER_PASSIV_MODE is defined, the mDNS responder ignores a successful probing
// This allows to drive the responder in a environment, where 'update()' isn't called in the loop
//#define ENABLE_ESP_MDNS_RESPONDER_PASSIV_MODE
// Enable/disable debug trace macros
#ifdef DEBUG_ESP_MDNS_RESPONDER
#define DEBUG_ESP_MDNS_INFO
#define DEBUG_ESP_MDNS_ERR
#define DEBUG_ESP_MDNS_TX
#define DEBUG_ESP_MDNS_RX
#endif
#ifdef DEBUG_ESP_MDNS_RESPONDER
#ifdef DEBUG_ESP_MDNS_INFO
#define DEBUG_EX_INFO(A) A
#else
#define DEBUG_EX_INFO(A) do { (void)0; } while (0)
#endif
#ifdef DEBUG_ESP_MDNS_ERR
#define DEBUG_EX_ERR(A) A
#else
#define DEBUG_EX_ERR(A) do { (void)0; } while (0)
#endif
#ifdef DEBUG_ESP_MDNS_TX
#define DEBUG_EX_TX(A) A
#else
#define DEBUG_EX_TX(A) do { (void)0; } while (0)
#endif
#ifdef DEBUG_ESP_MDNS_RX
#define DEBUG_EX_RX(A) A
#else
#define DEBUG_EX_RX(A) do { (void)0; } while (0)
#endif
#ifdef DEBUG_ESP_PORT
#define DEBUG_OUTPUT DEBUG_ESP_PORT
#else
#define DEBUG_OUTPUT Serial
#endif
#else
#define DEBUG_EX_INFO(A) do { (void)0; } while (0)
#define DEBUG_EX_ERR(A) do { (void)0; } while (0)
#define DEBUG_EX_TX(A) do { (void)0; } while (0)
#define DEBUG_EX_RX(A) do { (void)0; } while (0)
#endif
/* Replaced by 'lwip/prot/dns.h' definitions
#ifdef MDNS_IP4_SUPPORT
#define MDNS_MULTICAST_ADDR_IP4 (IPAddress(224, 0, 0, 251)) // ip_addr_t v4group = DNS_MQUERY_IPV4_GROUP_INIT
#endif
#ifdef MDNS_IP6_SUPPORT
#define MDNS_MULTICAST_ADDR_IP6 (IPAddress("FF02::FB")) // ip_addr_t v6group = DNS_MQUERY_IPV6_GROUP_INIT
#endif*/
//#define MDNS_MULTICAST_PORT 5353
/*
This is NOT the TTL (Time-To-Live) for MDNS records, but the
subnet level distance MDNS records should travel.
1 sets the subnet distance to 'local', which is default for MDNS.
(Btw.: 255 would set it to 'as far as possible' -> internet)
However, RFC 3171 seems to force 255 instead
*/
#define MDNS_MULTICAST_TTL 255/*1*/
/*
This is the MDNS record TTL
Host level records are set to 2min (120s)
service level records are set to 75min (4500s)
*/
#define MDNS_HOST_TTL 120
#define MDNS_SERVICE_TTL 4500
/*
Compressed labels are flaged by the two topmost bits of the length byte being set
*/
#define MDNS_DOMAIN_COMPRESS_MARK 0xC0
/*
Avoid endless recursion because of malformed compressed labels
*/
#define MDNS_DOMAIN_MAX_REDIRCTION 6
/*
Default service priority and weight in SRV answers
*/
#define MDNS_SRV_PRIORITY 0
#define MDNS_SRV_WEIGHT 0
/*
Delay between and number of probes for host and service domains
Delay between and number of announces for host and service domains
Delay between and number of service queries; the delay is multiplied by the resent number in '_checkServiceQueryCache'
*/
#define MDNS_PROBE_DELAY 250
#define MDNS_PROBE_COUNT 3
#define MDNS_ANNOUNCE_DELAY 1000
#define MDNS_ANNOUNCE_COUNT 8
#define MDNS_DYNAMIC_QUERY_RESEND_COUNT 5
#define MDNS_DYNAMIC_QUERY_RESEND_DELAY 5000
/*
Force host domain to use only lowercase letters
*/
//#define MDNS_FORCE_LOWERCASE_HOSTNAME
/*
Enable/disable the usage of the F() macro in debug trace printf calls.
There needs to be an PGM comptible printf function to use this.
USE_PGM_PRINTF and F
*/
#define USE_PGM_PRINTF
#ifdef USE_PGM_PRINTF
#else
#ifdef F
#undef F
#endif
#define F(A) A
#endif
} // namespace MDNSImplementation
} // namespace esp8266
// Include the main header, so the submodlues only need to include this header
#include "LEAmDNS.h"
#endif // MDNS_PRIV_H

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +1,26 @@
/*
* LEAmDNS_Priv.h
*
* License (MIT license):
* 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.
*
*/
LEAmDNS_Priv.h
License (MIT license):
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.
*/
#ifndef MDNS_LWIPDEFS_H
#define MDNS_LWIPDEFS_H

View File

@ -23,22 +23,18 @@
*/
#include <Arduino.h>
#include <bearssl/bearssl_hash.h>
#include "Hash.h"
extern "C" {
#include "sha1/sha1.h"
}
/**
* create a sha1 hash from data
* @param data uint8_t *
* @param size uint32_t
* @param hash uint8_t[20]
*/
void sha1(uint8_t * data, uint32_t size, uint8_t hash[20]) {
SHA1_CTX ctx;
void sha1(const uint8_t* data, uint32_t size, uint8_t hash[20]) {
br_sha1_context ctx;
#ifdef DEBUG_SHA1
os_printf("DATA:");
@ -53,9 +49,9 @@ void sha1(uint8_t * data, uint32_t size, uint8_t hash[20]) {
os_printf("\n");
#endif
SHA1Init(&ctx);
SHA1Update(&ctx, data, size);
SHA1Final(hash, &ctx);
br_sha1_init(&ctx);
br_sha1_update(&ctx, data, size);
br_sha1_out(&ctx, hash);
#ifdef DEBUG_SHA1
os_printf("SHA1:");
@ -66,52 +62,35 @@ void sha1(uint8_t * data, uint32_t size, uint8_t hash[20]) {
#endif
}
void sha1(char * data, uint32_t size, uint8_t hash[20]) {
sha1((uint8_t *) data, size, hash);
void sha1(const char* data, uint32_t size, uint8_t hash[20]) {
sha1((const uint8_t *) data, size, hash);
}
void sha1(const uint8_t * data, uint32_t size, uint8_t hash[20]) {
sha1((uint8_t *) data, size, hash);
}
void sha1(const char * data, uint32_t size, uint8_t hash[20]) {
sha1((uint8_t *) data, size, hash);
}
void sha1(String data, uint8_t hash[20]) {
void sha1(const String& data, uint8_t hash[20]) {
sha1(data.c_str(), data.length(), hash);
}
String sha1(uint8_t* data, uint32_t size) {
String sha1(const uint8_t* data, uint32_t size) {
uint8_t hash[20];
String hashStr = "";
String hashStr((const char*)nullptr);
hashStr.reserve(20 * 2 + 1);
sha1(&data[0], size, &hash[0]);
for(uint16_t i = 0; i < 20; i++) {
String hex = String(hash[i], HEX);
if(hex.length() < 2) {
hex = "0" + hex;
}
char hex[3];
snprintf(hex, sizeof(hex), "%02x", hash[i]);
hashStr += hex;
}
return hashStr;
}
String sha1(char* data, uint32_t size) {
return sha1((uint8_t*) data, size);
}
String sha1(const uint8_t* data, uint32_t size) {
return sha1((uint8_t*) data, size);
}
String sha1(const char* data, uint32_t size) {
return sha1((uint8_t*) data, size);
return sha1((const uint8_t*) data, size);
}
String sha1(String data) {
String sha1(const String& data) {
return sha1(data.c_str(), data.length());
}

View File

@ -27,16 +27,12 @@
//#define DEBUG_SHA1
void sha1(uint8_t * data, uint32_t size, uint8_t hash[20]);
void sha1(char * data, uint32_t size, uint8_t hash[20]);
void sha1(const uint8_t * data, uint32_t size, uint8_t hash[20]);
void sha1(const char * data, uint32_t size, uint8_t hash[20]);
void sha1(String data, uint8_t hash[20]);
void sha1(const uint8_t* data, uint32_t size, uint8_t hash[20]);
void sha1(const char* data, uint32_t size, uint8_t hash[20]);
void sha1(const String& data, uint8_t hash[20]);
String sha1(uint8_t* data, uint32_t size);
String sha1(char* data, uint32_t size);
String sha1(const uint8_t* data, uint32_t size);
String sha1(const char* data, uint32_t size);
String sha1(String data);
String sha1(const String& data);
#endif /* HASH_H_ */

View File

@ -1,208 +0,0 @@
/**
* @file sha1.c
* @date 20.05.2015
* @author Steve Reid <steve@edmweb.com>
*
* from: http://www.virtualbox.org/svn/vbox/trunk/src/recompiler/tests/sha1.c
*/
/* from valgrind tests */
/* ================ sha1.c ================ */
/*
SHA-1 in C
By Steve Reid <steve@edmweb.com>
100% Public Domain
Test Vectors (from FIPS PUB 180-1)
"abc"
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
A million repetitions of "a"
34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
*/
/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */
/* #define SHA1HANDSOFF * Copies data before messing with it. */
#define SHA1HANDSOFF
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <c_types.h>
#include "sha1.h"
//#include <endian.h>
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
/* blk0() and blk() perform the initial expand. */
/* I got the idea of expanding during the round function from SSLeay */
#if BYTE_ORDER == LITTLE_ENDIAN
#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
|(rol(block->l[i],8)&0x00FF00FF))
#elif BYTE_ORDER == BIG_ENDIAN
#define blk0(i) block->l[i]
#else
#error "Endianness not defined!"
#endif
#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
^block->l[(i+2)&15]^block->l[i&15],1))
/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
/* Hash a single 512-bit block. This is the core of the algorithm. */
void ICACHE_FLASH_ATTR SHA1Transform(uint32_t state[5], uint8_t buffer[64])
{
uint32_t a, b, c, d, e;
typedef union {
unsigned char c[64];
uint32_t l[16];
} CHAR64LONG16;
#ifdef SHA1HANDSOFF
CHAR64LONG16 block[1]; /* use array to appear as a pointer */
memcpy(block, buffer, 64);
#else
/* The following had better never be used because it causes the
* pointer-to-const buffer to be cast into a pointer to non-const.
* And the result is written through. I threw a "const" in, hoping
* this will cause a diagnostic.
*/
CHAR64LONG16* block = (const CHAR64LONG16*)buffer;
#endif
/* Copy context->state[] to working vars */
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
/* 4 rounds of 20 operations each. Loop unrolled. */
R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
/* Add the working vars back into context.state[] */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
/* Wipe variables */
a = b = c = d = e = 0;
#ifdef SHA1HANDSOFF
memset(block, '\0', sizeof(block));
#endif
}
/* SHA1Init - Initialize new context */
void ICACHE_FLASH_ATTR SHA1Init(SHA1_CTX* context)
{
/* SHA1 initialization constants */
context->state[0] = 0x67452301;
context->state[1] = 0xEFCDAB89;
context->state[2] = 0x98BADCFE;
context->state[3] = 0x10325476;
context->state[4] = 0xC3D2E1F0;
context->count[0] = context->count[1] = 0;
}
/* Run your data through this. */
void ICACHE_FLASH_ATTR SHA1Update(SHA1_CTX* context, uint8_t* data, uint32_t len)
{
uint32_t i;
uint32_t j;
j = context->count[0];
if ((context->count[0] += len << 3) < j)
context->count[1]++;
context->count[1] += (len>>29);
j = (j >> 3) & 63;
if ((j + len) > 63) {
memcpy(&context->buffer[j], data, (i = 64-j));
SHA1Transform(context->state, context->buffer);
for ( ; i + 63 < len; i += 64) {
SHA1Transform(context->state, &data[i]);
}
j = 0;
}
else i = 0;
memcpy(&context->buffer[j], &data[i], len - i);
}
/* Add padding and return the message digest. */
void ICACHE_FLASH_ATTR SHA1Final(unsigned char digest[20], SHA1_CTX* context)
{
unsigned i;
unsigned char finalcount[8];
unsigned char c;
#if 0 /* untested "improvement" by DHR */
/* Convert context->count to a sequence of bytes
* in finalcount. Second element first, but
* big-endian order within element.
* But we do it all backwards.
*/
unsigned char *fcp = &finalcount[8];
for (i = 0; i < 2; i++)
{
uint32_t t = context->count[i];
int j;
for (j = 0; j < 4; t >>= 8, j++)
*--fcp = (unsigned char) t;
}
#else
for (i = 0; i < 8; i++) {
finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
>> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
}
#endif
c = 0200;
SHA1Update(context, &c, 1);
while ((context->count[0] & 504) != 448) {
c = 0000;
SHA1Update(context, &c, 1);
}
SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
for (i = 0; i < 20; i++) {
digest[i] = (unsigned char)
((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
}
/* Wipe variables */
memset(context, '\0', sizeof(*context));
memset(&finalcount, '\0', sizeof(finalcount));
}
/* ================ end of sha1.c ================ */

View File

@ -1,32 +0,0 @@
/**
* @file sha1.h
* @date 20.05.2015
* @author Steve Reid <steve@edmweb.com>
*
* from: http://www.virtualbox.org/svn/vbox/trunk/src/recompiler/tests/sha1.c
*/
/* ================ sha1.h ================ */
/*
SHA-1 in C
By Steve Reid <steve@edmweb.com>
100% Public Domain
*/
#ifndef SHA1_H_
#define SHA1_H_
typedef struct {
uint32_t state[5];
uint32_t count[2];
unsigned char buffer[64];
} SHA1_CTX;
void SHA1Transform(uint32_t state[5], uint8_t buffer[64]);
void SHA1Init(SHA1_CTX* context);
void SHA1Update(SHA1_CTX* context, uint8_t* data, uint32_t len);
void SHA1Final(unsigned char digest[20], SHA1_CTX* context);
#endif /* SHA1_H_ */
/* ================ end of sha1.h ================ */

View File

@ -24,7 +24,7 @@
#include <Arduino.h>
#include <stdlib.h>
#define SPI_HAS_TRANSACTION
#define SPI_HAS_TRANSACTION 1
// This defines are not representing the real Divider of the ESP8266
// the Defines match to an AVR Arduino on 16MHz for better compatibility

View File

@ -1,31 +1,31 @@
/*
TwoWire.cpp - TWI/I2C library for Arduino & Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
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 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.
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
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
Modified January 2017 by Bjorn Hammarberg (bjoham@esp8266.com) - i2c slave support
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
Modified January 2017 by Bjorn Hammarberg (bjoham@esp8266.com) - i2c slave support
*/
extern "C" {
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
}
#include "twi.h"
@ -58,226 +58,273 @@ static int default_scl_pin = SCL;
// Constructors ////////////////////////////////////////////////////////////////
TwoWire::TwoWire(){}
TwoWire::TwoWire() {}
// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(int sda, int scl){
default_sda_pin = sda;
default_scl_pin = scl;
twi_init(sda, scl);
flush();
void TwoWire::begin(int sda, int scl)
{
default_sda_pin = sda;
default_scl_pin = scl;
twi_init(sda, scl);
flush();
}
void TwoWire::begin(int sda, int scl, uint8_t address){
default_sda_pin = sda;
default_scl_pin = scl;
twi_setAddress(address);
twi_init(sda, scl);
twi_attachSlaveTxEvent(onRequestService);
twi_attachSlaveRxEvent(onReceiveService);
flush();
void TwoWire::begin(int sda, int scl, uint8_t address)
{
default_sda_pin = sda;
default_scl_pin = scl;
twi_setAddress(address);
twi_init(sda, scl);
twi_attachSlaveTxEvent(onRequestService);
twi_attachSlaveRxEvent(onReceiveService);
flush();
}
void TwoWire::pins(int sda, int scl){
default_sda_pin = sda;
default_scl_pin = scl;
void TwoWire::pins(int sda, int scl)
{
default_sda_pin = sda;
default_scl_pin = scl;
}
void TwoWire::begin(void){
begin(default_sda_pin, default_scl_pin);
void TwoWire::begin(void)
{
begin(default_sda_pin, default_scl_pin);
}
void TwoWire::begin(uint8_t address){
twi_setAddress(address);
twi_attachSlaveTxEvent(onRequestService);
twi_attachSlaveRxEvent(onReceiveService);
begin();
void TwoWire::begin(uint8_t address)
{
twi_setAddress(address);
twi_attachSlaveTxEvent(onRequestService);
twi_attachSlaveRxEvent(onReceiveService);
begin();
}
uint8_t TwoWire::status(){
return twi_status();
uint8_t TwoWire::status()
{
return twi_status();
}
void TwoWire::begin(int address){
begin((uint8_t)address);
void TwoWire::begin(int address)
{
begin((uint8_t)address);
}
void TwoWire::setClock(uint32_t frequency){
twi_setClock(frequency);
void TwoWire::setClock(uint32_t frequency)
{
twi_setClock(frequency);
}
void TwoWire::setClockStretchLimit(uint32_t limit){
twi_setClockStretchLimit(limit);
void TwoWire::setClockStretchLimit(uint32_t limit)
{
twi_setClockStretchLimit(limit);
}
size_t TwoWire::requestFrom(uint8_t address, size_t size, bool sendStop){
if(size > BUFFER_LENGTH){
size = BUFFER_LENGTH;
}
size_t read = (twi_readFrom(address, rxBuffer, size, sendStop) == 0)?size:0;
rxBufferIndex = 0;
rxBufferLength = read;
return read;
}
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;
txBufferIndex = 0;
txBufferLength = 0;
}
void TwoWire::beginTransmission(int address){
beginTransmission((uint8_t)address);
}
uint8_t TwoWire::endTransmission(uint8_t sendStop){
int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, sendStop);
txBufferIndex = 0;
txBufferLength = 0;
transmitting = 0;
return ret;
}
uint8_t TwoWire::endTransmission(void){
return endTransmission(true);
}
size_t TwoWire::write(uint8_t data){
if(transmitting){
if(txBufferLength >= BUFFER_LENGTH){
setWriteError();
return 0;
size_t TwoWire::requestFrom(uint8_t address, size_t size, bool sendStop)
{
if (size > BUFFER_LENGTH)
{
size = BUFFER_LENGTH;
}
txBuffer[txBufferIndex] = data;
++txBufferIndex;
txBufferLength = txBufferIndex;
} else {
twi_transmit(&data, 1);
}
return 1;
size_t read = (twi_readFrom(address, rxBuffer, size, sendStop) == 0) ? size : 0;
rxBufferIndex = 0;
rxBufferLength = read;
return read;
}
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;
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;
txBufferIndex = 0;
txBufferLength = 0;
}
void TwoWire::beginTransmission(int address)
{
beginTransmission((uint8_t)address);
}
uint8_t TwoWire::endTransmission(uint8_t sendStop)
{
int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, sendStop);
txBufferIndex = 0;
txBufferLength = 0;
transmitting = 0;
return ret;
}
uint8_t TwoWire::endTransmission(void)
{
return endTransmission(true);
}
size_t TwoWire::write(uint8_t data)
{
if (transmitting)
{
if (txBufferLength >= BUFFER_LENGTH)
{
setWriteError();
return 0;
}
txBuffer[txBufferIndex] = data;
++txBufferIndex;
txBufferLength = txBufferIndex;
}
}else{
twi_transmit(data, quantity);
}
return quantity;
else
{
twi_transmit(&data, 1);
}
return 1;
}
int TwoWire::available(void){
int result = rxBufferLength - rxBufferIndex;
if (!result) {
// yielding here will not make more data "available",
// but it will prevent the system from going into WDT reset
optimistic_yield(1000);
}
return result;
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;
}
}
}
else
{
twi_transmit(data, quantity);
}
return quantity;
}
int TwoWire::read(void){
int value = -1;
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
++rxBufferIndex;
}
return value;
int TwoWire::available(void)
{
int result = rxBufferLength - rxBufferIndex;
if (!result)
{
// yielding here will not make more data "available",
// but it will prevent the system from going into WDT reset
optimistic_yield(1000);
}
return result;
}
int TwoWire::peek(void){
int value = -1;
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
}
return value;
int TwoWire::read(void)
{
int value = -1;
if (rxBufferIndex < rxBufferLength)
{
value = rxBuffer[rxBufferIndex];
++rxBufferIndex;
}
return value;
}
void TwoWire::flush(void){
rxBufferIndex = 0;
rxBufferLength = 0;
txBufferIndex = 0;
txBufferLength = 0;
int TwoWire::peek(void)
{
int value = -1;
if (rxBufferIndex < rxBufferLength)
{
value = rxBuffer[rxBufferIndex];
}
return value;
}
void TwoWire::flush(void)
{
rxBufferIndex = 0;
rxBufferLength = 0;
txBufferIndex = 0;
txBufferLength = 0;
}
void TwoWire::onReceiveService(uint8_t* inBytes, size_t numBytes)
{
// don't bother if user hasn't registered a callback
if (!user_onReceive) {
return;
}
// // don't bother if rx buffer is in use by a master requestFrom() op
// // i know this drops data, but it allows for slight stupidity
// // meaning, they may not have read all the master requestFrom() data yet
// if(rxBufferIndex < rxBufferLength){
// return;
// }
// copy twi rx buffer into local read buffer
// this enables new reads to happen in parallel
for (uint8_t i = 0; i < numBytes; ++i) {
rxBuffer[i] = inBytes[i];
}
// set rx iterator vars
rxBufferIndex = 0;
rxBufferLength = numBytes;
// alert user program
user_onReceive(numBytes);
// don't bother if user hasn't registered a callback
if (!user_onReceive)
{
return;
}
// // don't bother if rx buffer is in use by a master requestFrom() op
// // i know this drops data, but it allows for slight stupidity
// // meaning, they may not have read all the master requestFrom() data yet
// if(rxBufferIndex < rxBufferLength){
// return;
// }
// copy twi rx buffer into local read buffer
// this enables new reads to happen in parallel
for (uint8_t i = 0; i < numBytes; ++i)
{
rxBuffer[i] = inBytes[i];
}
// set rx iterator vars
rxBufferIndex = 0;
rxBufferLength = numBytes;
// alert user program
user_onReceive(numBytes);
}
void TwoWire::onRequestService(void)
{
// don't bother if user hasn't registered a callback
if (!user_onRequest) {
return;
}
// reset tx buffer iterator vars
// !!! this will kill any pending pre-master sendTo() activity
txBufferIndex = 0;
txBufferLength = 0;
// alert user program
user_onRequest();
// don't bother if user hasn't registered a callback
if (!user_onRequest)
{
return;
}
// reset tx buffer iterator vars
// !!! this will kill any pending pre-master sendTo() activity
txBufferIndex = 0;
txBufferLength = 0;
// alert user program
user_onRequest();
}
void TwoWire::onReceive( void (*function)(int) ) {
// arduino api compatibility fixer:
// really hope size parameter will not exceed 2^31 :)
static_assert(sizeof(int) == sizeof(size_t), "something is wrong in Arduino kingdom");
user_onReceive = reinterpret_cast<void(*)(size_t)>(function);
void TwoWire::onReceive(void (*function)(int))
{
// arduino api compatibility fixer:
// really hope size parameter will not exceed 2^31 :)
static_assert(sizeof(int) == sizeof(size_t), "something is wrong in Arduino kingdom");
user_onReceive = reinterpret_cast<void(*)(size_t)>(function);
}
void TwoWire::onReceive( void (*function)(size_t) ) {
user_onReceive = function;
void TwoWire::onReceive(void (*function)(size_t))
{
user_onReceive = function;
twi_enableSlaveMode();
}
void TwoWire::onRequest( void (*function)(void) ){
user_onRequest = function;
void TwoWire::onRequest(void (*function)(void))
{
user_onRequest = function;
twi_enableSlaveMode();
}
// Preinstantiate Objects //////////////////////////////////////////////////////

View File

@ -1,24 +1,24 @@
/*
TwoWire.h - TWI/I2C library for Arduino & Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
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 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.
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
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
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
@ -33,7 +33,7 @@
class TwoWire : public Stream
{
private:
private:
static uint8_t rxBuffer[];
static uint8_t rxBufferIndex;
static uint8_t rxBufferLength;
@ -48,10 +48,10 @@ class TwoWire : public Stream
static void (*user_onReceive)(size_t);
static void onRequestService(void);
static void onReceiveService(uint8_t*, size_t);
public:
public:
TwoWire();
void begin(int sda, int scl);
void begin(int sda, int scl, uint8_t address);
void begin(int sda, int scl, uint8_t address);
void pins(int sda, int scl) __attribute__((deprecated)); // use begin(sda, scl) in new code
void begin();
void begin(uint8_t);
@ -63,22 +63,22 @@ class TwoWire : public Stream
uint8_t endTransmission(void);
uint8_t endTransmission(uint8_t);
size_t requestFrom(uint8_t address, size_t size, bool sendStop);
uint8_t status();
uint8_t status();
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);
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *, size_t);
virtual int available(void);
virtual int read(void);
virtual int peek(void);
virtual void flush(void);
void onReceive( void (*)(int) ); // arduino api
void onReceive( void (*)(size_t) ); // legacy esp8266 backward compatibility
void onRequest( void (*)(void) );
void onReceive(void (*)(int)); // arduino api
void onReceive(void (*)(size_t)); // legacy esp8266 backward compatibility
void onRequest(void (*)(void));
using Print::write;
};

View File

@ -1,80 +1,160 @@
/*
NTP-TZ-DST
NTP-TZ-DST (v2)
NetWork Time Protocol - Time Zone - Daylight Saving Time
This example shows how to read and set time,
and how to use NTP (set NTP0_OR_LOCAL1 to 0 below)
or an external RTC (set NTP0_OR_LOCAL1 to 1 below)
TZ and DST below have to be manually set
according to your local settings.
This example shows:
- how to read and set time
- how to set timezone per country/city
- how is local time automatically handled per official timezone definitions
- how to change internal sntp start and update delay
- how to use callbacks when time is updated
This example code is in the public domain.
*/
#include <ESP8266WiFi.h>
#include <time.h> // time() ctime()
#include <sys/time.h> // struct timeval
#include <coredecls.h> // settimeofday_cb()
////////////////////////////////////////////////////////
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
#define SSID STASSID
#define SSIDPWD STAPSK
#define TZ 1 // (utc+) TZ in hours
#define DST_MN 60 // use 60mn for summer time in some countries
// initial time (possibly given by an external RTC)
#define RTC_UTC_TEST 1510592825 // 1510592825 = Monday 13 November 2017 17:07:05 UTC
#define NTP0_OR_LOCAL1 1 // 0:use NTP 1:fake external RTC
#define RTC_TEST 1510592825 // 1510592825 = Monday 13 November 2017 17:07:05 UTC
// This database is autogenerated from IANA timezone database
// https://www.iana.org/time-zones
// and can be updated on demand in this repository
#include <TZ.h>
// "TZ_" macros follow DST change across seasons without source code change
// check for your nearest city in TZ.h
// espressif headquarter TZ
//#define MYTZ TZ_Asia_Shanghai
// example for "Not Only Whole Hours" timezones:
// Kolkata/Calcutta is shifted by 30mn
//#define MYTZ TZ_Asia_Kolkata
// example of a timezone with a variable Daylight-Saving-Time:
// demo: watch automatic time adjustment on Summer/Winter change (DST)
#define MYTZ TZ_Europe_London
////////////////////////////////////////////////////////
#define TZ_MN ((TZ)*60)
#define TZ_SEC ((TZ)*3600)
#define DST_SEC ((DST_MN)*60)
#include <ESP8266WiFi.h>
#include <coredecls.h> // settimeofday_cb()
#include <Schedule.h>
#include <PolledTimeout.h>
timeval cbtime; // time set in callback
bool cbtime_set = false;
#include <time.h> // time() ctime()
#include <sys/time.h> // struct timeval
void time_is_set(void) {
gettimeofday(&cbtime, NULL);
cbtime_set = true;
Serial.println("------------------ settimeofday() was called ------------------");
}
void setup() {
Serial.begin(115200);
settimeofday_cb(time_is_set);
#if NTP0_OR_LOCAL1
// local
ESP.eraseConfig();
time_t rtc = RTC_TEST;
timeval tv = { rtc, 0 };
timezone tz = { TZ_MN + DST_MN, 0 };
settimeofday(&tv, &tz);
#else // ntp
configTime(TZ_SEC, DST_SEC, "pool.ntp.org");
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, SSIDPWD);
// don't wait, observe time changing when ntp timestamp is received
#endif // ntp
}
#include <sntp.h> // sntp_servermode_dhcp()
// for testing purpose:
extern "C" int clock_gettime(clockid_t unused, struct timespec *tp);
////////////////////////////////////////////////////////
static timeval tv;
static timespec tp;
static time_t now;
static uint32_t now_ms, now_us;
static esp8266::polledTimeout::periodicMs showTimeNow(60000);
static int time_machine_days = 0; // 0 = now
static bool time_machine_running = false;
// OPTIONAL: change SNTP startup delay
// a weak function is already defined and returns 0 (RFC violation)
// it can be redefined:
//uint32_t sntp_startup_delay_MS_rfc_not_less_than_60000 ()
//{
// //info_sntp_startup_delay_MS_rfc_not_less_than_60000_has_been_called = true;
// return 60000; // 60s (or lwIP's original default: (random() % 5000))
//}
// OPTIONAL: change SNTP update delay
// a weak function is already defined and returns 1 hour
// it can be redefined:
//uint32_t sntp_update_delay_MS_rfc_not_less_than_15000 ()
//{
// //info_sntp_update_delay_MS_rfc_not_less_than_15000_has_been_called = true;
// return 15000; // 15s
//}
void showTime() {
gettimeofday(&tv, nullptr);
clock_gettime(0, &tp);
now = time(nullptr);
now_ms = millis();
now_us = micros();
Serial.println();
printTm("localtime:", localtime(&now));
Serial.println();
printTm("gmtime: ", gmtime(&now));
Serial.println();
// time from boot
Serial.print("clock: ");
Serial.print((uint32_t)tp.tv_sec);
Serial.print("s / ");
Serial.print((uint32_t)tp.tv_nsec);
Serial.println("ns");
// time from boot
Serial.print("millis: ");
Serial.println(now_ms);
Serial.print("micros: ");
Serial.println(now_us);
// EPOCH+tz+dst
Serial.print("gtod: ");
Serial.print((uint32_t)tv.tv_sec);
Serial.print("s / ");
Serial.print((uint32_t)tv.tv_usec);
Serial.println("us");
// EPOCH+tz+dst
Serial.print("time: ");
Serial.println((uint32_t)now);
// timezone and demo in the future
Serial.printf("timezone: %s\n", MYTZ);
// human readable
Serial.print("ctime: ");
Serial.print(ctime(&now));
#if LWIP_VERSION_MAJOR > 1
// LwIP v2 is able to list more details about the currently configured SNTP servers
for (int i = 0; i < SNTP_MAX_SERVERS; i++) {
IPAddress sntp = *sntp_getserver(i);
const char* name = sntp_getservername(i);
if (sntp.isSet()) {
Serial.printf("sntp%d: ", i);
if (name) {
Serial.printf("%s (%s) ", name, sntp.toString().c_str());
} else {
Serial.printf("%s ", sntp.toString().c_str());
}
Serial.printf("IPv6: %s Reachability: %o\n",
sntp.isV6() ? "Yes" : "No",
sntp_getreachability(i));
}
}
#endif
Serial.println();
}
#define PTM(w) \
Serial.print(":" #w "="); \
Serial.print(" " #w "="); \
Serial.print(tm->tm_##w);
void printTm(const char* what, const tm* tm) {
@ -84,61 +164,74 @@ void printTm(const char* what, const tm* tm) {
PTM(hour); PTM(min); PTM(sec);
}
timeval tv;
timespec tp;
time_t now;
uint32_t now_ms, now_us;
void time_is_set_scheduled() {
// everything is allowed in this function
void loop() {
gettimeofday(&tv, nullptr);
clock_gettime(0, &tp);
now = time(nullptr);
now_ms = millis();
now_us = micros();
// localtime / gmtime every second change
static time_t lastv = 0;
if (lastv != tv.tv_sec) {
lastv = tv.tv_sec;
Serial.println();
printTm("localtime", localtime(&now));
Serial.println();
printTm("gmtime ", gmtime(&now));
Serial.println();
Serial.println();
if (time_machine_days == 0) {
time_machine_running = !time_machine_running;
}
// time from boot
Serial.print("clock:");
Serial.print((uint32_t)tp.tv_sec);
Serial.print("/");
Serial.print((uint32_t)tp.tv_nsec);
Serial.print("ns");
// time from boot
Serial.print(" millis:");
Serial.print(now_ms);
Serial.print(" micros:");
Serial.print(now_us);
// EPOCH+tz+dst
Serial.print(" gtod:");
Serial.print((uint32_t)tv.tv_sec);
Serial.print("/");
Serial.print((uint32_t)tv.tv_usec);
Serial.print("us");
// EPOCH+tz+dst
Serial.print(" time:");
Serial.print((uint32_t)now);
// human readable
Serial.print(" ctime:(UTC+");
Serial.print((uint32_t)(TZ * 60 + DST_MN));
Serial.print("mn)");
Serial.print(ctime(&now));
// simple drifting loop
delay(100);
// time machine demo
if (time_machine_running) {
if (time_machine_days == 0)
Serial.printf("---- settimeofday() has been called - possibly from SNTP\n"
" (starting time machine demo to show libc's automatic DST handling)\n\n");
now = time(nullptr);
const tm* tm = localtime(&now);
Serial.printf("future=%3ddays: DST=%s - ",
time_machine_days,
tm->tm_isdst ? "true " : "false");
Serial.print(ctime(&now));
gettimeofday(&tv, nullptr);
constexpr int days = 30;
time_machine_days += days;
if (time_machine_days > 360) {
tv.tv_sec -= (time_machine_days - days) * 60 * 60 * 24;
time_machine_days = 0;
} else {
tv.tv_sec += days * 60 * 60 * 24;
}
settimeofday(&tv, nullptr);
} else {
showTime();
}
}
void setup() {
Serial.begin(115200);
Serial.println("\nStarting...\n");
// setup RTC time
// it will be used until NTP server will send us real current time
time_t rtc = RTC_UTC_TEST;
timeval tv = { rtc, 0 };
timezone tz = { 0, 0 };
settimeofday(&tv, &tz);
// install callback - called when settimeofday is called (by SNTP or us)
// once enabled (by DHCP), SNTP is updated every hour
settimeofday_cb(time_is_set_scheduled);
// NTP servers may be overriden by your DHCP server for a more local one
// (see below)
configTime(MYTZ, "pool.ntp.org");
// OPTIONAL: disable obtaining SNTP servers from DHCP
//sntp_servermode_dhcp(0); // 0: disable obtaining SNTP servers from DHCP (enabled by default)
// start network
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(STASSID, STAPSK);
// don't wait for network, observe time changing
// when NTP timestamp is received
Serial.printf("Time is currently set by a constant:\n");
showTime();
}
void loop() {
if (showTimeNow) {
showTime();
}
}

View File

@ -7,4 +7,4 @@ paragraph=
category=Other
url=
architectures=esp8266
dot_a_linkage=true
dot_a_linkage=false