add dev mode support

This commit is contained in:
Empire 2024-12-04 21:38:21 +01:00
parent 4c19d757c6
commit 4a8e0188b3
9 changed files with 2739 additions and 32 deletions

1
.gitignore vendored
View File

@ -8,5 +8,6 @@ target
Cargo.lock Cargo.lock
node_modules/ node_modules/
rust/src/webserver/bundle.js rust/src/webserver/bundle.js
rust/src/webserver/index.html
rust/build/ rust/build/
rust/image.bin rust/image.bin

View File

@ -294,7 +294,9 @@ pub fn httpd(_reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
let file_handle = BOARD_ACCESS.lock().unwrap().get_file_handle(&filename, false); let file_handle = BOARD_ACCESS.lock().unwrap().get_file_handle(&filename, false);
match file_handle { match file_handle {
Ok(mut file_handle) => { Ok(mut file_handle) => {
let mut response = request.into_ok_response()?;
let headers = [("Access-Control-Allow-Origin","*")];
let mut response = request.into_response(200, None, &headers)?;
const BUFFER_SIZE: usize = 512; const BUFFER_SIZE: usize = 512;
let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE]; let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
let mut total_read: usize = 0; let mut total_read: usize = 0;
@ -317,9 +319,7 @@ pub fn httpd(_reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
//todo set headers here for filename to be error //todo set headers here for filename to be error
let error_text = err.to_string(); let error_text = err.to_string();
println!("error handling get file {}", error_text); println!("error handling get file {}", error_text);
request cors_response(request, 500, &error_text)?;
.into_status_response(500)?
.write(error_text.as_bytes())?;
} }
} }
anyhow::Ok(()) anyhow::Ok(())
@ -345,15 +345,13 @@ pub fn httpd(_reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
break; break;
} }
} }
request.into_ok_response().unwrap().write(format!("saved {total_read} bytes").as_bytes()).unwrap(); cors_response(request, 200, &format!("saved {total_read} bytes"))?;
}, },
Err(err) => { Err(err) => {
//todo set headers here for filename to be error //todo set headers here for filename to be error
let error_text = err.to_string(); let error_text = err.to_string();
println!("error handling get file {}", error_text); println!("error handling get file {}", error_text);
request cors_response(request, 500, &error_text)?;
.into_status_response(500)?
.write(error_text.as_bytes())?;
} }
} }
anyhow::Ok(()) anyhow::Ok(())
@ -368,11 +366,11 @@ pub fn httpd(_reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
match board.delete_file(&filename) { match board.delete_file(&filename) {
Ok(_) => { Ok(_) => {
let info = format!("Deleted file {copy}"); let info = format!("Deleted file {copy}");
request.into_ok_response().unwrap().write(info.as_bytes()).unwrap(); cors_response(request, 200, &info)?;
}, },
Err(err) => { Err(err) => {
let info = format!("Could not delete file {copy} {err:?}"); let info = format!("Could not delete file {copy} {err:?}");
request.into_status_response(400).unwrap().write(info.as_bytes()).unwrap(); cors_response(request, 400, &info)?;
}, },
} }
anyhow::Ok(()) anyhow::Ok(())
@ -450,7 +448,7 @@ pub fn httpd(_reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
server server
.fn_handler("/", Method::Get, move |request| { .fn_handler("/", Method::Get, move |request| {
let mut response = request.into_ok_response()?; let mut response = request.into_ok_response()?;
response.write(include_bytes!("config.html"))?;let mut buf = [0_u8; 3072]; response.write(include_bytes!("index.html"))?;let mut buf = [0_u8; 3072];
anyhow::Ok(()) anyhow::Ok(())
}) })
.unwrap(); .unwrap();
@ -475,6 +473,13 @@ pub fn httpd(_reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
server server
} }
fn cors_response(request: Request<&mut EspHttpConnection>, status: u16, body: &str) -> Result<(), anyhow::Error>{
let headers = [("Access-Control-Allow-Origin","*")];
let mut response = request.into_response(status, None, &headers)?;
response.write(body.as_bytes())?;
response.flush()?;
return anyhow::Ok(());
}
type AnyhowHandler = type AnyhowHandler =
fn(&mut Request<&mut EspHttpConnection>) -> Result<Option<std::string::String>, anyhow::Error>; fn(&mut Request<&mut EspHttpConnection>) -> Result<Option<std::string::String>, anyhow::Error>;
@ -486,18 +491,16 @@ fn handle_error_to500(
match error { match error {
Ok(answer) => match answer { Ok(answer) => match answer {
Some(json) => { Some(json) => {
let mut response = request.into_ok_response()?; cors_response(request, 200, &json)?;
response.write(json.as_bytes())?; }
response.flush()?; None => {
cors_response(request, 200, "")?;
} }
None => {}
}, },
Err(err) => { Err(err) => {
let error_text = err.to_string(); let error_text = err.to_string();
println!("error handling process {}", error_text); println!("error handling process {}", error_text);
request cors_response(request, 500, &error_text)?;
.into_status_response(500)?
.write(error_text.as_bytes())?;
} }
} }
return anyhow::Ok(()); return anyhow::Ok(());

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,11 @@
{ {
"devDependencies": { "devDependencies": {
"copy-webpack-plugin": "^12.0.2",
"ts-loader": "^9.5.1", "ts-loader": "^9.5.1",
"typescript": "^5.3.3", "typescript": "^5.3.3",
"webpack": "^5.89.0", "webpack": "^5.89.0",
"webpack-cli": "^5.1.4" "webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.1.0"
}, },
"dependencies": { "dependencies": {
"source-map-loader": "^4.0.1" "source-map-loader": "^4.0.1"

View File

@ -1,3 +1,6 @@
declare var PUBLIC_URL: string;
let battery_flash_button = document.getElementById("battery_flash_button") as HTMLButtonElement; let battery_flash_button = document.getElementById("battery_flash_button") as HTMLButtonElement;
let battery_flash_file = document.getElementById("battery_flash_file") as HTMLInputElement; let battery_flash_file = document.getElementById("battery_flash_file") as HTMLInputElement;
let battery_flash_message = document.getElementById("battery_flash_message") as HTMLElement; let battery_flash_message = document.getElementById("battery_flash_message") as HTMLElement;
@ -36,6 +39,6 @@ battery_flash_button.onclick = async function (){
//ajax.open("POST", "/flashbattery"); //ajax.open("POST", "/flashbattery");
//ajax.send(battery_flash_file.files[0]); //ajax.send(battery_flash_file.files[0]);
ajax.open("POST", "/flashbattery?flash=true"); ajax.open("POST", PUBLIC_URL + "/flashbattery?flash=true");
ajax.send(battery_flash_file.files[0]); ajax.send(battery_flash_file.files[0]);
}; };

View File

@ -1,3 +1,6 @@
declare var PUBLIC_URL: string;
console.log("Url is " + PUBLIC_URL);
interface PlantConfig { interface PlantConfig {
ap_ssid: string, ap_ssid: string,
ssid: string, ssid: string,
@ -64,14 +67,14 @@ function setTime(){
time : new Date().toISOString() time : new Date().toISOString()
} }
var pretty = JSON.stringify(value, undefined, 1); var pretty = JSON.stringify(value, undefined, 1);
fetch("/time", { fetch(PUBLIC_URL + "/time", {
method :"POST", method :"POST",
body: pretty body: pretty
}) })
} }
function updateTime(){ function updateTime(){
fetch("/data") fetch(PUBLIC_URL +"/data")
.then(response => response.json()) .then(response => response.json())
.then(json => json as GetData) .then(json => json as GetData)
.then(time => { .then(time => {
@ -119,7 +122,7 @@ export function scanWifi(){
scanButton.disabled = false; scanButton.disabled = false;
alert("Failed to start see console") alert("Failed to start see console")
} }
ajax.open("POST", "/wifiscan"); ajax.open("POST", PUBLIC_URL+"/wifiscan");
ajax.send(); ajax.send();
} }
@ -453,7 +456,7 @@ let fromWrapper = (() => {
submitFormBtn.onclick = function (){ submitFormBtn.onclick = function (){
updateJson() updateJson()
fetch("/set_config", { fetch(PUBLIC_URL+"/set_config", {
method :"POST", method :"POST",
body: json.value, body: json.value,
@ -465,7 +468,7 @@ let fromWrapper = (() => {
} }
fetch("/get_config") fetch(PUBLIC_URL+"/get_config")
.then(response => response.json()) .then(response => response.json())
.then(loaded => { .then(loaded => {
var currentConfig = loaded as PlantConfig; var currentConfig = loaded as PlantConfig;

View File

@ -1,4 +1,7 @@
<html> <html>
<head>
</head>
<body> <body>
<input type="button" id="test" value="Test"> <input type="button" id="test" value="Test">
<h2>Current Firmware</h2> <h2>Current Firmware</h2>

View File

@ -1,3 +1,6 @@
declare var PUBLIC_URL: string;
export function uploadFile() { export function uploadFile() {
var file1 = document.getElementById("file1") as HTMLInputElement; var file1 = document.getElementById("file1") as HTMLInputElement;
var loaded_n_total = document.getElementById("loaded_n_total"); var loaded_n_total = document.getElementById("loaded_n_total");
@ -29,7 +32,7 @@ export function uploadFile() {
status.innerHTML = ajax.responseText; status.innerHTML = ajax.responseText;
answer.innerHTML = "aborted"; answer.innerHTML = "aborted";
}, false); }, false);
ajax.open("POST", "/ota"); ajax.open("POST", PUBLIC_URL+"/ota");
ajax.send(file); ajax.send(file);
} }
@ -45,7 +48,7 @@ let firmware_buildtime = document.getElementById("firmware_buildtime") as HTMLDi
let firmware_githash = document.getElementById("firmware_githash") as HTMLDivElement; let firmware_githash = document.getElementById("firmware_githash") as HTMLDivElement;
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
fetch("/version") fetch(PUBLIC_URL+"/version")
.then(response => response.json()) .then(response => response.json())
.then(json => json as VersionInfo) .then(json => json as VersionInfo)
.then(versionInfo => { .then(versionInfo => {

View File

@ -1,10 +1,37 @@
const webpack = require('webpack');
const CopyPlugin = require("copy-webpack-plugin");
const path = require('path'); const path = require('path');
const isDevServer = process.env.WEBPACK_SERVE;
console.log("Dev server is " + isDevServer);
var host;
if (isDevServer){
host = 'http://10.23.43.24';
} else {
host = '';
}
module.exports = { module.exports = {
mode: "development", mode: "development",
entry: ['./src/form.ts','./src/ota.ts', "./src/battery.ts"], entry: ['./src/form.ts','./src/ota.ts', "./src/battery.ts"],
devtool: 'inline-source-map', devtool: 'inline-source-map',
plugins: [
new CopyPlugin({
patterns: [
{
from: "src/index.html",
to: "index.html"
}
]
}),
new webpack.DefinePlugin({
PUBLIC_URL: JSON.stringify(host),
}),
new webpack.EnvironmentPlugin({
redirect: 'true'
})
],
module: { module: {
rules: [ rules: [
{ {
@ -21,4 +48,6 @@ module.exports = {
filename: 'bundle.js', filename: 'bundle.js',
path: path.resolve(__dirname, '../src/webserver'), path: path.resolve(__dirname, '../src/webserver'),
}, },
devServer: {
}
}; };