1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-04-22 21:23:07 +03:00

Merge branch 'master' into wifi_mesh_update_2.2

This commit is contained in:
aerlon 2020-06-05 23:23:57 +02:00 committed by GitHub
commit 5661ec07b1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 1170 additions and 134 deletions

View File

@ -135,3 +135,5 @@ ESP8266 core files are licensed under LGPL.
[SoftwareSerial repo](https://github.com/plerup/espsoftwareserial)
[Serial Monitor Arduino IDE plugin](https://github.com/mytrain/arduino-esp8266-serial-plugin) Original discussion [here](https://github.com/esp8266/Arduino/issues/1360), quick download [there](http://mytrain.fr/cms//images/mytrain/private/ESP8266SM.v3.zip).
[FTP Client/Server Library](https://github.com/dplasa/FTPClientServer)

View File

@ -12,7 +12,6 @@
#include <string.h>
#include "flash.h"
#include "eboot_command.h"
#include "spi_vendors.h"
#include <uzlib.h>
extern unsigned char _gzip_dict;
@ -115,10 +114,12 @@ int uzlib_flash_read_cb(struct uzlib_uncomp *m)
}
unsigned char gzip_dict[32768];
uint8_t buffer2[FLASH_SECTOR_SIZE]; // no room for this on the stack
int copy_raw(const uint32_t src_addr,
const uint32_t dst_addr,
const uint32_t size)
const uint32_t size,
const bool verify)
{
// require regions to be aligned
if ((src_addr & 0xfff) != 0 ||
@ -158,8 +159,10 @@ int copy_raw(const uint32_t src_addr,
gzip = true;
}
while (left > 0) {
if (SPIEraseSector(daddr/buffer_size)) {
return 2;
if (!verify) {
if (SPIEraseSector(daddr/buffer_size)) {
return 2;
}
}
if (!gzip) {
if (SPIRead(saddr, buffer, buffer_size)) {
@ -179,8 +182,17 @@ int copy_raw(const uint32_t src_addr,
buffer[i] = 0xff;
}
}
if (SPIWrite(daddr, buffer, buffer_size)) {
return 4;
if (verify) {
if (SPIRead(daddr, buffer2, buffer_size)) {
return 4;
}
if (memcmp(buffer, buffer2, buffer_size)) {
return 9;
}
} else {
if (SPIWrite(daddr, buffer, buffer_size)) {
return 4;
}
}
saddr += buffer_size;
daddr += buffer_size;
@ -190,29 +202,6 @@ int copy_raw(const uint32_t src_addr,
return 0;
}
//#define XMC_SUPPORT
#ifdef XMC_SUPPORT
// Define a few SPI0 registers we need access to
#define ESP8266_REG(addr) *((volatile uint32_t *)(0x60000000+(addr)))
#define SPI0CMD ESP8266_REG(0x200)
#define SPI0CLK ESP8266_REG(0x218)
#define SPI0C ESP8266_REG(0x208)
#define SPI0W0 ESP8266_REG(0x240)
#define SPICMDRDID (1 << 28)
/* spi_flash_get_id()
Returns the flash chip ID - same as the SDK function.
We need our own version as the SDK isn't available here.
*/
uint32_t __attribute__((noinline)) spi_flash_get_id() {
SPI0W0=0;
SPI0CMD=SPICMDRDID;
while (SPI0CMD) {}
return SPI0W0;
}
#endif // XMC_SUPPORT
int main()
{
int res = 9;
@ -235,47 +224,20 @@ int main()
if (cmd.action == ACTION_COPY_RAW) {
ets_putc('c'); ets_putc('p'); ets_putc(':');
#ifdef XMC_SUPPORT
// save the flash access speed registers
uint32_t spi0clk = SPI0CLK;
uint32_t spi0c = SPI0C;
uint32_t vendor = spi_flash_get_id() & 0x000000ff;
if (vendor == SPI_FLASH_VENDOR_XMC) {
uint32_t flashinfo=0;
if (SPIRead(0, &flashinfo, 4)) {
// failed to read the configured flash speed.
// Do not change anything,
} else {
// select an appropriate flash speed
// Register values are those used by ROM
switch ((flashinfo >> 24) & 0x0f) {
case 0x0: // 40MHz, slow to 20
case 0x1: // 26MHz, slow to 20
SPI0CLK = 0x00003043;
SPI0C = 0x00EAA313;
break;
case 0x2: // 20MHz, no change
break;
case 0xf: // 80MHz, slow to 26
SPI0CLK = 0x00002002;
SPI0C = 0x00EAA202;
break;
default:
break;
}
}
}
#endif // XMC_SUPPORT
ets_wdt_disable();
res = copy_raw(cmd.args[0], cmd.args[1], cmd.args[2]);
res = copy_raw(cmd.args[0], cmd.args[1], cmd.args[2], false);
ets_wdt_enable();
#ifdef XMC_SUPPORT
// restore the saved flash access speed registers
SPI0CLK = spi0clk;
SPI0C = spi0c;
#endif
ets_putc('0'+res); ets_putc('\n');
// Verify the copy
ets_putc('c'); ets_putc('m'); ets_putc('p'); ets_putc(':');
if (res == 0) {
ets_wdt_disable();
res = copy_raw(cmd.args[0], cmd.args[1], cmd.args[2], true);
ets_wdt_enable();
}
ets_putc('0'+res); ets_putc('\n');
if (res == 0) {
cmd.action = ACTION_LOAD_APP;

Binary file not shown.

View File

@ -52,7 +52,7 @@ static SpiOpResult PRECACHE_ATTR
_SPICommand(volatile uint32_t spiIfNum,
uint32_t spic,uint32_t spiu,uint32_t spiu1,uint32_t spiu2,
uint32_t *data,uint32_t writeWords,uint32_t readWords)
{
{
if (spiIfNum>1)
return SPI_RESULT_ERR;
@ -69,8 +69,11 @@ _SPICommand(volatile uint32_t spiIfNum,
volatile SpiFlashChip *fchip=flashchip;
volatile uint32_t spicmdusr=SPICMDUSR;
uint32_t saved_ps=0;
if (!spiIfNum) {
// Only need to precache when using SPI0
// Only need to disable interrupts and precache when using SPI0
saved_ps = xt_rsil(15);
PRECACHE_START();
Wait_SPI_Idlep((SpiFlashChip *)fchip);
}
@ -116,6 +119,9 @@ _SPICommand(volatile uint32_t spiIfNum,
SPIREG(SPI0C) = oldSPI0C;
PRECACHE_END();
if (!spiIfNum) {
xt_wsr_ps(saved_ps);
}
return (timeout>0 ? SPI_RESULT_OK : SPI_RESULT_TIMEOUT);
}

View File

@ -49,6 +49,9 @@ What spiffs does not:
- Presently, it does not detect or handle bad blocks.
- One configuration, one binary. There's no generic spiffs binary that handles all types of configurations.
## NOTICE
0.4.0 is under construction. This is a full rewrite and will change the underlying structure. Hence, it will not be compatible with earlier versions of the filesystem. The API is the same, with minor modifications. Some config flags will be removed (as they are mandatory in 0.4.0) and some features might fall away until 0.4.1. If you have any worries or questions, it can be discussed in issue [#179](https://github.com/pellepl/spiffs/issues/179)
## MORE INFO

View File

@ -163,11 +163,17 @@ static s32_t spiffs_delete_obj_lazy(spiffs *fs, spiffs_obj_id obj_id) {
return SPIFFS_OK;
}
SPIFFS_CHECK_RES(res);
u8_t flags = 0xff & ~SPIFFS_PH_FLAG_IXDELE;
u8_t flags = 0xff;
#if SPIFFS_NO_BLIND_WRITES
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
0, SPIFFS_PAGE_TO_PADDR(fs, objix_hdr_pix) + offsetof(spiffs_page_header, flags),
sizeof(flags), &flags);
SPIFFS_CHECK_RES(res);
#endif
flags &= ~SPIFFS_PH_FLAG_IXDELE;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
0, SPIFFS_PAGE_TO_PADDR(fs, objix_hdr_pix) + offsetof(spiffs_page_header, flags),
sizeof(u8_t),
(u8_t *)&flags);
sizeof(flags), &flags);
return res;
}
@ -425,10 +431,17 @@ static s32_t spiffs_lookup_check_validate(spiffs *fs, spiffs_obj_id lu_obj_id, s
// just finalize
SPIFFS_CHECK_DBG("LU: FIXUP: unfinalized page is referred, finalizing\n");
CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_FIX_LOOKUP, p_hdr->obj_id, p_hdr->span_ix);
u8_t flags = 0xff & ~SPIFFS_PH_FLAG_FINAL;
u8_t flags = 0xff;
#if SPIFFS_NO_BLIND_WRITES
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_READ,
0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix) + offsetof(spiffs_page_header, flags),
sizeof(flags), &flags);
SPIFFS_CHECK_RES(res);
#endif
flags &= ~SPIFFS_PH_FLAG_FINAL;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix) + offsetof(spiffs_page_header, flags),
sizeof(u8_t), (u8_t*)&flags);
sizeof(flags), &flags);
}
}
}

View File

@ -326,6 +326,17 @@ typedef uint8_t u8_t;
#define SPIFFS_IX_MAP 1
#endif
// By default SPIFFS in some cases relies on the property of NOR flash that bits
// cannot be set from 0 to 1 by writing and that controllers will ignore such
// bit changes. This results in fewer reads as SPIFFS can in some cases perform
// blind writes, with all bits set to 1 and only those it needs reset set to 0.
// Most of the chips and controllers allow this behavior, so the default is to
// use this technique. If your controller is one of the rare ones that don't,
// turn this option on and SPIFFS will perform a read-modify-write instead.
#ifndef SPIFFS_NO_BLIND_WRITES
#define SPIFFS_NO_BLIND_WRITES 0
#endif
// Set SPIFFS_TEST_VISUALISATION to non-zero to enable SPIFFS_vis function
// in the api. This function will visualize all filesystem using given printf
// function.
@ -354,11 +365,20 @@ typedef uint8_t u8_t;
#endif
#endif
#ifndef SPIFFS_SECURE_ERASE
#define SPIFFS_SECURE_ERASE 0
#endif
// Types depending on configuration such as the amount of flash bytes
// given to spiffs file system in total (spiffs_file_system_size),
// the logical block size (log_block_size), and the logical page size
// (log_page_size)
//
// Set SPIFFS_TYPES_OVERRIDE if you wish to have your own
// definitions for these types (for example, if you want them
// to be u32_t)
#ifndef SPIFFS_TYPES_OVERRIDE
// Block index type. Make sure the size of this type can hold
// the highest number of all blocks - i.e. spiffs_file_system_size / log_block_size
typedef u16_t spiffs_block_ix;
@ -373,5 +393,6 @@ typedef u16_t spiffs_obj_id;
// hold the largest possible span index on the system -
// i.e. (spiffs_file_system_size / log_page_size) - 1
typedef u16_t spiffs_span_ix;
#endif
#endif /* SPIFFS_CONFIG_H_ */

View File

@ -879,8 +879,6 @@ s32_t spiffs_page_delete(
spiffs *fs,
spiffs_page_ix pix) {
s32_t res;
spiffs_page_header hdr;
hdr.flags = 0xff & ~(SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_USED);
// mark deleted entry in source object lookup
spiffs_obj_id d_obj_id = SPIFFS_OBJ_ID_DELETED;
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_DELE,
@ -893,12 +891,29 @@ s32_t spiffs_page_delete(
fs->stats_p_deleted++;
fs->stats_p_allocated--;
#if SPIFFS_SECURE_ERASE
// Secure erase
unsigned char data[SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_header)];
bzero(data, sizeof(data));
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_DELE,
0,
SPIFFS_PAGE_TO_PADDR(fs, pix) + sizeof(spiffs_page_header), sizeof(data), data);
SPIFFS_CHECK_RES(res);
#endif
// mark deleted in source page
u8_t flags = 0xff;
#if SPIFFS_NO_BLIND_WRITES
res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_READ,
0, SPIFFS_PAGE_TO_PADDR(fs, pix) + offsetof(spiffs_page_header, flags),
sizeof(flags), &flags);
SPIFFS_CHECK_RES(res);
#endif
flags &= ~(SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_USED);
res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_DELE,
0,
SPIFFS_PAGE_TO_PADDR(fs, pix) + offsetof(spiffs_page_header, flags),
sizeof(u8_t),
(u8_t *)&hdr.flags);
sizeof(flags), &flags);
return res;
}
@ -2027,7 +2042,7 @@ s32_t spiffs_object_read(
// remaining data in page
len_to_read = MIN(len_to_read, SPIFFS_DATA_PAGE_SIZE(fs) - (cur_offset % SPIFFS_DATA_PAGE_SIZE(fs)));
// remaining data in file
len_to_read = MIN(len_to_read, fd->size);
len_to_read = MIN(len_to_read, fd->size - cur_offset);
SPIFFS_DBG("read: offset:" _SPIPRIi " rd:" _SPIPRIi " data spix:" _SPIPRIsp " is data_pix:" _SPIPRIpg " addr:" _SPIPRIad "\n", cur_offset, len_to_read, data_spix, data_pix,
(u32_t)(SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + (cur_offset % SPIFFS_DATA_PAGE_SIZE(fs))));
if (len_to_read <= 0) {

View File

@ -147,8 +147,8 @@ extern "C" {
#if defined(__GNUC__) || defined(__clang__)
/* For GCC and clang */
#if defined(__GNUC__) || defined(__clang__) || defined(__TI_COMPILER_VERSION__)
/* For GCC, clang and TI compilers */
#define SPIFFS_PACKED __attribute__((packed))
#elif defined(__ICCARM__) || defined(__CC_ARM)
/* For IAR ARM and Keil MDK-ARM compilers */
@ -266,8 +266,8 @@ extern "C" {
#define SPIFFS_FH_OFFS(fs, fh) ((fh) != 0 ? ((fh) + (fs)->cfg.fh_ix_offset) : 0)
#define SPIFFS_FH_UNOFFS(fs, fh) ((fh) != 0 ? ((fh) - (fs)->cfg.fh_ix_offset) : 0)
#else
#define SPIFFS_FH_OFFS(fs, fh) (fh)
#define SPIFFS_FH_UNOFFS(fs, fh) (fh)
#define SPIFFS_FH_OFFS(fs, fh) ((spiffs_file)(fh))
#define SPIFFS_FH_UNOFFS(fs, fh) ((spiffs_file)(fh))
#endif

View File

@ -175,7 +175,7 @@ void configTime(int timezone_sec, int daylightOffset_sec, const char* server1, c
tzr->d = 0;
tzr->s = 0;
tzr->change = 0;
tzr->offset = _timezone;
tzr->offset = -_timezone;
}
// sntp servers

View File

@ -48,7 +48,8 @@ void ICACHE_FLASH_ATTR print_stats(int force);
int ICACHE_FLASH_ATTR umm_info_safe_printf_P(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
#define UMM_INFO_PRINTF(fmt, ...) umm_info_safe_printf_P(PSTR(fmt), ##__VA_ARGS__)
#define UMM_INFO_PRINTF(fmt, ...) umm_info_safe_printf_P(PSTR4(fmt), ##__VA_ARGS__)
// use PSTR4() instead of PSTR() to ensure 4-bytes alignment in Flash, whatever the default alignment of PSTR_ALIGN
#endif

View File

@ -136,7 +136,7 @@ For reference:
Time-wait PCB state helps TCP not confusing two consecutive connections with the
same (s-ip,s-port,d-ip,d-port) when the first is already closed but still
having duplicate packets lost in internet arriving later during the second.
having duplicate packets lost in internet arriving later during the second.
Artificially clearing them is a workaround to help saving precious heap.
The following lines are compatible with both lwIP versions:
@ -147,7 +147,7 @@ The following lines are compatible with both lwIP versions:
struct tcp_pcb;
extern struct tcp_pcb* tcp_tw_pcbs;
extern "C" void tcp_abort (struct tcp_pcb* pcb);
void tcpCleanup (void) {
while (tcp_tw_pcbs)
tcp_abort(tcp_tw_pcbs);
@ -168,3 +168,15 @@ This script is also used to manage uncommon options that are currently not
available in the IDE menu.
`Read more <a05-board-generator.rst>`__.
My WiFi won't reconnect after deep sleep using ``WAKE_RF_DISABLED``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you implement deep sleep using ``WAKE_RF_DISABLED``, this forces what
appears to be a bare metal disabling of WiFi functionality, which is not
restored using ``WiFi.forceSleepWake()`` or ``WiFi.mode(WIFI_STA)``. If you need
to implement deep sleep with ``WAKE_RF_DISABLED`` and later connect to WiFi, you
will need to implement an additional (short) deep sleep using
``WAKE_RF_DEFAULT``.
Ref. `#3072 <https://github.com/esp8266/Arduino/issues/3072>`__

View File

@ -41,7 +41,7 @@ SPI
SPI library supports the entire Arduino SPI API including transactions, including setting phase (CPHA). Setting the Clock polarity (CPOL) is not supported, yet (SPI\_MODE2 and SPI\_MODE3 not working).
The usual SPI pins are:
The usual SPI pins are:
- ``MOSI`` = GPIO13
- ``MISO`` = GPIO12
@ -73,7 +73,7 @@ ESP-specific APIs
Some ESP-specific APIs related to deep sleep, RTC and flash memories are available in the ``ESP`` object.
``ESP.deepSleep(microseconds, mode)`` will put the chip into deep sleep. ``mode`` is one of ``WAKE_RF_DEFAULT``, ``WAKE_RFCAL``, ``WAKE_NO_RFCAL``, ``WAKE_RF_DISABLED``. (GPIO16 needs to be tied to RST to wake from deepSleep.) The chip can sleep for at most ``ESP.deepSleepMax()`` microseconds.
``ESP.deepSleep(microseconds, mode)`` will put the chip into deep sleep. ``mode`` is one of ``WAKE_RF_DEFAULT``, ``WAKE_RFCAL``, ``WAKE_NO_RFCAL``, ``WAKE_RF_DISABLED``. (GPIO16 needs to be tied to RST to wake from deepSleep.) The chip can sleep for at most ``ESP.deepSleepMax()`` microseconds. If you implement deep sleep with ``WAKE_RF_DISABLED`` and require WiFi functionality on wake up, you will need to implement an additional ``WAKE_RF_DEFAULT`` before WiFi functionality is available.
``ESP.deepSleepInstant(microseconds, mode)`` works similarly to ``ESP.deepSleep`` but sleeps instantly without waiting for WiFi to shutdown.
@ -87,7 +87,7 @@ Some ESP-specific APIs related to deep sleep, RTC and flash memories are availab
``ESP.getHeapFragmentation()`` returns the fragmentation metric (0% is clean, more than ~50% is not harmless)
``ESP.getMaxFreeBlockSize()`` returns the maximum allocatable ram block regarding heap fragmentation
``ESP.getMaxFreeBlockSize()`` returns the largest contiguous free RAM block in the heap, useful for checking heap fragmentation. **NOTE:** Maximum ``malloc()``able block will be smaller due to memory manager overheads.
``ESP.getChipId()`` returns the ESP8266 chip ID as a 32-bit integer.

View File

@ -0,0 +1,332 @@
/*
Graph - A web-based Graph display of ESP8266 data
This file is part of the ESP8266WebServer 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
See readme.md for more information.
*/
////////////////////////////////
// Select the FileSystem by uncommenting one of the lines below
//#define USE_SPIFFS
#define USE_LITTLEFS
//#define USE_SDFS
////////////////////////////////
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#if defined USE_SPIFFS
#include <FS.h>
FS* fileSystem = &SPIFFS;
SPIFFSConfig fileSystemConfig = SPIFFSConfig();
#elif defined USE_LITTLEFS
#include <LittleFS.h>
FS* fileSystem = &LittleFS;
LittleFSConfig fileSystemConfig = LittleFSConfig();
#elif defined USE_SDFS
#include <SDFS.h>
FS* fileSystem = &SDFS;
SDFSConfig fileSystemConfig = SDFSConfig();
// fileSystemConfig.setCSPin(chipSelectPin);
#else
#error Please select a filesystem first by uncommenting one of the "#define USE_xxx" lines at the beginning of the sketch.
#endif
#define DBG_OUTPUT_PORT Serial
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#endif
// Indicate which digital I/Os should be displayed on the chart.
// From GPIO16 to GPIO0, a '1' means the corresponding GPIO will be shown
// e.g. 0b11111000000111111
unsigned int gpioMask;
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "graph";
ESP8266WebServer server(80);
static const char TEXT_PLAIN[] PROGMEM = "text/plain";
static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR";
static const char FILE_NOT_FOUND[] PROGMEM = "FileNotFound";
////////////////////////////////
// Utils to return HTTP codes
void replyOK() {
server.send(200, FPSTR(TEXT_PLAIN), "");
}
void replyOKWithMsg(String msg) {
server.send(200, FPSTR(TEXT_PLAIN), msg);
}
void replyNotFound(String msg) {
server.send(404, FPSTR(TEXT_PLAIN), msg);
}
void replyBadRequest(String msg) {
DBG_OUTPUT_PORT.println(msg);
server.send(400, FPSTR(TEXT_PLAIN), msg + "\r\n");
}
void replyServerError(String msg) {
DBG_OUTPUT_PORT.println(msg);
server.send(500, FPSTR(TEXT_PLAIN), msg + "\r\n");
}
////////////////////////////////
// Request handlers
/*
Read the given file from the filesystem and stream it back to the client
*/
bool handleFileRead(String path) {
DBG_OUTPUT_PORT.println(String("handleFileRead: ") + path);
if (path.endsWith("/")) {
path += "index.htm";
}
String contentType = mime::getContentType(path);
if (!fileSystem->exists(path)) {
// File not found, try gzip version
path = path + ".gz";
}
if (fileSystem->exists(path)) {
File file = fileSystem->open(path, "r");
if (server.streamFile(file, contentType) != file.size()) {
DBG_OUTPUT_PORT.println("Sent less data than expected!");
}
file.close();
return true;
}
return false;
}
/*
The "Not Found" handler catches all URI not explicitely declared in code
First try to find and return the requested file from the filesystem,
and if it fails, return a 404 page with debug information
*/
void handleNotFound() {
String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks
if (handleFileRead(uri)) {
return;
}
// Dump debug data
String message;
message.reserve(100);
message = F("Error: File not found\n\nURI: ");
message += uri;
message += F("\nMethod: ");
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += F("\nArguments: ");
message += server.args();
message += '\n';
for (uint8_t i = 0; i < server.args(); i++) {
message += F(" NAME:");
message += server.argName(i);
message += F("\n VALUE:");
message += server.arg(i);
message += '\n';
}
message += "path=";
message += server.arg("path");
message += '\n';
DBG_OUTPUT_PORT.print(message);
return replyNotFound(message);
}
void setup(void) {
////////////////////////////////
// SERIAL INIT
DBG_OUTPUT_PORT.begin(115200);
DBG_OUTPUT_PORT.setDebugOutput(true);
DBG_OUTPUT_PORT.print('\n');
////////////////////////////////
// FILESYSTEM INIT
fileSystemConfig.setAutoFormat(false);
fileSystem->setConfig(fileSystemConfig);
bool fsOK = fileSystem->begin();
DBG_OUTPUT_PORT.println(fsOK ? F("Filesystem initialized.") : F("Filesystem init failed!"));
////////////////////////////////
// PIN INIT
pinMode(4, INPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
pinMode(15, OUTPUT);
////////////////////////////////
// WI-FI INIT
DBG_OUTPUT_PORT.printf("Connecting to %s\n", ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
DBG_OUTPUT_PORT.print(".");
}
DBG_OUTPUT_PORT.println("");
DBG_OUTPUT_PORT.print(F("Connected! IP address: "));
DBG_OUTPUT_PORT.println(WiFi.localIP());
////////////////////////////////
// MDNS INIT
if (MDNS.begin(host)) {
MDNS.addService("http", "tcp", 80);
DBG_OUTPUT_PORT.print(F("Open http://"));
DBG_OUTPUT_PORT.print(host);
DBG_OUTPUT_PORT.println(F(".local to open the graph page"));
}
////////////////////////////////
// WEB SERVER INIT
//get heap status, analog input value and all GPIO statuses in one json call
server.on("/espData", HTTP_GET, []() {
String json;
json.reserve(88);
json = "{\"time\":";
json += millis();
json += ", \"heap\":";
json += ESP.getFreeHeap();
json += ", \"analog\":";
json += analogRead(A0);
json += ", \"gpioMask\":";
json += gpioMask;
json += ", \"gpioData\":";
json += (uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16));
json += "}";
server.send(200, "text/json", json);
});
// Default handler for all URIs not defined above
// Use it to read files from filesystem
server.onNotFound(handleNotFound);
// Start server
server.begin();
DBG_OUTPUT_PORT.println("HTTP server started");
DBG_OUTPUT_PORT.println("Please pull GPIO4 low (e.g. press button) to switch output mode:");
DBG_OUTPUT_PORT.println(" 0 (OFF): outputs are off and hidden from chart");
DBG_OUTPUT_PORT.println(" 1 (AUTO): outputs are rotated automatically every second");
DBG_OUTPUT_PORT.println(" 2 (MANUAL): outputs can be toggled from the web page");
}
// Return default GPIO mask, that is all I/Os except SD card ones
unsigned int defaultMask() {
unsigned int mask = 0b11111111111111111;
for (auto pin = 0; pin <= 16; pin++) {
if (isFlashInterfacePin(pin)) {
mask &= ~(1 << pin);
}
}
return mask;
}
int rgbMode = 1; // 0=off - 1=auto - 2=manual
int rgbValue = 0;
esp8266::polledTimeout::periodicMs timeToChange(1000);
bool modeChangeRequested = false;
void loop(void) {
server.handleClient();
MDNS.update();
if (digitalRead(4) == 0) {
// button pressed
modeChangeRequested = true;
}
// see if one second has passed since last change, otherwise stop here
if (!timeToChange) {
return;
}
// see if a mode change was requested
if (modeChangeRequested) {
// increment mode (reset after 2)
rgbMode++;
if (rgbMode > 2) {
rgbMode = 0;
}
modeChangeRequested = false;
}
// act according to mode
switch (rgbMode) {
case 0: // off
gpioMask = defaultMask();
gpioMask &= ~(1 << 12); // Hide GPIO 12
gpioMask &= ~(1 << 13); // Hide GPIO 13
gpioMask &= ~(1 << 15); // Hide GPIO 15
// reset outputs
digitalWrite(12, 0);
digitalWrite(13, 0);
digitalWrite(15, 0);
break;
case 1: // auto
gpioMask = defaultMask();
// increment value (reset after 7)
rgbValue++;
if (rgbValue > 7) {
rgbValue = 0;
}
// output new values
digitalWrite(12, rgbValue & 0b001);
digitalWrite(13, rgbValue & 0b010);
digitalWrite(15, rgbValue & 0b100);
break;
case 2: // manual
gpioMask = defaultMask();
// keep outputs unchanged
break;
}
}

View File

@ -0,0 +1,527 @@
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/0.7.7/chartjs-plugin-zoom.js"></script>
<!-- or instead, put those files on the ESP filesystem along with index.htm and use:
<script src="Chart.js"></script>
<script src="hammer.js"></script>
<script src="chartjs-plugin-zoom.js"></script>
-->
<style>
body {
height:100%;
padding:0;
margin:0;
width:100%;
display:flex;
flex-direction:column;
}
#config {
margin:0px 8px;
display: flex;
flex-flow: row;
align-items: center;
justify-content: flex-start;
height: 40px;
}
#periodRange {
width:100%;
}
.left {
float:left;
}
#charts {
flex-grow:1;
}
</style>
</head>
<body >
<div id="config">
<span class="left">Max&nbsp;number&nbsp;of&nbsp;samples:&nbsp;</span>
<input id="maxSamplesField" type="number" min="100" max="10000" value="1000" step="100" size="4" class="left" />
<span class="left">.&nbsp;Sampling&nbsp;period:&nbsp;</span>
<input id="periodField" type="number" min="0" max="10000" value="1000" step="100" size="4" class="left" />
<span class="left">&nbsp;ms&nbsp;</span>
<input id="periodRange" type="range" min="0" max="10000" value="1000" step="100" />
<button id="startPauseButton">Pause</button>
<button id="clearButton" disabled="true">Clear</button>
</div>
<div id="charts">
<div class="chart-container" style="position: relative; height:50%;"><canvas id="digital" style="background-color:#000000"></canvas></div>
<div class="chart-container" style="position: relative; height:25%;"><canvas id="analog"></canvas></div>
<div class="chart-container" style="position: relative; height:25%;"><canvas id="heap" style="background-color:#EEEEEE"></canvas>
</div>
<script>
/////////////////////////////////////
// CREATE DIGITAL CHART
// Remember all GPIO datasets
var allDigitalDatasets = [];
var gpioColors = ['#D2FF71', '#59FFF4', '#DB399C', '#4245FF', '#FFB312', '#BB54E9', '#0BD400', '#42C2FF', '#FFFFFF', '#FF4242'];
var digitalChart = new Chart(document.getElementById('digital'), {
// The type of chart we want to create
type: 'scatter',
// The data for our dataset
data: {
// 17 GPIO datasets will be added by a loop at init time
datasets: []
},
// Configuration options go here
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Digital I/Os'
},
scales: {
xAxes: [{
id:"x-axis",
ticks: {
minRotation:0,
maxRotation:0
}
}],
// 17 GPIO scales will be added by a loop at init time
yAxes: []
},
tooltips: {
intersect: false
},
animation: {
duration: 0
},
hover: {
animationDuration: 0
}
}
});
/////////////////////////////////////
// CREATE ANALOG CHART
var analogChart = new Chart(document.getElementById('analog'), {
// The type of chart we want to create
type: 'scatter',
// The data for our dataset
data: {
datasets: [{
label: 'Analog',
backgroundColor: 'rgb(0,0,0,0)',
borderColor: 'rgb(255, 99, 132)',
data: [],
showLine:true
}]
},
// Configuration options go here
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Analog input'
},
legend: {
display: false
},
scales: {
xAxes: [{
id:"x-axis",
ticks: {
minRotation:0,
maxRotation:0
}
}],
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
tooltips: {
intersect: false
},
animation: {
duration: 0
},
hover: {
animationDuration: 0
},
// Zoom plugin options
plugins: {
zoom: {
pan: {
enabled: true,
mode: 'y',
},
zoom: {
enabled: true,
mode: 'y',
}
}
},
onClick: function() {this.resetZoom()}
}
});
/////////////////////////////////////
// CREATE HEAP CHART
var heapChart = new Chart(document.getElementById('heap'), {
// The type of chart we want to create
type: 'scatter',
// The data for our dataset
data: {
datasets: [{
label: 'Heap',
backgroundColor: 'rgb(99, 99, 255)',
borderColor: 'rgb(99, 99, 255)',
data: [],
showLine:true,
cubicInterpolationMode:'monotone'
}]
},
// Configuration options go here
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Free heap'
},
legend: {
display: false
},
scales: {
xAxes: [{
id:"x-axis",
ticks: {
minRotation:0,
maxRotation:0
}
}],
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
tooltips: {
intersect: false
},
animation: {
duration: 0
},
hover: {
animationDuration: 0
},
// Zoom plugin options
plugins: {
zoom: {
pan: {
enabled: true,
mode: 'y',
},
zoom: {
enabled: true,
mode: 'y',
}
}
},
onClick: function() {this.resetZoom()}
}
});
/////////////////////////////////////
// UTILITY FUNCTIONS
// Crete a blank dataset for the Digital chart
function createDigitalDataset(gpio) {
return {
showLine:true,
steppedLine: true,
backgroundColor: 'rgb(0, 0, 0, 0)',
xAxisID: 'x-axis',
pointRadius: 1,
borderWidth: 1,
data: [],
label: gpio,
yAxisID: 'gpio' + gpio + '-axis'
}
}
// Init structures for digitalChart
function initDigitalChart() {
// Clear auto-generated Y axis
digitalChart.options.scales.yAxes.length = 0;
// Add 17 hidden axes (one per GPIO) to be able to shift (stack) graphs vertically
for (var gpio = 0; gpio <= 16; gpio++) { // 17 GPIOs
// Add a scale
digitalChart.options.scales.yAxes.push(
{
id: 'gpio' + gpio + '-axis',
type: 'linear',
display:false,
ticks: {
min:0,
max:2
}
}
);
// Create a blank dataset for this gpio
allDigitalDatasets.push(createDigitalDataset(gpio));
}
// Only show the first two Y axes (one for each side), with all tick labels showing only 0's and 1's (modulo)
for (var i = 0; i < 2; i++) {
digitalChart.options.scales.yAxes[i].display = true;
digitalChart.options.scales.yAxes[i].ticks.autoSkip = false;
digitalChart.options.scales.yAxes[i].ticks.stepSize = 1;
digitalChart.options.scales.yAxes[i].ticks.callback = function(value, index, values) {return Math.abs(value)%2;};
}
// Show gridLines of first axis
digitalChart.options.scales.yAxes[0].gridLines = {color: "#333333"};
// Move second axis to the right
digitalChart.options.scales.yAxes[1].position = 'right';
}
// Compute a string with min/max/average on the given array of (x, y) points
function computeStats(sampleArray) {
var minY = Number.MAX_SAFE_INTEGER, maxY = 0, avgY = 0;
var prevX = 0;
sampleArray.forEach(function (point, index) {
if (point.y < minY) minY = point.y;
if (point.y > maxY) maxY = point.y;
if (prevX > 0) avgY = avgY + point.y * (point.x - prevX); // avg is weighted: samples with a longer period weight more
prevX = point.x;
});
avgY = avgY / (prevX - sampleArray[0].x);
return "min: " + minY + ", max: " + maxY + ", avg: " + Math.floor(avgY);
}
/////////////////////////////////////
// PERIODIC FETCH OF NEW DATA
var running = true;
var configDiv = document.getElementById("config");
var periodField = document.getElementById("periodField");
var currentGpioMask = 0;
function fetchNewData() {
if (!running) return;
var fetchStartMs = Date.now();
var xmlHttp = new XMLHttpRequest();
xmlHttp.onload = function() {
var processingDurationMs;
if(xmlHttp.status != 200) {
// Server error
configDiv.style.backgroundColor = "red";
console.log("GET ERROR: [" + xmlHttp.status+"] " + xmlHttp.responseText);
processingDurationMs = new Date() - fetchStartMs;
}
else {
configDiv.style.backgroundColor = "white";
// Response is e.g.: {"time":963074, "heap":47160, "analog":60, "gpioMask":16447, "gpioData":16405}
var espData = JSON.parse(xmlHttp.responseText);
var x = espData.time;
var maxSamples = parseInt(document.getElementById("maxSamplesField").value);
// Add point to heap chart
var data = heapChart.data.datasets[0].data;
data.push({x: espData.time, y: espData.heap});
// Limit its length to maxSamples
data.splice(0, data.length - maxSamples);
// Put stats in chart title
heapChart.options.title.text = "Free heap (" + computeStats(data) + ") - use mouse wheel or pinch to zoom";
// Remember smallest X
var minX = data[0].x;
// Add point to analog chart
data = analogChart.data.datasets[0].data;
data.push({x: espData.time, y: espData.analog});
// Limit its length to maxSamples
data.splice(0, data.length - maxSamples);
// Put stats in chart title
analogChart.options.title.text = "Analog input (" + computeStats(data) + ") - use mouse wheel or pinch to zoom";
// Remember smallest X
if (data[0].x < minX) minX = data[0].x;
// If GPIO mask has changed, reconfigure chart
if (espData.gpioMask != currentGpioMask) {
// Remove all datasets from chart
digitalChart.data.datasets.length = 0;
// And re-add the required datasets
var position = 0;
for (var gpio = 0; gpio <= 16; gpio++) { // 17 GPIOs
var gpioBitMask = 1 << gpio;
if (espData.gpioMask & gpioBitMask) {
// This GPIO must be part of the chart
dataset = allDigitalDatasets[gpio];
// give it the next available color
dataset.borderColor = gpioColors[position % gpioColors.length];
// add it to the chart
digitalChart.data.datasets.push(dataset);
// offset graph
digitalChart.options.scales.yAxes[gpio].ticks.min = position * -2;
position++;
}
else {
// Clear data
allDigitalDatasets[gpio].data = [];
}
}
// make sure all graphs have the same scale (max-min)
for (var gpio = 0; gpio <= 16; gpio++) { // 17 GPIOs
var ticks = digitalChart.options.scales.yAxes[gpio].ticks;
ticks.max = ticks.min + position * 2 - 1;
}
// chart must be updated, otherwise adding to previously hidden dataset fail
digitalChart.update();
currentGpioMask = espData.gpioMask
}
// And process each dataset, adding it back to the chart if requested, and adding the received value to it.
var position = 0;
for (var gpio = 0; gpio <= 16; gpio++) { // 17 GPIOs
var gpioBitMask = 1 << gpio;
if (espData.gpioMask & gpioBitMask) {
// This GPIO must be part of the chart
var dataset = digitalChart.data.datasets[position];
// Add received value to dataset
// console.log(espData.gpioData + " & " + gpioBitMask + " => " + (espData.gpioData & gpioBitMask));
data = dataset.data;
var point = {x: espData.time, y: (espData.gpioData & gpioBitMask)?1:0}
data.push(point);
// limit number of samples to maxSamples
data.splice(0, data.length - maxSamples);
// Remember smallest X
if (data[0].x < minX) minX = data[0].x;
position++;
}
}
// Set origin of X axis to minimum X value
if (heapChart.options.scales.xAxes[0].ticks.min === undefined || heapChart.options.scales.xAxes[0].ticks.min < minX) {
heapChart.options.scales.xAxes[0].ticks.min = minX;
analogChart.options.scales.xAxes[0].ticks.min = minX;
digitalChart.options.scales.xAxes[0].ticks.min = minX;
}
heapChart.update();
analogChart.update();
digitalChart.update();
// Check if we can keep up with this fetch rate, or increase interval by 50ms if not.
processingDurationMs = new Date() - fetchStartMs;
periodField.style.backgroundColor = (processingDurationMs > parseInt(periodField.value))?"#FF7777":"#FFFFFF";
}
// Schedule next call with the requested interval minus the time needed to process the previous call
// Note that contrary to setInterval, this technique guarantees that we will never have
// several fetch in parallel in case we can't keep up with the requested interval
var waitingDelayMs = parseInt(periodField.value) - processingDurationMs;
if (running) {
window.setTimeout(fetchNewData, (waitingDelayMs > 0)?waitingDelayMs:0);
}
};
xmlHttp.onerror = function(e) {
// Ajax call error
configDiv.style.backgroundColor = "red";
console.log("ERROR: [" + xmlHttp.status+"] " + xmlHttp.responseText);
// Also schedule next call in case of error
var waitingDelayMs = parseInt(periodField.value) - (new Date() - fetchStartMs);
window.setTimeout(fetchNewData, (waitingDelayMs > 0)?waitingDelayMs:0);
};
xmlHttp.open("GET", "/espData", true);
xmlHttp.send();
}
/////////////////////////////////////
// EVENT HANDLERS
// Keep range slider and text input in sync
document.getElementById('periodRange').addEventListener('input', function (e) {
document.getElementById('periodField').value = e.target.value;
});
document.getElementById('periodField').addEventListener('input', function (e) {
document.getElementById('periodRange').value = e.target.value;
});
// Start/pause button
document.getElementById('startPauseButton').addEventListener('click', function (e) {
running = !running;
if (running) {
document.getElementById('startPauseButton').textContent = "Pause";
document.getElementById('clearButton').disabled = true;
fetchNewData();
}
else {
document.getElementById('startPauseButton').textContent = "Start";
document.getElementById('clearButton').disabled = false;
}
});
// Clear button
document.getElementById('clearButton').addEventListener('click', function (e) {
heapChart.data.datasets[0].data.length = 0;
analogChart.data.datasets[0].data.length = 0;
for (var gpio = 0; gpio <= 16; gpio++) { // 17 GPIOs
allDigitalDatasets[gpio].data = [];
}
heapChart.update();
analogChart.update();
digitalChart.update();
});
/////////////////////////////////////
// GET THE BALL ROLLING
// Configure the digital chart
initDigitalChart();
// Get first sample
fetchNewData();
</script>
</html>

