web control/CORS (interim)

This commit is contained in:
2021-10-09 02:12:38 +03:00
parent f96f125fe6
commit 7e14e7143c
8 changed files with 88 additions and 29 deletions

View File

@@ -25,4 +25,5 @@
#-DSERIAL_BAUD=115200 #-DSERIAL_BAUD=115200
#-DdebugSerialPort=Serial #-DdebugSerialPort=Serial
-DRESTART_LAN_ON_MQTT_ERRORS -DRESTART_LAN_ON_MQTT_ERRORS
-D CORS=\"http://lazyhome.ru\"

View File

@@ -1,5 +1,12 @@
#include "config.h" #include "config.h"
String systemConfig::getMACString()
{
String res;
for (int i=0; i<6; i++) {res+= (((char)mac[i]>>4)+'0');res+=(((char)mac[i]&0xf)+'0');}
return res;
}
int systemConfig::openStream(char mode) int systemConfig::openStream(char mode)
{ {
#if defined(FS_STORAGE) #if defined(FS_STORAGE)
@@ -7,7 +14,7 @@ int systemConfig::openStream(char mode)
#else #else
stream->open(FN_CONFIG_BIN,mode); stream->open(FN_CONFIG_BIN,mode);
#endif #endif
stream->setSize(SYSCONF_SIZE); //stream->setSize(SYSCONF_SIZE);
}; };
bool systemConfig::isValidSysConf() bool systemConfig::isValidSysConf()

View File

