import { Hono } from '@hono/hono'; import { serveStatic } from '@hono/hono/serve-static'; import { html } from '@hono/hono/html'; import { Context } from '@hono/hono'; // Create Hono app const app = new Hono(); // Store AGV positions const agvPositions: Map = new Map(); let server: { shutdown: () => Promise } | null = null; let isRunning = false; // Serve static files app.use('/*', serveStatic({ root: './', getContent: async (path, c) => { try { const file = await Deno.readFile(path); return file; } catch { return null; } } })); // Main page with canvas app.get('/', (c: Context) => { return c.html(html` AGV Position Monitor

AGV Position Monitor

`); }); // API endpoint to get current positions app.get('/positions', (c: Context) => { // Convert Map to array of objects with id and position const positions = Array.from(agvPositions.entries()).map(([id, pos]) => ({ id, position: pos })); return c.json(positions); }); // Handle messages from main thread self.onmessage = (event) => { const message = event.data; if (message.type === 'positionUpdate') { const { agvId, position } = message.data; // console.log("agvId", agvId, "position", position); agvPositions.set(`${agvId.manufacturer}/${agvId.serialNumber}`, position); } else if (message.type === 'shutdown') { stopServer(); } }; // Start the server export async function startServer(port: number = 3001) { if (isRunning) { console.log("Web服务器已在运行中"); return false; } try { server = Deno.serve({ port }, app.fetch); isRunning = true; console.log(`Web服务器已启动,监听端口 ${port}`); return true; } catch (error) { console.error(`服务器启动失败: ${error}`); return false; } } // Stop the server export async function stopServer() { if (!isRunning || !server) { console.log("Web服务器未在运行"); return false; } try { await server.shutdown(); isRunning = false; server = null; console.log('Web服务器已关闭'); return true; } catch (error) { console.error(`服务器关闭失败: ${error}`); return false; } } // Start the server when the worker is initialized startServer();