Synced master branch with upstream from jeelabs

Signed-off-by: beegee-tokyo <bernd@giesecke.tk>
pull/188/head
beegee-tokyo 8 years ago
parent 87ea456883
commit 0654c1d038
  1. 1
      .gitignore
  2. 31
      .travis.yml
  3. 32
      Dockerfile
  4. 52
      Makefile
  5. 44
      WEB-SERVER.md
  6. 6
      cmd/cmd.h
  7. 2
      cmd/handlers.c
  8. 114
      createEspFs.pl
  9. 11
      esp-link/cgi.c
  10. 2
      esp-link/cgiservices.c
  11. 158
      esp-link/cgiwebserversetup.c
  12. 8
      esp-link/cgiwebserversetup.h
  13. 51
      esp-link/config.c
  14. 6
      esp-link/config.h
  15. 34
      esp-link/main.c
  16. 202
      espfs/espfs.c
  17. 27
      espfs/espfs.h
  18. 1
      espfs/mkespfsimage/Makefile
  19. 26
      html/console.html
  20. 43
      html/flash.html
  21. 33
      html/flash.js
  22. 6
      html/home.html
  23. 4
      html/ui.js
  24. 242
      html/userpage.js
  25. 29
      html/web-server.html
  26. 50
      httpd/httpd.c
  27. 3
      httpd/httpd.h
  28. 17
      httpd/httpdespfs.c
  29. 301
      httpd/multipart.c
  30. 32
      httpd/multipart.h
  31. 1
      rest/rest.c
  32. 32
      serial/console.c
  33. 1
      serial/console.h
  34. 15
      serial/serbridge.c
  35. 2
      serial/serbridge.h
  36. 2
      serial/slip.c
  37. 28
      serial/uart.c
  38. 3
      serial/uart.h
  39. 1
      syslog/syslog.h
  40. 454
      web-server/web-server.c
  41. 37
      web-server/web-server.h

1
.gitignore vendored

@ -15,6 +15,5 @@ esp-link.opensdf
esp-link.sdf esp-link.sdf
espfs/mkespfsimage/mman-win32/libmman.a espfs/mkespfsimage/mman-win32/libmman.a
.localhistory/ .localhistory/
#tools/
local.conf local.conf
*.tgz *.tgz

@ -0,0 +1,31 @@
# Travis-CI file for Esp-Link
language: c
before_install:
- curl -Ls http://s3.voneicken.com/xtensa-lx106-elf-20160330.tgx | tar Jxf -
- curl -Ls http://s3.voneicken.com/esp_iot_sdk_v2.0.0.p1.tgx | tar -C .. -Jxf -
after_script:
# upload to an S3 bucket, requires S3_BUCKET, AWS_ACCESS_KEY_ID and AWS_SECRET_KEY to be set
# in environment using travis' repository settings
- "if [[ -n \"$S3_BUCKET\" && -n \"$AWS_ACCESS_KEY_ID\" ]]; then
echo Uploading *.tgz to $S3_BUCKET;
curl -Ls https://github.com/rlmcpherson/s3gof3r/releases/download/v0.5.0/gof3r_0.5.0_linux_amd64.tar.gz | tar zxf - gof3r_0.5.0_linux_amd64/gof3r;
mv gof3r*/gof3r .;
ls *.tgz | xargs -I {} ./gof3r put -b $S3_BUCKET -k esp-link/{} --acl public-read -p {};
ls *.tgz | xargs -I {} echo \"URL: http://$S3_BUCKET/esp-link/{}\";
fi"
compiler: gcc
env:
script:
- export XTENSA_TOOLS_ROOT=$PWD/xtensa-lx106-elf/bin/
- export BRANCH=$TRAVIS_BRANCH
#- export SDK_BASE=$PWD/esp_iot_sdk_v2.0.0.p1
- make release
notifications:
email: false

@ -0,0 +1,32 @@
# Dockerfile for github.com/jeelabs/esp-link
#
# This dockerfile is intended to be used to compile esp-link as it's checked out on
# your desktop/laptop. You can git clone esp-link, and then compile it using
# a commandline of `docker run -v $PWD:/esp-link jeelabs/esp-link`. The -v mounts
# your esp-link source directory onto /esp-link in the container and the default command is
# to run make.
# If you would like to create your own container image, use `docker build -t esp-link .`
FROM ubuntu:16.04
RUN apt-get update \
&& apt-get install -y software-properties-common build-essential python curl git
RUN curl -Ls http://s3.voneicken.com/xtensa-lx106-elf-20160330.tgx | tar Jxf -
RUN curl -Ls http://s3.voneicken.com/esp_iot_sdk_v2.0.0.p1.tgx | tar -Jxf -
RUN apt-get install zlib1g-dev openjdk-8-jre-headless
ENV XTENSA_TOOLS_ROOT /xtensa-lx106-elf/bin/
# This could be used to create an image with esp-link in it from github:
#RUN git clone https://github.com/jeelabs/esp-link
# This could be used to create an image with esp-link in it from the local dir:
#COPY . esp-link/
# Expect the esp-link source/home dir to be mounted here:
VOLUME /esp-link
WORKDIR /esp-link
# Default command is to run a build, can be overridden on the docker commandline:
CMD make

