frontend-ota (#1)
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
2
Provider/frontend/.env
Normal file
2
Provider/frontend/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
VITE_API_BASE=http://192.168.50.216
|
||||
MKLITTLEFS_PATH=W:\Classified\Calendink\Provider\build\littlefs_py_venv\Scripts\littlefs-python.exe
|
||||
@@ -7,6 +7,7 @@
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"build:esp32": "vite build && node scripts/gzip.js",
|
||||
"ota:package": "node scripts/package.js",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
146
Provider/frontend/scripts/package.js
Normal file
146
Provider/frontend/scripts/package.js
Normal file
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* OTA Packaging Script
|
||||
* Generates www.bin from dist/ using mklittlefs or littlefs-python.
|
||||
*/
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import { resolve, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const projectRoot = resolve(__dirname, '..');
|
||||
const distDir = resolve(projectRoot, 'dist');
|
||||
const binDir = resolve(projectRoot, 'bin');
|
||||
const versionFile = resolve(projectRoot, 'version.json');
|
||||
|
||||
// Ensure bin directory exists
|
||||
if (!existsSync(binDir)) {
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Configuration matching partitions.csv (1MB = 1048576 bytes)
|
||||
const FS_SIZE = 1048576;
|
||||
const BLOCK_SIZE = 4096;
|
||||
const PAGE_SIZE = 256;
|
||||
|
||||
console.log('--- OTA Packaging ---');
|
||||
|
||||
/**
|
||||
* Handle versioning: Read current version
|
||||
*/
|
||||
function getVersion() {
|
||||
if (existsSync(versionFile)) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(versionFile, 'utf8'));
|
||||
} catch (e) {
|
||||
console.warn('Warning: Could not read version.json:', e.message);
|
||||
}
|
||||
}
|
||||
return { major: 0, minor: 0, revision: 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment and save revision
|
||||
*/
|
||||
function incrementVersion(version) {
|
||||
try {
|
||||
version.revision = (version.revision || 0) + 1;
|
||||
writeFileSync(versionFile, JSON.stringify(version, null, 2));
|
||||
console.log(`Version incremented to: ${version.major}.${version.minor}.${version.revision} for next build.`);
|
||||
} catch (e) {
|
||||
console.warn('Warning: Could not update version.json:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple .env parser to load MKLITTLEFS_PATH without external dependencies
|
||||
*/
|
||||
function loadEnv() {
|
||||
const envPaths = [
|
||||
resolve(projectRoot, '.env.local'),
|
||||
resolve(projectRoot, '.env')
|
||||
];
|
||||
|
||||
for (const path of envPaths) {
|
||||
if (existsSync(path)) {
|
||||
console.log(`Loading config from: ${path}`);
|
||||
const content = readFileSync(path, 'utf8');
|
||||
content.split('\n').forEach(line => {
|
||||
const [key, ...valueParts] = line.split('=');
|
||||
if (key && valueParts.length > 0) {
|
||||
const value = valueParts.join('=').trim().replace(/^["']|["']$/g, '');
|
||||
process.env[key.trim()] = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadEnv();
|
||||
const version = getVersion();
|
||||
const versionStr = `${version.major}.${version.minor}.${version.revision}`;
|
||||
const outputFile = resolve(binDir, `www_v${versionStr}.bin`);
|
||||
|
||||
if (!existsSync(distDir)) {
|
||||
console.error('Error: dist/ directory not found. Run "npm run build:esp32" first.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Try to find mklittlefs or littlefs-python
|
||||
const findTool = () => {
|
||||
// 1. Check environment variable (from manual set or .env)
|
||||
if (process.env.MKLITTLEFS_PATH) {
|
||||
if (existsSync(process.env.MKLITTLEFS_PATH)) {
|
||||
return process.env.MKLITTLEFS_PATH;
|
||||
}
|
||||
console.warn(`Warning: MKLITTLEFS_PATH set to ${process.env.MKLITTLEFS_PATH} but file not found.`);
|
||||
}
|
||||
|
||||
// 2. Check system PATH
|
||||
const tools = ['mklittlefs', 'littlefs-python'];
|
||||
for (const tool of tools) {
|
||||
try {
|
||||
execSync(`${tool} --version`, { stdio: 'ignore' });
|
||||
return tool;
|
||||
} catch (e) {
|
||||
// Not in path
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const tool = findTool();
|
||||
|
||||
if (!tool) {
|
||||
console.error('Error: No LittleFS tool found (checked mklittlefs and littlefs-python).');
|
||||
console.info('Please set MKLITTLEFS_PATH in your .env file.');
|
||||
console.info('Example: MKLITTLEFS_PATH=C:\\Espressif\\tools\\mklittlefs\\v3.2.0\\mklittlefs.exe');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Using tool: ${tool}`);
|
||||
console.log(`Packaging ${distDir} -> ${outputFile}...`);
|
||||
|
||||
let cmd;
|
||||
// Check if it is the Python version or the C++ version
|
||||
if (tool.includes('littlefs-python')) {
|
||||
// Python style: littlefs-python create <dir> <output> --fs-size=<size> --block-size=<block>
|
||||
cmd = `"${tool}" create "${distDir}" "${outputFile}" --fs-size=${FS_SIZE} --block-size=${BLOCK_SIZE}`;
|
||||
} else {
|
||||
// C++ style: mklittlefs -c <dir> -s <size> -b <block> -p <page> <output>
|
||||
cmd = `"${tool}" -c "${distDir}" -s ${FS_SIZE} -b ${BLOCK_SIZE} -p ${PAGE_SIZE} "${outputFile}"`;
|
||||
}
|
||||
|
||||
console.log(`Running: ${cmd}`);
|
||||
execSync(cmd, { stdio: 'inherit' });
|
||||
console.log('Success: www.bin created.');
|
||||
|
||||
// Auto-increment for the next build
|
||||
incrementVersion(version);
|
||||
} catch (e) {
|
||||
console.error('Error during packaging:', e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
<script>
|
||||
import { getSystemInfo, reboot } from "./lib/api.js";
|
||||
import OTAUpdate from "./lib/OTAUpdate.svelte";
|
||||
|
||||
/** @type {'loading' | 'ok' | 'error' | 'rebooting'} */
|
||||
let status = $state("loading");
|
||||
let errorMsg = $state("");
|
||||
let showRebootConfirm = $state(false);
|
||||
let isRecovering = $state(false);
|
||||
|
||||
let systemInfo = $state({
|
||||
chip: "—",
|
||||
@@ -41,14 +43,17 @@
|
||||
status = "ok";
|
||||
errorMsg = "";
|
||||
} catch (e) {
|
||||
status = "error";
|
||||
errorMsg = e.message || "Connection failed";
|
||||
if (!isRecovering) {
|
||||
status = "error";
|
||||
errorMsg = e.message || "Connection failed";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleReboot() {
|
||||
showRebootConfirm = false;
|
||||
status = "rebooting";
|
||||
isRecovering = true;
|
||||
try {
|
||||
await reboot();
|
||||
} catch (e) {
|
||||
@@ -56,12 +61,27 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Poll every 5 seconds
|
||||
let pollInterval;
|
||||
$effect(() => {
|
||||
fetchInfo();
|
||||
pollInterval = setInterval(fetchInfo, 5000);
|
||||
return () => clearInterval(pollInterval);
|
||||
});
|
||||
|
||||
// Resilient recovery polling: Only poll when we are waiting for a reboot
|
||||
$effect(() => {
|
||||
if (isRecovering) {
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
const info = await getSystemInfo();
|
||||
if (info) {
|
||||
console.log("Device back online! Refreshing UI...");
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (e) {
|
||||
// Still offline or rebooting, just keep waiting
|
||||
console.log("Waiting for device...");
|
||||
}
|
||||
}, 2000);
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
});
|
||||
|
||||
const infoItems = $derived([
|
||||
@@ -77,8 +97,8 @@
|
||||
<div class="w-full max-w-xl space-y-4">
|
||||
<!-- Header -->
|
||||
<div class="text-center mb-6">
|
||||
<h1 class="text-2xl font-bold text-accent">Calendink Provider</h1>
|
||||
<p class="text-text-secondary text-sm">ESP32-S3 System Dashboard</p>
|
||||
<h1 class="text-2xl font-bold text-accent">Calendink Provider 🚀</h1>
|
||||
<p class="text-text-secondary text-sm">ESP32-S3 System Dashboard v{__APP_VERSION__}</p>
|
||||
</div>
|
||||
|
||||
<!-- Status Badge -->
|
||||
@@ -146,11 +166,11 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Reboot Section -->
|
||||
<!-- Device Control Section (Reboot) -->
|
||||
<div class="bg-bg-card border border-border rounded-xl p-5">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold text-text-primary">
|
||||
<h2 class="text-sm font-semibold text-text-primary uppercase tracking-wider">
|
||||
Device Control
|
||||
</h2>
|
||||
<p class="text-xs text-text-secondary mt-1">
|
||||
@@ -170,6 +190,9 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Frontend Info & OTA Section -->
|
||||
<OTAUpdate onReboot={() => (status = "rebooting")} />
|
||||
|
||||
<!-- Reboot Confirmation Modal -->
|
||||
{#if showRebootConfirm}
|
||||
<div
|
||||
@@ -203,9 +226,5 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Footer -->
|
||||
<p class="text-center text-xs text-text-secondary/50 pt-2">
|
||||
Auto-refreshes every 5s
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
203
Provider/frontend/src/lib/OTAUpdate.svelte
Normal file
203
Provider/frontend/src/lib/OTAUpdate.svelte
Normal file
@@ -0,0 +1,203 @@
|
||||
<script>
|
||||
let { onReboot = null } = $props();
|
||||
import { getOTAStatus, uploadOTAFrontend } from "./api.js";
|
||||
|
||||
const IS_DEV = import.meta.env.DEV;
|
||||
|
||||
/** @type {'idle' | 'loading_status' | 'uploading' | 'success' | 'error'} */
|
||||
let status = $state("idle");
|
||||
let errorMsg = $state("");
|
||||
let uploadProgress = $state(0); // 0 to 100
|
||||
|
||||
let otaInfo = $state({
|
||||
active_slot: -1,
|
||||
active_partition: "—",
|
||||
target_partition: "—",
|
||||
});
|
||||
|
||||
let selectedFile = $state(null);
|
||||
let showAdvanced = $state(false);
|
||||
let isDragging = $state(false);
|
||||
|
||||
async function fetchStatus() {
|
||||
status = "loading_status";
|
||||
try {
|
||||
otaInfo = await getOTAStatus();
|
||||
status = "idle";
|
||||
} catch (e) {
|
||||
status = "error";
|
||||
errorMsg = "Failed to fetch OTA status: " + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch status on mount
|
||||
$effect(() => {
|
||||
fetchStatus();
|
||||
});
|
||||
|
||||
function handleFileChange(event) {
|
||||
const files = event.target.files;
|
||||
if (files && files.length > 0) {
|
||||
processFile(files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function handleDrop(event) {
|
||||
event.preventDefault();
|
||||
isDragging = false;
|
||||
const files = event.dataTransfer.files;
|
||||
if (files && files.length > 0) {
|
||||
processFile(files[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function processFile(file) {
|
||||
if (file.name.endsWith('.bin')) {
|
||||
selectedFile = file;
|
||||
errorMsg = "";
|
||||
} else {
|
||||
selectedFile = null;
|
||||
errorMsg = "Please select a valid .bin file";
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUpload() {
|
||||
if (!selectedFile) return;
|
||||
|
||||
status = "uploading";
|
||||
errorMsg = "";
|
||||
uploadProgress = 0;
|
||||
|
||||
const progressInterval = setInterval(() => {
|
||||
if (uploadProgress < 90) uploadProgress += 5;
|
||||
}, 500);
|
||||
|
||||
try {
|
||||
await uploadOTAFrontend(selectedFile);
|
||||
clearInterval(progressInterval);
|
||||
uploadProgress = 100;
|
||||
status = "success";
|
||||
if (onReboot) onReboot();
|
||||
} catch (e) {
|
||||
clearInterval(progressInterval);
|
||||
uploadProgress = 0;
|
||||
status = "error";
|
||||
errorMsg = e.message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if !IS_DEV}
|
||||
<div class="bg-bg-card border border-border rounded-xl overflow-hidden mt-4">
|
||||
<div class="px-5 py-3 border-b border-border flex items-center justify-between">
|
||||
<h2 class="text-sm font-semibold text-text-primary uppercase tracking-wider">
|
||||
Frontend Info
|
||||
</h2>
|
||||
<button
|
||||
onclick={() => showAdvanced = !showAdvanced}
|
||||
class="text-[10px] font-bold uppercase tracking-tight px-2 py-1 rounded bg-border text-text-secondary hover:text-text-primary transition-colors"
|
||||
>
|
||||
{showAdvanced ? 'Hide Tools' : 'OTA Update'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="p-5 space-y-4">
|
||||
<!-- Version & Slot Info -->
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div class="bg-bg-primary/30 p-3 rounded-lg border border-border/50">
|
||||
<div class="text-[10px] uppercase text-text-secondary font-bold mb-1">Version</div>
|
||||
<div class="text-sm font-mono text-accent">v{__APP_VERSION__}</div>
|
||||
</div>
|
||||
<div class="bg-bg-primary/30 p-3 rounded-lg border border-border/50">
|
||||
<div class="text-[10px] uppercase text-text-secondary font-bold mb-1">Active Slot</div>
|
||||
<div class="text-xs font-mono text-text-primary">
|
||||
{otaInfo.active_partition}
|
||||
{#if otaInfo.partitions}
|
||||
<span class="text-text-secondary ml-1">
|
||||
({(otaInfo.partitions.find(p => p.label === otaInfo.active_partition)?.free / 1024 / 1024).toFixed(2)} MB free)
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showAdvanced}
|
||||
<div class="pt-2 border-t border-border/50 space-y-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-xs font-bold text-text-primary">OTA Upgrade</h3>
|
||||
<div class="text-[10px] text-text-secondary">
|
||||
Target: <span class="font-mono">{otaInfo.target_partition}</span>
|
||||
{#if otaInfo.partitions}
|
||||
<span class="ml-1">
|
||||
({(otaInfo.partitions.find(p => p.label === otaInfo.target_partition)?.size / 1024 / 1024).toFixed(2)} MB capacity)
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if status === "success"}
|
||||
<div class="bg-success/10 border border-success/20 text-success p-3 rounded-lg text-xs flex items-center gap-2">
|
||||
<span class="w-1.5 h-1.5 rounded-full bg-success"></span>
|
||||
Update successful! The device is rebooting...
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Drag and Drop Zone -->
|
||||
<div
|
||||
role="button"
|
||||
aria-label="Upload partition image"
|
||||
tabindex="0"
|
||||
class="relative border-2 border-dashed rounded-xl p-6 transition-all duration-200 flex flex-col items-center justify-center gap-2
|
||||
{isDragging ? 'border-accent bg-accent/5' : 'border-border hover:border-border-hover bg-bg-primary/20'}
|
||||
{status === 'uploading' ? 'opacity-50 pointer-events-none' : ''}"
|
||||
ondragover={(e) => { e.preventDefault(); isDragging = true; }}
|
||||
ondragleave={() => isDragging = false}
|
||||
ondrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
accept=".bin"
|
||||
onchange={handleFileChange}
|
||||
class="absolute inset-0 opacity-0 cursor-pointer"
|
||||
/>
|
||||
|
||||
<div class="text-2xl">📦</div>
|
||||
{#if selectedFile}
|
||||
<div class="text-xs font-medium text-text-primary">{selectedFile.name}</div>
|
||||
<div class="text-[10px] text-text-secondary">{(selectedFile.size / 1024).toFixed(1)} KB</div>
|
||||
{:else}
|
||||
<div class="text-xs text-text-primary">Drag & Drop .bin here</div>
|
||||
<div class="text-[10px] text-text-secondary">or click to browse</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if selectedFile}
|
||||
<button
|
||||
onclick={handleUpload}
|
||||
disabled={status === "uploading"}
|
||||
class="w-full py-2 text-xs font-bold rounded-lg transition-colors
|
||||
bg-accent text-white hover:brightness-110
|
||||
disabled:opacity-40"
|
||||
>
|
||||
{status === "uploading" ? 'Processing Update...' : `Flash to ${otaInfo.target_partition}`}
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#if status === "uploading"}
|
||||
<div class="w-full bg-border rounded-full h-1 mt-1 overflow-hidden">
|
||||
<div
|
||||
class="bg-accent h-1 rounded-full transition-all duration-300"
|
||||
style="width: {uploadProgress}%"
|
||||
></div>
|
||||
</div>
|
||||
{:else if status === "error"}
|
||||
<p class="text-[10px] text-danger mt-1 bg-danger/5 p-2 rounded border border-danger/10">
|
||||
{errorMsg}
|
||||
</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -37,3 +37,39 @@ export async function reboot() {
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch OTA status from the ESP32.
|
||||
* @returns {Promise<{active_slot: number, active_partition: string, target_partition: string}>}
|
||||
*/
|
||||
export async function getOTAStatus() {
|
||||
const res = await fetch(`${API_BASE}/api/ota/status`);
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload a new frontend binary image.
|
||||
* @param {File} file The binary file to upload.
|
||||
* @returns {Promise<{status: string, message: string}>}
|
||||
*/
|
||||
export async function uploadOTAFrontend(file) {
|
||||
const res = await fetch(`${API_BASE}/api/ota/frontend`, {
|
||||
method: 'POST',
|
||||
body: file, // Send the raw file Blob/Buffer
|
||||
headers: {
|
||||
// Let the browser set Content-Type for the binary payload,
|
||||
// or we could force application/octet-stream.
|
||||
'Content-Type': 'application/octet-stream'
|
||||
}
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
throw new Error(`Upload failed (${res.status}): ${errorText || res.statusText}`);
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
5
Provider/frontend/version.json
Normal file
5
Provider/frontend/version.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"major": 0,
|
||||
"minor": 1,
|
||||
"revision": 7
|
||||
}
|
||||
@@ -2,9 +2,17 @@ import { defineConfig } from 'vite'
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import { viteSingleFile } from 'vite-plugin-singlefile'
|
||||
import { readFileSync } from 'fs'
|
||||
import { resolve } from 'path'
|
||||
|
||||
const version = JSON.parse(readFileSync(resolve(__dirname, 'version.json'), 'utf8'));
|
||||
const versionString = `${version.major}.${version.minor}.${version.revision}`;
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(versionString),
|
||||
},
|
||||
plugins: [
|
||||
svelte(),
|
||||
tailwindcss(),
|
||||
|
||||
Reference in New Issue
Block a user