diff --git a/.env.example b/.env.example index 6297085..cc5f742 100644 --- a/.env.example +++ b/.env.example @@ -3,9 +3,11 @@ PORT=3000 # Listen on LAN interfaces as well as localhost. CONSOLE_HOST=0.0.0.0 -# Only M3TER Manager requires login. Console itself is public. +# Only M3ter Manager requires login. Console itself is public. M3TER_MANAGER_USERNAME=admin M3TER_MANAGER_PASSWORD= +# Optional global telemetry history limit; invalid values fall back to 100. +# M3TER_TELEMETRY_LIMIT=100 # Module Configuration BACKEND_MODULES="core/arweave,core/is_on,core/prover,core/streamr" @@ -17,11 +19,15 @@ APPLICATION_ID=... CHIRPSTACK_HOST=localhost # Optional web UI origin; defaults to http://CHIRPSTACK_HOST:8080. # Browsers access it through the console's /chirpstack/ proxy. +# CHEFSTACK_URL=http://localhost:8080 +# CHIRPSTACK_WEB_URL remains supported; CHEFSTACK_URL takes precedence. # CHIRPSTACK_WEB_URL=http://localhost:8080 -# M3TER Manager uses the existing ChirpStack v4 REST proxy and the same API_TOKEN. +# M3ter Manager uses the existing ChirpStack v4 REST proxy and the same API_TOKEN. # This is the REST proxy's port, NOT the ChirpStack web UI port. # CHIRPSTACK_REST_URL=http://localhost:8090 -# MQTT reuses CHIRPSTACK_HOST on port 1883, just like the collector. +# Both consumers share this optional broker URL (mqtt/mqtts/ws/wss). +# When absent, preserve CHIRPSTACK_HOST on port 1883, default localhost. +# MQTT_URL=mqtt://localhost:1883 # M3TER_INACTIVE_SECONDS=300 # Contract & Network Configuration diff --git a/README.md b/README.md index 0b81e8e..f6b6435 100644 --- a/README.md +++ b/README.md @@ -76,9 +76,9 @@ npm install npm run dev ``` -## M3TER Manager +## M3ter Manager -**M3TER Manager** is a built-in desktop application for Switch Cumulus telemetry +**M3ter Manager** is a built-in desktop application for Switch Cumulus telemetry and technician downlinks. Launch it from the desktop, dock, or application launcher. Its Overview, Live monitoring, Analytics, Commands, Queue, and Meter information sections share the selected device, desktop theme, and responsive @@ -114,8 +114,10 @@ is needed. The API token needs device/application/profile read access and device queue enqueue/read/flush access for the configured application. MQTT requires permission to subscribe to that application's events. Configure ChirpStack's MQTT integration to publish JSON. Manager reuses the Console's original -`CHIRPSTACK_HOST` connection on port 1883. No new MQTT settings or separate client -are required. Opening or closing Manager does not own or stop this connection. +`CHIRPSTACK_HOST` connection on port 1883 (localhost by default). Optional +`MQTT_URL=mqtt://broker.example:1883` overrides the shared broker address for both +consumers; `mqtts://`, `ws://`, and `wss://` are also supported. URL credentials, +when required by the broker, stay on the backend. No separate client is created. Opening or closing Manager does not own or stop this connection. Both consumers receive messages independently; monitoring errors cannot disable the collector. The old monitor-only toggle has been removed: collection remains enabled. @@ -125,7 +127,7 @@ npm start ``` Then open the console on its configured port (3000 by default) and -launch **M3TER Manager**. The dashboard stays accessible while MQTT reconnects. +launch **M3ter Manager**. The dashboard stays accessible while MQTT reconnects. ### Architecture and API @@ -198,7 +200,17 @@ bounded queries. Uplinks deduplicate by ChirpStack event ID, or by a stable tupl of device/event type/source time/frame counter/payload when an ID is absent. Identical values with distinct events are preserved. Without an event ID or source timestamp, events are retained separately rather than risking data loss. -Source timestamps are preserved in metadata; invalid timestamps use receipt time. +Source timestamps are preserved in metadata; invalid timestamps use receipt time. The Overview's +Last Uplink uses the persisted console reception time of a successfully decoded, +non-duplicate uplink. MQTT heartbeats, connection events, UI refreshes and decode +errors cannot reset it. Source timestamps still drive the existing Analytics. + +MQTT payload transport is explicit: native ChirpStack `data` remains Base64; +hex producers supply `dataHex` or `data` with `dataEncoding: "hex"`. Hex must contain +complete byte pairs, without separators or a `0x` prefix. No alphabet guessing is +used. Both collector and Manager use the same byte conversion. Live Monitoring +shows the hexadecimal bytes and preserves the original field, encoding, and text +for inspection. Downlink encoding and firmware decoders are unchanged. Charts plot **raw accumulator snapshots**, not independent interval consumption. Repeated and growing values with the same nonce stay pending. A consecutive nonce @@ -210,8 +222,10 @@ are flagged, not credited as fresh consumption. Manager sends no automatic ackno Firmware source is not present here: observed transitions cannot establish unobserved energy, reset causes, downlink execution, or blockchain settlement. -The database retains at most **100 uplink records globally**, including malformed -payloads, and prunes their raw event copies too. A separate small per-device state +The database retains **100 uplink records globally by default**, including malformed +payloads. Set optional `M3TER_TELEMETRY_LIMIT` to a positive integer to change this +limit. Invalid values log a warning and safely fall back to 100. The limit applies +on startup and after every insertion, and prunes their raw event copies too. A separate small per-device state preserves the pending nonce/high-water mark and latest reading after eviction or restart. Existing history is replayed once before migration trims it. Non-telemetry activity, command history, device configuration and all original Console tables are preserved. SQLite reuses freed pages; migration does @@ -273,7 +287,10 @@ Open **ChirpStack** from the desktop, dock, or application launcher. Its web interface opens inside a console window; the browser uses `/chirpstack/` on the console's own port. The console server connects to `http://CHIRPSTACK_HOST:8080` (localhost by default). Set -`CHIRPSTACK_WEB_URL=http://your-chirpstack-host:8080` to override the web endpoint, +`CHEFSTACK_URL=http://your-chirpstack-host:8080` to override the web endpoint. +The existing `CHIRPSTACK_WEB_URL` remains supported, with `CHEFSTACK_URL` taking +precedence. Use an HTTP(S) origin without a path or URL credentials. This changes +the web integration only; keep the REST proxy and gRPC configuration as appropriate, or use an HTTPS origin. Only an origin is supported, without credentials or a subpath. In Docker this address must be reachable from the console container. @@ -835,10 +852,10 @@ appearance controls; the containing window follows the application setting. To update the existing Docker deployment from GitHub Actions images: ```sh -./install.sh -./install.sh --project-name your-existing-project +./auto-compose.sh +./auto-compose.sh --project-name your-existing-project # To select a fork/branch image published by the existing workflow: -./install.sh --image ghcr.io/fluxion9/console:feat-revamp +./auto-compose.sh --image ghcr.io/fluxion9/console:feat-revamp ``` Docker and its Compose plugin must already be installed. The script identifies @@ -853,3 +870,27 @@ volumes, database files or `.env` are removed. Other services are never brought `compose.local.yaml` remains available for deliberate developer builds; the update script does not use it. Readiness does not certify broker or blockchain availability. Use the original project name and data directory to preserve the same volumes. + +## Targeted desktop refinements + +The old **M3ters** meter-list application has been removed from the desktop, +along with its exclusive `/delete-meter` UI endpoint. The collector's database, +MQTT service, and meter records are preserved. **M3ter Manager** remains available. + +The Browser starts with a Google search interface. Queries use +`https://www.google.com/search?q=` with URL encoding and open in a new tab because +Google blocks embedded search pages. HTTP(S) addresses can still open inside the +Browser; its external link supports sites that block embedding. + +`compose.yaml` passes the existing `.env` into the single Console container, +which hosts both consumers. The update script leaves that file and persistent +volumes intact, including `MQTT_URL`, `CHEFSTACK_URL`, `M3TER_TELEMETRY_LIMIT`, and +`M3TER_MANAGER_PASSWORD`. No deployment-script or workflow changes are required. + +Application feedback is scoped to its owning window. Extension actions preserve +the originating window even if another app is focused while a request completes. +Use `showNotification(message, type, appElementOrId)` for extension feedback, and +pass `null` for a desktop-wide notice. `AppFeedback.showDialog(dialog, appElement)` +provides an app-contained dialog; `AppFeedback.confirm(appElement, title, message)` +returns a promise for confirmations. These dialogs allow switching to other apps +and inherit the owning application's light/dark mode. diff --git a/install.sh b/auto-compose.sh similarity index 97% rename from install.sh rename to auto-compose.sh index 6811d7d..6b7f82c 100755 --- a/install.sh +++ b/auto-compose.sh @@ -11,7 +11,7 @@ while [[ $# -gt 0 ]]; do if [[ "$1" == --project-name ]]; then project="$2"; else image="$2"; fi shift 2 ;; --help|-h) - echo 'Usage: ./install.sh [--project-name NAME] [--image ghcr.io/OWNER/console:TAG]' + echo 'Usage: ./auto-compose.sh [--project-name NAME] [--image ghcr.io/OWNER/console:TAG]' echo 'Pulls the published image for this device, updates only Console, and preserves .env and all volumes.' exit 0 ;; *) echo "Unknown option: $1" >&2; exit 2 ;; diff --git a/compose.local.yaml b/compose.local.yaml index 377bafd..7977231 100644 --- a/compose.local.yaml +++ b/compose.local.yaml @@ -1,4 +1,4 @@ -# Used by ./install.sh to deploy the current checkout with production data volumes. +# Optional local source build override; auto-compose.sh deploys published images using compose.yaml. services: console: image: m3tering-console:local diff --git a/src/lib/uplink-payload.ts b/src/lib/uplink-payload.ts new file mode 100644 index 0000000..aca6898 --- /dev/null +++ b/src/lib/uplink-payload.ts @@ -0,0 +1,20 @@ +/** Transport decoding only. Firmware decoders consume bytes, never encoded text. + * ChirpStack v4's unmarked `data` is Base64. Hex producers must use `dataHex` + * or explicitly mark `dataEncoding: 'hex'`; alphabet guessing is ambiguous. + */ +export function uplinkPayload(event: { data?: unknown; dataHex?: unknown; dataEncoding?: unknown }) { + const explicitHex = event.dataHex !== undefined; + const field = explicitHex ? 'dataHex' : 'data'; + const raw = explicitHex ? event.dataHex : event.data; + const encoding = explicitHex ? 'hex' : event.dataEncoding ?? 'base64'; + if (typeof raw !== 'string' || !raw || raw.length > 4096) throw new Error('Missing or oversized uplink payload'); + if (encoding !== 'hex' && encoding !== 'base64') throw new Error('Unsupported payload encoding; use hex or base64'); + if (encoding === 'hex') { + if (!/^(?:[a-fA-F0-9]{2})+$/.test(raw)) throw new Error('Invalid hex payload: expected complete hexadecimal byte pairs'); + } else if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(raw)) { + throw new Error('Invalid Base64 payload; hexadecimal data must use dataHex or dataEncoding: hex'); + } + const bytes = Buffer.from(raw, encoding); + if (encoding === 'base64' && bytes.toString('base64') !== raw) throw new Error('Invalid Base64 payload'); + return { bytes, raw, field, encoding, hex: bytes.toString('hex').toUpperCase() }; +} diff --git a/src/m3ter/auth.ts b/src/m3ter/auth.ts index 3dc46ef..799cc5e 100644 --- a/src/m3ter/auth.ts +++ b/src/m3ter/auth.ts @@ -21,7 +21,7 @@ export function managerAuthenticated(req: IncomingMessage): boolean { } export function requireManagerAuth(req: Request, res: Response, next: NextFunction): void { res.setHeader('Cache-Control', 'no-store'); - if (!managerAuthenticated(req)) { res.status(401).json({ error: 'Sign in to M3TER Manager to continue.' }); return; } + if (!managerAuthenticated(req)) { res.status(401).json({ error: 'Sign in to M3ter Manager to continue.' }); return; } next(); } function setCookie(req: Request, res: Response, value: string, maxAge: number) { diff --git a/src/m3ter/config.ts b/src/m3ter/config.ts new file mode 100644 index 0000000..8da3546 --- /dev/null +++ b/src/m3ter/config.ts @@ -0,0 +1,10 @@ +import { createLogger } from '../utils/logger'; + +const logger = createLogger('[manager]'); +export function telemetryLimit(): number { + const value = process.env.M3TER_TELEMETRY_LIMIT; + if (value === undefined) return 100; + if (/^[1-9]\d*$/.test(value) && Number.isSafeInteger(Number(value))) return Number(value); + logger.warn('Invalid M3TER_TELEMETRY_LIMIT; using the safe default of 100 records. Set a positive integer.'); + return 100; +} diff --git a/src/m3ter/monitor.ts b/src/m3ter/monitor.ts index f0ec14e..05e8dcd 100644 --- a/src/m3ter/monitor.ts +++ b/src/m3ter/monitor.ts @@ -4,6 +4,7 @@ import { decodeTelemetry } from './decoder'; import * as store from './store'; import { applicationId, deviceId } from './chirpstack'; import { getMeterByDevEui } from '../store/sqlite'; +import { uplinkPayload } from '../lib/uplink-payload'; export const managerEvents = new EventEmitter(); managerEvents.setMaxListeners(128); @@ -40,23 +41,30 @@ export function ingestEvent(topic: string, blob: Buffer): boolean { const receivedAt = Date.now(), parsedTime = Date.parse(event.time); const timestamp = Number.isFinite(parsedTime) && parsedTime > 0 && parsedTime < receivedAt + 300_000 ? parsedTime : receivedAt; const kind = parts[3].toLowerCase(); - const identity = event.deduplicationId || (event.time ? [event.time, event.fCnt, event.devAddr, event.data, event.queueItemId, event.acknowledged, event.downlinkId] : randomUUID()); + const fields = [event.time, event.fCnt, event.devAddr, event.data, event.queueItemId, event.acknowledged, event.downlinkId]; + if (event.dataHex !== undefined || event.dataEncoding !== undefined) fields.push(event.dataHex, event.dataEncoding); + const identity = event.deduplicationId || (event.time ? fields : randomUUID()); const eventKey = createHash('sha256').update(JSON.stringify([devEui, kind, identity])).digest('hex'); const rx = Array.isArray(event.rxInfo) ? event.rxInfo[0] : null; const metadata: Record = { sourceTime: typeof event.time === 'string' ? event.time.slice(0,100) : null, timestampSource: timestamp === parsedTime ? 'ChirpStack' : 'console receipt', name: String(event.deviceInfo.deviceName || devEui).slice(0, 200), applicationName: String(event.deviceInfo.applicationName || '').slice(0, 200), deviceProfileName: String(event.deviceInfo.deviceProfileName || '').slice(0, 200), fCnt: Number.isInteger(event.fCnt) ? event.fCnt : null, rssi: typeof rx?.rssi === 'number' ? rx.rssi : null, snr: typeof rx?.snr === 'number' ? rx.snr : null, gatewayId: typeof rx?.gatewayId === 'string' ? rx.gatewayId.slice(0, 32) : null }; - const rawPayload = typeof event.data === 'string' ? event.data.slice(0, 4096) : null; + const suppliedPayload = event.dataHex !== undefined ? event.dataHex : event.data; + const rawPayload = typeof suppliedPayload === 'string' ? suppliedPayload.slice(0, 4096) : null; + metadata.payloadField = event.dataHex !== undefined ? 'dataHex' : 'data'; + metadata.payloadEncoding = event.dataHex !== undefined ? 'hex' : event.dataEncoding ?? 'base64'; + if (typeof event.data === 'string' && event.dataHex !== undefined) metadata.upstreamData = event.data.slice(0, 4096); const record: store.ManagerEvent = { application, devEui, kind, source: 'ChirpStack', timestamp, receivedAt, eventKey, rawPayload, fPort: Number.isInteger(event.fPort) ? event.fPort : null, metadata, message: `ChirpStack ${kind} event` }; let inserted: boolean; if (kind === 'up') { let telemetry; try { - if (!rawPayload || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(rawPayload) || rawPayload !== event.data) throw new Error('Invalid Base64 payload'); + const payload = uplinkPayload(event); + metadata.payloadHex = payload.hex; const knownKey = store.deviceState(application, devEui)?.publicKey || getMeterByDevEui(devEui)?.publicKey; - telemetry = decodeTelemetry(event.fPort, Buffer.from(rawPayload, 'base64'), knownKey); + telemetry = decodeTelemetry(event.fPort, payload.bytes, knownKey); record.message = telemetry.verification === 'invalid' ? 'Telemetry decoded; signature INVALID. Voltage is outside the signed fields.' : 'Uplink decoded'; } catch (error) { record.kind = 'decode-error'; record.message = (error as Error).message; } inserted = store.recordUplink(record, telemetry, inactiveMilliseconds()); diff --git a/src/m3ter/store.ts b/src/m3ter/store.ts index bb63042..5573bbd 100644 --- a/src/m3ter/store.ts +++ b/src/m3ter/store.ts @@ -2,8 +2,11 @@ import type { Database } from 'better-sqlite3'; import { randomUUID } from 'crypto'; import type { Telemetry } from './decoder'; import { advance, Accumulator } from './accumulator'; +import { telemetryLimit } from './config'; let db: Database; +let retentionLimit = 100; export function initializeManagerStore(connection: Database): void { + retentionLimit = telemetryLimit(); db = connection; db.exec(` CREATE TABLE IF NOT EXISTS manager_devices (application TEXT, devEui TEXT, metadata TEXT NOT NULL DEFAULT '{}', publicKey TEXT, @@ -48,6 +51,13 @@ export function initializeManagerStore(connection: Database): void { } db.prepare('INSERT INTO manager_schema(version) VALUES(1)').run(); } + // Recover receipt times from persisted records, never from the startup clock. + if (!db.prepare('SELECT version FROM manager_schema WHERE version=2').get()) { + db.exec(`UPDATE manager_devices SET lastUplink=NULLIF(MAX( + COALESCE((SELECT MAX(receivedAt) FROM manager_readings r WHERE r.application=manager_devices.application AND r.devEui=manager_devices.devEui),0), + COALESCE((SELECT json_extract(latest,'$.receivedAt') FROM manager_accumulators a WHERE a.application=manager_devices.application AND a.devEui=manager_devices.devEui),0)),0); + INSERT INTO manager_schema(version) VALUES(2);`); + } trimHistory(); })(); // A process may have stopped after the upstream accepted a command. Never resend automatically. @@ -56,11 +66,11 @@ export function initializeManagerStore(connection: Database): void { // Global cap includes malformed and unsupported uplinks, so their raw payloads // cannot bypass retention. Device state survives deletion of any history row. function trimHistory(): void { - db.exec(`DELETE FROM manager_readings WHERE id IN ( + db.prepare(`DELETE FROM manager_readings WHERE id IN ( SELECT id FROM manager_events WHERE kind IN ('up','decode-error') - ORDER BY timestamp DESC,id DESC LIMIT -1 OFFSET 100); - DELETE FROM manager_events WHERE kind IN ('up','decode-error') AND id NOT IN ( - SELECT id FROM manager_events WHERE kind IN ('up','decode-error') ORDER BY timestamp DESC,id DESC LIMIT 100);`); + ORDER BY timestamp DESC,id DESC LIMIT -1 OFFSET ?)`).run(retentionLimit); + db.prepare(`DELETE FROM manager_events WHERE kind IN ('up','decode-error') AND id NOT IN ( + SELECT id FROM manager_events WHERE kind IN ('up','decode-error') ORDER BY timestamp DESC,id DESC LIMIT ?)`).run(retentionLimit); } export function accumulatorState(application: string, devEui: string): Accumulator | null { const row: any = db.prepare('SELECT state FROM manager_accumulators WHERE application=? AND devEui=?').get(application, devEui); @@ -112,11 +122,11 @@ export function recordUplink(event: ManagerEvent, telemetry?: Telemetry, inactiv const id = addEvent(event); if (id === null) return false; const old = deviceState(event.application, event.devEui!); updateDevice(event.application, event.devEui!, event.metadata); - const recent = Math.max(event.timestamp, old?.lastUplink || 0) >= Date.now() - inactiveAfter; + if (!telemetry) { trimHistory(); return true; } + const recent = Math.max(event.receivedAt, old?.lastUplink || 0) >= Date.now() - inactiveAfter; if (recent && (!old?.lastUplink || old.activity === 'inactive')) applicationEvent(event.application, event.devEui, 'active', 'Uplink observed after no recent activity'); db.prepare('UPDATE manager_devices SET lastUplink=MAX(COALESCE(lastUplink,0),?),activity=? WHERE application=? AND devEui=?') - .run(event.timestamp, recent ? 'active' : 'inactive', event.application, event.devEui); - if (!telemetry) { trimHistory(); return true; } + .run(event.receivedAt, recent ? 'active' : 'inactive', event.application, event.devEui); db.prepare(`INSERT INTO manager_readings(id,application,devEui,timestamp,receivedAt,fPort,nonce,rawEnergy,energy,rawVoltage,voltage,signature,publicKey,verification,decoded) VALUES(@id,@application,@devEui,@timestamp,@receivedAt,@fPort,@nonce,@rawEnergy,@energy,@rawVoltage,@voltage,@signature,@publicKey,@verification,@decoded)`) .run({ id, application: event.application, devEui: event.devEui, timestamp: event.timestamp, receivedAt: event.receivedAt, fPort: event.fPort, @@ -155,7 +165,7 @@ export function history(application: string, devEui: string, from: number, to: n COALESCE(SUM(accounting='cycle-advanced'),0) AS resets, COALESCE(SUM(accounting IN ('nonce-reset-or-gap','counter-reset-uncertain','uncertain-cycle-ended','late-report','invalid-signature')),0) AS uncertainReports, COALESCE(SUM(accounting='repeated-total'),0) AS repeatedReports FROM manager_readings r ${where}`).get(args); - return { rows, chart, total: summary.reports, offset, limit, summary, sampled: false, retentionLimit: 100 }; + return { rows, chart, total: summary.reports, offset, limit, summary, sampled: false, retentionLimit }; } export function events(application: string, devEui: string, offset = 0): any[] { return db.prepare(`SELECT * FROM manager_events WHERE application=? AND (devEui=? OR devEui IS NULL) diff --git a/src/public/browser-home.html b/src/public/browser-home.html new file mode 100644 index 0000000..36206c0 --- /dev/null +++ b/src/public/browser-home.html @@ -0,0 +1,4 @@ + +Google search · Console Browser + +