@ -4,7 +4,6 @@
# Makefile heavily adapted to esp-link and wireless flashing by Thorsten von Eicken # Makefile heavily adapted to esp-link and wireless flashing by Thorsten von Eicken
# Lots of work, in particular to support windows, by brunnels # Lots of work, in particular to support windows, by brunnels
# Original from esphttpd and others... # Original from esphttpd and others...
# VERBOSE=1
# #
# Start by setting the directories for the toolchain a few lines down # Start by setting the directories for the toolchain a few lines down
# the default target will build the firmware images # the default target will build the firmware images
@ -52,36 +51,37 @@ ESP_HOSTNAME ?= esp-link
# Base directory for the compiler. Needs a / at the end. # Base directory for the compiler. Needs a / at the end.
# Typically you'll install https://github.com/pfalcon/esp-open-sdk # Typically you'll install https://github.com/pfalcon/esp-open-sdk
# IMPORTANT: use esp-open-sdk `make STANDALONE=n`: the SDK bundled with esp-open-sdk will *not* work!
XTENSA_TOOLS_ROOT ?= $(abspath ../esp-open-sdk/xtensa-lx106-elf/bin)/ XTENSA_TOOLS_ROOT ?= $(abspath ../esp-open-sdk/xtensa-lx106-elf/bin)/
# Firmware version # Firmware version
# WARNING: if you change this expect to make code adjustments elsewhere, don't expect # WARNING: if you change this expect to make code adjustments elsewhere, don't expect
# that esp-link will magically work with a different version of the SDK!!! # that esp-link will magically work with a different version of the SDK!!!
SDK_VERS ?= esp_iot_sdk_v1.5.4 SDK_VERS ?= esp_iot_sdk_v2.0.0.p1
#SDK_VERS ?= esp_iot_sdk_v2.0.0
# Try to find the firmware manually extracted, e.g. after downloading from Espressif's BBS, # Try to find the firmware manually extracted, e.g. after downloading from Espressif's BBS,
# http://bbs.espressif.com/viewforum.php?f=46 # http://bbs.espressif.com/viewforum.php?f=46
SDK_BASE ?= $(wildcard ../$(SDK_VERS)) SDK_BASE ?= $(wildcard ../$(SDK_VERS))
# If the firmware isn't there, see whether it got downloaded as part of esp-open-sdk # If the firmware isn't there, see whether it got downloaded as part of esp-open-sdk
ifeq ($(SDK_BASE),) # This used to work at some point, but is not supported, uncomment if you feel lucky ;-)
SDK_BASE := $(wildcard $(XTENSA_TOOLS_ROOT)/../../$(SDK_VERS)) #ifeq ($(SDK_BASE),)
endif #SDK_BASE := $(wildcard $(XTENSA_TOOLS_ROOT)/../../$(SDK_VERS))
#endif
# Clean up SDK path # Clean up SDK path
SDK_BASE := $(abspath $(SDK_BASE)) SDK_BASE := $(abspath $(SDK_BASE))
$(warning Using SDK from $(SDK_BASE)) $(warning Using SDK from $(SDK_BASE))
# Path to bootloader file # Path to bootloader file
BOOTFILE ?= $(SDK_BASE/bin/boot_v1.5.bin) BOOTFILE ?= $(SDK_BASE/bin/boot_v1.6.bin)
# Esptool.py path and port, only used for 1-time serial flashing # Esptool.py path and port, only used for 1-time serial flashing
# Typically you'll use https://github.com/themadinventor/esptool # Typically you'll use https://github.com/themadinventor/esptool
# Windows users use the com port i.e: ESPPORT ?= com3 # Windows users use the com port i.e: ESPPORT ?= com3
ESPTOOL ?= $(abspath ../esp-open-sdk/esptool/esptool.py) ESPTOOL ?= $(abspath ../esp-open-sdk/esptool/esptool.py)
ESPPORT ?= /dev/ttyUSB0 ESPPORT ?= /dev/ttyUSB0
ESPBAUD ?= 460800 ESPBAUD ?= 230400
# --------------- chipset configuration --------------- # --------------- chipset configuration ---------------
@ -101,8 +101,8 @@ LED_SERIAL_PIN ?= 14
# --------------- esp-link modules config options --------------- # --------------- esp-link modules config options ---------------
# Optional Modules mqtt # Optional Modules mqtt rest socket webserver syslog
MODULES ?= mqtt rest socket syslog MODULES ?= mqtt rest socket webserver syslog
# --------------- esphttpd config options --------------- # --------------- esphttpd config options ---------------
@ -118,8 +118,6 @@ MODULES ?= mqtt rest socket syslog
# #
# Adding JPG or PNG files (and any other compressed formats) is not recommended, because GZIP # Adding JPG or PNG files (and any other compressed formats) is not recommended, because GZIP
# compression does not work effectively on compressed files. # compression does not work effectively on compressed files.
#Static gzipping is disabled by default.
GZIP_COMPRESSION ?= yes GZIP_COMPRESSION ?= yes
# If COMPRESS_W_HTMLCOMPRESSOR is set to "yes" then the static css and js files will be compressed with # If COMPRESS_W_HTMLCOMPRESSOR is set to "yes" then the static css and js files will be compressed with
@ -217,14 +215,18 @@ ifneq (,$(findstring rest,$(MODULES)))
CFLAGS += -DREST CFLAGS += -DREST
endif endif
ifneq (,$(findstring socket,$(MODULES)))
CFLAGS += -DSOCKET
endif
ifneq (,$(findstring syslog,$(MODULES))) ifneq (,$(findstring syslog,$(MODULES)))
CFLAGS += -DSYSLOG CFLAGS += -DSYSLOG
endif endif
ifneq (,$(findstring web-server,$(MODULES)))
CFLAGS += -DWEBSERVER
endif
ifneq (,$(findstring socket,$(MODULES)))
CFLAGS += -DSOCKET
endif
# which modules (subdirectories) of the project to include in compiling # which modules (subdirectories) of the project to include in compiling
LIBRARIES_DIR = libraries LIBRARIES_DIR = libraries
MODULES += espfs httpd user serial cmd esp-link MODULES += espfs httpd user serial cmd esp-link
@ -263,7 +265,6 @@ LD := $(XTENSA_TOOLS_ROOT)xtensa-lx106-elf-gcc
OBJCP := $(XTENSA_TOOLS_ROOT)xtensa-lx106-elf-objcopy OBJCP := $(XTENSA_TOOLS_ROOT)xtensa-lx106-elf-objcopy
OBJDP := $(XTENSA_TOOLS_ROOT)xtensa-lx106-elf-objdump OBJDP := $(XTENSA_TOOLS_ROOT)xtensa-lx106-elf-objdump
#### ####
SRC_DIR := $(MODULES) SRC_DIR := $(MODULES)
BUILD_DIR := $(addprefix $(BUILD_BASE)/,$(MODULES)) BUILD_DIR := $(addprefix $(BUILD_BASE)/,$(MODULES))
@ -371,7 +372,7 @@ $(FW_BASE)/user1.bin: $(USER1_OUT) $(FW_BASE)
$(Q) $(OBJCP) --only-section .rodata -O binary $(USER1_OUT) eagle.app.v6.rodata.bin $(Q) $(OBJCP) --only-section .rodata -O binary $(USER1_OUT) eagle.app.v6.rodata.bin
$(Q) $(OBJCP) --only-section .irom0.text -O binary $(USER1_OUT) eagle.app.v6.irom0text.bin $(Q) $(OBJCP) --only-section .irom0.text -O binary $(USER1_OUT) eagle.app.v6.irom0text.bin
ls -ls eagle*bin ls -ls eagle*bin
$(Q) COMPILE=gcc PATH=$(XTENSA_TOOLS_ROOT):$(PATH) python $(APPGEN_TOOL) $(USER1_OUT) 2 $(ESP_FLASH_MODE) $(ESP_FLASH_FREQ_DIV) $(ESP_SPI_SIZE) 0 $(Q) COMPILE=gcc PATH=$(XTENSA_TOOLS_ROOT):$(PATH) python $(APPGEN_TOOL) $(USER1_OUT) 2 $(ESP_FLASH_MODE) $(ESP_FLASH_FREQ_DIV) $(ESP_SPI_SIZE) 0 >/dev/null
$(Q) rm -f eagle.app.v6.*.bin $(Q) rm -f eagle.app.v6.*.bin
$(Q) mv eagle.app.flash.bin $@ $(Q) mv eagle.app.flash.bin $@
@echo "** user1.bin uses $$(stat -c '%s' $@) bytes of" $(ESP_FLASH_MAX) "available" @echo "** user1.bin uses $$(stat -c '%s' $@) bytes of" $(ESP_FLASH_MAX) "available"
@ -382,7 +383,7 @@ $(FW_BASE)/user2.bin: $(USER2_OUT) $(FW_BASE)
$(Q) $(OBJCP) --only-section .data -O binary $(USER2_OUT) eagle.app.v6.data.bin $(Q) $(OBJCP) --only-section .data -O binary $(USER2_OUT) eagle.app.v6.data.bin
$(Q) $(OBJCP) --only-section .rodata -O binary $(USER2_OUT) eagle.app.v6.rodata.bin $(Q) $(OBJCP) --only-section .rodata -O binary $(USER2_OUT) eagle.app.v6.rodata.bin
$(Q) $(OBJCP) --only-section .irom0.text -O binary $(USER2_OUT) eagle.app.v6.irom0text.bin $(Q) $(OBJCP) --only-section .irom0.text -O binary $(USER2_OUT) eagle.app.v6.irom0text.bin
$(Q) COMPILE=gcc PATH=$(XTENSA_TOOLS_ROOT):$(PATH) python $(APPGEN_TOOL) $(USER2_OUT) 2 $(ESP_FLASH_MODE) $(ESP_FLASH_FREQ_DIV) $(ESP_SPI_SIZE) 0 $(Q) COMPILE=gcc PATH=$(XTENSA_TOOLS_ROOT):$(PATH) python $(APPGEN_TOOL) $(USER2_OUT) 2 $(ESP_FLASH_MODE) $(ESP_FLASH_FREQ_DIV) $(ESP_SPI_SIZE) 1 >/dev/null
$(Q) rm -f eagle.app.v6.*.bin $(Q) rm -f eagle.app.v6.*.bin
$(Q) mv eagle.app.flash.bin $@ $(Q) mv eagle.app.flash.bin $@
$(Q) if [ $$(stat -c '%s' $@) -gt $$(( $(ESP_FLASH_MAX) )) ]; then echo "$@ too big!"; false; fi $(Q) if [ $$(stat -c '%s' $@) -gt $$(( $(ESP_FLASH_MAX) )) ]; then echo "$@ too big!"; false; fi
@ -431,7 +432,7 @@ $(BUILD_BASE)/espfs_img.o: html/ html/wifi/ espfs/mkespfsimage/mkespfsimage
$(Q) cp -r html/wifi/*.png html_compressed/wifi; $(Q) cp -r html/wifi/*.png html_compressed/wifi;
$(Q) cp -r html/wifi/*.js html_compressed/wifi; $(Q) cp -r html/wifi/*.js html_compressed/wifi;
ifeq ("$(COMPRESS_W_HTMLCOMPRESSOR)","yes") ifeq ("$(COMPRESS_W_HTMLCOMPRESSOR)","yes")
$(Q) echo "Compression assets with htmlcompressor. This may take a while..." $(Q) echo "Compressing assets with htmlcompressor. This may take a while..."
$(Q) java -jar tools/$(HTML_COMPRESSOR) \ $(Q) java -jar tools/$(HTML_COMPRESSOR) \
-t html --remove-surrounding-spaces max --remove-quotes --remove-intertag-spaces \ -t html --remove-surrounding-spaces max --remove-quotes --remove-intertag-spaces \
-o $(abspath ./html_compressed)/ \ -o $(abspath ./html_compressed)/ \
@ -441,7 +442,7 @@ ifeq ("$(COMPRESS_W_HTMLCOMPRESSOR)","yes")
-t html --remove-surrounding-spaces max --remove-quotes --remove-intertag-spaces \ -t html --remove-surrounding-spaces max --remove-quotes --remove-intertag-spaces \
-o $(abspath ./html_compressed)/wifi/ \ -o $(abspath ./html_compressed)/wifi/ \
$(WIFI_PATH)*.html $(WIFI_PATH)*.html
$(Q) echo "Compression assets with yui-compressor. This may take a while..." $(Q) echo "Compressing assets with yui-compressor. This may take a while..."
$(Q) for file in `find html_compressed -type f -name "*.js"`; do \ $(Q) for file in `find html_compressed -type f -name "*.js"`; do \
java -jar tools/$(YUI_COMPRESSOR) $$file --line-break 0 -o $$file; \ java -jar tools/$(YUI_COMPRESSOR) $$file --line-break 0 -o $$file; \
done done
@ -486,11 +487,14 @@ release: all
$(Q) egrep -a 'esp-link [a-z0-9.]+ - 201' $(FW_BASE)/user1.bin | cut -b 1-80 $(Q) egrep -a 'esp-link [a-z0-9.]+ - 201' $(FW_BASE)/user1.bin | cut -b 1-80
$(Q) egrep -a 'esp-link [a-z0-9.]+ - 201' $(FW_BASE)/user2.bin | cut -b 1-80 $(Q) egrep -a 'esp-link [a-z0-9.]+ - 201' $(FW_BASE)/user2.bin | cut -b 1-80
$(Q) cp $(FW_BASE)/user1.bin $(FW_BASE)/user2.bin $(SDK_BASE)/bin/blank.bin \ $(Q) cp $(FW_BASE)/user1.bin $(FW_BASE)/user2.bin $(SDK_BASE)/bin/blank.bin \
"$(SDK_BASE)/bin/boot_v1.5.bin" wiflash avrflash release/esp-link-$(BRANCH) "$(SDK_BASE)/bin/boot_v1.6.bin" "$(SDK_BASE)/bin/esp_init_data_default.bin" \
$(Q) tar zcf esp-link-$(BRANCH).tgz -C release esp-link-$(BRANCH) wiflash avrflash release/esp-link-$(BRANCH)
$(Q) echo "Release file: esp-link-$(BRANCH).tgz" $(Q) tar zcf esp-link-$(BRANCH)-$(SHA).tgz -C release esp-link-$(BRANCH)
$(Q) echo "Release file: esp-link-$(BRANCH)-$(SHA).tgz"
$(Q) rm -rf release $(Q) rm -rf release
docker:
$(Q) docker build -t jeelabs/esp-link .
clean: clean:
$(Q) rm -f $(APP_AR) $(Q) rm -f $(APP_AR)
$(Q) rm -f $(TARGET_OUT) $(Q) rm -f $(TARGET_OUT)

@ -0,0 +1,44 @@
ESP-LINK web-server tutorial
============================
LED flashing sample
--------------------
Circuit:
- 1: connect a Nodemcu (ESP8266) board and an Arduino Nano / UNO:
(RX - levelshifter - TX, TX - levelshifter - RX)
- 2: optionally connect RESET-s with a level shifter
Installation steps:
- 1: install the latest Arduino on the PC
- 2: install EspLink library from arduino/libraries path
- 3: open EspLinkWebSimpleLedControl sample from Arduino
- 4: upload the code onto an Arduino Nano/Uno
- 5: install esp-link
- 6: jump to the Web Server page on esp-link UI
- 7: upload SimpleLED.html ( arduino/libraries/EspLink/examples/EspLinkWebSimpleLedControl/SimpleLED.html )
- 8: jump to SimpleLED page on esp-link UI
- 9: turn on/off the LED
Complex application sample
--------------------------
Circuit:
- 1: connect a Nodemcu (ESP8266) board and an Arduino Nano / UNO:
(RX - levelshifter - TX, TX - levelshifter - RX)
- 2: optionally connect RESET-s with a level shifter
- 3: add a trimmer to A0 for Voltage measurement
Installation steps:
- 1: open EspLinkWebApp sample from Arduino
- 2: upload the code onto an Arduino Nano/Uno
- 3: jump to the Web Server page on esp-link UI
- 4: upload web-page.espfs.img ( arduino/libraries/EspLink/examples/EspLinkWebApp/web-page.espfs.img )
- 5: jump to LED/User/Voltage pages
- 6: try out different settings

@ -49,8 +49,12 @@ typedef enum {
CMD_REST_REQUEST, // do REST request CMD_REST_REQUEST, // do REST request
CMD_REST_SETHEADER, // define header CMD_REST_SETHEADER, // define header
CMD_SOCKET_SETUP = 30, // set-up callbacks CMD_WEB_DATA = 30, // MCU pushes data using this command
CMD_WEB_REQ_CB, // esp-link WEB callback
CMD_SOCKET_SETUP = 40, // set-up callbacks
CMD_SOCKET_SEND, // send data over UDP socket CMD_SOCKET_SEND, // send data over UDP socket
} CmdName; } CmdName;
typedef void (*cmdfunc_t)(CmdPacket *cmd); typedef void (*cmdfunc_t)(CmdPacket *cmd);

@ -12,6 +12,7 @@
#ifdef REST #ifdef REST
#include <rest.h> #include <rest.h>
#endif #endif
#include <web-server.h>
#ifdef SOCKET #ifdef SOCKET
#include <socket.h> #include <socket.h>
#endif #endif
@ -50,6 +51,7 @@ const CmdList commands[] = {
{CMD_REST_REQUEST, "REST_REQ", REST_Request}, {CMD_REST_REQUEST, "REST_REQ", REST_Request},
{CMD_REST_SETHEADER, "REST_SETHDR", REST_SetHeader}, {CMD_REST_SETHEADER, "REST_SETHDR", REST_SetHeader},
#endif #endif
{CMD_WEB_DATA, "WEB_DATA", WEB_Data},
#ifdef SOCKET #ifdef SOCKET
{CMD_SOCKET_SETUP, "SOCKET_SETUP", SOCKET_Setup}, {CMD_SOCKET_SETUP, "SOCKET_SETUP", SOCKET_Setup},
{CMD_SOCKET_SEND, "SOCKET_SEND", SOCKET_Send}, {CMD_SOCKET_SEND, "SOCKET_SEND", SOCKET_Send},

@ -0,0 +1,114 @@
#!/usr/bin/perl
use strict;
use Data::Dumper;
my $dir = shift @ARGV;
my $out = shift @ARGV;
my $espfs = '';
my @structured = read_dir_structure($dir, "");
for my $file (@structured)
{
my $flags = 0;
my $name = $file;
my $compression = 0;
if( $name =~ /\.gz$/ )
{
$flags |= 2;
$name =~ s/\.gz$//;
}
my $head = '<!doctype html><html><head><title>esp-link</title><link rel=stylesheet href="/pure.css"><link rel=stylesheet href="/style.css"><meta name=viewport content="width=device-width, initial-scale=1"><script src="/ui.js"></script><script src="/userpage.js"></script></head><body><div id=layout>';
open IF, "<", "$dir/$file" or die "Can't read file: $!";
my @fc = <IF>;
close(IF);
my $cnt = join("", @fc);
if( $name =~ /\.html$/ )
{
if( ! ( $flags & 2 ) )
{
$cnt = "$head$cnt";
}
else
{
printf("TODO: prepend headers to GZipped HTML content!\n");
}
}
$name .= chr(0);
$name .= chr(0) while( (length($name) & 3) != 0 );
my $size = length($cnt);
$espfs .= "ESfs";
$espfs .= chr($flags);
$espfs .= chr($compression);
$espfs .= chr( length($name) & 255 );
$espfs .= chr( length($name) / 256 );
$espfs .= chr( $size & 255 );
$espfs .= chr( ( $size / 0x100 ) & 255 );
$espfs .= chr( ( $size / 0x10000 ) & 255 );
$espfs .= chr( ( $size / 0x1000000 ) & 255 );
$espfs .= chr( $size & 255 );
$espfs .= chr( ( $size / 0x100 ) & 255 );
$espfs .= chr( ( $size / 0x10000 ) & 255 );
$espfs .= chr( ( $size / 0x1000000 ) & 255 );
$espfs .= $name;
$cnt .= chr(0) while( (length($cnt) & 3) != 0 );
$espfs .= $cnt;
}
$espfs .= "ESfs";
$espfs .= chr(1);
for(my $i=0; $i < 11; $i++)
{
$espfs .= chr(0);
}
open FH, ">", $out or die "Can't open file for write, $!";
print FH $espfs;
close(FH);
exit(0);
sub read_dir_structure
{
my ($dir, $base) = @_;
my @files;
opendir my $dh, $dir or die "Could not open '$dir' for reading: $!\n";
while (my $file = readdir $dh) {
if ($file eq '.' or $file eq '..') {
next;
}
my $path = "$dir/$file";
if( -d "$path" )
{
my @sd = read_dir_structure($path, "$base/$file");
push @files, @sd ;
}
else
{
push @files, "$base/$file";
}
}
close( $dh );
$_ =~ s/^\/// for(@files);
return @files;
}

@ -16,6 +16,7 @@ Some random cgi routines.
#include <esp8266.h> #include <esp8266.h>
#include "cgi.h" #include "cgi.h"
#include "config.h" #include "config.h"
#include "web-server.h"
#ifdef CGI_DBG #ifdef CGI_DBG
#define DBG(format, ...) do { os_printf(format, ## __VA_ARGS__); } while(0) #define DBG(format, ...) do { os_printf(format, ## __VA_ARGS__); } while(0)
@ -193,8 +194,7 @@ int ICACHE_FLASH_ATTR cgiMenu(HttpdConnData *connData) {
if (connData->conn==NULL) return HTTPD_CGI_DONE; // Connection aborted. Clean up. if (connData->conn==NULL) return HTTPD_CGI_DONE; // Connection aborted. Clean up.
char buff[1024]; char buff[1024];
// don't use jsonHeader so the response does get cached // don't use jsonHeader so the response does get cached
httpdStartResponse(connData, 200); noCacheHeaders(connData, 200);
httpdHeader(connData, "Cache-Control", "max-age=3600, must-revalidate");
httpdHeader(connData, "Content-Type", "application/json"); httpdHeader(connData, "Content-Type", "application/json");
httpdEndHeaders(connData); httpdEndHeaders(connData);
// limit hostname to 12 chars // limit hostname to 12 chars
@ -213,12 +213,15 @@ int ICACHE_FLASH_ATTR cgiMenu(HttpdConnData *connData) {
#ifdef MQTT #ifdef MQTT
"\"REST/MQTT\", \"/mqtt.html\", " "\"REST/MQTT\", \"/mqtt.html\", "
#endif #endif
"\"Debug log\", \"/log.html\"" "\"Debug log\", \"/log.html\","
"\"Upgrade Firmware\", \"/flash.html\","
"\"Web Server\", \"/web-server.html\""
"%s"
" ], " " ], "
"\"version\": \"%s\", " "\"version\": \"%s\", "
"\"name\": \"%s\"" "\"name\": \"%s\""
" }", " }",
esp_link_version, name); WEB_UserPages(), esp_link_version, name);
httpdSend(connData, buff, -1); httpdSend(connData, buff, -1);
return HTTPD_CGI_DONE; return HTTPD_CGI_DONE;

@ -68,6 +68,7 @@ int ICACHE_FLASH_ATTR cgiSystemInfo(HttpdConnData *connData) {
"\"name\": \"%s\", " "\"name\": \"%s\", "
"\"reset cause\": \"%d=%s\", " "\"reset cause\": \"%d=%s\", "
"\"size\": \"%s\", " "\"size\": \"%s\", "
"\"upload-size\": \"%d\", "
"\"id\": \"0x%02X 0x%04X\", " "\"id\": \"0x%02X 0x%04X\", "
"\"partition\": \"%s\", " "\"partition\": \"%s\", "
"\"slip\": \"%s\", " "\"slip\": \"%s\", "
@ -79,6 +80,7 @@ int ICACHE_FLASH_ATTR cgiSystemInfo(HttpdConnData *connData) {
rst_info->reason, rst_info->reason,
rst_codes[rst_info->reason], rst_codes[rst_info->reason],
flash_maps[system_get_flash_size_map()], flash_maps[system_get_flash_size_map()],
getUserPageSectionEnd()-getUserPageSectionStart(),
fid & 0xff, (fid & 0xff00) | ((fid >> 16) & 0xff), fid & 0xff, (fid & 0xff00) | ((fid >> 16) & 0xff),
part_id ? "user2.bin" : "user1.bin", part_id ? "user2.bin" : "user1.bin",
flashConfig.slip_enable ? "enabled" : "disabled", flashConfig.slip_enable ? "enabled" : "disabled",

@ -0,0 +1,158 @@
// Copyright (c) 2015 by Thorsten von Eicken, see LICENSE.txt in the esp-link repo
#include <esp8266.h>
#include <osapi.h>
#include "cgi.h"
#include "cgioptiboot.h"
#include "multipart.h"
#include "espfsformat.h"
#include "config.h"
#include "web-server.h"
int upload_offset = 0; // flash offset where to store page upload
int html_header_len = 0; // HTML header length (for uploading HTML files)
// this is the header to add if user uploads HTML file
const char * HTML_HEADER = "<!doctype html><html><head><title>esp-link</title>"
"<link rel=stylesheet href=\"/pure.css\"><link rel=stylesheet href=\"/style.css\">"
"<meta name=viewport content=\"width=device-width, initial-scale=1\"><script src=\"/ui.js\">"
"</script><script src=\"/userpage.js\"></script></head><body><div id=layout> ";
// multipart callback for uploading user defined pages
int ICACHE_FLASH_ATTR webServerSetupMultipartCallback(MultipartCmd cmd, char *data, int dataLen, int position)
{
switch(cmd)
{
case FILE_START:
upload_offset = 0;
html_header_len = 0;
// simple HTML file
if( ( dataLen > 5 ) && ( os_strcmp(data + dataLen - 5, ".html") == 0 ) ) // if the file ends with .html, wrap into an espfs image
{
// write the start block on esp-fs
int spi_flash_addr = getUserPageSectionStart();
spi_flash_erase_sector(spi_flash_addr/SPI_FLASH_SEC_SIZE);
EspFsHeader hdr;
hdr.magic = 0xFFFFFFFF; // espfs magic is invalid during upload
hdr.flags = 0;
hdr.compression = 0;
int len = dataLen + 1;
while(( len & 3 ) != 0 )
len++;
hdr.nameLen = len;
hdr.fileLenComp = hdr.fileLenDecomp = 0xFFFFFFFF;
spi_flash_write( spi_flash_addr + upload_offset, (uint32_t *)(&hdr), sizeof(EspFsHeader) );
upload_offset += sizeof(EspFsHeader);
char nameBuf[len];
os_memset(nameBuf, 0, len);
os_memcpy(nameBuf, data, dataLen);
spi_flash_write( spi_flash_addr + upload_offset, (uint32_t *)(nameBuf), len );
upload_offset += len;
html_header_len = os_strlen(HTML_HEADER) & ~3; // upload only 4 byte aligned part
char buf[html_header_len];
os_memcpy(buf, HTML_HEADER, html_header_len);
spi_flash_write( spi_flash_addr + upload_offset, (uint32_t *)(buf), html_header_len );
upload_offset += html_header_len;
}
break;
case FILE_DATA:
if(( position < 4 ) && (upload_offset == 0)) // for espfs images check the magic number
{
for(int p = position; p < 4; p++ )
{
if( data[p - position] != ((ESPFS_MAGIC >> (p * 8) ) & 255 ) )
{
os_printf("Not an espfs image!\n");
return 1;
}
data[p - position] = 0xFF; // espfs magic is invalid during upload
}
}
int spi_flash_addr = getUserPageSectionStart() + upload_offset + position;
int spi_flash_end_addr = spi_flash_addr + dataLen;
if( spi_flash_end_addr + dataLen >= getUserPageSectionEnd() )
{
os_printf("No more space in the flash!\n");
return 1;
}
int ptr = 0;
while( spi_flash_addr < spi_flash_end_addr )
{
if (spi_flash_addr % SPI_FLASH_SEC_SIZE == 0){
spi_flash_erase_sector(spi_flash_addr/SPI_FLASH_SEC_SIZE);
}
int max = (spi_flash_addr | (SPI_FLASH_SEC_SIZE - 1)) + 1;
int len = spi_flash_end_addr - spi_flash_addr;
if( spi_flash_end_addr > max )
len = max - spi_flash_addr;
spi_flash_write( spi_flash_addr, (uint32_t *)(data + ptr), len );
ptr += len;
spi_flash_addr += len;
}
break;
case FILE_DONE:
{
if( html_header_len != 0 )
{
// write the terminating block on esp-fs
int spi_flash_addr = getUserPageSectionStart() + upload_offset + position;
uint32_t pad = 0;
uint8_t pad_cnt = (4 - position) & 3;
if( pad_cnt )
spi_flash_write( spi_flash_addr, &pad, pad_cnt );
spi_flash_addr += pad_cnt;
// create ESPFS image
EspFsHeader hdr;
hdr.magic = ESPFS_MAGIC;
hdr.flags = 1;
hdr.compression = 0;
hdr.nameLen = 0;
hdr.fileLenComp = hdr.fileLenDecomp = 0;
spi_flash_write( spi_flash_addr, (uint32_t *)(&hdr), sizeof(EspFsHeader) );
uint32_t totallen = html_header_len + position;
// restore ESPFS magic
spi_flash_write( (int)getUserPageSectionStart(), (uint32_t *)&hdr.magic, sizeof(uint32_t) );
// set file size
spi_flash_write( (int)getUserPageSectionStart() + 8, &totallen, sizeof(uint32_t) );
spi_flash_write( (int)getUserPageSectionStart() + 12, &totallen, sizeof(uint32_t) );
}
else
{
// set espfs magic (set it valid)
uint32_t magic = ESPFS_MAGIC;
spi_flash_write( (int)getUserPageSectionStart(), (uint32_t *)&magic, sizeof(uint32_t) );
}
WEB_Init(); // reload the content
}
break;
}
return 0;
}
MultipartCtx * webServerContext = NULL; // multipart upload context for web server
// this callback is called when user uploads the web-page
int ICACHE_FLASH_ATTR cgiWebServerSetupUpload(HttpdConnData *connData)
{
if( webServerContext == NULL )
webServerContext = multipartCreateContext( webServerSetupMultipartCallback );
return multipartProcess(webServerContext, connData);
}

@ -0,0 +1,8 @@
#ifndef CGIWEBSERVER_H
#define CGIWEBSERVER_H
#include <httpd.h>
int ICACHE_FLASH_ATTR cgiWebServerSetupUpload(HttpdConnData *connData);
#endif /* CGIWEBSERVER_H */

