Files
ESP8266Audio/examples/WebRadio/WebRadio.ino
T
Earle F. Philhower, III 143c4e65ae Move request buff to stack
Save 384 heap bytes by handling the web request buffering in the loop()
stack context.
2017-12-14 09:47:00 -08:00

358 lines
9.1 KiB
Arduino

/*
WebRadio Example
Very simple HTML app to control web streaming
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 "AudioFileSourceICYStream.h"
#include "AudioFileSourceBuffer.h"
#include "AudioGeneratorMP3.h"
#include "AudioGeneratorAAC.h"
#include "AudioOutputI2SDAC.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.
// Enter your WiFi setup here:
const char *SSID = "....";
const char *PASSWORD = "....";
WiFiServer server(80);
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...
static const char HEAD[] PROGMEM = R"KEWL(
<head>
<title>ESP8266 Web Radio</title>
<script type="text/javascript">
function updateTitle() {
var x = new XMLHttpRequest();
x.open("GET", "title");
x.onload = function() { document.getElementById("titlespan").innerHTML=x.responseText; setTimeout(updateTitle, 5000); }
x.onerror = function() { setTimeout(updateTitle, 5000); }
x.send();
}
setTimeout(updateTitle, 1000);
function showValue(n) {
document.getElementById("volspan").innerHTML=n;
var x = new XMLHttpRequest();
x.open("GET", "setvol?vol="+n);
x.send();
}
function updateStatus() {var x = new XMLHttpRequest();
x.open("GET", "status");
x.onload = function() { document.getElementById("statusspan").innerHTML=x.responseText; setTimeout(updateStatus, 5000); }
x.onerror = function() { setTimeout(updateStatus, 5000); }
x.send();
}
setTimeout(updateStatus, 2000);
</script>
</head>)KEWL";
static const char BODY[] PROGMEM = R"KEWL(
<body>
ESP8266 Web Radio!
<hr>
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>
<form action="stop" method="POST"><input type="submit" value="Stop"></form>
</body>)KEWL";
void HandleIndex(WiFiClient *client)
{
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 HandleStatus(WiFiClient *client)
{
WebHeaders(client, NULL);
client->write(status, strlen(status));
}
void HandleTitle(WiFiClient *client)
{
WebHeaders(client, NULL);
client->write(title, strlen(title));
}
void HandleVolume(WiFiClient *client, char *params)
{
char *namePtr;
char *valPtr;
while (ParseParam(&params, &namePtr, &valPtr)) {
ParamInt("vol", volume);
}
Serial.printf_P(PSTR("Set volume: %d\n"), volume);
RedirectToIndex(client);
}
void HandleChangeURL(WiFiClient *client, char *params)
{
char *namePtr;
char *valPtr;
char newURL[64];
char newType[4];
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;
if (!strcmp_P(newType, PSTR("aac"))) {
isAAC = true;
} else {
isAAC = false;
}
strcpy_P(status, PSTR("Changing URL..."));
Serial.printf_P("Changed URL to: %s(%s)\n", url, newType);
RedirectToIndex(client);
} else {
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;
} else {
// Who knows what yo do? Not me!
}
}
void StatusCallback(void *cbData, int code, const char *string)
{
const char *ptr = reinterpret_cast<const char *>(cbData);
(void) code;
(void) ptr;
strncpy(status, string, sizeof(status)-1);
status[sizeof(status)-1] = 0;
}
void setup()
{
Serial.begin(115200);
delay(1000);
Serial.printf_P(PSTR("Connecting to WiFi\n"));
// WiFi.disconnect();
// WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_STA);
// WiFi.hostname("melody");
// byte zero[] = {0,0,0,0};
// WiFi.config(zero, zero, zero, zero);
WiFi.begin(SSID, PASSWORD);
// Try forever
while (WiFi.status() != WL_CONNECTED) {
Serial.printf_P(PSTR("...Connecting to WiFi\n"));
delay(1000);
}
Serial.printf_P(PSTR("Connected\n"));
Serial.printf_P(PSTR("Go to http://"));
Serial.print(WiFi.localIP());
Serial.printf_P(PSTR("/ to control the web radio.\n"));
server.begin();
strcpy_P(url, PSTR("none"));
strcpy_P(status, PSTR("OK"));
strcpy_P(title, PSTR("Idle"));
file = NULL;
buff = NULL;
out = NULL;
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;
if (millis()-lastms > 1000) {
lastms = millis();
Serial.printf_P(PSTR("Running for %d seconds...Free mem=%d\n"), lastms/1000, ESP.getFreeHeap());
}
if (newUrl) {
StartNewURL();
}
if (decoder && decoder->isRunning()) {
strcpy_P(status, PSTR("Playing")); // By default we're OK unless the decoder says otherwise
if (!decoder->loop()) {
Serial.printf_P(PSTR("Stopping decoder\n"));
decoder->stop();
strcpy_P(title, PSTR("Stopped"));
}
} else {
// Nothing here
}
char *reqUrl;
char *params;
WiFiClient client = server.available();
char *reqBuff = (char *)alloca(384);
if (client && WebReadRequest(&client, reqBuff, 384, &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();
}
}