This commit is contained in:
APEX FIGHT 2025-01-30 02:40:44 -05:00
parent 72bfed7a3f
commit 3fc7bc1820
17 changed files with 107468 additions and 0 deletions

5
esp32-otaserv/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

10
esp32-otaserv/.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

View File

@ -0,0 +1 @@
100000

View File

@ -0,0 +1,2 @@
SSID
password

View File

@ -0,0 +1,6 @@
function main(headers, contents, ip, port) {
var head = "HTTP/1.1 200 OK\r\nContent-Type: text\r\n\r\n";
var get = "GET /resource.txt HTTP/1.1\r\n\r\n\r\n";
writeFile("data",getDeviceData());
return head + readFile("/run/data") + "\r\n";
}

View File

@ -0,0 +1,3 @@
function main(){
writeFile("data",getDeviceData());
}

View File

@ -0,0 +1,6 @@
function main(headers, contents, ip, port) {
var head = "HTTP/1.1 200 OK\r\nContent-Type: xml\r\n\r\n";
var get = "GET /resource.txt HTTP/1.1\r\n\r\n\r\n";
return head + readFile("/sys/addressbook") + "\r\n";
}

View File

View File

@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

46
esp32-otaserv/lib/README Normal file
View File

@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps = ofekp/TinyUPnP@^3.1.4
board_build.filesystem = littlefs

View File

@ -0,0 +1,29 @@
{
"folders": [
{
"path": "../../../../../Desktop/esp32"
},
{
"name": "esp32-otaserv",
"path": ".."
}
],
"settings": {
"files.associations": {
"*.tcc": "cpp",
"chrono": "cpp",
"ctime": "cpp",
"iomanip": "cpp",
"limits": "cpp",
"numeric": "cpp",
"ratio": "cpp",
"streambuf": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"utility": "cpp",
"charconv": "cpp",
"format": "cpp",
"*.inc": "cpp"
}
}
}

708
esp32-otaserv/src/main.cpp Normal file
View File