@ -31,7 +31,10 @@ FlashConfig flashDefault = {
.rx_pullup = 1, .rx_pullup = 1,
.sntp_server = "us.pool.ntp.org\0", .sntp_server = "us.pool.ntp.org\0",
.syslog_host = "\0", .syslog_minheap = 8192, .syslog_filter = 7, .syslog_showtick = 1, .syslog_showdate = 0, .syslog_host = "\0", .syslog_minheap = 8192, .syslog_filter = 7, .syslog_showtick = 1, .syslog_showdate = 0,
.mdns_enable = 1, .mdns_servername = "http\0", .timezone_offset = 0 .mdns_enable = 1, .mdns_servername = "http\0", .timezone_offset = 0,
.data_bits = EIGHT_BITS,
.parity = NONE_BITS,
.stop_bits = ONE_STOP_BIT,
}; };
typedef union { typedef union {
@ -152,6 +155,12 @@ bool ICACHE_FLASH_ATTR configRestore(void) {
os_memset(flashConfig.mqtt_old_host, 0, 32); os_memset(flashConfig.mqtt_old_host, 0, 32);
} else os_printf("mqtt_host is '%s'\n", flashConfig.mqtt_host); } else os_printf("mqtt_host is '%s'\n", flashConfig.mqtt_host);
if (flashConfig.data_bits == 0) {
// restore to default 8N1
flashConfig.data_bits = flashDefault.data_bits;
flashConfig.parity = flashDefault.parity;
flashConfig.stop_bits = flashDefault.stop_bits;
}
return true; return true;
} }
@ -195,3 +204,43 @@ getFlashSize() {
return 0; return 0;
return 1 << size_id; return 1 << size_id;
} }
const uint32_t getUserPageSectionStart()
{
enum flash_size_map map = system_get_flash_size_map();
switch(map)
{
case FLASH_SIZE_4M_MAP_256_256:
return FLASH_SECT + FIRMWARE_SIZE - 3*FLASH_SECT;// bootloader + firmware - 12KB (highly risky...)
case FLASH_SIZE_8M_MAP_512_512:
return FLASH_SECT + FIRMWARE_SIZE;
case FLASH_SIZE_16M_MAP_512_512:
case FLASH_SIZE_16M_MAP_1024_1024:
case FLASH_SIZE_32M_MAP_512_512:
case FLASH_SIZE_32M_MAP_1024_1024:
return 0x100000;
default:
return 0xFFFFFFFF;
}
}
const uint32_t getUserPageSectionEnd()
{
enum flash_size_map map = system_get_flash_size_map();
switch(map)
{
case FLASH_SIZE_4M_MAP_256_256:
return FLASH_SECT + FIRMWARE_SIZE - 2*FLASH_SECT;
case FLASH_SIZE_8M_MAP_512_512:
return FLASH_SECT + FIRMWARE_SIZE + 2*FLASH_SECT;
case FLASH_SIZE_16M_MAP_512_512:
case FLASH_SIZE_16M_MAP_1024_1024:
return 0x1FC000;
case FLASH_SIZE_32M_MAP_512_512:
case FLASH_SIZE_32M_MAP_1024_1024:
return 0x3FC000;
default:
return 0xFFFFFFFF;
}
}

@ -38,6 +38,9 @@ typedef struct {
char mdns_servername[32]; char mdns_servername[32];
int8_t timezone_offset; int8_t timezone_offset;
char mqtt_host[64]; // MQTT host we connect to, was 32-char mqtt_old_host char mqtt_host[64]; // MQTT host we connect to, was 32-char mqtt_old_host
int8_t data_bits;
int8_t parity;
int8_t stop_bits;
} FlashConfig; } FlashConfig;
extern FlashConfig flashConfig; extern FlashConfig flashConfig;
@ -46,4 +49,7 @@ bool configRestore(void);
void configWipe(void); void configWipe(void);
const size_t getFlashSize(); const size_t getFlashSize();
const uint32_t getUserPageSectionStart();
const uint32_t getUserPageSectionEnd();
#endif #endif