Search with Google

Enter a search in the toolbar above. Google results open in a new tab because Google does not allow embedded search pages.

You can also enter an HTTP or HTTPS address to browse here. If a site blocks embedding, use “Open in new tab”.

diff --git a/src/public/css/global.css b/src/public/css/global.css index 3f7ccea..ed2ebd6 100644 --- a/src/public/css/global.css +++ b/src/public/css/global.css @@ -153,16 +153,7 @@ label { display:block; } .input-row { display:flex; gap:10px; } .input-row input { flex:1; min-width:0; } .input-row button { white-space:nowrap; } -.meter-form { padding:18px; background:var(--surface-alt); border:1px solid var(--border); border-radius:var(--small-radius); margin-bottom:24px; } -.meter-form label { font-size:11px; margin-bottom:8px; } .table-scroll { max-width:100%; overflow:auto; } -.meter-table { width:100%; border-collapse:collapse; font-size:12px; } -.meter-table th { color:var(--muted); font-weight:500; font-size:11px; text-align:left; padding:12px; border-bottom:1px solid var(--border); } -.meter-table td { padding:14px 12px; border-bottom:1px solid var(--border); } -.meter-table td:first-child { white-space:nowrap; } -.public-key { overflow-wrap:anywhere; font:11px/1.6 ui-monospace,monospace; } -.meter-avatar { display:inline-grid; place-items:center; background:var(--surface-alt); width:32px; height:32px; border-radius:var(--small-radius); margin-right:10px; } -.meter-avatar svg { width:20px; height:20px; } .danger { color:#b54d51; } .empty-state { text-align:center; padding:40px 10px; color:var(--muted); } .empty-state svg { width:36px; height:36px; } @@ -321,7 +312,7 @@ dialog::backdrop { background:#14232e88; backdrop-filter:blur(3px); }dialog h2 { .settings-layout { flex-direction:column; }.settings-nav { width:100%; padding:8px; flex-direction:row; gap:5px; border-right:0; border-bottom:1px solid var(--border); }.settings-identity,.settings-footnote { display:none; }.settings-nav button { flex:1; justify-content:center; gap:6px; padding:10px 6px; min-height:44px; font-size:11px; }.settings-nav button svg { width:16px; height:16px; }.settings-content { padding:22px 18px; } .theme-grid { gap:12px; }.theme-preview { height:90px; }.theme-card-title { font-size:11px; }.theme-card small { font-size:10px; }.theme-card-copy { padding:8px 4px; }.theme-check { flex-shrink:0; } .setting-row { gap:12px; }.setting-row select { max-width:110px; }.setting-row .nes-btn { padding:8px 10px; }.switch { width:44px; height:28px; }.switch::after { width:20px; height:20px; } - .browser-toolbar { flex-wrap:wrap; gap:6px; font-size:11px; }.meter-table td,.meter-table th { padding:10px 6px; }.meter-avatar { display:none; }.input-row { flex-wrap:wrap; }.input-row button { flex:1; }.input-row input { flex-basis:160px; } + .browser-toolbar { flex-wrap:wrap; gap:6px; font-size:11px; }.input-row { flex-wrap:wrap; }.input-row button { flex:1; }.input-row input { flex-basis:160px; } .nes-btn,.quiet-button { min-height:44px; }.extension-window .window-content { overflow-wrap:anywhere; }.extension-window .nes-container { padding:14px; } .publisher-stat { padding:16px; }.publisher-stat #streamr-last-publish { font-size:15px; } } @@ -358,3 +349,17 @@ dialog::backdrop { background:#14232e88; backdrop-filter:blur(3px); }dialog h2 { #paint-status { margin:0; padding:0 12px 8px; font:12px var(--font-body, sans-serif); } .paint-surface { overflow:auto; flex:1; min-height:0; padding:12px; background:var(--surface-muted); } #paint-canvas { display:block; width:100%; max-width:1200px; height:auto; background:#fff; touch-action:none; cursor:crosshair; } + +#browser-search { display:flex; flex:1; gap:8px; min-width:0; } +#browser-query { flex:1; width:100%; min-width:0; } + +/* Feedback is positioned and clipped by its owning app, never the desktop. */ +.app-notification-area { position:absolute; z-index:20; right:12px; bottom:12px; width:min(380px,calc(100% - 24px)); max-height:40%; overflow:auto; pointer-events:none; } +.notification { display:flex; align-items:flex-start; gap:12px; overflow-wrap:anywhere; pointer-events:auto; } +.notification > span { flex:1; min-width:0; } +.notification > button { flex-shrink:0; } +.app-dialog-layer { position:absolute; z-index:30; inset:48px 0 0; padding:12px; display:flex; align-items:center; justify-content:center; background:#14232e88; } +.app-dialog-layer > dialog.app-dialog { position:relative; inset:auto; margin:0; width:min(430px,100%); max-width:100%; max-height:100%; overflow:auto; overscroll-behavior:contain; padding:24px; } +.app-dialog-layer > #mm-dialog { width:min(540px,100%); max-height:100%; } +@media(max-width:700px) { .app-dialog-layer { padding:8px; } .app-dialog-layer > dialog.app-dialog { padding:18px; } } +@media(max-height:500px) and (min-width:701px) { .app-dialog-layer { top:40px; } } diff --git a/src/public/js/actions.js b/src/public/js/actions.js index 58cdf24..cc36904 100644 --- a/src/public/js/actions.js +++ b/src/public/js/actions.js @@ -11,6 +11,8 @@ * @returns {Promise<{success: boolean, message?: string, data?: any}>} */ async function invokeAction(moduleId, actionId, buttonElement) { + // Capture ownership before awaiting: switching apps must not redirect feedback. + const owner = buttonElement?.closest('.app-window') || document.getElementById(moduleId)?.closest('.app-window') || null; // Show loading state if button provided let originalContent = null; if (buttonElement) { @@ -32,15 +34,15 @@ async function invokeAction(moduleId, actionId, buttonElement) { // Show result feedback if (result.success) { - showNotification(result.message || "Action completed successfully", "success"); + showNotification(result.message || "Action completed successfully", "success", owner); } else { - showNotification(result.message || "Action failed", "error"); + showNotification(result.message || "Action failed", "error", owner); } return result; } catch (error) { console.error("Action invocation failed:", error); - showNotification("Failed to invoke action: " + error.message, "error"); + showNotification("Failed to invoke action: " + error.message, "error", owner); return { success: false, message: error.message }; } finally { // Restore button state @@ -52,15 +54,8 @@ async function invokeAction(moduleId, actionId, buttonElement) { } } -// Shared themed feedback for built-in applications and extensions. -let notificationTimer; -function showNotification(message, type) { - const area = document.getElementById('notification-area'); - if (!area) return; - clearTimeout(notificationTimer); - const notification = document.createElement('div'); - notification.className = 'notification ' + (type === 'error' ? 'error' : 'success'); - notification.textContent = message; - area.replaceChildren(notification); - notificationTimer = setTimeout(() => notification.remove(), 6000); +// Extensions can pass their app element or app ID as the third argument. +// Pass null explicitly for a desktop-wide notification. +function showNotification(message, type, owner) { + AppFeedback.notify(message, type, owner); } diff --git a/src/public/js/app-feedback.js b/src/public/js/app-feedback.js new file mode 100644 index 0000000..e5921b9 --- /dev/null +++ b/src/public/js/app-feedback.js @@ -0,0 +1,89 @@ +/* App-owned feedback stays in the window's stacking context and color theme. */ +(() => { + const dialogs = new Map(), timers = new WeakMap(); + const app = owner => typeof owner === 'string' ? document.getElementById(owner)?.closest('.app-window') : owner?.closest('.app-window'); + function notify(message, type = 'success', owner = document.activeElement?.closest('.app-window') || document.querySelector('.app-window.is-active')) { + const window = app(owner); + let area = window?.querySelector(':scope > .app-notification-area'); + if (window && !area) { + area = document.createElement('div'); area.className = 'app-notification-area'; + area.setAttribute('aria-live', 'polite'); area.setAttribute('aria-atomic', 'true'); window.append(area); + } + area ||= document.getElementById('notification-area'); + if (!area) return; + clearTimeout(timers.get(area)); + const notification = document.createElement('div'); notification.className = `notification ${type === 'error' ? 'error' : 'success'}`; + const text = document.createElement('span'); text.textContent = message; + const dismiss = document.createElement('button'); dismiss.type = 'button'; dismiss.className = 'quiet-button'; + dismiss.textContent = '×'; dismiss.setAttribute('aria-label', 'Dismiss notification'); + dismiss.addEventListener('click', () => { clearTimeout(timers.get(area)); notification.remove(); }); + notification.append(text, dismiss); area.replaceChildren(notification); + timers.set(area, setTimeout(() => { + // Background results remain available in their originating application. + if (!window || (!window.hidden && window.classList.contains('is-active'))) notification.remove(); + }, 6000)); + } + function showDialog(dialog, owner) { + const window = app(owner); + if (!window || dialog.open) return; + const opener = document.activeElement; + const overlay = document.createElement('div'); overlay.className = 'app-dialog-layer'; + const restore = new Map(); + dialog.classList.add('app-dialog'); dialog.setAttribute('aria-modal', 'false'); + const heading = dialog.querySelector('h2'); + if (heading) { heading.id ||= `${dialog.id}-heading`; dialog.setAttribute('aria-labelledby', heading.id); } + overlay.append(dialog); window.append(overlay); + for (const child of window.children) { + if (child !== overlay && !child.classList.contains('window-titlebar')) { restore.set(child, child.inert); child.inert = true; } + } + const abort = new AbortController(); + const focusable = () => [...dialog.querySelectorAll('button,input,select,textarea,a[href],[tabindex]')] + .filter(element => !element.disabled && element.tabIndex >= 0 && element.getClientRects().length); + const focus = () => (dialog.querySelector('[autofocus]') || focusable()[0] || dialog).focus(); + dialog.tabIndex = -1; + dialog.addEventListener('keydown', event => { + if (event.key === 'Escape') { + event.preventDefault(); event.stopPropagation(); + if (dialog.dispatchEvent(new Event('cancel', { cancelable: true }))) dialog.close('cancel'); + } else if (event.key === 'Tab') { + const items = focusable(), first = items[0], last = items[items.length - 1]; + if (!first) { event.preventDefault(); dialog.focus(); } + else if (event.shiftKey && (document.activeElement === first || document.activeElement === dialog)) { event.preventDefault(); last.focus(); } + else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } + } + }, { signal: abort.signal }); + // Clicking another app is allowed; clicking this app's backdrop returns focus. + overlay.addEventListener('pointerdown', event => { if (event.target === overlay) { event.preventDefault(); focus(); } }, { signal: abort.signal }); + const cleanup = () => { + abort.abort(); restore.forEach((inert, child) => { child.inert = inert; }); + window.append(dialog); overlay.remove(); dialogs.delete(dialog); + if (!window.hidden && window.classList.contains('is-active') && window.contains(opener) && opener.isConnected) opener.focus(); + }; + dialog.addEventListener('close', cleanup, { once: true }); + dialogs.set(dialog, window); + dialog.show(); focus(); + } + function confirm(owner, title, message, accept = 'Confirm') { + const window = app(owner); + if (!window || [...dialogs.values()].includes(window)) return Promise.resolve(false); + const dialog = document.createElement('dialog'); dialog.id = `${window.id}-confirmation`; + const form = document.createElement('form'); form.method = 'dialog'; + const heading = document.createElement('h2'); heading.textContent = title; + const detail = document.createElement('p'); detail.textContent = message; + const controls = document.createElement('div'); controls.className = 'dialog-actions'; + const cancel = document.createElement('button'); cancel.className = 'nes-btn'; cancel.value = 'cancel'; cancel.textContent = 'Cancel'; cancel.autofocus = true; + const submit = document.createElement('button'); submit.className = 'nes-btn is-primary'; submit.value = 'confirm'; submit.textContent = accept; + controls.append(cancel, submit); form.append(heading, detail, controls); dialog.append(form); + return new Promise(resolve => { + showDialog(dialog, window); + dialog.addEventListener('close', () => { const accepted = dialog.returnValue === 'confirm'; dialog.remove(); resolve(accepted); }, { once: true }); + }); + } + window.addEventListener('desktop:close', event => { + for (const [dialog, owner] of dialogs) if (owner.id === event.detail.id) dialog.close('cancel'); + }); + window.addEventListener('desktop:open', event => { + for (const [dialog, owner] of dialogs) if (owner.id === event.detail.id && dialog.open) dialog.focus(); + }); + window.AppFeedback = Object.freeze({ notify, showDialog, confirm }); +})(); diff --git a/src/public/js/browser.js b/src/public/js/browser.js new file mode 100644 index 0000000..a000a71 --- /dev/null +++ b/src/public/js/browser.js @@ -0,0 +1,21 @@ +(() => { + const form = document.getElementById('browser-search'); + form.addEventListener('submit', event => { + const input = document.getElementById('browser-query').value.trim(); + if (!input) { event.preventDefault(); return; } + const external = document.getElementById('browser-external'); + if (/^https?:\/\//i.test(input)) { + event.preventDefault(); + try { + const url = new URL(input); + if (url.username || url.password) throw new Error(); + document.querySelector('#browser iframe').src = url.href; + external.href = url.href; + } catch { showNotification('Enter a valid HTTP or HTTPS address without credentials.', 'error', document.getElementById('browser')); } + return; + } + document.getElementById('browser-query').value = input; + external.href = `https://www.google.com/search?q=${encodeURIComponent(input)}`; + // Native GET form submission performs URL encoding and opens Google top-level. + }); +})(); diff --git a/src/public/js/click.js b/src/public/js/click.js index a894b63..19f0bb4 100644 --- a/src/public/js/click.js +++ b/src/public/js/click.js @@ -5,11 +5,3 @@ function clickButton() { interfaceClick.currentTime = 0; interfaceClick.play().catch(() => {}); } -function deleteMeter(publicKey) { - clickButton(); - fetch('/delete-meter?publicKey=' + encodeURIComponent(publicKey), { method: 'DELETE' }) - .then(async response => { - if (!response.ok) throw new Error((await response.json()).message || 'Unable to delete meter'); - window.location.reload(); - }).catch(error => showNotification(error.message, 'error')); -} diff --git a/src/public/js/desktop.js b/src/public/js/desktop.js index fd81688..be6723b 100644 --- a/src/public/js/desktop.js +++ b/src/public/js/desktop.js @@ -47,7 +47,7 @@ function persist() { if (!P.save(preferences) && !storageWarning) { storageWarning = true; - showNotification('Browser storage is unavailable. Preferences will last for this visit only.', 'error'); + showNotification('Browser storage is unavailable. Preferences will last for this visit only.', 'error', null); } } function updatePreferences(patch) { @@ -106,7 +106,8 @@ if (Object.keys(preferences.positions).length) { // Native dialogs retain returnValue between openings, including Escape. $('reset-dialog').returnValue = 'cancel'; - $('reset-dialog').showModal(); + if ($('settings').hidden || !$('settings').classList.contains('is-active')) launch('settings'); + AppFeedback.showDialog($('reset-dialog'), $('settings')); } else updatePreferences({ mode: 'auto', positions: {} }); } @@ -245,6 +246,7 @@ if (focus) win.element.querySelector('.window-titlebar').focus({ preventScroll: true }); } $('active-app-name').textContent = win ? win.element.dataset.windowTitle : 'Desktop'; + document.title = win ? `${win.element.dataset.windowTitle} · M3tering Console` : 'M3tering Console · Desktop'; syncDock(); } function nextWindow() { @@ -353,7 +355,7 @@ function launch(id) { const app = registry.get(id); const win = app && windows.get(app.windowId); - if (!win) { showNotification('This extension has no application window available.', 'error'); return; } + if (!win) { showNotification('This extension has no application window available.', 'error', null); return; } closeLauncher(false); $('desktop-context').hidden = true; const wasOpen = win.open; diff --git a/src/public/js/m3ter-commands.js b/src/public/js/m3ter-commands.js index 3eaa862..47a68ff 100644 --- a/src/public/js/m3ter-commands.js +++ b/src/public/js/m3ter-commands.js @@ -10,7 +10,7 @@ submit.textContent = button || 'Close'; submit.hidden = !button; $('mm-cancel').textContent = button ? 'Cancel' : 'Close'; $('mm-confirm-label').hidden = !sensitive; confirm.checked = false; submit.disabled = !!sensitive; - if (!dialog.open) dialog.showModal(); + if (!dialog.open) AppFeedback.showDialog(dialog, $('m3ter-manager')); } confirm.addEventListener('change', () => { submit.disabled = !confirm.checked; }); $('mm-cancel').addEventListener('click', () => { if (!working) dialog.close(); }); @@ -58,7 +58,7 @@ $('mm-queue-clear').addEventListener('click', () => { const device = selected(); if (!device?.devEui || working) return; intent = { type: 'clear', devEui: device.devEui }; - display('Clear this meter’s queue?', [node('p', `${device.name} · ${device.devEui}`), node('p', 'This removes ALL currently queued downlinks for this meter, including commands queued outside M3TER Manager. Previously transmitted commands cannot be recalled.')], 'Clear all pending downlinks', true); + display('Clear this meter’s queue?', [node('p', `${device.name} · ${device.devEui}`), node('p', 'This removes ALL currently queued downlinks for this meter, including commands queued outside M3ter Manager. Previously transmitted commands cannot be recalled.')], 'Clear all pending downlinks', true); }); function renderCatalogue(commands) { catalogue = commands; const parent = $('mm-commands'); parent.replaceChildren(); @@ -92,7 +92,7 @@ const data = await api(`/devices/${device.devEui}/commands?offset=${historyOffset}`); if (selected()?.devEui !== device.devEui) return; const parent = $('mm-command-history'); if (!append) parent.replaceChildren(); - if (!data.commands.length && !append) parent.append(node('p', 'No commands have been submitted from M3TER Manager.', 'mm-note')); + if (!data.commands.length && !append) parent.append(node('p', 'No commands have been submitted from M3ter Manager.', 'mm-note')); data.commands.forEach(row => parent.append(recordDetails(`${new Date(row.timestamp).toLocaleString()} · ${row.command.name}${row.command.parameter ? ' · ' + row.command.parameter : ''} · ${row.status}`, row.command, `${row.detail || 'Awaiting delivery evidence.'} Queue ID: ${row.queueId || 'Unavailable'} · Submitted by ${row.actor}`))); historyOffset += data.commands.length; $('mm-commands-more').hidden = data.commands.length < 50; diff --git a/src/public/js/m3ter-manager.js b/src/public/js/m3ter-manager.js index 5856ce0..ff30f37 100644 --- a/src/public/js/m3ter-manager.js +++ b/src/public/js/m3ter-manager.js @@ -50,7 +50,7 @@ if (!device) return; text('mm-name', device.name || device.devEui); text('mm-eui', device.devEui); text('mm-energy', fixed(latest?.energy, 6)); text('mm-voltage', fixed(latest?.voltage, 1)); text('mm-nonce', latest?.nonce ?? '—'); - text('mm-energy-time', latest ? `${date(latest.timestamp)} · ${state?.accumulation?.uncertain ? 'Uncertain cycle' : 'Pending snapshot'} · signed fields ${latest.verification}` : 'Awaiting telemetry'); + text('mm-energy-time', latest ? date(latest.timestamp) : 'Awaiting telemetry'); text('mm-voltage-note', device.phaseMode === 'three-phase' && latest ? `Sum of phases · calculated mean ${fixed(latest.voltage / 3, 1)} V (metadata mode)` : `Transmitted value · ${device.phaseMode || 'phase mode unknown'}`); const values = [ ['Meter', device.name], ['DevEUI', device.devEui], ['Application', device.applicationName || state?.metadata?.applicationName], @@ -72,14 +72,22 @@ } function renderHistory() { if (!historyData) return; - for (const view of ['overview', 'history']) for (const field of ['energy','voltage']) M3terCharts.render($(`mm-${view}-${field}`), historyData.chart, field); + for (const view of ['overview', 'history']) for (const field of ['energy','voltage']) { + const container = $(`mm-${view}-${field}`); + M3terCharts.render(container, historyData.chart, field); + // Keep Analytics unchanged while simplifying the Overview for screen readers too. + if (view === 'overview') { + const svg = container.querySelector('svg'); + if (svg) svg.setAttribute('aria-label', `${field === 'energy' ? 'Energy in kWh' : 'Voltage in volts'}. Use left and right arrows to inspect readings.`); + } + } const summary = historyData.summary; - text('mm-summary', `${historyData.total} retained reports (100 globally). Completed-cycle observed lower bounds: ${fixed(summary?.observedConsumption || 0, 6)} kWh. Collector-recorded energy in those completed cycles: ${fixed(summary?.collectedEnergy || 0, 6)} kWh. These are not blockchain settlement totals. Pending snapshots are not added. ${summary?.uncertainReports || 0} uncertain or delayed reports.`); + text('mm-summary', `${historyData.total} retained reports (${historyData.retentionLimit} globally). Completed-cycle observed lower bounds: ${fixed(summary?.observedConsumption || 0, 6)} kWh. Collector-recorded energy in those completed cycles: ${fixed(summary?.collectedEnergy || 0, 6)} kWh. These are not blockchain settlement totals. Pending snapshots are not added. ${summary?.uncertainReports || 0} uncertain or delayed reports.`); const parent = $('mm-readings'); parent.replaceChildren(); historyData.rows.forEach(row => { const tr = node('tr'); [date(row.timestamp), fixed(row.energy,6), fixed(row.voltage,1), row.nonce, row.fPort].forEach(value => tr.append(node('td', String(value)))); const td = node('td'), button = node('button', 'Inspect', 'nes-btn'); button.addEventListener('click', () => commands.inspect('Uplink details', - `Meter: ${row.devEui}\nUTC: ${new Date(row.timestamp).toISOString()}\nReceived: ${new Date(row.receivedAt).toISOString()}\nFPort: ${row.fPort}\nNonce: ${row.nonce}\nRaw energy: ${row.rawEnergy}\nAccumulator: ${row.energy} kWh\nCompleted previous cycle lower bound: ${row.intervalEnergy ?? 'Pending / uncertain'} kWh\nCollector-recorded energy for completed cycle: ${row.collectedEnergy ?? 'Unavailable'} kWh\nCompleted nonce: ${row.completedNonce ?? 'None'}\nAccounting: ${row.accounting}\nRaw voltage: ${row.rawVoltage}\nVoltage: ${row.voltage} V\nSignature status: ${row.verification}\nSignature (hex): ${row.signature}\nPublic key: ${row.publicKey || 'Not present in this uplink'}\nRaw payload (Base64): ${row.rawPayload}\nRadio metadata: ${row.metadata}`)); td.append(button); tr.append(td); parent.append(tr); + `Meter: ${row.devEui}\nUTC: ${new Date(row.timestamp).toISOString()}\nReceived: ${new Date(row.receivedAt).toISOString()}\nFPort: ${row.fPort}\nNonce: ${row.nonce}\nRaw energy: ${row.rawEnergy}\nAccumulator: ${row.energy} kWh\nCompleted previous cycle lower bound: ${row.intervalEnergy ?? 'Pending / uncertain'} kWh\nCollector-recorded energy for completed cycle: ${row.collectedEnergy ?? 'Unavailable'} kWh\nCompleted nonce: ${row.completedNonce ?? 'None'}\nAccounting: ${row.accounting}\nRaw voltage: ${row.rawVoltage}\nVoltage: ${row.voltage} V\nSignature status: ${row.verification}\nSignature (hex): ${row.signature}\nPublic key: ${row.publicKey || 'Not present in this uplink'}\nRaw payload (${JSON.parse(row.metadata || '{}').payloadEncoding === 'hex' ? 'Hex' : 'Base64'}): ${row.rawPayload}\nRadio metadata: ${row.metadata}`)); td.append(button); tr.append(td); parent.append(tr); }); if (!historyData.rows.length) { const tr = node('tr'), cell = node('td', 'No readings in this range.'); cell.colSpan = 6; tr.append(cell); parent.append(tr); } text('mm-history-count', `${historyData.total ? historyOffset + 1 : 0}–${Math.min(historyOffset + historyData.rows.length, historyData.total)} of ${historyData.total}`); @@ -91,7 +99,17 @@ const data = await api(`/devices/${current}/events?offset=${eventOffset}`); if (device?.devEui !== current) return; const parent = $('mm-events'); if (!append) parent.replaceChildren(); if (!data.events.length && !append) parent.append(node('li', 'No activity recorded yet.')); - data.events.forEach(event => { const li = node('li'); li.append(node('strong', event.message), node('small', `${date(event.timestamp)} · ${event.source}${event.devEui ? '' : ' · application-wide'}`)); parent.append(li); }); + data.events.forEach(event => { + const li = node('li'); li.append(node('strong', event.message), node('small', `${date(event.timestamp)} · ${event.source}${event.devEui ? '' : ' · application-wide'}`)); + if (event.rawPayload !== null && event.rawPayload !== undefined) { + const metadata = typeof event.metadata === 'string' ? JSON.parse(event.metadata) : event.metadata || {}; + const details = node('details'); details.append(node('summary', 'Inspect payload')); + if (metadata.payloadHex) details.append(node('small', 'Payload (hex)'), node('code', metadata.payloadHex, 'mm-long-code')); + details.append(node('small', `Original ${metadata.payloadField || 'data'} (${metadata.payloadEncoding || 'base64'})`), node('code', event.rawPayload, 'mm-long-code')); + li.append(details); + } + parent.append(li); + }); eventOffset += data.events.length; $('mm-events-more').hidden = data.events.length < 100; } async function refresh(telemetryOnly = false) { @@ -179,7 +197,7 @@ try { config = await api('/config'); if (!active || version !== authVersion) return; monitoring = config.monitoring; commands.renderCatalogue(config.commands); if (config.demo) root.querySelector('.mm-brand small').textContent = 'Demo network · simulated meters'; await loadDevices(); if (!active || version !== authVersion) return; - notice(config.billingAutomationActive ? 'Existing console billing automation is enabled and may also control these meters. M3TER Manager only observes telemetry; it does not acknowledge energy reports automatically.' : ''); + notice(config.billingAutomationActive ? 'Existing console billing automation is enabled and may also control these meters. M3ter Manager only observes telemetry; it does not acknowledge energy reports automatically.' : ''); connectStream(); clockTimer = setInterval(renderActivity, 1000); if (device) await refresh(); } catch (error) { notice(''); showError(error); } } diff --git a/src/public/js/paint.js b/src/public/js/paint.js index 532730b..dc5181b 100644 --- a/src/public/js/paint.js +++ b/src/public/js/paint.js @@ -21,7 +21,7 @@ const end = event => { if (event.pointerId === pointer) { pointer = null; status.textContent = 'Drawing updated. Save PNG to keep a copy.'; } }; ['pointerup','pointercancel','lostpointercapture'].forEach(name => canvas.addEventListener(name,end)); document.getElementById('paint-undo').addEventListener('click', () => { const previous = undo.pop(); if(previous) ctx.putImageData(previous,0,0); }); - document.getElementById('paint-clear').addEventListener('click', () => { if (!window.confirm('Clear this drawing? You can undo this change.')) return; remember(); white(); }); + document.getElementById('paint-clear').addEventListener('click', async () => { if (!await AppFeedback.confirm(document.getElementById('paint'), 'Clear this drawing?', 'You can undo this change.', 'Clear drawing')) return; remember(); white(); }); document.getElementById('paint-save').addEventListener('click', () => canvas.toBlob(blob => { if (!blob) { status.textContent = 'Could not save the drawing. Please retry.'; return; } const url = URL.createObjectURL(blob), link = document.createElement('a'); link.href=url; link.download='console-paint.png'; link.click(); setTimeout(()=>URL.revokeObjectURL(url),1000); diff --git a/src/services/chirpstack.ts b/src/services/chirpstack.ts index 5871c0e..01eb894 100644 --- a/src/services/chirpstack.ts +++ b/src/services/chirpstack.ts @@ -8,9 +8,9 @@ const hopHeaders = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-aut export function chirpstackTarget(): URL { const host = process.env.CHIRPSTACK_HOST || 'localhost'; - const target = new URL(process.env.CHIRPSTACK_WEB_URL || `http://${host.includes(':') && !host.startsWith('[') ? `[${host}]` : host}:8080`); + const target = new URL(process.env.CHEFSTACK_URL || process.env.CHIRPSTACK_WEB_URL || `http://${host.includes(':') && !host.startsWith('[') ? `[${host}]` : host}:8080`); if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password || target.pathname !== '/' || target.search || target.hash) { - throw new Error('CHIRPSTACK_WEB_URL must be an HTTP(S) origin without credentials or a path'); + throw new Error('CHEFSTACK_URL / CHIRPSTACK_WEB_URL must be an HTTP(S) origin without credentials or a path'); } return target; } @@ -37,7 +37,7 @@ function unavailable(res: Response, configuration = false): void { if (res.headersSent) { res.destroy(); return; } res.removeHeader('Content-Length'); res.removeHeader('Content-Encoding'); - res.status(502).type('html').send(`ChirpStack unavailable

ChirpStack is unavailable

${configuration ? 'Check the CHIRPSTACK_WEB_URL configuration on the console server.' : 'The console could not reach ChirpStack. Make sure the ChirpStack server is running and CHIRPSTACK_HOST or CHIRPSTACK_WEB_URL points to it.'}

Try again

`); + res.status(502).type('html').send(`ChirpStack unavailable

ChirpStack is unavailable

${configuration ? 'Check the CHEFSTACK_URL or CHIRPSTACK_WEB_URL configuration on the console server.' : 'The console could not reach ChirpStack. Make sure the ChirpStack server is running and CHIRPSTACK_HOST, CHEFSTACK_URL or CHIRPSTACK_WEB_URL points to it.'}

Try again

`); } /** Mount before JSON/body middleware: gRPC-Web bodies and event streams stay intact. */ diff --git a/src/services/mqtt.ts b/src/services/mqtt.ts index 42ab2d6..9ce587e 100644 --- a/src/services/mqtt.ts +++ b/src/services/mqtt.ts @@ -11,6 +11,7 @@ import { } from '../store/sqlite'; import type { State, TransactionRecord } from '../types'; import { decodePayload } from '../lib/decode'; +import { uplinkPayload } from '../lib/uplink-payload'; import { runHook, notifyHook, verifyPayloadSignature } from '../lib/utils'; import { getLatestTransactionNonce } from '../lib/sync'; import { createMeterLogger, createLogger } from '../utils/logger'; @@ -21,8 +22,17 @@ const deviceLocks = new Set(); const meterLocks = new Set(); let monitoringClient: MqttClient | undefined; +// One address for the existing process-level service and both consumers. +export function mqttConnection(): string | { host: string; port: number } { + if (!process.env.MQTT_URL) return { host: process.env.CHIRPSTACK_HOST || 'localhost', port: 1883 }; + try { + const url = new URL(process.env.MQTT_URL); + if (!['mqtt:', 'mqtts:', 'ws:', 'wss:'].includes(url.protocol) || !url.hostname || url.hash) throw new Error(); + return process.env.MQTT_URL; + } catch { throw new Error('MQTT_URL must be a valid mqtt, mqtts, ws or wss broker URL.'); } +} // Optional arguments are dependency injection for integration tests, not configuration. -export async function handleUplinks(connection = { host: process.env.CHIRPSTACK_HOST || 'localhost', port: 1883 }, collect = handleMessage): Promise { +export async function handleUplinks(connection = mqttConnection(), collect = handleMessage): Promise { if (monitoringClient) return true; const application = applicationId(); const topic = `application/${application}/device/+/event/+`; @@ -30,8 +40,8 @@ export async function handleUplinks(connection = { host: process.env.CHIRPSTACK_ try { connectionState(state, message); } catch { logger.error('Manager status update failed; MQTT collection continues'); } }; status('connecting'); - const client = monitoringClient = connect({ ...connection, clientId: `console-${randomUUID()}`, - clean: true, resubscribe: false, connectTimeout: 9000, reconnectPeriod: 2000 }); + const options = { clientId: `console-${randomUUID()}`, clean: true, resubscribe: false, connectTimeout: 9000, reconnectPeriod: 2000 }; + const client = monitoringClient = typeof connection === 'string' ? connect(connection, options) : connect({ ...connection, ...options }); client.on('reconnect', () => { status('reconnecting'); void notifyHook('onMqttReconnect', client); }); client.on('offline', () => status('disconnected')); client.on('close', () => status('disconnected')); @@ -95,10 +105,7 @@ export async function handleMessage(blob: Buffer): Promise { } deviceLocks.add(devEui!); ownsDeviceLock = true; - if (typeof message.data !== 'string' || !message.data || !/^[A-Za-z0-9+/]+={0,2}$/.test(message.data)) { - throw new Error('Message has no valid base64 payload'); - } - const transaction = Buffer.from(message.data, 'base64'); + const transaction = uplinkPayload(message).bytes; const decoded = decodePayload(transaction); const payloadHadPublicKey = !!decoded.extensions.deviceId; const publicKey = decoded.extensions.deviceId || getMeterByDevEui(devEui!)?.publicKey.replace(/^0x/, ''); diff --git a/src/services/server.ts b/src/services/server.ts index 25fc9d4..2d20610 100644 --- a/src/services/server.ts +++ b/src/services/server.ts @@ -5,7 +5,6 @@ import { requireSameOrigin } from './auth'; import { proxyChirpstack } from './chirpstack'; import { managerRouter, attachManagerStream } from '../m3ter/api'; import { createLogger } from '../utils/logger'; -import { getAllMeterRecords, deleteMeterByPublicKey } from '../store/sqlite'; import { getUIComponents, invokeUIAction } from '../lib/utils'; const logger = createLogger('[server]'); @@ -37,14 +36,12 @@ app.use('/api/m3ter-manager', managerRouter); app.get('/', async (req: Request, res: Response, next) => { try { - const m3ters = getAllMeterRecords(); - // Get UI components from loaded UI extensions const { icons, windows } = await getUIComponents(); - logger.info('Rendering index page with m3ters, icons, and windows'); + logger.info('Rendering index page with icons and windows'); - res.render('index', { m3ters, icons, windows }); + res.render('index', { icons, windows }); logger.info('Server handled GET request at `/`'); } catch (error) { next(error); } }); @@ -65,24 +62,6 @@ app.post('/api/actions/:moduleId/:actionId', async (req: Request, res: Response, } catch (error) { next(error); } }); -app.delete('/delete-meter', async (req: Request, res: Response, next) => { - try { - const publicKey = typeof req.query.publicKey === 'string' ? req.query.publicKey : ''; - if (publicKey) { - const deleted = deleteMeterByPublicKey(publicKey.toString()); - if (!deleted) { - res.status(404).send({ message: 'meter not found' }); - return; - } - } else { - res.status(400).send({ message: 'public key not specified' }); - return; - } - logger.info('Server handled DELETE request at `/delete-meter`'); - res.status(200).send({ message: 'deleted meter' }); - } catch (error) { next(error); } -}); - export const server = http.createServer(app); attachManagerStream(server); diff --git a/src/views/index.hbs b/src/views/index.hbs index 30a3183..0820b21 100644 --- a/src/views/index.hbs +++ b/src/views/index.hbs @@ -8,12 +8,11 @@
- - + {{#each icons}} {{/each}} @@ -22,16 +21,6 @@
A workspace for a connected world.
- - +