Use low-mem web server to save RAM for playback

Instead of ESP8266WebServer, which is something of a RAM hog and has
extensive use of Strings and allocations, use a simpler one with no
dynamic memory allocations at all, borrowed from PsychoPlug
https://github.com/earlephilhower/psychoplug.
This commit is contained in:
Earle F. Philhower, III committed 2017-12-12 17:06:21 -08:00
1 parent cce9ceaffd
commit 94489c005a
3 files changed
+592 -124

No files matched your search

+205 -124
View File
@@ -25,7 +25,9 @@
#include "AudioGeneratorMP3.h"
#include "AudioGeneratorAAC.h"
#include "AudioOutputI2SDAC.h"
#include "ESP8266WebServer.h"
// Custom web server that doesn't need much RAM
#include "web.h"
// To run, set your ESP8266 build to 160MHz, update the SSID info, and upload.
@@ -33,27 +35,24 @@
const char *SSID = "....";
const char *PASSWORD = "....";
ESP8266WebServer server(80);
WiFiServer server(80);
AudioGenerator *decoder;
AudioFileSourceICYStream *file;
AudioFileSourceBuffer *buff;
AudioOutputI2SDAC *out;
AudioGenerator *decoder = NULL;
AudioFileSourceICYStream *file = NULL;
AudioFileSourceBuffer *buff = NULL;
AudioOutputI2SDAC *out = NULL;
int volume = 100;
char title[64];
char url[64];
char status[64];
bool newUrl = false;
bool isAAC = false;
// C++11 multiline string constants are neato...
const char INDEX[] PROGMEM = R"KEWL(<html>
static const char HEAD[] PROGMEM = R"KEWL(
<head>
<title>ESP8266 Web Radio</title>
</head>
<body>
ESP8266 Web Radio!
<hr>
Currently Playing: <span id="titlespan">%s</span><br>
<script type="text/javascript">
function updateTitle() {
var x = new XMLHttpRequest();
@@ -62,183 +61,194 @@ Currently Playing: <span id="titlespan">%s</span><br>
x.send();
}
setTimeout(updateTitle, 1000);
</script>
Volume: <input type="range" name="vol" min="1" max="150" steps="10" value="%d" onchange="showValue(this.value)"/> <span id="volspan">%d</span>%%
<script type="text/javascript">
function showValue(n) {
document.getElementById("volspan").innerHTML=n;
var x = new XMLHttpRequest();
x.open("GET", "setvol?vol="+n);
x.send();
}
</script>
<hr>
Status: <span id="statusspan">%s</span>
<script type="text/javascript">
function updateTitle() {
var x = new XMLHttpRequest();
function updateTitle() {var x = new XMLHttpRequest();
x.open("GET", "status");
x.onload = function() { document.getElementById("statusspan").innerHTML=x.responseText; setTimeout(updateStatus, 5000); }
x.send();
}
setTimeout(updateStatus, 2000);
</script>
</head>)KEWL";
static const char BODY[] PROGMEM = R"KEWL(
<body>
ESP8266 Web Radio!
<hr>
<form action="changeurl" method="POST">
Currently Playing: <span id="titlespan">%s</span><br>
Volume: <input type="range" name="vol" min="1" max="150" steps="10" value="%d" onchange="showValue(this.value)"/> <span id="volspan">%d</span>%%
<hr>
Status: <span id="statusspan">%s</span>
<hr>
<form action="changeurl" method="GET">
Current URL: %s<br>
Change URL: <input type="text" name="url">
<select name="type"><option value="mp3">MP3</option><option value="aac">AAC</option></select>
<input type="submit" value="Change"></form>
</body>
</html>)KEWL";
<form action="stop" method="POST"><input type="submit" value="Stop"></form>
</body>)KEWL";
// Static spot to store the web sprintf's
void IndexHTML()
void HandleIndex(WiFiClient *client)
{
int sz=1500;
char *webbuff = (char*)malloc(sz);
snprintf_P(webbuff, sz, INDEX, title, volume, volume, status, url);
webbuff[sz-1-1] = 0;
server.send(200, "text/html", webbuff );
free(webbuff);
char buff[sizeof(BODY) + 64*3 + 3*2];
Serial.printf_P(PSTR("Sending INDEX...Free mem=%d\n"), ESP.getFreeHeap());
WebHeaders(client, NULL);
WebPrintf(client, DOCTYPE);
client->write_P( PSTR("<html>"), 6 );
client->write_P( HEAD, strlen_P(HEAD) );
sprintf_P(buff, BODY, title, volume, volume, status, url);
client->write(buff, strlen(buff) );
client->write_P( PSTR("</html>"), 7 );
Serial.printf_P(PSTR("Sent INDEX...Free mem=%d\n"), ESP.getFreeHeap());
}
void Send404()
void HandleStatus(WiFiClient *client)
{
server.send(404, "text/plain", "404: Not Found");
WebHeaders(client, NULL);
client->write(status, strlen(status));
}
void GetTitle()
void HandleTitle(WiFiClient *client)
{
server.send(200, "text/plain", title);
WebHeaders(client, NULL);
client->write(title, strlen(title));
}
void GetStatus()
void HandleVolume(WiFiClient *client, char *params)
{
server.send(200, "text/plain", status);
}
void SetVol()
{
if (server.hasArg("vol")) {
int vol = 100;
int ret = sscanf(server.arg("vol").c_str(), "%d", &vol);
if (ret==1) {
if (vol < 0) vol = 0;
if (vol > 150) vol = 150;
if (out) out->SetGain(((float)vol)/100.0);
volume = vol;
Serial.printf("Set volume: %d\n", volume);
server.sendHeader("Location", "/", true);
server.send(301, "text/plain", "");
}
char *namePtr;
char *valPtr;
while (ParseParam(&params, &namePtr, &valPtr)) {
ParamInt("vol", volume);
}
Serial.printf_P(PSTR("Set volume: %d\n"), volume);
RedirectToIndex(client);
}
void ChangeURL()
void HandleChangeURL(WiFiClient *client, char *params)
{
if (server.hasArg("url") && server.hasArg("type")) {
// Stop and free existing ones
if (decoder) {
decoder->stop();
delete decoder;
}
if (buff) {
buff->close();
delete buff;
}
if (out) {
out->stop();
delete out;
}
if (file) {
file->close();
delete file;
}
char *namePtr;
char *valPtr;
char newURL[64];
char newType[4];
strncpy(url, server.arg("url").c_str(), sizeof(url)-1);
newURL[0] = 0;
newType[0] = 0;
while (ParseParam(&params, &namePtr, &valPtr)) {
ParamText("url", newURL);
ParamText("type", newType);
}
if (newURL[0] && newType[0]) {
newUrl = true;
strncpy(url, newURL, sizeof(url)-1);
url[sizeof(url)-1] = 0;
file = new AudioFileSourceICYStream(server.arg("url").c_str());
file->RegisterMetadataCB(MDCallback, (void*)"ICY");
buff = new AudioFileSourceBuffer(file, 2048);
buff->RegisterStatusCB(StatusCallback, (void*)"buffer");
out = new AudioOutputI2SDAC();
if (!strcmp(server.arg("type").c_str(), "aac")) {
decoder = new AudioGeneratorAAC();
if (!strcmp_P(newType, PSTR("aac"))) {
isAAC = true;
} else {
decoder = new AudioGeneratorMP3();
isAAC = false;
}
decoder->RegisterStatusCB(StatusCallback, (void*)"mp3");
decoder->begin(buff, out);
out->SetGain(((float)volume)/100.0);
server.sendHeader("Location", "/", true);
server.send(301, "text/plain", "");
strcpy_P(status, PSTR("Changing URL..."));
Serial.printf_P("Changed URL to: %s(%s)\n", url, newType);
RedirectToIndex(client);
} else {
Send404(); // Need to specify those params or you're in error!
WebError(client, 404, NULL, false);
}
}
void RedirectToIndex(WiFiClient *client)
{
WebError(client, 301, PSTR("Location: /\r\n"), true);
}
void HandleStop(WiFiClient *client)
{
Serial.printf_P(PSTR("HandleStop()\n"));
if (decoder) {
decoder->stop();
delete decoder;
decoder = NULL;
}
if (out) {
out->stop();
delete out;
out = NULL;
}
if (buff) {
buff->close();
delete buff;
buff = NULL;
}
if (file) {
file->close();
delete file;
file = NULL;
}
strcpy_P(status, PSTR("Stopped"));
RedirectToIndex(client);
}
void MDCallback(void *cbData, const char *type, bool isUnicode, Stream *stream)
{
const char *ptr = reinterpret_cast<const char *>(cbData);
(void) isUnicode; // Punt this ball for now
(void) ptr;
if (strstr(type, "Title")) {
strncpy(title, stream->readString().c_str(), sizeof(title));
title[sizeof(title)-1] = 0;
// Serial.printf("Set title: %s\n", title);
} else {
// Serial.printf("METADATA(%s) '%s' = '%s'\n", ptr, type, stream->readString().c_str());
// Who knows what yo do? Not me!
}
// Serial.flush();
}
void StatusCallback(void *cbData, int code, const char *string)
{
const char *ptr = reinterpret_cast<const char *>(cbData);
// Serial.printf("STATUS(%s) '%d' = '%s'\n", ptr, code, string);
(void) code;
(void) ptr;
strncpy(status, string, sizeof(status)-1);
status[sizeof(status)-1] = 0;
// Serial.flush();
}
void setup()
{
Serial.begin(115200);
delay(1000);
Serial.println("Connecting to WiFi");
WiFi.disconnect();
WiFi.softAPdisconnect(true);
delay(1000);
Serial.printf_P(PSTR("Connecting to WiFi\n"));
// WiFi.disconnect();
// WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_STA);
WiFi.hostname("melody");
// WiFi.hostname("melody");
byte zero[] = {0,0,0,0};
WiFi.config(zero, zero, zero, zero);
// byte zero[] = {0,0,0,0};
// WiFi.config(zero, zero, zero, zero);
WiFi.begin(SSID, PASSWORD);
// Try forever
while (WiFi.status() != WL_CONNECTED) {
Serial.println("...Connecting to WiFi");
Serial.printf_P(PSTR("...Connecting to WiFi\n"));
delay(1000);
}
Serial.println("Connected\n");
Serial.printf_P(PSTR("Connected\n"));
Serial.print("Go to http://");
Serial.printf_P(PSTR("Go to http://"));
Serial.print(WiFi.localIP());
Serial.println("/ to control the web radio.");
Serial.printf_P(PSTR("/ to control the web radio.\n"));
server.on("/", HTTP_GET, IndexHTML);
server.on("/setvol", HTTP_GET, SetVol);
server.on("/title", HTTP_GET, GetTitle);
server.on("/status", HTTP_GET, GetStatus);
server.on("/changeurl", HTTP_POST, ChangeURL);
server.onNotFound(Send404);
server.begin();
strcpy(url, "none");
strcpy(status, "OK");
strcpy(title, "Idle");
strcpy_P(url, PSTR("none"));
strcpy_P(status, PSTR("OK"));
strcpy_P(title, PSTR("Idle"));
file = NULL;
buff = NULL;
@@ -246,28 +256,99 @@ void setup()
decoder = NULL;
}
void StartNewURL()
{
Serial.printf_P(PSTR("Changing URL to: "));
Serial.println(url);
newUrl = false;
// Stop and free existing ones
if (decoder) {
decoder->stop();
delete decoder;
}
if (buff) {
buff->close();
delete buff;
}
if (out) {
out->stop();
delete out;
}
if (file) {
file->close();
delete file;
}
file = new AudioFileSourceICYStream(url);
file->RegisterMetadataCB(MDCallback, NULL);
buff = new AudioFileSourceBuffer(file, 1500);
buff->RegisterStatusCB(StatusCallback, NULL);
out = new AudioOutputI2SDAC();
decoder = isAAC ? (AudioGenerator*) new AudioGeneratorAAC() : (AudioGenerator*) new AudioGeneratorMP3();
decoder->RegisterStatusCB(StatusCallback, NULL);
decoder->begin(file, out);
out->SetGain(((float)volume)/100.0);
if (!decoder->isRunning()) {
Serial.printf_P(PSTR("Can't connect to URL"));
decoder->stop();
out->stop();
buff->close();
delete decoder;
delete file;
delete buff;
delete out;
decoder = NULL;
strcpy_P(status, PSTR("Unable to connect to URL"));
}
}
void loop()
{
static int lastms = 0;
server.handleClient();
if (millis()-lastms > 1000) {
lastms = millis();
Serial.printf("Running for %d seconds...Free mem=%d\n", lastms/1000, ESP.getFreeHeap());
//Serial.flush();
Serial.printf_P(PSTR("Running for %d seconds...Free mem=%d\n"), lastms/1000, ESP.getFreeHeap());
}
if (newUrl) {
StartNewURL();
}
if (!decoder) return;
if (decoder->isRunning()) {
if (decoder && decoder->isRunning()) {
strcpy(status, "OK"); // By default we're OK unless the decoder says otherwise
if (!decoder->loop()) {
Serial.println("Stopping decoder");
Serial.printf_P(PSTR("Stopping decoder"));
decoder->stop();
strcpy(title, "Stopped");
strcpy_P(title, PSTR("Stopped"));
}
} else {
// Nothing here
}
char *reqUrl;
char *params;
WiFiClient client = server.available();
if (client && WebReadRequest(&client, &reqUrl, &params)) {
Serial.printf_P(PSTR("URL: '%s'\n"), reqUrl);
if (IsIndexHTML(reqUrl)) {
HandleIndex(&client);
} else if (!strcmp_P(reqUrl, PSTR("stop"))) {
HandleStop(&client);
} else if (!strcmp_P(reqUrl, PSTR("status"))) {
HandleStatus(&client);
} else if (!strcmp_P(reqUrl, PSTR("title"))) {
HandleTitle(&client);
} else if (!strcmp_P(reqUrl, PSTR("setvol"))) {
HandleVolume(&client, params);
} else if (!strcmp_P(reqUrl, PSTR("changeurl"))) {
HandleChangeURL(&client, params);
} else {
WebError(&client, 404, NULL, false);
}
}
if (client) {
client.flush();
client.stop();
}
}
+323
View File
@@ -0,0 +1,323 @@
/*
PsychoPlug
ESP8266 based remote outlet with standalone timer and MQTT integration
Copyright (C) 2017 Earle F. Philhower, III
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "web.h"
#define LogPrintf(fmt, ...) { Serial.printf_P(PSTR(fmt), ## __VA_ARGS__); }
// Web request line (URL, PARAMs parsed in-line)
static char reqBuff[384];
void WebPrintError(WiFiClient *client, int code)
{
switch(code) {
case 301: WebPrintf(client, "301 Moved Permanently"); break;
case 400: WebPrintf(client, "400 Bad Request"); break;
case 401: WebPrintf(client, "401 Unauthorized"); break;
case 404: WebPrintf(client, "404 Not Found"); break;
case 405: WebPrintf(client, "405 Method Not Allowed"); break;
default: WebPrintf(client, "500 Server Error"); break;
}
}
void WebError(WiFiClient *client, int code, const char *headers, bool usePMEM)
{
LogPrintf("+WebError: Begin, free=%d\n", ESP.getFreeHeap());
LogPrintf(" Sending headers...\n");
WebPrintf(client, "HTTP/1.1 %d\r\n", code);
WebPrintf(client, "Server: PsychoPlug\r\n");
WebPrintf(client, "Content-type: text/html\r\n");
WebPrintf(client, "Cache-Control: no-cache, no-store, must-revalidate\r\n");
WebPrintf(client, "Pragma: no-cache\r\n");
WebPrintf(client, "Expires: 0\r\n");
WebPrintf(client, "Connection: close\r\n");
LogPrintf("+WebError: Writing error headers: %08x\n", headers);
if (headers) {
if (!usePMEM) {
WebPrintf(client, "%s", headers);
} else {
WebPrintfPSTR(client, headers);
}
}
WebPrintf(client, "\r\n\r\n");
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>");
WebPrintError(client, code);
WebPrintf(client, "</title>" ENCODING "</head>\n");
WebPrintf(client, "<body><h1>");
WebPrintError(client, code);
WebPrintf(client, "</h1></body></html>\r\n");
LogPrintf("-WebError\n");
}
void WebHeaders(WiFiClient *client, PGM_P /*const char **/headers)
{
WebPrintf(client, "HTTP/1.1 200 OK\r\n");
WebPrintf(client, "Server: PsychoPlug\r\n");
WebPrintf(client, "Content-type: text/html\r\n");
WebPrintf(client, "Cache-Control: no-cache, no-store, must-revalidate\r\n");
WebPrintf(client, "Pragma: no-cache\r\n");
WebPrintf(client, "Connection: close\r\n");
WebPrintf(client, "Expires: 0\r\n");
if (headers) {
WebPrintfPSTR(client, headers);
}
WebPrintf(client, "\r\n");
}
// In-place decoder, overwrites source with decoded values. Needs 0-termination on input
// Try and keep memory needs low, speed not critical
static uint8_t b64lut(uint8_t i)
{
if (i >= 'A' && i <= 'Z') return i - 'A';
if (i >= 'a' && i <= 'z') return i - 'a' + 26;
if (i >= '0' && i <= '9') return i - '0' + 52;
if (i == '-') return 62;
if (i == '_') return 63;
else return 64;// sentinel
}
void Base64Decode(char *str)
{
char *dest;
dest = str;
if (strlen(str)%4) return; // Not multiple of 4 == error
while (*str) {
uint8_t a = b64lut(*(str++));
uint8_t b = b64lut(*(str++));
uint8_t c = b64lut(*(str++));
uint8_t d = b64lut(*(str++));
*(dest++) = (a << 2) | ((b & 0x30) >> 4);
if (c == 64) break;
*(dest++) = ((b & 0x0f) << 4) | ((c & 0x3c) >> 2);
if (d == 64) break;
*(dest++) = ((c & 0x03) << 6) | d;
}
*dest = 0; // Terminate the string
}
void URLDecode(char *ptr)
{
while (*ptr) {
if (*ptr == '+') {
*ptr = ' ';
} else if (*ptr == '%') {
if (*(ptr+1) && *(ptr+2)) {
byte a = *(ptr + 1);
byte b = *(ptr + 2);
if (a>='0' && a<='9') a -= '0';
else if (a>='a' && a<='f') a = a - 'a' + 10;
else if (a>='A' && a<='F') a = a - 'A' + 10;
if (b>='0' && b<='9') b -= '0';
else if (b>='a' && b<='f') b = b - 'a' + 10;
else if (b>='A' && b<='F') b = b - 'A' + 10;
*ptr = ((a&0x0f)<<4) | (b&0x0f);
// Safe strcpy the rest of the string back
char *p1 = ptr + 1;
char *p2 = ptr + 3;
while (*p2) { *p1 = *p2; p1++; p2++; }
*p1 = 0;
}
// OTW this is a bad encoding, just pass unchanged
}
ptr++;
}
}
// Parse HTTP request
bool WebReadRequest(WiFiClient *client, char **urlStr, char **paramStr)
{
static char NUL = 0; // Get around writable strings...
*urlStr = NULL;
*paramStr = NULL;
LogPrintf("+WebReadRequest @ %d\n", millis());
unsigned long timeoutMS = millis() + 5000; // Max delay before we timeout
while (!client->available() && millis() < timeoutMS) { delay(10); }
if (!client->available()) {
LogPrintf("-WebReadRequest: Timeout @ %d\n", millis());
return false;
}
int wlen = client->readBytesUntil('\r', reqBuff, sizeof(reqBuff)-1);
reqBuff[wlen] = 0;
// Delete HTTP version (well, anything after the 2nd space)
char *ptr = reqBuff;
while (*ptr && *ptr!=' ') ptr++;
if (*ptr) ptr++;
while (*ptr && *ptr!=' ') ptr++;
*ptr = 0;
URLDecode(reqBuff);
char *url;
char *qp;
if (!memcmp_P(reqBuff, PSTR("GET "), 4)) {
client->flush(); // Don't need anything here...
// Break into URL and form data
url = reqBuff+4;
while (*url && *url=='/') url++; // Strip off leading /s
qp = strchr(url, '?');
if (qp) {
*qp = 0; // End URL
qp++;
} else {
qp = &NUL;
}
} else if (!memcmp_P(reqBuff, PSTR("POST "), 5)) {
uint8_t newline;
client->read(&newline, 1); // Get rid of \n
url = reqBuff+5;
while (*url && *url=='/') url++; // Strip off leading /s
qp = strchr(url, '?');
if (qp) *qp = 0; // End URL @ ?
// In a POST the params are in the body
int sizeleft = sizeof(reqBuff) - strlen(reqBuff) - 1;
qp = reqBuff + strlen(reqBuff) + 1;
int wlen = client->readBytesUntil('\r', qp, sizeleft-1);
qp[wlen] = 0;
client->flush();
URLDecode(qp);
} else {
// Not a GET or POST, error
WebError(client, 405, PSTR("Allow: GET, POST"));
LogPrintf("-WebReadRequest(): Illegal command\n");
return false;
}
if (urlStr) *urlStr = url;
if (paramStr) *paramStr = qp;
LogPrintf("-WebReadRequest(): Success\n");
return true;
}
// Scan out and update a pointeinto the param string, returning the name and value or false if done
bool ParseParam(char **paramStr, char **name, char **value)
{
char *data = *paramStr;
if (*data==0) return false;
char *namePtr = data;
while ((*data != 0) && (*data != '=') && (*data != '&')) data++;
if (*data) { *data = 0; data++; }
char *valPtr = data;
if (*data == '=') data++;
while ((*data != 0) && (*data != '=') && (*data != '&')) data++;
if (*data) { *data = 0; data++;}
*paramStr = data;
*name = namePtr;
*value = valPtr;
return true;
}
bool IsIndexHTML(const char *url)
{
if (!url) return false;
if (*url==0 || !strcmp_P(url, PSTR("/")) || !strcmp_P(url, PSTR("/index.html")) || !strcmp_P(url, PSTR("index.html"))) return true;
else return false;
}
void WebFormText(WiFiClient *client, /*const char **/ PGM_P label, const char *name, const char *value, bool enabled)
{
WebPrintfPSTR(client, label);
WebPrintf(client, ": <input type=\"text\" name=\"%s\" id=\"%s\" value=\"%s\" %s><br>\n", name, name, value, !enabled?"disabled":"");
}
void WebFormText(WiFiClient *client, /*const char **/ PGM_P label, const char *name, const int value, bool enabled)
{
WebPrintfPSTR(client, label);
WebPrintf(client, ": <input type=\"text\" name=\"%s\" id=\"%s\" value=\"%d\" %s><br>\n", name, name, value, !enabled?"disabled":"");
}
void WebFormCheckbox(WiFiClient *client, /*const char **/ PGM_P label, const char *name, bool checked, bool enabled)
{
WebPrintf(client, "<input type=\"checkbox\" name=\"%s\" id=\"%s\" %s %s> ", name, name, checked?"checked":"", !enabled?"disabled":"");
WebPrintfPSTR(client, label);
WebPrintf(client, "<br>\n");
}
void WebFormCheckboxDisabler(WiFiClient *client, PGM_P /*const char **/label, const char *name, bool invert, bool checked, bool enabled, const char *ids[])
{
WebPrintf(client,"<input type=\"checkbox\" name=\"%s\" id=\"%s\" onclick=\"", name,name);
if (invert) WebPrintf(client, "var x = true; if (this.checked) { x = false; }\n")
else WebPrintf(client, "var x = false; if (this.checked) { x = true; }\n");
for (byte i=0; ids[i][0]; i++ ) {
WebPrintf(client, "document.getElementById('%s').disabled = x;\n", ids[i]);
}
WebPrintf(client, "\" %s %s> ", checked?"checked":"", !enabled?"disabled":"")
WebPrintfPSTR(client, label);
WebPrintf(client, "<br>\n");
}
// Scan an integer from a string, place it into dest, and then return # of bytes scanned
int ParseInt(char *src, int *dest)
{
byte count = 0;
bool neg = false;
int res = 0;
if (!src) return 0;
if (src[0] == '-') {neg = true; src++; count++;}
while (*src && (*src>='0') && (*src<='9')) {
res = res * 10;
res += *src - '0';
src++;
count++;
}
if (neg) res *= -1;
if (dest) *dest = res;
return count;
}
void Read4Int(char *str, byte *p)
{
int i;
str += ParseInt(str, &i); p[0] = i; if (*str) str++;
str += ParseInt(str, &i); p[1] = i; if (*str) str++;
str += ParseInt(str, &i); p[2] = i; if (*str) str++;
str += ParseInt(str, &i); p[3] = i;
}
+64
View File
@@ -0,0 +1,64 @@
/*
PsychoPlug
ESP8266 based remote outlet with standalone timer and MQTT integration
Copyright (C) 2017 Earle F. Philhower, III
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _web_h
#define _web_h
// Global way of writing out dynamic HTML to socket
// snprintf guarantees a null termination
#define WebPrintf(c, fmt, ...) { char webBuff[192]; snprintf_P(webBuff, sizeof(webBuff), PSTR(fmt), ## __VA_ARGS__); (c)->print(webBuff); delay(10);}
#define WebPrintfPSTR(c, fmt, ...) { char webBuff[192]; snprintf_P(webBuff, sizeof(webBuff), (fmt), ## __VA_ARGS__); (c)->print(webBuff); delay(10);}
// Common HTTP header bits
#define DOCTYPE "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"
#define ENCODING "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n"
// Web header creation
void WebPrintError(WiFiClient *client, int code); // Sends only the error code string and a description
void WebError(WiFiClient *client, int code, const char *headers, bool usePMEM = true); // Sends whole HTTP error headers
void WebHeaders(WiFiClient *client, PGM_P /*const char **/headers); // Send success headers
// Web decoding utilities
void Base64Decode(char *str); // In-place B64 decode
void URLDecode(char *ptr); // In-place URL decode
// GET/POST parsing
bool WebReadRequest(WiFiClient *client, char **urlStr, char **paramStr);
bool ParseParam(char **paramStr, char **name, char **value); // Get next name/parameter from a param string
bool IsIndexHTML(const char *url); // Is this meant to be index.html (/, index.htm, etc.)
// HTML FORM generation
void WebFormText(WiFiClient *client, /*const char **/ PGM_P label, const char *name, const char *value, bool enabled);
void WebFormText(WiFiClient *client, /*const char **/ PGM_P label, const char *name, const int value, bool enabled);
void WebFormCheckbox(WiFiClient *client, /*const char **/ PGM_P label, const char *name, bool checked, bool enabled);
void WebFormCheckboxDisabler(WiFiClient *client, PGM_P /*const char **/label, const char *name, bool invert, bool checked, bool enabled, const char *ids[]);
// HTML FORM parsing
int ParseInt(char *src, int *dest);
void Read4Int(char *str, byte *p);
#define ParamText(name, dest) { if (!strcmp(namePtr, (name))) strlcpy((dest), valPtr, sizeof(dest)); }
#define ParamCheckbox(name, dest) { if (!strcmp(namePtr, (name))) (dest) = !strcmp("on", valPtr); }
#define ParamInt(name, dest) { if (!strcmp(namePtr, (name))) ParseInt(valPtr, &dest); }
#define Param4Int(name, dest) { if (!strcmp(namePtr, (name))) Read4Int(valPtr, (dest)); }
#endif