mirror of https://github.com/jeelabs/esp-link.git
Signed-off-by: beegee-tokyo <bernd@giesecke.tk>pull/188/head
parent
87ea456883
commit
0654c1d038
@ -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 |
@ -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 |
||||
|
@ -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; |
||||
} |
@ -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 */ |
@ -1,19 +1,42 @@ |
||||
#ifndef ESPFS_H |
||||
#define ESPFS_H |
||||
|
||||
#include "espfsformat.h" |
||||
|
||||
typedef enum { |
||||
ESPFS_INIT_RESULT_OK, |
||||
ESPFS_INIT_RESULT_NO_IMAGE, |
||||
ESPFS_INIT_RESULT_BAD_ALIGN, |
||||
} 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 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); |
||||
EspFsFile *espFsOpen(char *fileName); |
||||
EspFsInitResult espFsInit(EspFsContext *ctx, void *flashAddress, EspFsSource source); |
||||
EspFsFile *espFsOpen(EspFsContext *ctx, char *fileName); |
||||
int espFsIsValid(EspFsContext *ctx); |
||||
int espFsFlags(EspFsFile *fh); |
||||
int espFsRead(EspFsFile *fh, char *buff, int len); |
||||
void espFsClose(EspFsFile *fh); |
||||
|
||||
void espFsIteratorInit(EspFsContext *ctx, EspFsIterator *iterator); |
||||
int espFsIteratorNext(EspFsIterator *iterator); |
||||
|
||||
#endif |
@ -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; } |
||||
} |
||||
); |
||||
} |
@ -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> |
@ -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 */ |
@ -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…
Reference in new issue