@ -19,6 +19,7 @@
#include "cgimqtt.h" #include "cgimqtt.h"
#include "cgiflash.h" #include "cgiflash.h"
#include "cgioptiboot.h" #include "cgioptiboot.h"
#include "cgiwebserversetup.h"
#include "auth.h" #include "auth.h"
#include "espfs.h" #include "espfs.h"
#include "uart.h" #include "uart.h"
@ -30,6 +31,7 @@
#include "log.h" #include "log.h"
#include "gpio.h" #include "gpio.h"
#include "cgiservices.h" #include "cgiservices.h"
#include "web-server.h"
#ifdef SYSLOG #ifdef SYSLOG
#include "syslog.h" #include "syslog.h"
@ -74,6 +76,7 @@ HttpdBuiltInUrl builtInUrls[] = {
{ "/log/reset", cgiReset, NULL }, { "/log/reset", cgiReset, NULL },
{ "/console/reset", ajaxConsoleReset, NULL }, { "/console/reset", ajaxConsoleReset, NULL },
{ "/console/baud", ajaxConsoleBaud, NULL }, { "/console/baud", ajaxConsoleBaud, NULL },
{ "/console/fmt", ajaxConsoleFormat, NULL },
{ "/console/text", ajaxConsole, NULL }, { "/console/text", ajaxConsole, NULL },
{ "/console/send", ajaxConsoleSend, NULL }, { "/console/send", ajaxConsoleSend, NULL },
//Enable the line below to protect the WiFi configuration with an username/password combo. //Enable the line below to protect the WiFi configuration with an username/password combo.
@ -96,6 +99,8 @@ HttpdBuiltInUrl builtInUrls[] = {
#ifdef MQTT #ifdef MQTT
{ "/mqtt", cgiMqtt, NULL }, { "/mqtt", cgiMqtt, NULL },
#endif #endif
{ "/web-server/upload", cgiWebServerSetupUpload, NULL },
{ "*.json", WEB_CgiJsonHook, NULL }, //Catch-all cgi JSON queries
{ "*", cgiEspFsHook, NULL }, //Catch-all cgi function for the filesystem { "*", cgiEspFsHook, NULL }, //Catch-all cgi function for the filesystem
{ NULL, NULL, NULL } { NULL, NULL, NULL }
}; };
@ -117,13 +122,30 @@ extern uint32_t _binary_espfs_img_start;
extern void app_init(void); extern void app_init(void);
extern void mqtt_client_init(void); extern void mqtt_client_init(void);
void user_rf_pre_init(void) { void ICACHE_FLASH_ATTR
user_rf_pre_init(void) {
//default is enabled //default is enabled
system_set_os_print(DEBUG_SDK); system_set_os_print(DEBUG_SDK);
} }
/* user_rf_cal_sector_set is a required function that is called by the SDK to get a flash
* sector number where it can store RF calibration data. This was introduced with SDK 1.5.4.1
* and is necessary because Espressif ran out of pre-reserved flash sectors. Ooops... */
uint32 ICACHE_FLASH_ATTR
user_rf_cal_sector_set(void) {
uint32_t sect = 0;
switch (system_get_flash_size_map()) {
case FLASH_SIZE_4M_MAP_256_256: // 512KB
sect = 128 - 10; // 0x76000
default:
sect = 128; // 0x80000
}
return sect;
}
// Main routine to initialize esp-link. // Main routine to initialize esp-link.
void user_init(void) { void ICACHE_FLASH_ATTR
user_init(void) {
// uncomment the following three lines to see flash config messages for troubleshooting // uncomment the following three lines to see flash config messages for troubleshooting
//uart_init(115200, 115200); //uart_init(115200, 115200);
//logInit(); //logInit();
@ -135,7 +157,8 @@ void user_init(void) {
gpio_init(); gpio_init();
gpio_output_set(0, 0, 0, (1<<15)); // some people tie it to GND, gotta ensure it's disabled gpio_output_set(0, 0, 0, (1<<15)); // some people tie it to GND, gotta ensure it's disabled
// init UART // init UART
uart_init(flashConfig.baud_rate, 115200); uart_init(CALC_UARTMODE(flashConfig.data_bits, flashConfig.parity, flashConfig.stop_bits),
flashConfig.baud_rate, 115200);
logInit(); // must come after init of uart logInit(); // must come after init of uart
// Say hello (leave some time to cause break in TX after boot loader's msg // Say hello (leave some time to cause break in TX after boot loader's msg
os_delay_us(10000L); os_delay_us(10000L);
@ -147,11 +170,14 @@ void user_init(void) {
// Wifi // Wifi
wifiInit(); wifiInit();
// init the flash filesystem with the html stuff // init the flash filesystem with the html stuff
espFsInit(&_binary_espfs_img_start); espFsInit(espLinkCtx, &_binary_espfs_img_start, ESPFS_MEMORY);
//EspFsInitResult res = espFsInit(&_binary_espfs_img_start); //EspFsInitResult res = espFsInit(&_binary_espfs_img_start);
//os_printf("espFsInit %s\n", res?"ERR":"ok"); //os_printf("espFsInit %s\n", res?"ERR":"ok");
// mount the http handlers // mount the http handlers
httpdInit(builtInUrls, 80); httpdInit(builtInUrls, 80);
WEB_Init();
// init the wifi-serial transparent bridge (port 23) // init the wifi-serial transparent bridge (port 23)
serbridgeInit(23, 2323); serbridgeInit(23, 2323);
uart_add_recv_cb(&serbridgeUartCb); uart_add_recv_cb(&serbridgeUartCb);

@ -30,6 +30,7 @@ It's written for use with httpd, but doesn't need to be used as such.
#define os_malloc malloc #define os_malloc malloc
#define os_free free #define os_free free
#define os_memcpy memcpy #define os_memcpy memcpy
#define os_memset memset
#define os_strncmp strncmp #define os_strncmp strncmp
#define os_strcmp strcmp #define os_strcmp strcmp
#define os_strcpy strcpy #define os_strcpy strcpy
@ -40,9 +41,21 @@ It's written for use with httpd, but doesn't need to be used as such.
#include "espfsformat.h" #include "espfsformat.h"
#include "espfs.h" #include "espfs.h"
static char* espFsData = NULL; EspFsContext espLinkCtxDef;
EspFsContext userPageCtxDef;
EspFsContext * espLinkCtx = &espLinkCtxDef;
EspFsContext * userPageCtx = &userPageCtxDef;
struct EspFsContext
{
char* data;
EspFsSource source;
uint8_t valid;
};
struct EspFsFile { struct EspFsFile {
EspFsContext *ctx;
EspFsHeader *header; EspFsHeader *header;
char decompressor; char decompressor;
int32_t posDecomp; int32_t posDecomp;
@ -67,29 +80,12 @@ Accessing the flash through the mem emulation at 0x40200000 is a bit hairy: All
a memory exception, crashing the program. a memory exception, crashing the program.
*/ */
EspFsInitResult ICACHE_FLASH_ATTR espFsInit(void *flashAddress) {
// base address must be aligned to 4 bytes
if (((int)flashAddress & 3) != 0) {
return ESPFS_INIT_RESULT_BAD_ALIGN;
}
// check if there is valid header at address
EspFsHeader testHeader;
os_memcpy(&testHeader, flashAddress, sizeof(EspFsHeader));
if (testHeader.magic != ESPFS_MAGIC) {
return ESPFS_INIT_RESULT_NO_IMAGE;
}
espFsData = (char *)flashAddress;
return ESPFS_INIT_RESULT_OK;
}
//Copies len bytes over from dst to src, but does it using *only* //Copies len bytes over from dst to src, but does it using *only*
//aligned 32-bit reads. Yes, it's no too optimized but it's short and sweet and it works. //aligned 32-bit reads. Yes, it's no too optimized but it's short and sweet and it works.
//ToDo: perhaps os_memcpy also does unaligned accesses? //ToDo: perhaps os_memcpy also does unaligned accesses?
#ifdef __ets__ #ifdef __ets__
void ICACHE_FLASH_ATTR memcpyAligned(char *dst, char *src, int len) { void ICACHE_FLASH_ATTR memcpyAligned(char *dst, const char *src, int len) {
int x; int x;
int w, b; int w, b;
for (x=0; x<len; x++) { for (x=0; x<len; x++) {
@ -106,6 +102,51 @@ void ICACHE_FLASH_ATTR memcpyAligned(char *dst, char *src, int len) {
#define memcpyAligned memcpy #define memcpyAligned memcpy
#endif #endif
void ICACHE_FLASH_ATTR memcpyFromFlash(char *dst, const char *src, int len)
{
if( spi_flash_read( (int)src, (void *)dst, len ) != SPI_FLASH_RESULT_OK )
os_memset( dst, 0, len ); // if read was not successful, reply with zeroes
}
// memcpy on MEMORY/FLASH file systems
void espfs_memcpy( EspFsContext * ctx, void * dest, const void * src, int count )
{
if( ctx->source == ESPFS_MEMORY )
os_memcpy( dest, src, count );
else
memcpyFromFlash(dest, src, count);
}
// aligned memcpy on MEMORY/FLASH file systems
void espfs_memcpyAligned( EspFsContext * ctx, void * dest, const void * src, int count )
{
if( ctx->source == ESPFS_MEMORY )
memcpyAligned(dest, src, count);
else
memcpyFromFlash(dest, src, count);
}
// initializes an EspFs context
EspFsInitResult ICACHE_FLASH_ATTR espFsInit(EspFsContext *ctx, void *flashAddress, EspFsSource source) {
ctx->valid = 0;
ctx->source = source;
// base address must be aligned to 4 bytes
if (((int)flashAddress & 3) != 0) {
return ESPFS_INIT_RESULT_BAD_ALIGN;
}
// check if there is valid header at address
EspFsHeader testHeader;
espfs_memcpy(ctx, &testHeader, flashAddress, sizeof(EspFsHeader));
if (testHeader.magic != ESPFS_MAGIC) {
return ESPFS_INIT_RESULT_NO_IMAGE;
}
ctx->data = (char *)flashAddress;
ctx->valid = 1;
return ESPFS_INIT_RESULT_OK;
}
// Returns flags of opened file. // Returns flags of opened file.
int ICACHE_FLASH_ATTR espFsFlags(EspFsFile *fh) { int ICACHE_FLASH_ATTR espFsFlags(EspFsFile *fh) {
if (fh == NULL) { if (fh == NULL) {
@ -116,57 +157,93 @@ int ICACHE_FLASH_ATTR espFsFlags(EspFsFile *fh) {
} }
int8_t flags; int8_t flags;
memcpyAligned((char*)&flags, (char*)&fh->header->flags, 1); espfs_memcpyAligned(fh->ctx, (char*)&flags, (char*)&fh->header->flags, 1);
return (int)flags; return (int)flags;
} }
//Open a file and return a pointer to the file desc struct. // creates and initializes an iterator over the espfs file system
EspFsFile ICACHE_FLASH_ATTR *espFsOpen(char *fileName) { void ICACHE_FLASH_ATTR espFsIteratorInit(EspFsContext *ctx, EspFsIterator *iterator)
if (espFsData == NULL) { {
#ifdef ESPFS_DBG if( ctx->data == NULL )
os_printf("Call espFsInit first!\n"); {
#endif iterator->ctx = NULL;
return NULL; return;
} }
char *p=espFsData; iterator->ctx = ctx;
char *hpos; iterator->position = NULL;
char namebuf[256]; }
EspFsHeader h;
EspFsFile *r; // moves iterator to the next file on espfs
//Strip initial slashes // returns 1 if iterator move was successful, otherwise 0 (last file)
while(fileName[0]=='/') fileName++; // iterator->header and iterator->name will contain file information
//Go find that file! int ICACHE_FLASH_ATTR espFsIteratorNext(EspFsIterator *iterator)
while(1) { {
hpos=p; if( iterator->ctx == NULL )
//Grab the next file header. return 0;
os_memcpy(&h, p, sizeof(EspFsHeader));
if (h.magic!=ESPFS_MAGIC) { char * position = iterator->position;
if( position == NULL )
position = iterator->ctx->data; // first node
else
{
// jump the iterator to the next file
position+=sizeof(EspFsHeader) + iterator->header.nameLen+iterator->header.fileLenComp;
if ((int)position&3) position+=4-((int)position&3); //align to next 32bit val
}
iterator->position = position;
EspFsHeader * hdr = &iterator->header;
espfs_memcpy(iterator->ctx, hdr, position, sizeof(EspFsHeader));
if (hdr->magic!=ESPFS_MAGIC) {
#ifdef ESPFS_DBG #ifdef ESPFS_DBG
os_printf("Magic mismatch. EspFS image broken.\n"); os_printf("Magic mismatch. EspFS image broken.\n");
#endif #endif
return NULL; return 0;
} }
if (h.flags&FLAG_LASTFILE) { if (hdr->flags&FLAG_LASTFILE) {
//os_printf("End of image.\n"); //os_printf("End of image.\n");
return NULL; iterator->ctx = NULL; // invalidate the iterator
return 0;
} }
position += sizeof(EspFsHeader);
//Grab the name of the file. //Grab the name of the file.
p+=sizeof(EspFsHeader); espfs_memcpy(iterator->ctx, iterator->name, position, sizeof(iterator->name));
os_memcpy(namebuf, p, sizeof(namebuf));
// os_printf("Found file '%s'. Namelen=%x fileLenComp=%x, compr=%d flags=%d\n", return 1;
// namebuf, (unsigned int)h.nameLen, (unsigned int)h.fileLenComp, h.compression, h.flags); }
if (os_strcmp(namebuf, fileName)==0) {
//Open a file and return a pointer to the file desc struct.
EspFsFile ICACHE_FLASH_ATTR *espFsOpen(EspFsContext *ctx, char *fileName) {
EspFsIterator it;
espFsIteratorInit(ctx, &it);
if (it.ctx == NULL) {
#ifdef ESPFS_DBG
os_printf("Call espFsInit first!\n");
#endif
return NULL;
}
//Strip initial slashes
while(fileName[0]=='/') fileName++;
//Search the file
while( espFsIteratorNext(&it) )
{
if (os_strcmp(it.name, fileName)==0) {
//Yay, this is the file we need! //Yay, this is the file we need!
p+=h.nameLen; //Skip to content. EspFsFile * r=(EspFsFile *)os_malloc(sizeof(EspFsFile)); //Alloc file desc mem
r=(EspFsFile *)os_malloc(sizeof(EspFsFile)); //Alloc file desc mem
//os_printf("Alloc %p[%d]\n", r, sizeof(EspFsFile)); //os_printf("Alloc %p[%d]\n", r, sizeof(EspFsFile));
if (r==NULL) return NULL; if (r==NULL) return NULL;
r->header=(EspFsHeader *)hpos; r->ctx = ctx;
r->decompressor=h.compression; r->header=(EspFsHeader *)it.position;
r->posComp=p; r->decompressor=it.header.compression;
r->posStart=p; r->posComp=it.position + it.header.nameLen + sizeof(EspFsHeader);
r->posStart=it.position + it.header.nameLen + sizeof(EspFsHeader);
r->posDecomp=0; r->posDecomp=0;
if (h.compression==COMPRESS_NONE) { if (it.header.compression==COMPRESS_NONE) {
r->decompData=NULL; r->decompData=NULL;
} else { } else {
#ifdef ESPFS_DBG #ifdef ESPFS_DBG
@ -176,10 +253,8 @@ EspFsFile ICACHE_FLASH_ATTR *espFsOpen(char *fileName) {
} }
return r; return r;
} }
//We don't need this file. Skip name and file
p+=h.nameLen+h.fileLenComp;
if ((int)p&3) p+=4-((int)p&3); //align to next 32bit val
} }
return NULL;
} }
//Read len bytes from the given file into buff. Returns the actual amount of bytes read. //Read len bytes from the given file into buff. Returns the actual amount of bytes read.
@ -187,15 +262,15 @@ int ICACHE_FLASH_ATTR espFsRead(EspFsFile *fh, char *buff, int len) {
int flen, fdlen; int flen, fdlen;
if (fh==NULL) return 0; if (fh==NULL) return 0;
//Cache file length. //Cache file length.
memcpyAligned((char*)&flen, (char*)&fh->header->fileLenComp, 4); espfs_memcpyAligned(fh->ctx, (char*)&flen, (char*)&fh->header->fileLenComp, 4);
memcpyAligned((char*)&fdlen, (char*)&fh->header->fileLenDecomp, 4); espfs_memcpyAligned(fh->ctx, (char*)&fdlen, (char*)&fh->header->fileLenDecomp, 4);
//Do stuff depending on the way the file is compressed. //Do stuff depending on the way the file is compressed.
if (fh->decompressor==COMPRESS_NONE) { if (fh->decompressor==COMPRESS_NONE) {
int toRead; int toRead;
toRead=flen-(fh->posComp-fh->posStart); toRead=flen-(fh->posComp-fh->posStart);
if (len>toRead) len=toRead; if (len>toRead) len=toRead;
// os_printf("Reading %d bytes from %x\n", len, (unsigned int)fh->posComp); // os_printf("Reading %d bytes from %x\n", len, (unsigned int)fh->posComp);
memcpyAligned(buff, fh->posComp, len); espfs_memcpyAligned(fh->ctx, buff, fh->posComp, len);
fh->posDecomp+=len; fh->posDecomp+=len;
fh->posComp+=len; fh->posComp+=len;
// os_printf("Done reading %d bytes, pos=%x\n", len, fh->posComp); // os_printf("Done reading %d bytes, pos=%x\n", len, fh->posComp);
@ -211,5 +286,8 @@ void ICACHE_FLASH_ATTR espFsClose(EspFsFile *fh) {
os_free(fh); os_free(fh);
} }
// checks if the file system is valid (detect if the content is an espfs image or random data)
int ICACHE_FLASH_ATTR espFsIsValid(EspFsContext *ctx) {
return ctx->valid;
}

@ -1,19 +1,42 @@
#ifndef ESPFS_H #ifndef ESPFS_H
#define ESPFS_H #define ESPFS_H
#include "espfsformat.h"
typedef enum { typedef enum {
ESPFS_INIT_RESULT_OK, ESPFS_INIT_RESULT_OK,
ESPFS_INIT_RESULT_NO_IMAGE, ESPFS_INIT_RESULT_NO_IMAGE,
ESPFS_INIT_RESULT_BAD_ALIGN, ESPFS_INIT_RESULT_BAD_ALIGN,
} EspFsInitResult; } EspFsInitResult;
// Only 1 MByte of the flash can be directly accessed with ESP8266
// If flash size is >1 Mbyte, SDK API is required to retrieve flash content
typedef enum {
ESPFS_MEMORY, // read data directly from memory (fast, max 1 MByte)
ESPFS_FLASH, // read data from flash using SDK API (no limit for the size)
} EspFsSource;
typedef struct EspFsFile EspFsFile; typedef struct EspFsFile EspFsFile;
typedef struct EspFsContext EspFsContext;
typedef struct {
EspFsHeader header; // the header of the current file
EspFsContext *ctx; // pointer to espfs context
char name[256]; // the name of the current file
char *position; // position of the iterator (pointer on the file system)
} EspFsIterator;
extern EspFsContext * espLinkCtx;
extern EspFsContext * userPageCtx;
EspFsInitResult espFsInit(void *flashAddress); EspFsInitResult espFsInit(EspFsContext *ctx, void *flashAddress, EspFsSource source);
EspFsFile *espFsOpen(char *fileName); EspFsFile *espFsOpen(EspFsContext *ctx, char *fileName);
int espFsIsValid(EspFsContext *ctx);
int espFsFlags(EspFsFile *fh); int espFsFlags(EspFsFile *fh);
int espFsRead(EspFsFile *fh, char *buff, int len); int espFsRead(EspFsFile *fh, char *buff, int len);
void espFsClose(EspFsFile *fh); void espFsClose(EspFsFile *fh);
void espFsIteratorInit(EspFsContext *ctx, EspFsIterator *iterator);
int espFsIteratorNext(EspFsIterator *iterator);
#endif #endif

@ -34,6 +34,7 @@ clean:
else else
CC=gcc
CFLAGS=-I.. -std=gnu99 CFLAGS=-I.. -std=gnu99
ifeq ("$(GZIP_COMPRESSION)","yes") ifeq ("$(GZIP_COMPRESSION)","yes")
CFLAGS+= -DESPFS_GZIP CFLAGS+= -DESPFS_GZIP

@ -18,7 +18,17 @@
<option value="19200">19200</option> <option value="19200">19200</option>
<option value="9600">9600</option> <option value="9600">9600</option>
</select> </select>
&nbsp; Fmt: 8N1 &nbsp; Fmt:
<select id="fmt-sel" class="pure-button" href="#">
<option value="8N1">8N1</option>
<option value="8E1">8E1</option>
<option value="8N2">8N2</option>
<option value="8E2">8E2</option>
<option value="7N1">7N1</option>
<option value="7E1">7E1</option>
<option value="7N2">7N2</option>
<option value="7E2">7E2</option>
</select>
</p> </p>
<div class="pure-g"> <div class="pure-g">
<div class="pure-u-1-4"><legend><b>Console</b></legend></div> <div class="pure-u-1-4"><legend><b>Console</b></legend></div>
@ -93,6 +103,20 @@
); );
}); });
ajaxJson('GET', "/console/fmt",
function(data) { $("#fmt-sel").value = data.fmt; },
function(s, st) { showNotification(st); }
);
bnd($("#fmt-sel"), "change", function(ev) {
ev.preventDefault();
var fmt = $("#fmt-sel").value;
ajaxSpin('POST', "/console/fmt?fmt="+fmt,
function(resp) { showNotification("" + fmt + " format set"); },
function(s, st) { showWarning("Error setting format: " + st); }
);
});
consoleSendInit(); consoleSendInit();
addClass($('html')[0], "height100"); addClass($('html')[0], "height100");

@ -0,0 +1,43 @@
<div id="main">
<div class="header">
<h1>Upgrade Firmware</h1>
</div>
<div class="content">
<div class="pure-g">
<div class="pure-u-1 pure-u-md-1-2">
<div class="card">
<h1>Upgrade Firmware
<div id="fw-spinner" class="spinner spinner-small"></div>
</h1>
<form action="#" id="fw-form" class="pure-form" hidden>
<legend>Firmware Info</legend>
<p>
Current firmware: <span style="font-weight: bold;" id="current-fw"></span>
</p>
<div class="pure-form-stacked">
<p>
Make sure you upload the file called: <span style="font-weight: bold;" id="fw-slot"></span>
</p>
<label>Firmware File</label>
<input type="file" name="fw-file" id="fw-file"/>
</div>
<button id="fw-button" type="submit" class="pure-button button-primary">
Update the firmware
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="flash.js"></script>
<script type="text/javascript">
onLoad(function() {
fetchFlash();
bnd($("#fw-form"), "submit", flashFirmware);
});
</script>
</body></html>

@ -0,0 +1,33 @@
//===== FLASH cards
function flashFirmware(e) {
e.preventDefault();
var fw_data = document.getElementById('fw-file').files[0];
$("#fw-form").setAttribute("hidden", "");
$("#fw-spinner").removeAttribute("hidden");
showNotification("Firmware is being updated ...");
ajaxReq("POST", "/flash/upload", function (resp) {
ajaxReq("GET", "/flash/reboot", function (resp) {
showNotification("Firmware has been successfully updated!");
setTimeout(function(){ window.location.reload()}, 4000);
$("#fw-spinner").setAttribute("hidden", "");
$("#fw-form").removeAttribute("hidden");
});
}, null, fw_data)
}
function fetchFlash() {
ajaxReq("GET", "/flash/next", function (resp) {
$("#fw-slot").innerHTML = resp;
$("#fw-spinner").setAttribute("hidden", "");
$("#fw-form").removeAttribute("hidden");
});
ajaxJson("GET", "/menu", function(data) {
var v = $("#current-fw");
if (v != null) { v.innerHTML = data.version; }
}
);
}

@ -123,6 +123,12 @@
<div class="popup pop-left">Size configured into bootloader, must match chip size</div> <div class="popup pop-left">Size configured into bootloader, must match chip size</div>
</div> </div>
</td></tr> </td></tr>
<tr><td>Webpage size</td><td>
<div>
<span class="system-upload-size"></span>
<div class="popup pop-left">The maximal size of the custom web page a user can upload.</div>
</div>
</td></tr>
<tr><td>Current partition</td><td class="system-partition"></td></tr> <tr><td>Current partition</td><td class="system-partition"></td></tr>
<tr><td colspan=2 class="popup-target">Description:<br> <tr><td colspan=2 class="popup-target">Description:<br>
<div class="click-to-edit system-description"> <div class="click-to-edit system-description">

@ -151,7 +151,7 @@ function toggleClass(el, cl) {
//===== AJAX //===== AJAX
function ajaxReq(method, url, ok_cb, err_cb) { function ajaxReq(method, url, ok_cb, err_cb, data) {
var xhr = j(); var xhr = j();
xhr.open(method, url, true); xhr.open(method, url, true);
var timeout = setTimeout(function() { var timeout = setTimeout(function() {
@ -173,7 +173,7 @@ function ajaxReq(method, url, ok_cb, err_cb) {
} }
// console.log("XHR send:", method, url); // console.log("XHR send:", method, url);
try { try {
xhr.send(); xhr.send(data);
} catch(err) { } catch(err) {
console.log("XHR EXC :", method, url, "->", err); console.log("XHR EXC :", method, url, "->", err);
err_cb(599, err); err_cb(599, err);

@ -0,0 +1,242 @@
//===== Java script for user pages
var loadCounter = 0;
var refreshRate = 0;
var refreshTimer;
var hiddenInputs = [];
function notifyResponse( data )
{
Object.keys(data).forEach(function(v) {
var elems = document.getElementsByName(v);
var ndx;
for(ndx = 0; ndx < elems.length; ndx++ )
{
var el = elems[ndx];
if(el.tagName == "INPUT")
{
if( el.type == "radio" )
{
el.checked = data[v] == el.value;
}
else if( el.type == "checkbox" )
{
if( data[v] == "on" )
el.checked = true;
else if( data[v] == "off" )
el.checked = false;
else if( data[v] == true )
el.checked = true;
else
el.checked = false;
}
else
{
el.value = data[v];
}
}
if(el.tagName == "SELECT")
{
el.value = data[v];
}
}
var elem = document.getElementById(v);
if( elem != null )
{
if(elem.tagName == "P" || elem.tagName == "DIV" || elem.tagName == "SPAN" || elem.tagName == "TR" || elem.tagName == "TH" || elem.tagName == "TD" ||
elem.tagName == "TEXTAREA" )
{
elem.innerHTML = data[v];
}
if(elem.tagName == "UL" || elem.tagName == "OL")
{
var list = data[v];
var html = "";
for (var i=0; i<list.length; i++) {
html = html.concat("<li>" + list[i] + "</li>");
}
elem.innerHTML = html;
}
if(elem.tagName == "TABLE")
{
var list = data[v];
var html = "";
if( list.length > 0 )
{
var ths = list[0];
html = html.concat("<tr>");
for (var i=0; i<ths.length; i++) {
html = html.concat("<th>" + ths[i] + "</th>");
}
html = html.concat("</tr>");
}
for (var i=1; i<list.length; i++) {
var tds = list[i];
html = html.concat("<tr>");
for (var j=0; j<tds.length; j++) {
html = html.concat("<td>" + tds[j] + "</td>");
}
html = html.concat("</tr>");
}
elem.innerHTML = html;
}
}
});
if( refreshRate != 0 )
{
clearTimeout(refreshTimer);
refreshTimer = setTimeout( function () {
ajaxJson("GET", window.location.pathname + ".json?reason=refresh", notifyResponse );
}, refreshRate );
}
}
function notifyButtonPressed( btnId )
{
ajaxJson("POST", window.location.pathname + ".json?reason=button\&id=" + btnId, notifyResponse);
}
function refreshFormData()
{
setTimeout( function () {
ajaxJson("GET", window.location.pathname + ".json?reason=refresh", function (resp) {
notifyResponse(resp);
if( loadCounter > 0 )
{
loadCounter--;
refreshFormData();
}
} );
} , 250);
}
function recalculateHiddenInputs()
{
for(var i=0; i < hiddenInputs.length; i++)
{
var hinput = hiddenInputs[i];
var name = hinput.name;
var elems = document.getElementsByName(name);
for(var j=0; j < elems.length; j++ )
{
var chk = elems[j];
var inptp = chk.type;
if( inptp == "checkbox" ) {
if( chk.checked )
{
hinput.disabled = true;
hinput.value = "on";
}
else
{
hinput.disabled = false;
hinput.value = "off";
}
}
}
}
}
document.addEventListener("DOMContentLoaded", function(){
// collect buttons
var btns = document.getElementsByTagName("button");
var ndx;
for (ndx = 0; ndx < btns.length; ndx++) {
var btn = btns[ndx];
var id = btn.getAttribute("id");
var onclk = btn.getAttribute("onclick");
var type = btn.getAttribute("type");
if( id != null && onclk == null && type == "button" )
{
var fn;
eval( "fn = function() { notifyButtonPressed(\"" + id + "\") }" );
btn.onclick = fn;
}
}
// collect forms
var frms = document.getElementsByTagName("form");
for (ndx = 0; ndx < frms.length; ndx++) {
var frm = frms[ndx];
var method = frm.method;
var action = frm.action;
frm.method = "POST";
frm.action = window.location.pathname + ".json?reason=submit";
loadCounter = 4;
frm.onsubmit = function () {
recalculateHiddenInputs();
refreshFormData();
return true;
};
}
// collect metas
var metas = document.getElementsByTagName("meta");
for (ndx = 0; ndx < metas.length; ndx++) {
var meta = metas[ndx];
if( meta.getAttribute("name") == "refresh-rate" )
{
refreshRate = meta.getAttribute("content");
}
}
// collect checkboxes
var inputs = document.getElementsByTagName("input");
for (ndx = 0; ndx < inputs.length; ndx++) {
var inp = inputs[ndx];
if( inp.getAttribute("type") == "checkbox" )
{
var name = inp.getAttribute("name");
var hasHidden = false;
if( name != null )
{
var inpelems = document.getElementsByName(name);
for(var i=0; i < inpelems.length; i++ )
{
var inptp = inpelems[i].type;
if( inptp == "hidden" )
hasHidden = true;
}
}
if( !hasHidden )
{
var parent = inp.parentElement;
var input = document.createElement("input");
input.type = "hidden";
input.name = inp.name;
parent.appendChild(input);
hiddenInputs.push(input);
}
}
}
// load variables at first time
var loadVariables = function() {
ajaxJson("GET", window.location.pathname + ".json?reason=load", notifyResponse,
function () { setTimeout(loadVariables, 1000); }
);
};
loadVariables();
});

@ -0,0 +1,29 @@
<div id="main">
<div class="header">
<h1>Web Server</h1>
</div>
<div class="content">
<p>User defined web pages can be uploaded to esp-link. This is useful if esp-link acts as a web server while MCU provides
the measurement data.</p>
<form method="post" action="web-server/upload" name="submit" enctype="multipart/form-data" onSubmit="return onSubmit()">
The custom web page to upload: <input type="file" name="webpage">
<input type="submit" name="submit" value="Submit">
</form>
</div>
</div>
<script>
var allowSubmit = true;
function onSubmit() {
setTimeout(function() {
window.location.reload();
}, 1000);
return true;
}
</script>
</body></html>

@ -132,6 +132,7 @@ static void ICACHE_FLASH_ATTR httpdRetireConn(HttpdConnData *conn) {
if (conn->post->buff != NULL) os_free(conn->post->buff); if (conn->post->buff != NULL) os_free(conn->post->buff);
conn->cgi = NULL; conn->cgi = NULL;
conn->post->buff = NULL; conn->post->buff = NULL;
conn->post->multipartBoundary = NULL;
} }
//Stupid li'l helper function that returns the value of a hex char. //Stupid li'l helper function that returns the value of a hex char.
@ -354,14 +355,18 @@ static void ICACHE_FLASH_ATTR httpdProcessRequest(HttpdConnData *conn) {
if (conn->cgi == NULL) { if (conn->cgi == NULL) {
while (builtInUrls[i].url != NULL) { while (builtInUrls[i].url != NULL) {
int match = 0; int match = 0;
int urlLen = os_strlen(builtInUrls[i].url);
//See if there's a literal match //See if there's a literal match
if (os_strcmp(builtInUrls[i].url, conn->url) == 0) match = 1; if (os_strcmp(builtInUrls[i].url, conn->url) == 0) match = 1;
//See if there's a wildcard match //See if there's a wildcard match
if (builtInUrls[i].url[os_strlen(builtInUrls[i].url) - 1] == '*' && if (builtInUrls[i].url[urlLen - 1] == '*' &&
os_strncmp(builtInUrls[i].url, conn->url, os_strlen(builtInUrls[i].url) - 1) == 0) match = 1; os_strncmp(builtInUrls[i].url, conn->url, urlLen - 1) == 0) match = 1;
else if (builtInUrls[i].url[0] == '*' && ( strlen(conn->url) >= urlLen -1 ) &&
os_strncmp(builtInUrls[i].url + 1, conn->url + strlen(conn->url) - urlLen + 1, urlLen - 1) == 0) match = 1;
if (match) { if (match) {
//os_printf("Is url index %d\n", i); //os_printf("Is url index %d\n", i);
conn->cgiData = NULL; conn->cgiData = NULL;
conn->cgiResponse = NULL;
conn->cgi = builtInUrls[i].cgiCb; conn->cgi = builtInUrls[i].cgiCb;
conn->cgiArg = builtInUrls[i].cgiArg; conn->cgiArg = builtInUrls[i].cgiArg;
break; break;
@ -509,6 +514,7 @@ static void ICACHE_FLASH_ATTR httpdRecvCb(void *arg, char *data, unsigned short
if (data[x] == '\n' && (char *)os_strstr(conn->priv->head, "\r\n\r\n") != NULL) { if (data[x] == '\n' && (char *)os_strstr(conn->priv->head, "\r\n\r\n") != NULL) {
//Indicate we're done with the headers. //Indicate we're done with the headers.
conn->post->len = 0; conn->post->len = 0;
conn->post->multipartBoundary = NULL;
//Reset url data //Reset url data
conn->url = NULL; conn->url = NULL;
//Iterate over all received headers and parse them. //Iterate over all received headers and parse them.
@ -621,3 +627,43 @@ void ICACHE_FLASH_ATTR httpdInit(HttpdBuiltInUrl *fixedUrls, int port) {
espconn_accept(&httpdConn); espconn_accept(&httpdConn);
espconn_tcp_set_max_con_allow(&httpdConn, MAX_CONN); espconn_tcp_set_max_con_allow(&httpdConn, MAX_CONN);
} }
// looks up connection handle based on ip / port
HttpdConnData * ICACHE_FLASH_ATTR httpdLookUpConn(uint8_t * ip, int port) {
int i;
for (i = 0; i<MAX_CONN; i++)
{
HttpdConnData *conn = connData+i;
if (conn->conn == NULL)
continue;
if (conn->cgi == NULL)
continue;
if (conn->conn->proto.tcp->remote_port != port )
continue;
if (os_memcmp(conn->conn->proto.tcp->remote_ip, ip, 4) != 0)
continue;
return conn;
}
return NULL;
}
// this method is used for setting the response of a CGI handler outside of the HTTP callback
// this method useful at the following scenario:
// Browser -> CGI handler -> MCU request
// MCU response -> CGI handler -> browser
// when MCU response arrives, the handler looks up connection based on ip/port and call httpdSetCGIResponse with the data to transmit
int ICACHE_FLASH_ATTR httpdSetCGIResponse(HttpdConnData * conn, void * response) {
char sendBuff[MAX_SENDBUFF_LEN];
conn->priv->sendBuff = sendBuff;
conn->priv->sendBuffLen = 0;
conn->cgiResponse = response;
httpdProcessRequest(conn);
conn->cgiResponse = NULL;
return HTTPD_CGI_DONE;
}

@ -30,6 +30,7 @@ struct HttpdConnData {
const void *cgiArg; const void *cgiArg;
void *cgiData; void *cgiData;
void *cgiPrivData; // Used for streaming handlers storing state between requests void *cgiPrivData; // Used for streaming handlers storing state between requests
void *cgiResponse; // used for forwarding response to the CGI handler
HttpdPriv *priv; HttpdPriv *priv;
cgiSendCallback cgi; cgiSendCallback cgi;
HttpdPostData *post; HttpdPostData *post;
@ -66,5 +67,7 @@ void ICACHE_FLASH_ATTR httpdEndHeaders(HttpdConnData *conn);
int ICACHE_FLASH_ATTR httpdGetHeader(HttpdConnData *conn, char *header, char *ret, int retLen); int ICACHE_FLASH_ATTR httpdGetHeader(HttpdConnData *conn, char *header, char *ret, int retLen);
int ICACHE_FLASH_ATTR httpdSend(HttpdConnData *conn, const char *data, int len); int ICACHE_FLASH_ATTR httpdSend(HttpdConnData *conn, const char *data, int len);
void ICACHE_FLASH_ATTR httpdFlush(HttpdConnData *conn); void ICACHE_FLASH_ATTR httpdFlush(HttpdConnData *conn);
HttpdConnData * ICACHE_FLASH_ATTR httpdLookUpConn(uint8_t * ip, int port);
int ICACHE_FLASH_ATTR httpdSetCGIResponse(HttpdConnData * conn, void *response);
#endif #endif

@ -14,11 +14,12 @@ Connector to let httpd use the espfs filesystem to serve the files in it.
*/ */
#include "httpdespfs.h" #include "httpdespfs.h"
#define MAX_URL_LEN 255
// The static files marked with FLAG_GZIP are compressed and will be served with GZIP compression. // The static files marked with FLAG_GZIP are compressed and will be served with GZIP compression.
// If the client does not advertise that he accepts GZIP send following warning message (telnet users for e.g.) // If the client does not advertise that he accepts GZIP send following warning message (telnet users for e.g.)
static const char *gzipNonSupportedMessage = "HTTP/1.0 501 Not implemented\r\nServer: esp8266-httpd/"HTTPDVER"\r\nConnection: close\r\nContent-Type: text/plain\r\nContent-Length: 52\r\n\r\nYour browser does not accept gzip-compressed data.\r\n"; static const char *gzipNonSupportedMessage = "HTTP/1.0 501 Not implemented\r\nServer: esp8266-httpd/"HTTPDVER"\r\nConnection: close\r\nContent-Type: text/plain\r\nContent-Length: 52\r\n\r\nYour browser does not accept gzip-compressed data.\r\n";
//This is a catch-all cgi function. It takes the url passed to it, looks up the corresponding //This is a catch-all cgi function. It takes the url passed to it, looks up the corresponding
//path in the filesystem and if it exists, passes the file through. This simulates what a normal //path in the filesystem and if it exists, passes the file through. This simulates what a normal
//webserver would do with static files. //webserver would do with static files.
@ -40,8 +41,20 @@ cgiEspFsHook(HttpdConnData *connData) {
if (file==NULL) { if (file==NULL) {
//First call to this cgi. Open the file so we can read it. //First call to this cgi. Open the file so we can read it.
file=espFsOpen(connData->url); file=espFsOpen(espLinkCtx, connData->url);
if (file==NULL) { if (file==NULL) {
if( espFsIsValid(userPageCtx) )
{
int maxLen = strlen(connData->url) * 2 + 1;
if( maxLen > MAX_URL_LEN )
maxLen = MAX_URL_LEN;
char decodedURL[maxLen];
httpdUrlDecode(connData->url, strlen(connData->url), decodedURL, maxLen);
file = espFsOpen(userPageCtx, decodedURL );
if( file == NULL )
return HTTPD_CGI_NOTFOUND;
}
else
return HTTPD_CGI_NOTFOUND; return HTTPD_CGI_NOTFOUND;
} }

@ -0,0 +1,301 @@
#include <esp8266.h>
#include <osapi.h>
#include "multipart.h"
#include "cgi.h"
#define BOUNDARY_SIZE 100
typedef enum {
STATE_SEARCH_BOUNDARY = 0, // state: searching multipart boundary
STATE_SEARCH_HEADER, // state: search multipart file header
STATE_SEARCH_HEADER_END, // state: search the end of the file header
STATE_UPLOAD_FILE, // state: read file content
STATE_ERROR, // state: error (stop processing)
} MultipartState;
struct _MultipartCtx {
MultipartCallback callBack; // callback for multipart events
int position; // current file position
int startTime; // timestamp when connection was initiated
int recvPosition; // receive position (how many bytes was processed from the HTTP post)
char * boundaryBuffer; // buffer used for boundary detection
int boundaryBufferPtr; // pointer in the boundary buffer
MultipartState state; // multipart processing state
};
// this method is responsible for creating the multipart context
MultipartCtx * ICACHE_FLASH_ATTR multipartCreateContext(MultipartCallback callback)
{
MultipartCtx * ctx = (MultipartCtx *)os_malloc(sizeof(MultipartCtx));
ctx->callBack = callback;
ctx->position = ctx->startTime = ctx->recvPosition = ctx->boundaryBufferPtr = 0;
ctx->boundaryBuffer = NULL;
ctx->state = STATE_SEARCH_BOUNDARY;
return ctx;
}
// for allocating buffer for multipart upload
void ICACHE_FLASH_ATTR multipartAllocBoundaryBuffer(MultipartCtx * context)
{
if( context->boundaryBuffer == NULL )
context->boundaryBuffer = (char *)os_malloc(3*BOUNDARY_SIZE + 1);
context->boundaryBufferPtr = 0;
}
// for freeing multipart buffer
void ICACHE_FLASH_ATTR multipartFreeBoundaryBuffer(MultipartCtx * context)
{
if( context->boundaryBuffer != NULL )
{
os_free(context->boundaryBuffer);
context->boundaryBuffer = NULL;
}
}
// for destroying the context
void ICACHE_FLASH_ATTR multipartDestroyContext(MultipartCtx * context)
{
multipartFreeBoundaryBuffer(context);
os_free(context);
}
// this is because of os_memmem is missing
void * mp_memmem(const void *l, size_t l_len, const void *s, size_t s_len)
{
register char *cur, *last;
const char *cl = (const char *)l;
const char *cs = (const char *)s;
/* we need something to compare */
if (l_len == 0 || s_len == 0)
return NULL;
/* "s" must be smaller or equal to "l" */
if (l_len < s_len)
return NULL;
/* special case where s_len == 1 */
if (s_len == 1)
return memchr(l, (int)*cs, l_len);
/* the last position where its possible to find "s" in "l" */
last = (char *)cl + l_len - s_len;
for (cur = (char *)cl; cur <= last; cur++)
if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
return cur;
return NULL;
}
// this method is for processing data coming from the HTTP post request
// context: the multipart context
// boundary: a string which indicates boundary
// data: the received data
// len: the received data length (can't be bigger than BOUNDARY_SIZE)
// last: last packet indicator
//
// Detecting a boundary is not easy. One has to take care of boundaries which are splitted in 2 packets
// [Packet 1, 5 bytes of the boundary][Packet 2, remaining 10 bytes of the boundary];
//
// Algorythm:
// - create a buffer which size is 3*BOUNDARY_SIZE
// - put data into the buffer as long as the buffer size is smaller than 2*BOUNDARY_SIZE
// - search boundary in the received buffer, if found: boundary reached -> process data before boundary -> process boundary
// - if not found -> process the first BOUNDARY_SIZE amount of bytes from the buffer
// - remove processed data from the buffer
// this algorythm guarantees that no boundary loss will happen
int ICACHE_FLASH_ATTR multipartProcessData(MultipartCtx * context, char * boundary, char * data, int len, int last)
{
if( len != 0 ) // add data to the boundary buffer
{
os_memcpy(context->boundaryBuffer + context->boundaryBufferPtr, data, len);
context->boundaryBufferPtr += len;
context->boundaryBuffer[context->boundaryBufferPtr] = 0;
}
while( context->boundaryBufferPtr > 0 )
{
if( ! last && context->boundaryBufferPtr <= 2 * BOUNDARY_SIZE ) // return if buffer is too small and not the last packet is processed
return 0;
int dataSize = BOUNDARY_SIZE;
char * boundaryLoc = mp_memmem( context->boundaryBuffer, context->boundaryBufferPtr, boundary, os_strlen(boundary) );
if( boundaryLoc != NULL )
{
int pos = boundaryLoc - context->boundaryBuffer;
if( pos > BOUNDARY_SIZE ) // process in the next call
boundaryLoc = NULL;
else
dataSize = pos;
}
if( dataSize != 0 ) // data to process
{
switch( context->state )
{
case STATE_SEARCH_HEADER:
case STATE_SEARCH_HEADER_END:
{
char * chr = os_strchr( context->boundaryBuffer, '\n' );
if( chr != NULL )
{
// chop datasize to contain only one line
int pos = chr - context->boundaryBuffer + 1;
if( pos < dataSize ) // if chop smaller than the dataSize, delete the boundary
{
dataSize = pos;
boundaryLoc = NULL; // process boundary next time
}
if( context->state == STATE_SEARCH_HEADER_END )
{
if( pos == 1 || ( ( pos == 2 ) && ( context->boundaryBuffer[0] == '\r' ) ) ) // empty line?
{
context->state = STATE_UPLOAD_FILE;
context->position = 0;
}
}
else if( os_strncmp( context->boundaryBuffer, "Content-Disposition:", 20 ) == 0 )
{
char * fnam = os_strstr( context->boundaryBuffer, "filename=" );
if( fnam != NULL )
{
int pos = fnam - context->boundaryBuffer + 9;
if( pos < dataSize )
{
while(context->boundaryBuffer[pos] == ' ') pos++; // skip spaces
if( context->boundaryBuffer[pos] == '"' ) // quote start
{
pos++;
int start = pos;
while( pos < context->boundaryBufferPtr )
{
if( context->boundaryBuffer[pos] == '"' ) // quote end
break;
pos++;
}
if( pos < context->boundaryBufferPtr )
{
context->boundaryBuffer[pos] = 0; // terminating zero for the file name
os_printf("Uploading file: %s\n", context->boundaryBuffer + start);
if( context->callBack( FILE_START, context->boundaryBuffer + start, pos - start, 0 ) ) // FILE_START callback
return 1; // if an error happened
context->boundaryBuffer[pos] = '"'; // restore the original quote
context->state = STATE_SEARCH_HEADER_END;
}
}
}
}
}
}
}
break;
case STATE_UPLOAD_FILE:
{
char c = context->boundaryBuffer[dataSize];
context->boundaryBuffer[dataSize] = 0; // add terminating zero (for easier handling)
if( context->callBack( FILE_DATA, context->boundaryBuffer, dataSize, context->position ) ) // FILE_DATA callback
return 1;
context->boundaryBuffer[dataSize] = c;
context->position += dataSize;
}
break;
default:
break;
}
}
if( boundaryLoc != NULL ) // boundary found?
{
dataSize += os_strlen(boundary); // jump over the boundary
if( context->state == STATE_UPLOAD_FILE )
{
if( context->callBack( FILE_DONE, NULL, 0, context->position ) ) // file done callback
return 1; // if an error happened
os_printf("File upload done\n");
}
context->state = STATE_SEARCH_HEADER; // search the next header
}
// move the buffer back with dataSize
context->boundaryBufferPtr -= dataSize;
os_memcpy(context->boundaryBuffer, context->boundaryBuffer + dataSize, context->boundaryBufferPtr);
}
return 0;
}
// for processing multipart requests
int ICACHE_FLASH_ATTR multipartProcess(MultipartCtx * context, HttpdConnData * connData )
{
if (connData->conn==NULL) return HTTPD_CGI_DONE; // Connection aborted. Clean up.
if (connData->requestType == HTTPD_METHOD_POST) {
HttpdPostData *post = connData->post;
if( post->multipartBoundary == NULL )
{
errorResponse(connData, 404, "Only multipart POST is supported");
return HTTPD_CGI_DONE;
}
if( connData->startTime != context->startTime )
{
// reinitialize, as this is a new request
context->position = 0;
context->recvPosition = 0;
context->startTime = connData->startTime;
context->state = STATE_SEARCH_BOUNDARY;
multipartAllocBoundaryBuffer(context);
}
if( context->state != STATE_ERROR )
{
int feed = 0;
while( feed < post->buffLen )
{
int len = post->buffLen - feed;
if( len > BOUNDARY_SIZE )
len = BOUNDARY_SIZE;
if( multipartProcessData(context, post->multipartBoundary, post->buff + feed, len, 0) )
{
context->state = STATE_ERROR;
break;
}
feed += len;
}
}
context->recvPosition += post->buffLen;
if( context->recvPosition < post->len )
return HTTPD_CGI_MORE;
if( context->state != STATE_ERROR )
{
// this is the last package, process the remaining data
if( multipartProcessData(context, post->multipartBoundary, NULL, 0, 1) )
context->state = STATE_ERROR;
}
multipartFreeBoundaryBuffer( context );
if( context->state == STATE_ERROR )
errorResponse(connData, 400, "Invalid file upload!");
else
{
httpdStartResponse(connData, 204);
httpdEndHeaders(connData);
}
return HTTPD_CGI_DONE;
}
else {
errorResponse(connData, 404, "Only multipart POST is supported");
return HTTPD_CGI_DONE;
}
}

@ -0,0 +1,32 @@
#ifndef MULTIPART_H
#define MULTIPART_H
#include <httpd.h>
typedef enum {
FILE_START, // multipart: the start of a new file
FILE_DATA, // multipart: file data
FILE_DONE, // multipart: file end
} MultipartCmd;
// multipart callback
// -> FILE_START : data+dataLen contains the filename, position is 0
// -> FILE_DATA : data+dataLen contains file data, position is the file position
// -> FILE_DONE : data+dataLen is 0, position is the complete file size
typedef int (* MultipartCallback)(MultipartCmd cmd, char *data, int dataLen, int position);
struct _MultipartCtx; // the context for multipart listening
typedef struct _MultipartCtx MultipartCtx;
// use this for creating a multipart context
MultipartCtx * ICACHE_FLASH_ATTR multipartCreateContext(MultipartCallback callback);
// for destroying multipart context
void ICACHE_FLASH_ATTR multipartDestroyContext(MultipartCtx * context);
// use this function for processing HTML multipart updates
int ICACHE_FLASH_ATTR multipartProcess(MultipartCtx * context, HttpdConnData * post );
#endif /* MULTIPART_H */

@ -116,7 +116,6 @@ tcpclient_recv(void *arg, char *pdata, unsigned short len) {
espconn_disconnect(client->pCon); espconn_disconnect(client->pCon);
} }
// Data is sent
static void ICACHE_FLASH_ATTR static void ICACHE_FLASH_ATTR
tcpclient_sent_cb(void *arg) { tcpclient_sent_cb(void *arg) {
struct espconn *pCon = (struct espconn *)arg; struct espconn *pCon = (struct espconn *)arg;

@ -80,6 +80,38 @@ ajaxConsoleBaud(HttpdConnData *connData) {
httpdSend(connData, buff, -1); httpdSend(connData, buff, -1);
return HTTPD_CGI_DONE; return HTTPD_CGI_DONE;
} }
int ICACHE_FLASH_ATTR
ajaxConsoleFormat(HttpdConnData *connData) {
if (connData->conn==NULL) return HTTPD_CGI_DONE; // Connection aborted. Clean up.
char buff[16];
int len, status = 400;
uint32 conf0;
len = httpdFindArg(connData->getArgs, "fmt", buff, sizeof(buff));
if (len >= 3) {
int c = buff[0];
if (c >= '5' && c <= '8')
flashConfig.data_bits = c - '5' + FIVE_BITS;
if (buff[1] == 'N' || buff[1] == 'E')
flashConfig.parity = buff[1] == 'E' ? EVEN_BITS : NONE_BITS;
if (buff[2] == '1' || buff[2] == '2')
flashConfig.stop_bits = buff[2] == '2' ? TWO_STOP_BIT : ONE_STOP_BIT;
conf0 = CALC_UARTMODE(flashConfig.data_bits, flashConfig.parity, flashConfig.stop_bits);
uart_config(0, flashConfig.baud_rate, conf0);
status = configSave() ? 200 : 400;
} else if (connData->requestType == HTTPD_METHOD_GET) {
status = 200;
}
jsonHeader(connData, status);
os_sprintf(buff, "{\"fmt\": \"%c%c%c\"}",
flashConfig.data_bits + '5',
flashConfig.parity ? 'E' : 'N',
flashConfig.stop_bits ? '2': '1');
httpdSend(connData, buff, -1);
return HTTPD_CGI_DONE;
}
int ICACHE_FLASH_ATTR int ICACHE_FLASH_ATTR
ajaxConsoleSend(HttpdConnData *connData) { ajaxConsoleSend(HttpdConnData *connData) {

@ -8,6 +8,7 @@ void ICACHE_FLASH_ATTR console_write_char(char c);
int ajaxConsole(HttpdConnData *connData); int ajaxConsole(HttpdConnData *connData);
int ajaxConsoleReset(HttpdConnData *connData); int ajaxConsoleReset(HttpdConnData *connData);
int ajaxConsoleBaud(HttpdConnData *connData); int ajaxConsoleBaud(HttpdConnData *connData);
int ajaxConsoleFormat(HttpdConnData *connData);
int ajaxConsoleSend(HttpdConnData *connData); int ajaxConsoleSend(HttpdConnData *connData);
int tplConsole(HttpdConnData *connData, char *token, void **arg); int tplConsole(HttpdConnData *connData, char *token, void **arg);

@ -23,7 +23,7 @@ static struct espconn serbridgeConn2; // programming port
static esp_tcp serbridgeTcp1, serbridgeTcp2; static esp_tcp serbridgeTcp1, serbridgeTcp2;
static int8_t mcu_reset_pin, mcu_isp_pin; static int8_t mcu_reset_pin, mcu_isp_pin;
extern uint8_t slip_disabled; // disable slip to allow flashing of attached MCU uint8_t in_mcu_flashing; // for disabling slip during MCU flashing
void (*programmingCB)(char *buffer, short length) = NULL; void (*programmingCB)(char *buffer, short length) = NULL;
@ -124,14 +124,14 @@ telnetUnwrap(uint8_t *inBuf, int len, uint8_t state)
#ifdef SERBR_DBG #ifdef SERBR_DBG
else { os_printf("MCU isp: no pin\n"); } else { os_printf("MCU isp: no pin\n"); }
#endif #endif
slip_disabled++; in_mcu_flashing++;
break; break;
case RTS_OFF: case RTS_OFF:
if (mcu_isp_pin >= 0) { if (mcu_isp_pin >= 0) {
GPIO_OUTPUT_SET(mcu_isp_pin, 1); GPIO_OUTPUT_SET(mcu_isp_pin, 1);
os_delay_us(100L); os_delay_us(100L);
} }
if (slip_disabled > 0) slip_disabled--; if (in_mcu_flashing > 0) in_mcu_flashing--;
break; break;
} }
state = TN_end; state = TN_end;
@ -222,7 +222,7 @@ serbridgeRecvCb(void *arg, char *data, unsigned short len)
//if (mcu_isp_pin >= 0) GPIO_OUTPUT_SET(mcu_isp_pin, 1); //if (mcu_isp_pin >= 0) GPIO_OUTPUT_SET(mcu_isp_pin, 1);
os_delay_us(1000L); // wait a millisecond before writing to the UART below os_delay_us(1000L); // wait a millisecond before writing to the UART below
conn->conn_mode = cmPGM; conn->conn_mode = cmPGM;
slip_disabled++; // disable SLIP so it doesn't interfere with flashing in_mcu_flashing++; // disable SLIP so it doesn't interfere with flashing
#ifdef SKIP_AT_RESET #ifdef SKIP_AT_RESET
serledFlash(50); // short blink on serial LED serledFlash(50); // short blink on serial LED
return; return;
@ -355,7 +355,7 @@ serbridgeUartCb(char *buf, short length)
{ {
if (programmingCB) { if (programmingCB) {
programmingCB(buf, length); programmingCB(buf, length);
} else if (!flashConfig.slip_enable || slip_disabled > 0) { } else if (!flashConfig.slip_enable || in_mcu_flashing > 0) {
//os_printf("SLIP: disabled got %d\n", length); //os_printf("SLIP: disabled got %d\n", length);
console_process(buf, length); console_process(buf, length);
} else { } else {
@ -504,3 +504,8 @@ serbridgeInit(int port1, int port2)
espconn_tcp_set_max_con_allow(&serbridgeConn2, MAX_CONN); espconn_tcp_set_max_con_allow(&serbridgeConn2, MAX_CONN);
espconn_regist_time(&serbridgeConn2, SER_BRIDGE_TIMEOUT, 0); espconn_regist_time(&serbridgeConn2, SER_BRIDGE_TIMEOUT, 0);
} }
int ICACHE_FLASH_ATTR serbridgeInMCUFlashing()
{
return in_mcu_flashing;
}

@ -36,6 +36,8 @@ void ICACHE_FLASH_ATTR serbridgeInitPins(void);
void ICACHE_FLASH_ATTR serbridgeUartCb(char *buf, short len); void ICACHE_FLASH_ATTR serbridgeUartCb(char *buf, short len);
void ICACHE_FLASH_ATTR serbridgeReset(); void ICACHE_FLASH_ATTR serbridgeReset();
int ICACHE_FLASH_ATTR serbridgeInMCUFlashing();
// callback when receiving UART chars when in programming mode // callback when receiving UART chars when in programming mode
extern void (*programmingCB)(char *buffer, short length); extern void (*programmingCB)(char *buffer, short length);

@ -13,8 +13,6 @@
#define DBG(format, ...) do { } while(0) #define DBG(format, ...) do { } while(0)
#endif #endif
uint8_t slip_disabled; // temporarily disable slip to allow flashing of attached MCU
extern void ICACHE_FLASH_ATTR console_process(char *buf, short len); extern void ICACHE_FLASH_ATTR console_process(char *buf, short len);
// This SLIP parser tries to conform to RFC 1055 https://tools.ietf.org/html/rfc1055. // This SLIP parser tries to conform to RFC 1055 https://tools.ietf.org/html/rfc1055.

@ -44,8 +44,8 @@ static void uart0_rx_intr_handler(void *para);
* Parameters : uart_no, use UART0 or UART1 defined ahead * Parameters : uart_no, use UART0 or UART1 defined ahead
* Returns : NONE * Returns : NONE
*******************************************************************************/ *******************************************************************************/
static void ICACHE_FLASH_ATTR void ICACHE_FLASH_ATTR
uart_config(uint8 uart_no) uart_config(uint8 uart_no, UartBautRate baudrate, uint32 conf0)
{ {
if (uart_no == UART1) { if (uart_no == UART1) {
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_U1TXD_BK); PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_U1TXD_BK);
@ -59,14 +59,11 @@ uart_config(uint8 uart_no)
//PIN_PULLUP_DIS (PERIPHS_IO_MUX_U0RXD_U); //PIN_PULLUP_DIS (PERIPHS_IO_MUX_U0RXD_U);
} }
uart_div_modify(uart_no, UART_CLK_FREQ / UartDev.baut_rate); uart_div_modify(uart_no, UART_CLK_FREQ / baudrate);
if (uart_no == UART1) //UART 1 always 8 N 1 if (uart_no == UART1) //UART 1 always 8 N 1
WRITE_PERI_REG(UART_CONF0(uart_no), conf0 = CALC_UARTMODE(EIGHT_BITS, NONE_BITS, ONE_STOP_BIT);
CALC_UARTMODE(EIGHT_BITS, NONE_BITS, ONE_STOP_BIT)); WRITE_PERI_REG(UART_CONF0(uart_no), conf0);
else
WRITE_PERI_REG(UART_CONF0(uart_no),
CALC_UARTMODE(UartDev.data_bits, UartDev.parity, UartDev.stop_bits));
//clear rx and tx fifo,not ready //clear rx and tx fifo,not ready
SET_PERI_REG_MASK(UART_CONF0(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST); SET_PERI_REG_MASK(UART_CONF0(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST);
@ -267,13 +264,11 @@ uart0_baud(int rate) {
* Returns : NONE * Returns : NONE
*******************************************************************************/ *******************************************************************************/
void ICACHE_FLASH_ATTR void ICACHE_FLASH_ATTR
uart_init(UartBautRate uart0_br, UartBautRate uart1_br) uart_init(uint32 conf0, UartBautRate uart0_br, UartBautRate uart1_br)
{ {
// rom use 74880 baut_rate, here reinitialize // rom use 74880 baut_rate, here reinitialize
UartDev.baut_rate = uart0_br; uart_config(UART0, uart0_br, conf0);
uart_config(UART0); uart_config(UART1, uart1_br, conf0);
UartDev.baut_rate = uart1_br;
uart_config(UART1);
for (int i=0; i<4; i++) uart_tx_one_char(UART1, '\n'); for (int i=0; i<4; i++) uart_tx_one_char(UART1, '\n');
for (int i=0; i<4; i++) uart_tx_one_char(UART0, '\n'); for (int i=0; i<4; i++) uart_tx_one_char(UART0, '\n');
ETS_UART_INTR_ENABLE(); ETS_UART_INTR_ENABLE();
@ -295,10 +290,3 @@ uart_add_recv_cb(UartRecv_cb cb) {
os_printf("UART: max cb count exceeded\n"); os_printf("UART: max cb count exceeded\n");
} }
void ICACHE_FLASH_ATTR
uart_reattach()
{
uart_init(BIT_RATE_74880, BIT_RATE_74880);
// ETS_UART_INTR_ATTACH(uart_rx_intr_handler_ssc, &(UartDev.rcv_buff));
// ETS_UART_INTR_ENABLE();
}

@ -8,7 +8,7 @@ typedef void (*UartRecv_cb)(char *buf, short len);
// Initialize UARTs to the provided baud rates (115200 recommended). This also makes the os_printf // Initialize UARTs to the provided baud rates (115200 recommended). This also makes the os_printf
// calls use uart1 for output (for debugging purposes) // calls use uart1 for output (for debugging purposes)
void uart_init(UartBautRate uart0_br, UartBautRate uart1_br); void uart_init(uint32 conf0, UartBautRate uart0_br, UartBautRate uart1_br);
// Transmit a buffer of characters on UART0 // Transmit a buffer of characters on UART0
void uart0_tx_buffer(char *buf, uint16 len); void uart0_tx_buffer(char *buf, uint16 len);
@ -27,5 +27,6 @@ void uart_add_recv_cb(UartRecv_cb cb);
uint16_t uart0_rx_poll(char *buff, uint16_t nchars, uint32_t timeout_us); uint16_t uart0_rx_poll(char *buff, uint16_t nchars, uint32_t timeout_us);
void uart0_baud(int rate); void uart0_baud(int rate);
void uart_config(uint8 uart_no, UartBautRate baudrate, uint32 conf0);
#endif /* __UART_H__ */ #endif /* __UART_H__ */

@ -70,6 +70,7 @@ enum syslog_facility {
#define REG_READ(_r) (*(volatile uint32 *)(_r)) #define REG_READ(_r) (*(volatile uint32 *)(_r))
#define WDEV_NOW() REG_READ(0x3ff20c00) #define WDEV_NOW() REG_READ(0x3ff20c00)
// This variable disappeared from lwip in SDK 2.0...
extern uint32_t realtime_stamp; // 1sec NTP ticker extern uint32_t realtime_stamp; // 1sec NTP ticker
typedef struct syslog_host_t syslog_host_t; typedef struct syslog_host_t syslog_host_t;

@ -0,0 +1,454 @@
#include "web-server.h"
#include <espconn.h>
#include "espfs.h"
#include "config.h"
#include "cgi.h"
#include "cmd.h"
#include "serbridge.h"
// the file is responsible for handling user defined web-pages
// - collects HTML files from user image, shows them on the left frame
// - handles JSON data coming from the browser
// - handles SLIP messages coming from MCU
#define WEB_CB "webCb"
#define MAX_ARGUMENT_BUFFER_SIZE 1024
struct ArgumentBuffer
{
char argBuffer[MAX_ARGUMENT_BUFFER_SIZE];
int argBufferPtr;
int numberOfArgs;
};
static char* web_server_reasons[] = {
"load", // readable name for RequestReason::LOAD
"refresh", // readable name for RequestReason::REFRESH
"button", // readable name for RequestReason::BUTTON
"submit" // readable name for RequestReason::SUBMIT
};
// this variable contains the names of the user defined pages
// this information appears at the left frame below of the built in URL-s
// format: ,"UserPage1", "/UserPage1.html", "UserPage2", "/UserPage2.html",
char * webServerPages = NULL;
char * ICACHE_FLASH_ATTR WEB_UserPages()
{
return webServerPages;
}
// generates the content of webServerPages variable (called at booting/web page uploading)
void ICACHE_FLASH_ATTR WEB_BrowseFiles()
{
char buffer[1024];
buffer[0] = 0;
if( espFsIsValid( userPageCtx ) )
{
EspFsIterator it;
espFsIteratorInit(userPageCtx, &it);
while( espFsIteratorNext(&it) )
{
int nameLen = os_strlen(it.name);
if( nameLen >= 6 )
{
// fetch HTML files
if( os_strcmp( it.name + nameLen-5, ".html" ) == 0 )
{
int slashPos = nameLen - 5;
// chop path and .html from the name
while( slashPos > 0 && it.name[slashPos-1] != '/' )
slashPos--;
// here we check buffer overrun
int maxLen = 10 + os_strlen( it.name ) + (nameLen - slashPos -5);
if( maxLen >= sizeof(buffer) )
break;
os_strcat(buffer, ", \"");
int writePos = os_strlen(buffer);
for( int i=slashPos; i < nameLen-5; i++ )
buffer[writePos++] = it.name[i];
buffer[writePos] = 0; // terminating zero
os_strcat(buffer, "\", \"/");
os_strcat(buffer, it.name);
os_strcat(buffer, "\"");
}
}
}
}
if( webServerPages != NULL )
os_free( webServerPages );
int len = os_strlen(buffer) + 1;
webServerPages = (char *)os_malloc( len );
os_memcpy( webServerPages, buffer, len );
}
// initializer
void ICACHE_FLASH_ATTR WEB_Init()
{
espFsInit(userPageCtx, (void *)getUserPageSectionStart(), ESPFS_FLASH);
if( espFsIsValid( userPageCtx ) )
os_printf("Valid user file system found!\n");
else
os_printf("No user file system found!\n");
WEB_BrowseFiles(); // collect user defined HTML files
}
// initializes the argument buffer
static void WEB_argInit(struct ArgumentBuffer * argBuffer)
{
argBuffer->numberOfArgs = 0;
argBuffer->argBufferPtr = 0;
}
// adds an argument to the argument buffer (returns 0 if successful)
static int WEB_addArg(struct ArgumentBuffer * argBuffer, char * arg, int argLen )
{
if( argBuffer->argBufferPtr + argLen + sizeof(int) >= MAX_ARGUMENT_BUFFER_SIZE )
return -1; // buffer overflow
os_memcpy(argBuffer->argBuffer + argBuffer->argBufferPtr, &argLen, sizeof(int));
if( argLen != 0 )
{
os_memcpy( argBuffer->argBuffer + argBuffer->argBufferPtr + sizeof(int), arg, argLen );
argBuffer->numberOfArgs++;
}
argBuffer->argBufferPtr += argLen + sizeof(int);
return 0;
}
// creates and sends a SLIP message from the argument buffer
static void WEB_sendArgBuffer(struct ArgumentBuffer * argBuffer, HttpdConnData *connData, int id, RequestReason reason)
{
cmdResponseStart(CMD_WEB_REQ_CB, id, 4 + argBuffer->numberOfArgs);
uint16_t r = (uint16_t)reason;
cmdResponseBody(&r, sizeof(uint16_t)); // 1st argument: reason
cmdResponseBody(&connData->conn->proto.tcp->remote_ip, 4); // 2nd argument: IP
cmdResponseBody(&connData->conn->proto.tcp->remote_port, sizeof(uint16_t)); // 3rd argument: port
cmdResponseBody(connData->url, os_strlen(connData->url)); // 4th argument: URL
int p = 0;
for( int j=0; j < argBuffer->numberOfArgs; j++ )
{
int argLen;
os_memcpy( &argLen, argBuffer->argBuffer + p, sizeof(int) );
char * arg = argBuffer->argBuffer + p + sizeof(int);
cmdResponseBody(arg, argLen);
p += argLen + sizeof(int);
}
cmdResponseEnd();
}
// this method processes SLIP data from MCU and converts to JSON
// this method receives JSON from the browser, sends SLIP data to MCU
static int ICACHE_FLASH_ATTR WEB_handleJSONRequest(HttpdConnData *connData)
{
if( !flashConfig.slip_enable )
{
errorResponse(connData, 400, "Slip processing is disabled!");
return HTTPD_CGI_DONE;
}
CmdCallback* cb = cmdGetCbByName( WEB_CB );
if( cb == NULL )
{
errorResponse(connData, 500, "No MCU callback is registered!");
return HTTPD_CGI_DONE;
}
if( serbridgeInMCUFlashing() )
{
errorResponse(connData, 500, "Slip disabled at uploading program onto the MCU!");
return HTTPD_CGI_DONE;
}
char reasonBuf[16];
int i;
int len = httpdFindArg(connData->getArgs, "reason", reasonBuf, sizeof(reasonBuf));
if( len < 0 )
{
errorResponse(connData, 400, "No reason specified!");
return HTTPD_CGI_DONE;
}
RequestReason reason = INVALID;
for(i=0; i < sizeof(web_server_reasons)/sizeof(char *); i++)
{
if( os_strcmp( web_server_reasons[i], reasonBuf ) == 0 )
reason = (RequestReason)i;
}
if( reason == INVALID )
{
errorResponse(connData, 400, "Invalid reason!");
return HTTPD_CGI_DONE;
}
struct ArgumentBuffer argBuffer;
WEB_argInit( &argBuffer );
switch(reason)
{
case BUTTON:
{
char id_buf[40];
int id_len = httpdFindArg(connData->getArgs, "id", id_buf, sizeof(id_buf));
if( id_len <= 0 )
{
errorResponse(connData, 400, "No button ID specified!");
return HTTPD_CGI_DONE;
}
if( WEB_addArg(&argBuffer, id_buf, id_len) )
{
errorResponse(connData, 400, "Post too large!");
return HTTPD_CGI_DONE;
}
}
break;
case SUBMIT:
{
if( connData->post->received < connData->post->len )
{
errorResponse(connData, 400, "Post too large!");
return HTTPD_CGI_DONE;
}
int bptr = 0;
while( bptr < connData->post->len )
{
char * line = connData->post->buff + bptr;
char * eo = os_strchr(line, '&' );
if( eo != NULL )
{
*eo = 0;
bptr = eo - connData->post->buff + 1;
}
else
{
eo = line + os_strlen( line );
bptr = connData->post->len;
}
int len = os_strlen(line);
while( len >= 1 && ( line[len-1] == '\r' || line[len-1] == '\n' ))
len--;
line[len] = 0;
char * val = os_strchr(line, '=');
if( val != NULL )
{
*val = 0;
char * name = line;
int vblen = os_strlen(val+1) * 2;
char value[vblen];
httpdUrlDecode(val+1, strlen(val+1), value, vblen);
int namLen = os_strlen(name);
int valLen = os_strlen(value);
char arg[namLen + valLen + 3];
int argPtr = 0;
arg[argPtr++] = (char)WEB_STRING;
os_strcpy( arg + argPtr, name );
argPtr += namLen;
arg[argPtr++] = 0;
os_strcpy( arg + argPtr, value );
argPtr += valLen;
if( WEB_addArg(&argBuffer, arg, argPtr) )
{
errorResponse(connData, 400, "Post too large!");
return HTTPD_CGI_DONE;
}
}
}
}
break;
case LOAD:
case REFRESH:
default:
break;
}
if( WEB_addArg(&argBuffer, NULL, 0) )
{
errorResponse(connData, 400, "Post too large!");
return HTTPD_CGI_DONE;
}
os_printf("Web callback to MCU: %s\n", reasonBuf);
WEB_sendArgBuffer(&argBuffer, connData, (uint32_t)cb->callback, reason );
if( reason == SUBMIT )
{
httpdStartResponse(connData, 204);
httpdEndHeaders(connData);
return HTTPD_CGI_DONE;
}
return HTTPD_CGI_MORE;
}
// this method receives SLIP data from MCU sends JSON to the browser
static int ICACHE_FLASH_ATTR WEB_handleMCUResponse(HttpdConnData *connData, CmdRequest * response)
{
char jsonBuf[1500];
int jsonPtr = 0;
jsonBuf[jsonPtr++] = '{';
int c = 2;
while( c++ < cmdGetArgc(response) )
{
int len = cmdArgLen(response);
char buf[len+1];
buf[len] = 0;
cmdPopArg(response, buf, len);
if(len == 0)
break; // last argument
if( c > 3 ) // skip the first argument
jsonBuf[jsonPtr++] = ',';
if( jsonPtr + 20 + len > sizeof(jsonBuf) )
{
errorResponse(connData, 500, "Response too large!");
return HTTPD_CGI_DONE;
}
WebValueType type = (WebValueType)buf[0];
int nameLen = os_strlen(buf+1);
jsonBuf[jsonPtr++] = '"';
os_memcpy(jsonBuf + jsonPtr, buf + 1, nameLen);
jsonPtr += nameLen;
jsonBuf[jsonPtr++] = '"';
jsonBuf[jsonPtr++] = ':';
char * value = buf + 2 + nameLen;
switch(type)
{
case WEB_NULL:
os_memcpy(jsonBuf + jsonPtr, "null", 4);
jsonPtr += 4;
break;
case WEB_INTEGER:
{
int v;
os_memcpy( &v, value, 4);
char intbuf[20];
os_sprintf(intbuf, "%d", v);
os_strcpy(jsonBuf + jsonPtr, intbuf);
jsonPtr += os_strlen(intbuf);
}
break;
case WEB_BOOLEAN:
if( *value ) {
os_memcpy(jsonBuf + jsonPtr, "true", 4);
jsonPtr += 4;
} else {
os_memcpy(jsonBuf + jsonPtr, "false", 5);
jsonPtr += 5;
}
break;
case WEB_FLOAT:
{
float f;
os_memcpy( &f, value, 4);
char intbuf[20];
os_sprintf(intbuf, "%f", f);
os_strcpy(jsonBuf + jsonPtr, intbuf);
jsonPtr += os_strlen(intbuf);
}
break;
case WEB_STRING:
jsonBuf[jsonPtr++] = '"';
while(*value)
{
if( *value == '\\' || *value == '"' )
jsonBuf[jsonPtr++] = '\\';
jsonBuf[jsonPtr++] = *(value++);
}
jsonBuf[jsonPtr++] = '"';
break;
case WEB_JSON:
os_memcpy(jsonBuf + jsonPtr, value, len - 2 - nameLen);
jsonPtr += len - 2 - nameLen;
break;
}
}
jsonBuf[jsonPtr++] = '}';
noCacheHeaders(connData, 200);
httpdHeader(connData, "Content-Type", "application/json");
char cl[16];
os_sprintf(cl, "%d", jsonPtr);
httpdHeader(connData, "Content-Length", cl);
httpdEndHeaders(connData);
httpdSend(connData, jsonBuf, jsonPtr);
return HTTPD_CGI_DONE;
}
// this method is responsible for the MCU <==JSON==> Browser communication
int ICACHE_FLASH_ATTR WEB_CgiJsonHook(HttpdConnData *connData)
{
if (connData->conn==NULL) return HTTPD_CGI_DONE; // Connection aborted. Clean up.
void * cgiData = connData->cgiData;
if( cgiData == NULL )
{
connData->cgiData = (void *)1; // indicate, that request was processed
return WEB_handleJSONRequest(connData);
}
if( connData->cgiResponse != NULL ) // data from MCU
return WEB_handleMCUResponse(connData, (CmdRequest *)(connData->cgiResponse));
return HTTPD_CGI_MORE;
}
// this method is called when MCU transmits WEB_DATA command
void ICACHE_FLASH_ATTR WEB_Data(CmdPacket *cmd)
{
CmdRequest req;
cmdRequest(&req, cmd);
if (cmdGetArgc(&req) < 2) return;
uint8_t ip[4];
cmdPopArg(&req, ip, 4); // pop the IP address
uint16_t port;
cmdPopArg(&req, &port, 2); // pop the HTTP port
HttpdConnData * conn = httpdLookUpConn(ip, port); // look up connection based on IP/port
if( conn != NULL && conn->cgi == WEB_CgiJsonHook ) // make sure that the right CGI handler is configured
httpdSetCGIResponse( conn, &req );
else
os_printf("WEB_DATA ignored as no valid HTTP connection found!\n");
}

@ -0,0 +1,37 @@
#ifndef WEB_SERVER_H
#define WEB_SERVER_H
#include <esp8266.h>
#include "httpd.h"
#include "cmd.h"
typedef enum
{
LOAD=0, // loading web-page content at the first time
REFRESH, // loading web-page subsequently
BUTTON, // HTML button pressed
SUBMIT, // HTML form is submitted
INVALID=-1,
} RequestReason;
typedef enum
{
WEB_STRING=0, // the value is string
WEB_NULL, // the value is NULL
WEB_INTEGER, // the value is integer
WEB_BOOLEAN, // the value is boolean
WEB_FLOAT, // the value is float
WEB_JSON // the value is JSON data
} WebValueType;
void WEB_Init();
char * WEB_UserPages();
int WEB_CgiJsonHook(HttpdConnData *connData);
void WEB_Data(CmdPacket *cmd);
#endif /* WEB_SERVER_H */
Loading…
Cancel
Save