diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 9ca2b9137..a9ac84549 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -168,6 +168,12 @@ body:
# or relevant YAML / sdkconfig lines / collector command
+ - type: textarea
+ id: diagnostic_report
+ attributes:
+ label: Diagnostic report (optional)
+ description: In the Web Monitor, connect to the device and select Generate report. Review the preview, then paste the fenced JSON or attach the downloaded file.
+
- type: textarea
id: logs
attributes:
diff --git a/.github/actions/build-pages/action.yml b/.github/actions/build-pages/action.yml
index 1f7c6f5c5..1a8673fc9 100644
--- a/.github/actions/build-pages/action.yml
+++ b/.github/actions/build-pages/action.yml
@@ -43,7 +43,7 @@ runs:
- name: Build static pages
shell: bash
- run: python3 .github/scripts/build_static_pages.py
+ run: python3 .github/scripts/build_static_pages.py --site-revision "$(git rev-parse HEAD)"
- uses: ./.github/actions/setup-doxygen
diff --git a/.github/cla-signatures.json b/.github/cla-signatures.json
index 34fc09d04..aedcda663 100644
--- a/.github/cla-signatures.json
+++ b/.github/cla-signatures.json
@@ -32,6 +32,10 @@
{
"login": "mgoodfellow",
"signedAt": "2026-10-28"
+ },
+ {
+ "login": "FhDBro",
+ "signedAt": "2026-11-01"
}
]
}
diff --git a/.github/scripts/build_static_pages.py b/.github/scripts/build_static_pages.py
index a3d7fdeff..36e24dcce 100644
--- a/.github/scripts/build_static_pages.py
+++ b/.github/scripts/build_static_pages.py
@@ -18,6 +18,8 @@
from __future__ import annotations
+import argparse
+import re
import sys
from html import escape
from html.parser import HTMLParser
@@ -315,4 +317,15 @@ def build() -> None:
if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--site-revision", help="Git commit to identify a deployed application shell")
+ args = parser.parse_args()
+ if args.site_revision and not re.fullmatch(r"[a-f0-9]{40}", args.site_revision):
+ parser.error("site revision must be a full Git commit hash")
build()
+ if args.site_revision:
+ # Interactive routes load the root application shell.
+ shell = WEB_ROOT / "index.html"
+ marker = f''
+ content = re.sub(r'\n', "", shell.read_text())
+ shell.write_text(content.replace("
", "\n" + marker, 1))
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 19b464586..deb805a0e 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -2,6 +2,11 @@
All notable changes to this project will be documented in this file.
+## [3.3.0] - Work in progress
+
+- The Web Monitor can copy or download a local diagnostic report with 30-second CSI and Wi-Fi statistics, recent motion and faults, redacted device state, and browser and site versions.
+- **Micro** sends a single valid CORS origin on Direct responses so the Web Monitor can open the event stream and collect a diagnostic report.
+
---
## [3.2.2] - 2026-11-25 - Raw Wi-Fi targets and Direct Wi-Fi recovery
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 23617e483..f808ec0fb 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -13,6 +13,7 @@ Most problems can be fixed from the browser: the [troubleshooting guide](https:/
- [Calibration stalls or startup quality is poor](#calibration-stalls-or-startup-quality-is-poor)
- [Tuning essentials](#tuning-essentials)
- [Device not reachable](#device-not-reachable)
+- [Diagnostic report](#diagnostic-report)
## Check the sensing input
@@ -132,3 +133,9 @@ From the browser, follow [device not reachable](https://espectre.dev/guides/trou
You can connect with the device IP, its name, its 16-character ID, or the last 6 characters of the ID. Names and short IDs rely on mDNS. If discovery fails, run `./espectre devices`, enter the IP, or look it up in your router's DHCP list. See [browser bootstrap](DISCOVERY.md#browser-bootstrap) for how discovery works.
Once connected, go back to [Check the sensing input](#check-the-sensing-input).
+
+## Diagnostic report
+
+In [Live motion](https://espectre.dev/tools/monitor/), expand **Diagnostics** and select **Generate report**. The monitor samples CSI occupancy, packet rates, and Wi-Fi signal for 30 seconds. It includes the latest motion observed on this connection and its fault events. The report uses the diagnostic fields advertised by the connected firmware. If no samples arrive, the report still includes device state and marks sampling as `no_samples`. A measured rate of zero is a valid sample.
+
+The browser masks device and network identifiers before displaying the preview. Review it, then select **Copy fenced JSON** to paste it into an issue, or **Download JSON** to save a file.
diff --git a/docs/web/404.html b/docs/web/404.html
index a46c6f85e..426e4d6ff 100644
--- a/docs/web/404.html
+++ b/docs/web/404.html
@@ -10,7 +10,7 @@
Page not found | ESPectre
-
+
diff --git a/docs/web/assets/css/styles.css b/docs/web/assets/css/styles.css
index 315bb91c1..0179327d4 100644
--- a/docs/web/assets/css/styles.css
+++ b/docs/web/assets/css/styles.css
@@ -2206,6 +2206,99 @@ body.modal-open { overflow: hidden; }
.device-live-diagnostics > summary small { margin-left: auto; color: var(--dim); font-size: 11.5px; }
.device-live-diagnostics .diag-grid { padding: 0 18px 18px; }
.device-live-diagnostics .tool-note { margin: 0; padding: 0 18px 18px; }
+.diag-report-panel {
+ border-top: 1px solid var(--border);
+ padding: 16px 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.diag-report-card {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ background: var(--surface2);
+}
+.diag-report-card strong {
+ display: block;
+ font-size: 12px;
+}
+.diag-report-card p {
+ margin: 2px 0 0;
+ color: var(--dim);
+ font-size: 11px;
+ line-height: 1.4;
+}
+.diag-report-progress {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ background: var(--surface2);
+}
+.diag-report-progress-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+.diag-report-track {
+ width: 100%;
+ height: 6px;
+ background: var(--surface-soft, rgba(0, 0, 0, 0.06));
+ border-radius: 999px;
+ overflow: hidden;
+}
+.diag-report-bar {
+ height: 100%;
+ background: var(--accent);
+ transition: width 0.3s ease;
+}
+.diag-report-status {
+ font-size: 12px;
+ color: var(--text);
+}
+.diag-report-result {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.diag-report-result-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 10px;
+}
+.diag-report-result-title {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text);
+}
+.diag-report-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.diag-report-preview {
+ margin: 0;
+ padding: 12px;
+ max-height: 240px;
+ overflow: auto;
+ font-family: var(--font-mono, monospace);
+ font-size: 11px;
+ line-height: 1.45;
+ background: var(--surface-soft, rgba(0, 0, 0, 0.04));
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ white-space: pre;
+}
/* Theremin */
.theremin-stage {
@@ -3928,6 +4021,9 @@ body.modal-open { overflow: hidden; }
.live-controls-grid { grid-template-columns: minmax(0, 1fr); }
.live-control-wide { grid-column: auto; }
.live-calibration { align-items: stretch; flex-direction: column; }
+ .diag-report-card { align-items: stretch; flex-direction: column; }
+ .diag-report-result-header { align-items: stretch; flex-direction: column; }
+ .diag-report-actions { flex-direction: column; }
.device-live-diagnostics > summary { align-items: flex-start; flex-direction: column; gap: 4px; position: relative; }
.device-live-diagnostics > summary small { margin-left: 0; padding-right: 24px; }
.device-live-diagnostics > summary::after { position: absolute; right: 18px; top: 18px; }
@@ -3949,7 +4045,8 @@ body.modal-open { overflow: hidden; }
.scrolly-caption,
.scrolly-nav span,
.scrolly-cue,
- .scrolly-skip { transition: none; }
+ .scrolly-skip,
+ .diag-report-bar { transition: none; }
.scene-ui-dot,
.pulse,
.spinner,
diff --git a/docs/web/assets/js/browser-support.js b/docs/web/assets/js/browser-support.js
index fb6ef64e5..3cc6733ea 100644
--- a/docs/web/assets/js/browser-support.js
+++ b/docs/web/assets/js/browser-support.js
@@ -23,11 +23,12 @@
: /Firefox\//i.test(userAgent) ? 'firefox'
: /(?:Chrome|CriOS)\//i.test(userAgent) ? 'chrome'
: /Safari\//i.test(userAgent) ? 'safari' : 'other';
- const versionMatch = userAgent.match(browser === 'edge' ? /Edg\/(\d+)/i
- : browser === 'firefox' ? /Firefox\/(\d+)/i
- : browser === 'chrome' ? /(?:Chrome|CriOS)\/(\d+)/i
- : browser === 'safari' ? /Version\/(\d+)/i : null);
- const browserMajor = versionMatch ? Number(versionMatch[1]) : 0;
+ const versionMatch = userAgent.match(browser === 'edge' ? /Edg\/(\d+(?:\.\d+)*)/i
+ : browser === 'firefox' ? /Firefox\/(\d+(?:\.\d+)*)/i
+ : browser === 'chrome' ? /(?:Chrome|CriOS)\/(\d+(?:\.\d+)*)/i
+ : browser === 'safari' ? /Version\/(\d+(?:\.\d+)*)/i : null);
+ const browserVersion = versionMatch?.[1] || null;
+ const browserMajor = parseInt(browserVersion, 10) || 0;
const operatingSystem = ios ? 'ios'
: android ? 'android'
: /mac/i.test(platform) ? 'macos'
@@ -45,6 +46,7 @@
serial,
browser,
browserMajor,
+ browserVersion,
operatingSystem,
hostedDirect,
// ESPectre supports browser flashing only on desktop Chrome or Edge.
diff --git a/docs/web/assets/js/direct-discovery.js b/docs/web/assets/js/direct-discovery.js
index d7bf04eb5..bfe801d7f 100644
--- a/docs/web/assets/js/direct-discovery.js
+++ b/docs/web/assets/js/direct-discovery.js
@@ -175,6 +175,13 @@
function ingestDirectEvent(name, data) {
if (name === 'motion') {
+ if (directClient?.connected && Number.isFinite(data.score)) {
+ directResourceSession(directClient).motion = {
+ score: data.score,
+ state: data.state,
+ timestamp_ms: data.timestamp_ms ?? null
+ };
+ }
applySensingCadence(data);
applyLiveTelemetry(
Number(data.score ?? 0),
@@ -199,14 +206,20 @@
return;
}
if (name === 'ota') applyOtaStatus(data);
- if (name === 'fault') toast(data.message || 'The device reported a runtime fault.');
+ if (name === 'fault') {
+ if (directClient?.connected) {
+ const at = Date.now();
+ directResourceSession(directClient).faults.push({ at, timestamp: new Date(at).toISOString(), fault: data });
+ }
+ toast(data.message || 'The device reported a runtime fault.');
+ }
}
const directResourceSessions = new WeakMap();
function directResourceSession(client) {
if (!directResourceSessions.has(client)) {
- directResourceSessions.set(client, { snapshots: new Map(), pending: new Map() });
+ directResourceSessions.set(client, { snapshots: new Map(), pending: new Map(), faults: [] });
}
return directResourceSessions.get(client);
}
diff --git a/docs/web/assets/js/monitor-tool.js b/docs/web/assets/js/monitor-tool.js
index 107dba32c..b35cc0190 100644
--- a/docs/web/assets/js/monitor-tool.js
+++ b/docs/web/assets/js/monitor-tool.js
@@ -82,6 +82,11 @@
}
function resetMonitorLiveView() {
+ const session = directResourceSessions.get(directClient);
+ if (session) {
+ session.faults.length = 0;
+ session.motion = null;
+ }
monitorResetChart();
const stateEl = $('.js-mon-state');
if (stateEl) {
@@ -92,6 +97,7 @@
if (moveEl) moveEl.textContent = '—';
monitorStats({});
monitorDiagStatus('');
+ resetMonitorReportView();
conn.movement = 0;
conn.motion = false;
renderTelemetry();
@@ -630,6 +636,480 @@
);
}
+ /* ============================================== diagnostic report */
+
+ let monitorReportSampling = null;
+ let monitorReportJson = '';
+
+ function calculateRateStats(values) {
+ const numbers = (values || [])
+ .filter((v) => typeof v === 'number' && Number.isFinite(v))
+ .sort((a, b) => a - b);
+ if (!numbers.length) return { min: null, median: null, max: null };
+ const min = numbers[0];
+ const max = numbers[numbers.length - 1];
+ const mid = Math.floor(numbers.length / 2);
+ const median = numbers.length % 2 !== 0 ? numbers[mid] : (numbers[mid - 1] + numbers[mid]) / 2;
+ return {
+ min: Number(min.toFixed(4)),
+ median: Number(median.toFixed(4)),
+ max: Number(max.toFixed(4))
+ };
+ }
+
+ function isMulticastOrBroadcastMac(mac) {
+ return (parseInt(mac.slice(0, 2), 16) & 1) === 1;
+ }
+
+ function isMulticastOrLoopbackIp(ip) {
+ if (ip.startsWith('127.') || ip === '::1' || ip === '0.0.0.0' || ip === '255.255.255.255') return true;
+ const first = parseInt(ip.split('.')[0], 10);
+ if (first >= 224 && first <= 239) return true;
+ return false;
+ }
+
+ function redactDiagnosticReport(data) {
+ if (!data || typeof data !== 'object') return data;
+
+ const terms = new Map();
+ for (const [value, replacement] of [
+ [data.wifi?.ssid, ''],
+ [data.wifi?.sta_ssid, ''],
+ [data.wifi?.ap_ssid, ''],
+ [data.device?.name, ''],
+ [data.device?.label, ''],
+ [data.device?.hostname, ''],
+ [data.device?.device_id, '']
+ ]) {
+ if (typeof value !== 'string' || !value.length) continue;
+ const term = value.toLowerCase();
+ if (!terms.has(term)) terms.set(term, replacement);
+ }
+
+ const secretKey = /password|passphrase|secret|token|api_key|private_key|credentials/i;
+ function collectSecrets(obj, withinSecret = false) {
+ for (const [key, val] of Object.entries(obj)) {
+ const secret = withinSecret || secretKey.test(key);
+ if (secret && typeof val === 'string' && val) terms.set(val.toLowerCase(), '[REDACTED]');
+ if (val && typeof val === 'object') collectSecrets(val, secret);
+ }
+ }
+ collectSecrets(data);
+
+ // Match once, longest identity first, so short names cannot alter a longer match or a placeholder.
+ const identities = [...terms.keys()].sort((a, b) => b.length - a.length)
+ .map(term => term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ const identityAvailable = Boolean(data.device?.name && (data.wifi?.ssid || data.wifi?.sta_ssid));
+ const patterns = [
+ /(?(?\b(?:[\da-f]{2}[:-]){5}[\da-f]{2}\b)/.source,
+ /(?\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b)/.source,
+ /(?\b(?:[a-z\d][-a-z\d]*\.)+local\b)/.source
+ ];
+ const addresses = new RegExp('^(?:' + patterns.join('|') + ')$', 'i');
+ const sensitive = new RegExp([...patterns, ...identities].join('|'), 'gi');
+ const replacement = (match, ipv6, mac, ip, hostname) => {
+ if (ipv6) {
+ // A colon-separated MAC or timestamp can also match the IPv6 candidate.
+ if (/^(?:[\da-f]{2}:){5}[\da-f]{2}$/i.test(ipv6)) mac = ipv6;
+ else {
+ const address = ipv6.split('%')[0];
+ try {
+ const host = new URL('http://[' + address + ']/').hostname;
+ return host === '[::1]' || host === '[::]' || host.startsWith('[ff')
+ ? address : '';
+ } catch {
+ if (address.includes('::') || address.split(':').length >= 8) return '';
+ return terms.get(match.toLowerCase()) ?? match;
+ }
+ }
+ }
+ if (mac) {
+ if (isMulticastOrBroadcastMac(mac)) return mac;
+ return mac.slice(0, 5) + (mac[2] + '**').repeat(4);
+ }
+ if (ip) return isMulticastOrLoopbackIp(ip) ? ip : ip.split('.').slice(0, 2).join('.') + '.x.x';
+ if (hostname) return '.local';
+ return terms.get(match.toLowerCase());
+ };
+
+ // These fields contain protocol tokens or report metadata even if a user picks the same name.
+ const structuredStrings = new Set([
+ 'capabilities.resources', 'capabilities.events', 'capabilities.protocol_version',
+ 'capabilities.operations.name', 'capabilities.operations.method', 'capabilities.operations.path',
+ 'capabilities.operations.fields', 'sampling.status', 'timestamp', 'fault_events.timestamp',
+ 'device.firmware_version', 'diagnostics.esp_idf_version', 'diagnostics.firmware_build_date',
+ 'diagnostics.recent_logs.level', 'last_motion.state',
+ 'device.chip', 'device.frontend', 'device.firmware', 'device.csi_profile', 'health.status',
+ 'wifi.band', 'wifi.apply_state', 'sensing.mode', 'sensing.detector', 'sensing.traffic_generator_mode',
+ 'sensing.csi_sample_spacing'
+ ]);
+
+ const transform = (key, val, path) => {
+ const lowerKey = key.toLowerCase();
+
+ if (lowerKey === 'credentials' || lowerKey.endsWith('_credentials')) {
+ return undefined;
+ }
+
+ if (secretKey.test(lowerKey)) {
+ if (typeof val === 'boolean') return val;
+ return val == null ? val : '[REDACTED]';
+ }
+
+ if (path === 'device.name' && typeof val === 'string') return '';
+ if (path === 'device.label' && typeof val === 'string') return '';
+ if (lowerKey === 'hostname' && typeof val === 'string') return '';
+ if (['ssid', 'sta_ssid', 'ap_ssid'].includes(lowerKey) && typeof val === 'string') return '';
+
+ if (lowerKey === 'device_id' && typeof val === 'string') {
+ return val.length > 8 ? `${val.slice(0, 4)}...${val.slice(-4)}` : '';
+ }
+
+ if (typeof val === 'string') {
+ if (structuredStrings.has(path)) return val;
+ if (!identityAvailable && !addresses.test(val)) return '[REDACTED]';
+ return val.replace(sensitive, replacement);
+ }
+
+ if (Array.isArray(val)) {
+ return val.map((item) => transform(key, item, path)).filter((item) => item !== undefined);
+ }
+
+ if (val && typeof val === 'object') {
+ const result = {};
+ for (const [k, v] of Object.entries(val)) {
+ const transformed = transform(k, v, path ? path + '.' + k : k);
+ if (transformed !== undefined) result[k] = transformed;
+ }
+ return result;
+ }
+
+ return val;
+ };
+
+ return transform('', data, '');
+ }
+
+ function monitorCancelDiagnosticReport({ silent = false } = {}) {
+ if (!monitorReportSampling) return;
+ monitorReportSampling.cancel(silent);
+ }
+
+ function resetMonitorReportView() {
+ monitorCancelDiagnosticReport({ silent: true });
+ monitorReportJson = '';
+ const progressEl = $('.js-mon-report-progress');
+ const resultEl = $('.js-mon-report-result');
+ const previewEl = $('.js-mon-report-preview');
+ const startBtn = $('.js-mon-report-start');
+ if (progressEl) progressEl.hidden = true;
+ if (resultEl) resultEl.hidden = true;
+ if (previewEl) previewEl.textContent = '';
+ if (startBtn) startBtn.disabled = false;
+ }
+
+ function monitorStartDiagnosticReport({
+ sampleDurationSec = 30,
+ sampleIntervalMs = 1000
+ } = {}) {
+ if (monitorReportSampling) return Promise.resolve(null);
+ const mode = conn.mode;
+ const direct = mode === 'direct';
+ const client = directClient;
+ if (!direct && mode !== 'demo') {
+ toast('Connect to a device before generating a diagnostic report.');
+ return Promise.resolve(null);
+ }
+ if (direct && !client?.connected) {
+ toast('Direct HTTP connection is not ready. Connect and try again.');
+ return Promise.resolve(null);
+ }
+
+ const session = direct ? directResourceSession(client) : null;
+ monitorReportJson = '';
+ const startBtn = $('.js-mon-report-start');
+ if (startBtn) startBtn.disabled = true;
+
+ const progressEl = $('.js-mon-report-progress');
+ const trackEl = $('.js-mon-report-track');
+ const barEl = $('.js-mon-report-bar');
+ const statusEl = $('.js-mon-report-status');
+ const resultEl = $('.js-mon-report-result');
+ const previewEl = $('.js-mon-report-preview');
+ const copyBtn = $('.js-mon-report-copy');
+
+ if (progressEl) progressEl.hidden = false;
+ if (resultEl) resultEl.hidden = true;
+ if (barEl) barEl.style.width = '0%';
+ if (trackEl) trackEl.setAttribute('aria-valuenow', '0');
+ if (statusEl) statusEl.textContent = `Sampling diagnostics (0/${sampleDurationSec}s)…`;
+
+ const samples = {
+ csi_occupancy: [],
+ csi_accepted_pps: [],
+ csi_filtered_pps: [],
+ csi_hw_error_pps: [],
+ csi_callback_pps: [],
+ generator_pps: [],
+ wifi_rssi_dbm: []
+ };
+
+ let startedAt = Date.now();
+ const durationMs = sampleDurationSec * 1000;
+ let samplesCollected = 0;
+ const controller = new AbortController();
+
+ return new Promise((resolve) => {
+ const samplingState = {
+ timer: null,
+ cancel(silent = false) {
+ if (samplingState.timer) clearTimeout(samplingState.timer);
+ controller.abort();
+ monitorReportSampling = null;
+ if (progressEl) progressEl.hidden = true;
+ if (startBtn) {
+ startBtn.disabled = false;
+ if (typeof startBtn.focus === 'function') startBtn.focus();
+ }
+ if (!silent) toast('Diagnostic report cancelled.');
+ resolve(null);
+ }
+ };
+ monitorReportSampling = samplingState;
+
+ const isCurrent = () => {
+ if (monitorReportSampling !== samplingState) return false;
+ if (conn.mode === mode && (!direct || (client.connected && directClient === client
+ && directResourceSessions.get(client) === session))) return true;
+ samplingState.cancel(true);
+ toast('Device disconnected while sampling diagnostics.');
+ return false;
+ };
+
+ let available;
+ let sampleFields = Object.keys(samples);
+ const readResource = async (name, params = {}) => {
+ try {
+ return await client.request('get', name, params, {
+ timeoutMs: 5000,
+ signal: controller.signal
+ });
+ } catch {
+ return { error: 'unavailable' };
+ }
+ };
+
+ const pollSample = async () => {
+ if (!isCurrent()) return;
+ if (direct && !available) {
+ const catalog = await readResource('diagnostics');
+ if (!isCurrent()) return;
+ available = new Set(Array.isArray(catalog?.fields) ? catalog.fields.map(f => f.name) : []);
+ sampleFields = available.size ? sampleFields.filter(field => available.has(field))
+ : ['csi_occupancy', 'csi_accepted_pps', 'csi_filtered_pps', 'csi_hw_error_pps'];
+ startedAt = Date.now();
+ }
+ const pollStartedAt = Date.now();
+ let values;
+ if (direct) {
+ try {
+ if (sampleFields.length) values = await client.request('get', 'diagnostics', { fields: sampleFields }, {
+ timeoutMs: Math.min(2000, sampleIntervalMs), signal: controller.signal
+ });
+ } catch {
+ // Keep sampling after a missed read.
+ }
+ if (!isCurrent()) return;
+ } else {
+ const targetPps = csiTargetPps();
+ values = {
+ csi_accepted_pps: Math.max(1, targetPps - 10),
+ csi_occupancy: Math.max(1, targetPps - 16) / targetPps,
+ csi_filtered_pps: 0,
+ csi_hw_error_pps: 0
+ };
+ }
+ let collected = false;
+ for (const [field, readings] of Object.entries(samples)) {
+ if (Number.isFinite(values?.[field])) {
+ readings.push(values[field]);
+ if (field.startsWith('csi_')) collected = true;
+ }
+ }
+ if (collected) samplesCollected++;
+ const elapsedMs = Date.now() - startedAt;
+ const pct = Math.min(100, Math.round(100 * elapsedMs / durationMs));
+ if (barEl) barEl.style.width = `${pct}%`;
+ if (trackEl) trackEl.setAttribute('aria-valuenow', String(pct));
+ if (statusEl) statusEl.textContent = `Sampling diagnostics (${Math.min(Math.floor(elapsedMs / 1000), sampleDurationSec)}/${sampleDurationSec}s)…`;
+
+ const remainingMs = durationMs - elapsedMs;
+ if (remainingMs <= 0) {
+ await finishReport();
+ } else {
+ const untilNextPoll = Math.max(0, sampleIntervalMs - (Date.now() - pollStartedAt));
+ samplingState.timer = setTimeout(pollSample, Math.min(untilNextPoll, remainingMs));
+ }
+ };
+
+ const finishReport = async () => {
+ if (monitorReportSampling !== samplingState) return;
+ if (statusEl) statusEl.textContent = 'Reading device resources…';
+
+ let capabilities = {};
+ let device = {};
+ let health = {};
+ let sensing = {};
+ let wifi = {};
+ const diagnostics = {};
+ const reportFields = [
+ 'wifi_channel', 'free_memory_kb', 'minimum_free_memory_kb', 'loop_time_ms',
+ 'csi_callbacks_total', 'csi_accepted_total', 'csi_filtered_total', 'csi_hw_error_total',
+ 'csi_admitted_pps', 'csi_missing_slots_pps', 'csi_excess_pps', 'csi_stale_pps'
+ ];
+
+ if (direct) {
+ [capabilities, device, health, sensing, wifi] = await Promise.all([
+ readResource('capabilities'),
+ readResource('device'),
+ readResource('health'),
+ readResource('sensing'),
+ readResource('wifi')
+ ]);
+ if (!isCurrent()) return;
+ const selected = reportFields.filter(field => available.has(field));
+ for (let i = 0; i < selected.length; i += 4) {
+ const fields = selected.slice(i, i + 4);
+ const values = await readResource('diagnostics', { fields });
+ if (!isCurrent()) return;
+ for (const field of fields) diagnostics[field] = values?.[field] ?? null;
+ }
+ } else if (mode === 'demo') {
+ capabilities = { protocol_version: '1.0', resources: ['device', 'health', 'sensing', 'wifi', 'diagnostics'] };
+ device = {
+ name: 'Demo sensor',
+ device_id: conn.deviceId || '2222222222222222',
+ chip: 'esp32s3',
+ firmware_version: '1.0.0'
+ };
+ health = { status: 'healthy', uptime: 3600, free_memory_kb: 161.4 };
+ sensing = { detector: 'lightweight', csi_target_pps: csiTargetPps(), motion_on_hits: 3, motion_off_hits: 5 };
+ wifi = { ssid: 'DemoNetwork', sta_ip: '192.168.1.50', sta_mac: '30:ae:a4:07:0a:24', wifi_channel: 6, password_configured: true };
+ }
+
+ const rawReport = {
+ timestamp: new Date().toISOString(),
+ sampling: {
+ duration_seconds: sampleDurationSec,
+ status: samplesCollected ? 'complete' : 'no_samples',
+ samples_collected: samplesCollected,
+ rates: Object.fromEntries(Object.entries(samples)
+ .filter(([name]) => name !== 'wifi_rssi_dbm')
+ .map(([name, readings]) => [name, calculateRateStats(readings)])),
+ wifi_rssi_dbm: calculateRateStats(samples.wifi_rssi_dbm)
+ },
+ diagnostics,
+ last_motion: session?.motion ?? null,
+ fault_events: session ? session.faults.slice() : [],
+ capabilities,
+ device,
+ health,
+ sensing,
+ wifi
+ };
+
+ const browser = window.ESPectreBrowserSupport?.current;
+ const revision = document.querySelector?.('meta[name="espectre-site-revision"]')?.content;
+ const asset = document.querySelector?.('script[src*="/assets/js/monitor-tool.js"]')?.src;
+ const sanitized = {
+ privacy: 'Generated locally. Network and device identifiers are masked. Review before sharing.',
+ source: mode,
+ client: {
+ site: ['espectre.dev', 'test.espectre.dev'].includes(window.location?.hostname)
+ ? window.location.hostname : 'local_or_custom',
+ site_revision: /^[a-f0-9]{40}$/i.test(revision) ? revision : null,
+ monitor_revision: asset?.match(/[?&]v=([a-f0-9]{12})(?:&|$)/i)?.[1] ?? null,
+ browser: browser?.browser ?? null,
+ browser_version: browser?.browserVersion ?? null
+ },
+ ...redactDiagnosticReport(rawReport)
+ };
+ monitorReportJson = JSON.stringify(sanitized, null, 2);
+
+ if (previewEl) previewEl.textContent = monitorReportJson;
+ if (progressEl) progressEl.hidden = true;
+ if (resultEl) resultEl.hidden = false;
+ if (startBtn) startBtn.disabled = false;
+ if (copyBtn && typeof copyBtn.focus === 'function') copyBtn.focus();
+ monitorReportSampling = null;
+ toast(samplesCollected ? 'Diagnostic report ready.' : 'No diagnostic samples received. The report contains device state only.');
+ resolve(sanitized);
+ };
+
+ pollSample();
+ });
+ }
+
+ async function monitorCopyDiagnosticReport() {
+ if (!monitorReportJson) {
+ toast('No diagnostic report available to copy.');
+ return;
+ }
+ const fenced = '```json\n' + monitorReportJson + '\n```';
+ const copyBtn = $('.js-mon-report-copy');
+ try {
+ if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(fenced);
+ } else if (typeof document !== 'undefined') {
+ const ta = document.createElement('textarea');
+ ta.value = fenced;
+ ta.style.position = 'fixed';
+ ta.style.opacity = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ try {
+ if (!document.execCommand('copy')) throw new Error('Copy was declined');
+ } finally {
+ document.body.removeChild(ta);
+ }
+ }
+ if (copyBtn) {
+ const prevText = copyBtn.textContent;
+ copyBtn.textContent = 'Copied!';
+ setTimeout(() => {
+ if (copyBtn.textContent === 'Copied!') copyBtn.textContent = prevText;
+ }, 2000);
+ }
+ toast('Fenced JSON copied to clipboard.');
+ } catch (err) {
+ console.warn('Clipboard write failed:', err);
+ toast('Failed to copy to clipboard.');
+ }
+ }
+
+ function monitorDownloadDiagnosticReport() {
+ if (!monitorReportJson) {
+ toast('No diagnostic report available to download.');
+ return;
+ }
+ try {
+ const blob = new Blob([monitorReportJson], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = `espectre-diagnostic-report-${Date.now()}.json`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+ toast('Diagnostic report downloaded.');
+ } catch (err) {
+ console.warn('Download failed:', err);
+ toast('Failed to download report.');
+ }
+ }
+
function monitorInit() {
const diagnostics = $('.device-live-diagnostics');
if (diagnostics) {
@@ -692,5 +1172,9 @@
document.getElementById('sense-raw-target').addEventListener('change', monitorChangeRawTarget);
document.getElementById('sense-raw-target-manual').addEventListener('change', monitorChangeRawTarget);
document.getElementById('sense-raw-target-refresh').addEventListener('click', monitorRefreshRawTrafficTargets);
+ $('.js-mon-report-start')?.addEventListener('click', () => monitorStartDiagnosticReport());
+ $('.js-mon-report-cancel')?.addEventListener('click', () => monitorCancelDiagnosticReport());
+ $('.js-mon-report-copy')?.addEventListener('click', () => monitorCopyDiagnosticReport());
+ $('.js-mon-report-download')?.addEventListener('click', () => monitorDownloadDiagnosticReport());
window.addEventListener('resize', monitorResizeChart);
}
diff --git a/docs/web/content/guides/troubleshooting.html b/docs/web/content/guides/troubleshooting.html
index 1dff7d670..0957d0ad4 100644
--- a/docs/web/content/guides/troubleshooting.html
+++ b/docs/web/content/guides/troubleshooting.html
@@ -92,6 +92,6 @@
Problems covered in other guides
Still stuck?
-
Open an issue on GitHub with your board, firmware, and version, and a screenshot of Diagnostics or a few lines of the device log. The troubleshooting reference explains the log line, the configuration options, and external traffic.
+
Open an issue on GitHub with your board, firmware, and version. You can use Diagnostic report in Live motion to sample key rates and bundle a privacy-redacted diagnostic JSON ready to paste into your issue. The troubleshooting reference explains the log line, the configuration options, and external traffic.