@@ -22,6 +22,7 @@ class systemConfig {
bool isValidSysConf(); bool isValidSysConf();
bool getMAC(); bool getMAC();
String getMACString();
bool setMAC(macAddress& mac); bool setMAC(macAddress& mac);
char * getMQTTpwd(char * buffer, uint16_t bufLen); char * getMQTTpwd(char * buffer, uint16_t bufLen);

View File

@@ -60,9 +60,10 @@ NRFFlashStorage EEPROM;
if (fs = SPIFFS.open(_filename,modestr)) if (fs = SPIFFS.open(_filename,modestr))
{ {
openedMode=mode; openedMode=mode;
streamSize = DEFAULT_FILESIZE_LIMIT;
if (_filename.endsWith(".json")) {contentType=HTTP_TEXT_JSON;textMode=true;} if (_filename.endsWith(".json")) {contentType=HTTP_TEXT_JSON;textMode=true;streamSize = MAX_JSON_CONF_SIZE; }
else if (_filename.endsWith(".bin")) {contentType=HTTP_OCTET_STREAM;textMode=false;} else if (_filename.endsWith(".bin")) {contentType=HTTP_OCTET_STREAM;textMode=false;streamSize = SYSCONF_SIZE; }
else if (_filename.endsWith(".txt")) {contentType=HTTP_TEXT_PLAIN;textMode=true;} else if (_filename.endsWith(".txt")) {contentType=HTTP_TEXT_PLAIN;textMode=true;}
else if (_filename.endsWith(".html")) {contentType=HTTP_TEXT_HTML;textMode=true;} else if (_filename.endsWith(".html")) {contentType=HTTP_TEXT_HTML;textMode=true;}
else if (_filename.endsWith(".gif")) {contentType=HTTP_IMAGE_GIF;textMode=false;} else if (_filename.endsWith(".gif")) {contentType=HTTP_IMAGE_GIF;textMode=false;}

View File

@@ -48,18 +48,7 @@ Streamlog errorSerial(&debugSerialPort,LOG_ERROR, ledRED);
Streamlog infoSerial (&debugSerialPort,LOG_INFO); Streamlog infoSerial (&debugSerialPort,LOG_INFO);
#endif #endif
/*
#if defined(FS_STORAGE)
flashStream sysConfStream("/config.bin");
flashStream JSONStream("/config.json");
#else
flashStream sysConfStream(SYSCONF_OFFSET,EEPROM_offsetJSON);
flashStream JSONStream(EEPROM_offsetJSON,MAX_JSON_CONF_SIZE);
#endif
*/
flashStream sysConfStream; flashStream sysConfStream;
systemConfig sysConf(&sysConfStream); systemConfig sysConf(&sysConfStream);
extern long timer0_overflow_count; extern long timer0_overflow_count;
@@ -242,15 +231,19 @@ bool isNotRetainingStatus() {
// ... same sor other http codes // ... same sor other http codes
// if response != "" - put response in http answer // if response != "" - put response in http answer
uint16_t httpHandler(Client& client, String request, long contentLength, bool authorized, String& response ) uint16_t httpHandler(Client& client, String request, uint8_t method, long contentLength, bool authorized, String& response )
{ {
//String response = ""; //String response = "";
debugSerial<<request<<endl; debugSerial<<request<<endl;
if (request == (F("GET /"))) if (method == HTTP_GET && request == (F("/")))
{ {
ArduinoOTA.sendHttpResponse(client,301,false); // Send only HTTP header, no close socket ArduinoOTA.sendHttpResponse(client,301,false); // Send only HTTP header, no close socket
client.println(F("Location: http://lazyhome.ru/pwa?mac=")); client.println(
// todo for (int i=0; i<6; i++) {response+=(sysConf.mac[i]>>4,HEX);response+=(sysConf.mac[i]&0xf,HEX);} "Location: http://lazyhome.ru/pwa?mac="+sysConf.getMACString()
+"&ip="+Ethernet.localIP()//.toString()
+"&port="+ OTA_PORT
);
//response+=(F("&ip=")); //response+=(F("&ip="));
//todo response+=(Ethernet.localIP()); //todo response+=(Ethernet.localIP());
client.println(); client.println();
@@ -258,11 +251,12 @@ uint16_t httpHandler(Client& client, String request, long contentLength, bool au
client.stop(); client.stop();
return 1; return 1;
} }
if (!authorized) return 401;
if (request.startsWith(F("POST /item/"))) if (method == HTTP_POST && request.startsWith(F("/item/")))
{ {
request.remove(0,11); if (!authorized) return 401;
request.remove(0,6);
String body=client.readStringUntil('\n'); String body=client.readStringUntil('\n');
Item item((char*)request.c_str()); Item item((char*)request.c_str());
if (!item.isValid() || !item.Ctrl((char*) body.c_str())) return 400; if (!item.isValid() || !item.Ctrl((char*) body.c_str())) return 400;
@@ -273,9 +267,10 @@ uint16_t httpHandler(Client& client, String request, long contentLength, bool au
response=ic.toString(buf, sizeof(buf)); response=ic.toString(buf, sizeof(buf));
return 200 | HTTP_TEXT_PLAIN; return 200 | HTTP_TEXT_PLAIN;
} }
else if (request.startsWith(F("GET /item/"))) else if (method == HTTP_GET && request.startsWith(F("/item/")))
{ {
request.remove(0,10); if (!authorized) return 401;
request.remove(0,6);
Item item((char*)request.c_str()); Item item((char*)request.c_str());
if (!item.isValid()) return 400; if (!item.isValid()) return 400;
@@ -290,9 +285,10 @@ uint16_t httpHandler(Client& client, String request, long contentLength, bool au
return 200 | HTTP_TEXT_PLAIN; return 200 | HTTP_TEXT_PLAIN;
} }
else if (request.startsWith(F("POST /command/"))) else if (method == HTTP_POST && request.startsWith(F("/command/")))
{ {
request.remove(0,14); if (!authorized) return 401;
request.remove(0,9);
String body=client.readStringUntil('\n'); String body=client.readStringUntil('\n');
request+=" "; request+=" ";
@@ -469,11 +465,10 @@ lan_status lanLoop() {
#ifdef NOETHER #ifdef NOETHER
lanStatus=DO_NOTHING;//-14; lanStatus=DO_NOTHING;//-14;
#endif #endif
//Serial.println(lanStatus);
switch (lanStatus) { switch (lanStatus) {
case INITIAL_STATE: case INITIAL_STATE:
// statusLED.set(ledRED|((configLoaded)?ledBLINK:0));
statusLED.set(ledRED|((configLoaded)?ledBLINK:0)); statusLED.set(ledRED|((configLoaded)?ledBLINK:0));
#if defined(WIFI_ENABLE) #if defined(WIFI_ENABLE)

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <Arduino.h> #include <Arduino.h>
#define DEFAULT_FILESIZE_LIMIT 65535
#ifndef MAX_JSON_CONF_SIZE #ifndef MAX_JSON_CONF_SIZE
#if defined(__SAM3X8E__) #if defined(__SAM3X8E__)

View File

@@ -15,6 +15,7 @@ uint16_t contentType;
public: public:
seekableStream(unsigned int size):Stream(),streamSize(size) {}; seekableStream(unsigned int size):Stream(),streamSize(size) {};
virtual bool checkPermissions(char mode) {return true;};
unsigned int getSize() {return streamSize;} unsigned int getSize() {return streamSize;}
void setSize (unsigned int size) {streamSize = size;}; void setSize (unsigned int size) {streamSize = size;};
virtual unsigned int seek(unsigned int _pos = 0) = 0; virtual unsigned int seek(unsigned int _pos = 0) = 0;

53
pwc/index.html Normal file
View File

@@ -0,0 +1,53 @@
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function post_cmd(endpoint, param) {
var username = $("input#login").val();
var password = $("input#password").val();
var surl = $("input#url").val();
var settings = {
"url": surl+endpoint,
//"http://192.168.11.234:65280"+endpoint,
"method": "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
xhr.setRequestHeader ("Pragma", "no-cache");
//xhr.withCredentials = true;
},
"timeout": 20000,
"headers": {
"Content-Type": "text/plain"
},
"data": param+"\n",
};
$.ajax(settings).done(function (response) {
document.getElementById("resp").innerHTML = response;
});
}
</script>
<h1>LazyHome PWA </h1>
<form name="cookieform" id="loginform">
<table>
<tr>
<td>URL:<td><input type="text" name="url" id="url" value="" class="text"/>
<tr>
<td>Login: <td><input type="text" name="login" id="login" value="arduino" class="text"/>
<td>Password: <td> <input type="text" name="password" id="password" value="password" class="text"/>
</tr>
</table>
</form>
<table>
<tr>
<td><button onclick='post_cmd("/item/relays/cmd","toggle")'>Toggle</button>
<td><button onclick='post_cmd("/command/save","")'>Save</button>
<td><button onclick='post_cmd("/command/reboot","")'>Reboot</button>
<td><button onclick='post_cmd("/command/get,"")'>Get</button>
<td><button onclick='post_cmd("/command/load","")'>Load</button>
<tr>
<td>item:<td><input type="text" name="item" id="item" value="" class="text"/>
<td>command:<td><input type="text" name="command" id="command" value="toggle" class="text"/>
<td><button onclick='post_cmd("/item/"+$("input#item").val(),$("input#command").val())'>Exec</button>
</table>
<p id="resp"></p>