View File

@ -0,0 +1,48 @@
# Graph readme
## What is this sketch about ?
This example consists of a web page that displays misc ESP8266 information, namely values of GPIOs, ADC measurement and free heap
using http requests and a html/javascript frontend.
A similar functionality used to be hidden in previous versions of the FSBrowser example.
## How to use it ?
1. Uncomment one of the `#define USE_xxx` directives in the sketch to select the ESP filesystem to store the index.htm file on
2. Provide the credentials of your WiFi network (search for `STASSID`)
3. Compile and upload the sketch to your ESP8266 device
4. For normal use, copy the contents of the `data` folder to the filesystem. To do so:
- for SDFS, copy that contents (not the data folder itself, just its contents) to the root of a FAT/FAT32-formated SD card connected to the SPI port of the ESP8266
- for SPIFFS or LittleFS, please follow the instructions at https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html#uploading-files-to-file-system
5. Once the data and sketch have been uploaded, access the page by pointing your browser to http://graph.local
## What does it demonstrate ?
1. Use of the ESP8266WebServer library to return files from the ESP filesystem
2. Use of the ESP8266WebServer library to return a dynamic JSON document
3. Querying the state of ESP I/Os as well as free heap
4. Ajax calls to a JSON API of the ESP from a webpage
5. Rendering of "real-time" data in a webpage
## Usage
- the page should start showing samples right away
- the sampling period (interval between requests to the ESP) can be selected. If the system cannot keep up with the rhythm, the interval will get longer (and the period input field will turn red to indicate it). Note that the X-axis is the time since ESP bootup, in milliseconds.
- the maximum number of samples can be selected. Warning: this uses up browser memory and power, so a large number might increase the sampling period.
- sampling can be paused or restarted, and graph can be cleared during pause
- the list of GPIOs to be displayed can be customized from Arduino code by changing the gpioMask value included in the json document
- in that list, some GPIOs can be temporarily hidden by clicking on their labels on top
- analog and heap graphs can be zoomed in using the mouse wheel. A click resets the zoom level
## Options
This sample is "fully compatible" with the FSBrowser sample. In other words, if you copy the `espData` handler over from this sketch to the FSBrowser example sketch, and upload the index.htm page to its filesystem, you will be able to use both the FSBrowser and the graph page at the same time.
## Dependency
The html page requires the [Chart.js](https://www.chartjs.org/) (v2.9.3 at the time of writing) library, which is loaded from a CDN, as well as its [zoom plugin](https://github.com/chartjs/chartjs-plugin-zoom/blob/master/README.md) (v0.7.7) and [hammer.js](http://hammerjs.github.io/) (v2.0.8) for gesture capture.
Consequently, internet access from your web browser is required for this app to work as-is.
If your browser has no web access (e.g. if you are connected to the ESP8266 as an access-point), you can download those three files locally and upload them along with the index.htm page, and uncomment the block at the top of the index.htm page
## Notes
- The code in the loop is just to demonstrate that the app is working by toggling a few I/Os.
However, values have been particularly chosen to be meaningful for the [Witty Cloud](https://gregwareblog.wordpress.com/2016/01/10/esp-witty/) board, rotating colors of the RGB led.
When placed close to a reflecting area, the light sensor (LDR) of the board also shows an analog image of the RGB led power.
The button rotates mode between "RGB rotate", "RGB stop", "RGB off" (and corresponding GPIOs disappearing from the graph), .
- If you use SDFS, if your card's CS pin is not connected to the default pin (4), uncomment the `fileSystemConfig.setCSPin(chipSelectPin);` line and specify the GPIO the CS pin is connected to
- `index.htm` is the default index returned if your URL does not end with a filename (works on subfolders as well)

View File

@ -5,48 +5,97 @@
namespace mime
{
// Table of extension->MIME strings stored in PROGMEM, needs to be global due to GCC section typing rules
const Entry mimeTable[maxType] PROGMEM =
static const char kHtmlSuffix[] PROGMEM = ".html";
static const char kHtmSuffix[] PROGMEM = ".htm";
static const char kTxtSuffix[] PROGMEM = ".txt";
#ifndef MIMETYPE_MINIMAL
static const char kCssSuffix[] PROGMEM = ".css";
static const char kJsSuffix[] PROGMEM = ".js";
static const char kJsonSuffix[] PROGMEM = ".json";
static const char kPngSuffix[] PROGMEM = ".png";
static const char kGifSuffix[] PROGMEM = ".gif";
static const char kJpgSuffix[] PROGMEM = ".jpg";
static const char kJpegSuffix[] PROGMEM = ".jpeg";
static const char kIcoSuffix[] PROGMEM = ".ico";
static const char kSvgSuffix[] PROGMEM = ".svg";
static const char kTtfSuffix[] PROGMEM = ".ttf";
static const char kOtfSuffix[] PROGMEM = ".otf";
static const char kWoffSuffix[] PROGMEM = ".woff";
static const char kWoff2Suffix[] PROGMEM = ".woff2";
static const char kEotSuffix[] PROGMEM = ".eot";
static const char kSfntSuffix[] PROGMEM = ".sfnt";
static const char kXmlSuffix[] PROGMEM = ".xml";
static const char kPdfSuffix[] PROGMEM = ".pdf";
static const char kZipSuffix[] PROGMEM = ".zip";
static const char kAppcacheSuffix[] PROGMEM = ".appcache";
#endif // MIMETYPE_MINIMAL
static const char kGzSuffix[] PROGMEM = ".gz";
static const char kDefaultSuffix[] PROGMEM = "";
static const char kHtml[] PROGMEM = "text/html";
static const char kTxt[] PROGMEM = "text/plain";
#ifndef MIMETYPE_MINIMAL
static const char kCss[] PROGMEM = "text/css";
static const char kJs[] PROGMEM = "application/javascript";
static const char kJson[] PROGMEM = "application/json";
static const char kPng[] PROGMEM = "image/png";
static const char kGif[] PROGMEM = "image/gif";
static const char kJpg[] PROGMEM = "image/jpeg";
static const char kJpeg[] PROGMEM = "image/jpeg";
static const char kIco[] PROGMEM = "image/x-icon";
static const char kSvg[] PROGMEM = "image/svg+xml";
static const char kTtf[] PROGMEM = "application/x-font-ttf";
static const char kOtf[] PROGMEM = "application/x-font-opentype";
static const char kWoff[] PROGMEM = "application/font-woff";
static const char kWoff2[] PROGMEM = "application/font-woff2";
static const char kEot[] PROGMEM = "application/vnd.ms-fontobject";
static const char kSfnt[] PROGMEM = "application/font-sfnt";
static const char kXml[] PROGMEM = "text/xml";
static const char kPdf[] PROGMEM = "application/pdf";
static const char kZip[] PROGMEM = "application/zip";
static const char kAppcache[] PROGMEM = "text/cache-manifest";
#endif // MIMETYPE_MINIMAL
static const char kGz[] PROGMEM = "application/x-gzip";
static const char kDefault[] PROGMEM = "application/octet-stream";
const Entry mimeTable[maxType] PROGMEM =
{
{ ".html", "text/html" },
{ ".htm", "text/html" },
{ ".css", "text/css" },
{ ".txt", "text/plain" },
{ ".js", "application/javascript" },
{ ".json", "application/json" },
{ ".png", "image/png" },
{ ".gif", "image/gif" },
{ ".jpg", "image/jpeg" },
{ ".jpeg", "image/jpeg" },
{ ".ico", "image/x-icon" },
{ ".svg", "image/svg+xml" },
{ ".ttf", "application/x-font-ttf" },
{ ".otf", "application/x-font-opentype" },
{ ".woff", "application/font-woff" },
{ ".woff2", "application/font-woff2" },
{ ".eot", "application/vnd.ms-fontobject" },
{ ".sfnt", "application/font-sfnt" },
{ ".xml", "text/xml" },
{ ".pdf", "application/pdf" },
{ ".zip", "application/zip" },
{ ".gz", "application/x-gzip" },
{ ".appcache", "text/cache-manifest" },
{ "", "application/octet-stream" }
{ kHtmlSuffix, kHtml },
{ kHtmSuffix, kHtml },
{ kTxtSuffix, kTxtSuffix },
#ifndef MIMETYPE_MINIMAL
{ kCssSuffix, kCss },
{ kJsSuffix, kJs },
{ kJsonSuffix, kJson },
{ kPngSuffix, kPng },
{ kGifSuffix, kGif },
{ kJpgSuffix, kJpg },
{ kJpegSuffix, kJpeg },
{ kIcoSuffix, kIco },
{ kSvgSuffix, kSvg },
{ kTtfSuffix, kTtf },
{ kOtfSuffix, kOtf },
{ kWoffSuffix, kWoff },
{ kWoff2Suffix, kWoff2 },
{ kEotSuffix, kEot },
{ kSfntSuffix, kSfnt },
{ kXmlSuffix, kXml },
{ kPdfSuffix, kPdf },
{ kZipSuffix, kZip },
{ kAppcacheSuffix, kAppcache },
#endif // MIMETYPE_MINIMAL
{ kGzSuffix, kGz },
{ kDefaultSuffix, kDefault }
};
String getContentType(const String& path) {
char buff[sizeof(mimeTable[0].mimeType)];
// Check all entries but last one for match, return if found
for (size_t i=0; i < sizeof(mimeTable)/sizeof(mimeTable[0])-1; i++) {
strcpy_P(buff, mimeTable[i].endsWith);
if (path.endsWith(buff)) {
strcpy_P(buff, mimeTable[i].mimeType);
return String(buff);
for (size_t i = 0; i < maxType; i++) {
if (path.endsWith(FPSTR(mimeTable[i].endsWith))) {
return String(FPSTR(mimeTable[i].mimeType));
}
}
// Fall-through and just return default type
strcpy_P(buff, mimeTable[sizeof(mimeTable)/sizeof(mimeTable[0])-1].mimeType);
return String(buff);
return String(FPSTR(kDefault));
}
}

View File

@ -10,8 +10,9 @@ enum type
{
html,
htm,
css,
txt,
#ifndef MIMETYPE_MINIMAL // allow to compile with only the strict minimum of mime-types
css,
js,
json,
png,
@ -29,16 +30,17 @@ enum type
xml,
pdf,
zip,
gz,
appcache,
#endif // MIMETYPE_MINIMAL
gz,
none,
maxType
};
struct Entry
{
const char endsWith[16];
const char mimeType[32];
const char * endsWith;
const char * mimeType;
};

View File

@ -377,11 +377,16 @@ public:
if (mode == SeekEnd) {
offset = -offset; // TODO - this seems like its plain wrong vs. POSIX
}
auto lastPos = position();
int rc = lfs_file_seek(_fs->getFS(), _getFD(), offset, (int)mode); // NB. SeekMode === LFS_SEEK_TYPES
if (rc < 0) {
DEBUGV("lfs_file_seek rc=%d\n", rc);
return false;
}
if (position() > size()) {
seek(lastPos, SeekSet); // Pretend the seek() never happened
return false;
}
return true;
}

View File

@ -174,6 +174,30 @@ TEST_CASE(TESTPRE "open(w+) truncates file", TESTPAT)
REQUIRE( t == "");
}
TEST_CASE(TESTPRE "peek() returns -1 on EOF", TESTPAT)
{
FS_MOCK_DECLARE(64, 8, 512, "");
REQUIRE(FSTYPE.begin());
createFile("/file1", "some text");
auto f = FSTYPE.open("/file1", "r+");
REQUIRE(f.seek(8));
REQUIRE(f.peek() == 't');
REQUIRE(f.read() == 't');
REQUIRE(f.peek() == -1);
REQUIRE(f.read() == -1);
f.close();
}
TEST_CASE(TESTPRE "seek() pase EOF returns error (#7323)", TESTPAT)
{
FS_MOCK_DECLARE(64, 8, 512, "");
REQUIRE(FSTYPE.begin());
createFile("/file1", "some text");
auto f = FSTYPE.open("/file1", "r+");
REQUIRE_FALSE(f.seek(10));
f.close();
}
#ifdef FS_HAS_DIRS
#if FSTYPE != SDFS

View File

@ -31,12 +31,26 @@ extern "C" {
#define PGM_VOID_P const void *
#endif
// PSTR() macro modified to start on a 32-bit boundary. This adds on average
// 1.5 bytes/string, but in return memcpy_P and strcpy_P will work 4~8x faster
#ifndef PSTR
#ifndef PSTR_ALIGN
// PSTR() macro starts by default on a 32-bit boundary. This adds on average
// 1.5 bytes/string, but in return memcpy_P and strcpy_P will work 4~8x faster
// Allow users to override the alignment with PSTR_ALIGN
#define PSTR_ALIGN 4
#endif
#ifndef PSTRN
// Multi-alignment variant of PSTR, n controls the alignment and should typically be 1 or 4
// Adapted from AVR-specific code at https://forum.arduino.cc/index.php?topic=194603.0
// Uses C attribute section instead of ASM block to allow for C language string concatenation ("x" "y" === "xy")
#define PSTR(s) (__extension__({static const char __c[] __attribute__((__aligned__(4))) __attribute__((section( "\".irom0.pstr." __FILE__ "." __STRINGIZE(__LINE__) "." __STRINGIZE(__COUNTER__) "\", \"aSM\", @progbits, 1 #"))) = (s); &__c[0];}))
#define PSTRN(s,n) (__extension__({static const char __c[] __attribute__((__aligned__(n))) __attribute__((section( "\".irom0.pstr." __FILE__ "." __STRINGIZE(__LINE__) "." __STRINGIZE(__COUNTER__) "\", \"aSM\", @progbits, 1 #"))) = (s); &__c[0];}))
#endif
#ifndef PSTR
// PSTR() uses the default alignment defined by PSTR_ALIGN
#define PSTR(s) PSTRN(s,PSTR_ALIGN)
#endif
#ifndef PSTR4
// PSTR4() enforces 4-bytes alignment whatever the value of PSTR_ALIGN
// as required by functions like ets_strlen() or ets_memcpy()
#define PSTR4(s) PSTRN(s,4)
#endif
// Flash memory must be read using 32 bit aligned addresses else a processor