@ -0,0 +1,708 @@
#include <Arduino.h>
#include <WiFi.h>
#include <TinyUPnP.h>
#include <freertos/timers.h>
#include <LittleFS.h>
#include "FS.h"
#include <duktape.h>
#define UPNP_DEBUG false
#define HOSTNAME "HOSTNAME"
#define SSID1 "SSID"
#define PASSWD "PASSWORD"
#define PORT 35868
#define LOCATION "DESCRIPTION OF LOCATION"
#define INFO "MORE INFO"
#define MYID "#3#"
#define UPDREQ ":35868#3#(endl)" //update with port and id
// put function declarations here:
#define duk_create_heap_default() \
duk_create_heap(NULL, NULL, NULL, NULL, fatal_error)
TinyUPnP *upnp = new TinyUPnP(20000);
bool connectWifi(const char* ssid, const char* pw);
void passThrough(String headers, String contents, WiFiClient cli);
void updateInfo(String contents, WiFiClient cli);
void getInfo(WiFiClient cli);
void unknownConnection(String headers, String contents, WiFiClient cli);
void updateAddressBook(String contents, WiFiClient cli, bool flag);
void watchdog(void * p);
void clearAddressBook(WiFiClient cli);
void handshake();
void push_bindings(duk_context *ctx);
void periodUpdate(void * p);
duk_context *dukContext;
String getDirTree(String path);
WiFiServer server(PORT);
static void fatal_error(void *udata, const char *msg){
Serial.println(msg);
ESP.restart();
}
static void push_file_as_string(duk_context *ctx, String str){
File f = LittleFS.open(str);
if (!f) {
return;
}
size_t len = f.size();
char buf[len];
f.readBytes(buf, len);
duk_push_lstring(ctx, (const char *) buf, len);
}
static duk_ret_t readFile(duk_context *ctx){
const char *fileName = duk_require_string(ctx, 0);
File f = LittleFS.open(fileName);
size_t size = f.size();
char buf[size];
f.readBytes(buf,size);
if (f){
duk_push_lstring(ctx, buf, size);
} else duk_push_false(ctx);
f.close();
return 1;
}
static duk_ret_t httpReq(duk_context *ctx){ // ip, port, req, timeout
const char *ip = duk_require_string(ctx, 0);
int port = duk_require_int(ctx, 1);
const char *req = duk_require_string(ctx, 2);
int timeout = duk_require_int(ctx, 3);
WiFiClient client;
client.stop();
//Serial.println(req);
if (client.connect(ip,port)){
client.print(req);
//Serial.println(ip);
//Serial.println(port);
//Serial.println("CONNECTED");
unsigned long time = millis();
while(client.available() == 0){
if(millis() - time > timeout){ //if change in time is past timeout
//Serial.println(">>> Client Timeout !");
client.stop();
duk_push_false(ctx);
return 1;
}
}
//Serial.println("strart");
String res = "";
while (client.available()){
res = client.readString();
//Serial.println("res: " + res);
}
//Serial.println("loopend");
duk_push_string(ctx, res.c_str());
} else {
duk_push_false(ctx);
return 1;
}
return 1;
}
static duk_ret_t writeFile(duk_context *ctx){
//Serial.println("writing file");
const char *fileName = duk_require_string(ctx, 0);
const char *contents = duk_require_string(ctx, 1);
String fileNameStr = fileName;
//Serial.println(fileNameStr);
File f = LittleFS.open("/run/" + fileNameStr,FILE_WRITE,true);
f.print(contents);
if (f){
duk_push_true(ctx);
} else duk_push_false(ctx);
f.close();
return 1;
}
static duk_ret_t getDeviceData(duk_context *ctx){
//Serial.println("recieving dev data");
String data = "";
data = data + WiFi.SSID() + "\n";
data = data + WiFi.BSSIDstr() + "\n";
data = data + WiFi.macAddress() + "\n";
data = data + WiFi.broadcastIP().toString() + "\n";
data = data + WiFi.gatewayIP().toString() + "\n";
data = data + WiFi.localIP().toString();
//Serial.println(data.c_str());
duk_push_string(ctx, data.c_str());
return 1;
}
void setup() {
Serial.begin(9600);
Serial.println("Serial Started");
if (!LittleFS.begin(true)) {
Serial.println("An Error has occurred while mounting FileSystem");
ESP.restart();
}
String netconf = LittleFS.open("/conf/netconf").readString();
Serial.println(netconf.substring(0,netconf.indexOf("\n")));
Serial.println(netconf.substring(netconf.indexOf("\n")+1));
if (!connectWifi(netconf.substring(0,netconf.indexOf("\n")).c_str(), netconf.substring(netconf.indexOf("\n")+1).c_str())){
Serial.println("failed to connect to saved net");
if(!connectWifi(SSID1, PASSWD)){
ESP.restart();
}
}
TaskHandle_t timeout;
xTaskCreatePinnedToCore( //start watchdog
watchdog,
"failsafe",
5000,
NULL,
0,
&timeout,
0
);
upnp->addPortMappingConfig(WiFi.localIP(),PORT,"TCP",3600,HOSTNAME); //map port
portMappingResult portmaps = upnp->commitPortMappings();
upnp->updatePortMappings(10000, NULL);
if (portmaps == SUCCESS){
Serial.println("SUCCESS");
server.begin();
} else if (portmaps == ALREADY_MAPPED){
Serial.println("already mapped");
server.begin();
} else {
Serial.println("----------OTHER ERROR------------");
ESP.restart();
}
handshake();
dukContext = duk_create_heap_default();
Serial.println("server listening");
Serial.println("firmware V1.2 Loaded");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
//Serial.println("Starting coroutine");
/*
TaskHandle_t periodicalUpdate;
xTaskCreatePinnedToCore(
periodUpdate,
"periodicalupd",
100000,
NULL,
1,
&periodicalUpdate,
0
);*/
}
void handshake(){
File addressbook = LittleFS.open("/sys/addressbook");
String book = addressbook.readString();
while (book.indexOf("$") != -1){
String entry = book.substring(book.lastIndexOf("$"));
//Serial.println("entry " + entry);
String ip = entry.substring(entry.indexOf("$") + 1, entry.indexOf(":"));
//Serial.println("ip ");
//Serial.println(ip.c_str());
int port = entry.substring(entry.indexOf(":") + 1 , entry.indexOf("#")).toInt();
//Serial.println("port ");
//Serial.println(port);
WiFiClient client;
int timeout = 2;
while (timeout >= 0)
{
if (client.connect(ip.c_str(), port)){
String printstr = "POST / HTTP/1.1\r\nRequest-type: Update-Addressbook\r\n\r\n" + String(UPDREQ) + "\r\n\r\n";
client.print(printstr);
break;
}
timeout--;
}
book = book.substring(0,book.lastIndexOf("$")); // pop entry off book
}
}
void watchdog(void * p){
while (true){
if (WiFi.status() != WL_CONNECTED){ // restart on problem
ESP.restart();
}
if (floor(esp_timer_get_time()/1000000) > 600){ //restart every so ofton because this upnp tool is weird and im too impatient to test it
ESP.restart();
}
vTaskDelay(500/portTICK_PERIOD_MS);
}
}
/*void periodUpdate(void * p){
Serial.println("started periodical update coroutine");
duk_context *dukContext2 = duk_create_heap_default();
int interval = LittleFS.open("/conf/loopinterval").readString().toInt();
if (interval == -1){
Serial.println("loop off");
vTaskDelete(NULL);
}
while (true){
Serial.println("start");
push_file_as_string(dukContext2, "/run/loop.js");
if (duk_peval(dukContext2) != 0){
duk_pop(dukContext2);
continue;
}
duk_pop(dukContext2);
duk_push_global_object(dukContext2);
push_bindings(dukContext2);
duk_get_prop_string(dukContext2, -1, "main");
duk_pcall(dukContext2,0);
duk_pop(dukContext2);
duk_pop(dukContext2);
vTaskDelay(interval/portTICK_PERIOD_MS);
Serial.println("start");
}
}*/
void loop() {
/*
if (LittleFS.exists("/run/loop.js")){
push_file_as_string(dukContext, "/run/loop.js");
if (duk_peval(dukContext) != 0 ){
Serial.println("JS ERROR: ");
Serial.println(duk_safe_to_string(dukContext, -1)); //if theres an error, log it and try again
duk_pop(dukContext);
} else {
duk_pop(dukContext);
duk_push_global_object(dukContext);
duk_get_prop_string(dukContext, -1, "loop");
duk_pcall(dukContext, 0);
Serial.println(duk_safe_to_string(dukContext, -1));
duk_pop(dukContext);
duk_pop(dukContext);
}
}
*/
WiFiClient client = server.accept();
if (client){
String requestType = "";
//Serial.println("CONNECTION SUCCESS");
//Serial.println(client.remoteIP());
String currentLine = "";
String contents = "";
String headers = "";
//Serial.println();
int n = 0;
while (client.available()){
char c = client.read();
//Serial.print(c);
if (c == '\n') {
if (currentLine.length() == 0) {
//Serial.println("-----------------");
if (n==1){
//end of request
//Serial.println("manually disconnecting");
break;
}
n++;
} else {
if (currentLine.startsWith("Request-type:")){
requestType = currentLine;
}
if (n == 1){
contents += currentLine;
contents += '\n';
} else {
headers += currentLine;
headers += '\n';
}
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
}
//Serial.println("client disconnected");
if (requestType.endsWith("Custom-Request")){
passThrough(headers, contents, client);
}
else if (requestType.endsWith("Update-Info")){
updateInfo(contents, client);
}
else if (requestType.endsWith("Get-Info")){
getInfo(client);
} else if (requestType.endsWith("Update-Addressbook")) {
updateAddressBook(contents, client, true);
} else if (requestType.endsWith("Clear-Addressbook")){
clearAddressBook(client);
} else if (requestType.endsWith("Ext-Addressbook")) {
updateAddressBook(contents, client, false);
} else {
unknownConnection(headers, contents, client);
}
}
}
void updateInfo(String contents, WiFiClient cli)
{
/*
$delfile.txt(endl)
------------------------
$dirname/of/dir(endl)
------------------------
$wriname/of/dir/file.txt(endl)
file
*/
//Serial.println(contents);
contents = contents.substring(contents.indexOf("$")+1);
//Serial.println(contents);
if (contents.startsWith("del")) {
//Serial.println("del file");
//Serial.println(contents);
contents = contents.substring(3);
if (LittleFS.remove("/run/"+contents.substring(0,contents.indexOf("(endl)")))){
//Serial.println("deleted file");
} else if (LittleFS.rmdir("/run/"+contents.substring(0,contents.indexOf("(endl)")))){
//Serial.println("deleted dir");
} else //Serial.println("failed to remove file");
cli.stop();
return;
} else if (contents.startsWith("dir")){
contents = contents.substring(3);
if (LittleFS.mkdir("/run/"+contents.substring(0,contents.indexOf("(endl)")))){
//Serial.println("succesfully made dir");
} else {
//Serial.println("had problem creating directory");
//Serial.println("/run/" + contents.substring(0,contents.indexOf("(endl)")));
}
cli.stop();
return;
} else if (contents.startsWith("conf")){
contents = contents.substring(4);
//Serial.println("configuring");
//Serial.println(contents);
if (contents.startsWith("/netconf")){
//Serial.println("configuring wifi");
File file = LittleFS.open("/conf/netconf",FILE_WRITE);
contents = contents.substring(8,contents.indexOf("(endl)"));
file.print(contents);
//Serial.println("contents:");
//Serial.println(contents);
file.close();
}else if (contents.startsWith("/loopinterval")){
File file = LittleFS.open("/conf/loopinterval",FILE_WRITE);
contents = contents.substring(8,contents.indexOf("(endl)"));
file.print(contents);
file.close();
}
cli.stop();
return;
}
else if (!contents.startsWith("wri")){
cli.stop();
return;
}
//Serial.println("writing file");
contents = contents.substring(3);
String fileName = contents.substring(0,contents.indexOf("(endl)"));// /dir/file.txt
String toWrite = contents.substring(contents.indexOf("(endl)")+6, contents.lastIndexOf("}")+1);
File run = LittleFS.open("/run/" + fileName, FILE_WRITE);
//Serial.println(fileName);
//Serial.println(toWrite);
if (!run) {
cli.stop();
run.close();
return;
}
run.print(toWrite);
cli.stop();
run.close();
return;
}
void getInfo(WiFiClient cli)
{
//Serial.println("sending info");
cli.println("HTTP/1.1 200 OK");
cli.println("Content-Type: text");
cli.println();
cli.println(WiFi.SSID());
cli.println(LOCATION);
cli.println(INFO);
cli.println("{");
cli.println(getDirTree("/run"));
cli.println();
cli.println("}");
cli.println();
cli.print("addressbook:");
cli.print(LittleFS.open("/sys/addressbook").readString());
//respond with filesystem, network, location, and addressbook data
cli.stop();
}
String getDirTree(String path){
String result = "";
File dir = LittleFS.open(path);
File file = dir.openNextFile();
while (file){
if (file.isDirectory()) {
result = result + "\n" + file.name() + "\n{";
result = result + getDirTree(file.path());
result = result + "\n}";
} else {
result = result + "\n" + file.name();
}
file = dir.openNextFile();
}
return result;
}
void clearAddressBook(WiFiClient cli){
//Serial.println("clearing addressbook");
File f = LittleFS.open("/sys/addressbook",FILE_WRITE);
f.print("");
f.close();
cli.stop();
}
void passThrough(String headers, String contents, WiFiClient cli)
{
/*\
Serial.println("-------------------------------");
Serial.println(headers);
Serial.println("-------------------------------");
Serial.println(contents);
Serial.println("-------------------------------");
*/
push_file_as_string(dukContext, "/run/main.js");
if (duk_peval(dukContext) != 0 ){
//Serial.println("JS ERROR: ");
//Serial.println(duk_safe_to_string(dukContext, -1)); //if theres an error, log it and try again
cli.println("HTTP/1.1 200 OK");
cli.println("Content-Type: text");
cli.println();
cli.println(duk_safe_to_string(dukContext, -1));
cli.println();
duk_pop(dukContext);
cli.stop();
return;
}
duk_pop(dukContext);
duk_push_global_object(dukContext);
push_bindings(dukContext);
duk_get_prop_string(dukContext, -1, "main");
duk_push_string(dukContext, headers.c_str());
duk_push_string(dukContext, contents.c_str());
duk_push_string(dukContext, cli.remoteIP().toString().c_str());
duk_push_int(dukContext, cli.remotePort());
duk_pcall(dukContext, 4);
/*
Serial.println("result: ");
Serial.println(duk_safe_to_string(dukContext, -1));
*/
cli.print(duk_safe_to_string(dukContext, -1));
duk_pop(dukContext);
duk_pop(dukContext);
//duk_destroy_heap(dukContext);
cli.stop();
}
void updateAddressBook(String contents, WiFiClient cli, bool flag){
/*
:35869#0(endl)
$73.249.55.105:35869#0(endl)
*/
if (flag){ // non given ip
contents = contents.substring(contents.indexOf(":"));
String ip = "$" + cli.remoteIP().toString(); // add pub ip
//ip = ip.substring(0, ip.indexOf("f"));
//Serial.println("ip " + ip);
contents = ip + contents;
}
contents = contents.substring(contents.indexOf("$"), contents.indexOf("(endl)"));
String id = contents.substring(contents.indexOf("#"));
//Serial.println("adding ip " + contents);
//Serial.println(id);
File addressbook = LittleFS.open("/sys/addressbook");
String modbook = addressbook.readString();
int addressIndex = modbook.indexOf(id);
//Serial.println(addressIndex);
if (addressIndex != -1){
//Serial.println("replacing ip");
String previousAddress = modbook.substring(modbook.substring(0,addressIndex-2).lastIndexOf("$"));
//Serial.println("prev add " + previousAddress);
//Serial.println("current contents: ");
//Serial.println(contents);
modbook.replace(previousAddress, contents);
} else {
//Serial.println("adding ip to list");
modbook = modbook + contents;
}
addressbook.close();
LittleFS.remove("/sys/addressbook");
addressbook = LittleFS.open("/sys/addressbook",FILE_WRITE, true);
addressbook.print(modbook);
addressbook.close();
cli.stop();
}
void unknownConnection(String headers, String contents, WiFiClient cli) //"DMZ" style. needs full fledged keep alive / non http support by adding js functionality to interact with sockets
{
Serial.println("-------------------------------");
Serial.println(headers);
Serial.println("-------------------------------");
Serial.println(contents);
Serial.println("-------------------------------");
if (!LittleFS.exists("/run/dmz.js")) return;
push_file_as_string(dukContext, "/run/dmz.js");
if (duk_peval(dukContext) != 0 ){
//Serial.println("JS ERROR: ");
//Serial.println(duk_safe_to_string(dukContext, -1)); //if theres an error, log it and try again
cli.println("HTTP/1.1 200 OK");
cli.println("Content-Type: text");
cli.println();
cli.println(duk_safe_to_string(dukContext, -1));
cli.println();
duk_pop(dukContext);
cli.stop();
return;
}
duk_pop(dukContext);
duk_push_global_object(dukContext);
push_bindings(dukContext);
duk_get_prop_string(dukContext, -1, "main");
duk_push_string(dukContext, headers.c_str());
duk_push_string(dukContext, contents.c_str());
duk_push_string(dukContext, cli.remoteIP().toString().c_str());
duk_push_int(dukContext, cli.remotePort());
duk_pcall(dukContext, 4);
/*
Serial.println("result: ");
Serial.println(duk_safe_to_string(dukContext, -1));
*/
cli.print(duk_safe_to_string(dukContext, -1));
duk_pop(dukContext);
duk_pop(dukContext);
//duk_destroy_heap(dukContext);
cli.stop();
return; //rather have some versions not do anything than do something stupid.
}
bool connectWifi(const char *ssid, const char *pw){
WiFi.setHostname(HOSTNAME);
WiFi.enableSTA(true);
WiFi.begin(ssid, pw);
int i = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
i++;
Serial.print(".");
if (i > 50){
return false;
}
}
return true;
}
void push_bindings(duk_context *ctx){
duk_push_c_function(ctx, httpReq, 4);
duk_put_prop_string(ctx, -2, "httpReq");
duk_push_c_function(ctx, readFile, 1);
duk_put_prop_string(ctx, -2, "readFile");
duk_push_c_function(ctx, writeFile, 2);
duk_put_prop_string(ctx, -2, "writeFile");
duk_push_c_function(ctx, getDeviceData, 0);
duk_put_prop_string(ctx, -2, "getDeviceData");
}

11
esp32-otaserv/test/README Normal file
View File

@ -0,0 +1,11 @@
This directory is intended for PlatformIO Test Runner and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html