### Clone Repository and Setup Virtual Environment Source: https://github.com/francescopace/espectre/blob/main/CONTRIBUTING.md Clone the ESPectre repository and set up a Python virtual environment for development. Activate the environment before installing dependencies. ```bash git clone https://github.com/francescopace/espectre.git cd espectre python3 -m venv venv source venv/bin/activate # On macOS/Linux # venv\Scripts\activate # On Windows pip install -r micro-espectre/requirements.txt ``` -------------------------------- ### Run Smoke Test with Act Source: https://github.com/francescopace/espectre/blob/main/test/README.md Install 'act' and use it to run a specific smoke test, for example, 'build' for the QEMU ESP32-C3 environment. ```bash # Install act (https://github.com/nektos/act) brew install act # macOS # Run a specific smoke test act -j build --matrix chip:"QEMU ESP32-C3" -P ubuntu-latest=catthehacker/ubuntu:act-latest ``` -------------------------------- ### Install ESPHome with Virtual Environment Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Create a Python virtual environment and install ESPHome. Activate the environment before proceeding with ESPHome commands. ```bash python3 -m venv venv source venv/bin/activate # On macOS/Linux pip install esphome ``` -------------------------------- ### Create a New Unity Test File Source: https://github.com/francescopace/espectre/blob/main/test/README.md Example of creating a new C++ test file for a feature using the PlatformIO Unity framework. Includes setup, teardown, a sample test, and entry points for native and ESP-IDF environments. ```cpp #include void setUp(void) {} void tearDown(void) {} void test_example(void) { TEST_ASSERT_EQUAL(1, 1); } int process(void) { UNITY_BEGIN(); RUN_TEST(test_example); return UNITY_END(); } #if defined(ESP_PLATFORM) extern "C" void app_main(void) { process(); } #else int main(int argc, char **argv) { return process(); } #endif ``` -------------------------------- ### Install Full Dependencies Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/README.md Installs all project dependencies, including those for ML training and CLI tools, by referencing the requirements file. ```bash # Full dependencies (includes ML training, CLI tools, etc.) pip install -r requirements.txt ``` -------------------------------- ### Configure WiFi and MQTT Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Copies the example configuration file to create a local configuration file for setting up WiFi and MQTT credentials. ```bash # Create configuration file cp src/config_local.py.example src/config_local.py ``` -------------------------------- ### Setup Python Environment for Micro-ESPectre Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Steps to clone the repository, navigate to the micro-espectre directory, verify the Python version, and create/activate a virtual environment. ```bash # Clone the repository git clone https://github.com/francescopace/espectre.git cd espectre/micro-espectre # Verify Python version (3.12 required) python3 --version # Should show Python 3.12.x # Create and activate virtual environment python3.12 -m venv venv # macOS/Linux — use python3 if pyenv auto-selected 3.12 source venv/bin/activate # On macOS/Linux # venv\Scripts\activate # On Windows # Your prompt should now show (venv) prefix ``` -------------------------------- ### Install ESPHome CLI Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Installs the ESPHome command-line interface. It's recommended to use a virtual environment for this installation. ```bash # Create virtual environment (recommended) python3 -m venv venv source venv/bin/activate # On macOS/Linux # venv\Scripts\activate # On Windows # Install ESPHome pip install esphome ``` -------------------------------- ### Flash and Deploy Firmware Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/ML_DATA_COLLECTION.md Flash the ESPectre firmware to your device. This is a one-time setup step. ```bash ./me flash --erase ./me deploy ``` -------------------------------- ### Custom Hardware Configuration Example Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Example YAML configuration for ESP32 variants, specifying the variant, framework, and sdkconfig options. Adjust CPU frequency based on the specific ESP32 variant. ```yaml esp32: variant: ESP32C6 # or ESP32S3, etc. framework: type: esp-idf version: 5.5.1 sdkconfig_options: # CPU frequency (platform-dependent) CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ: "160" # 160 for C6, 240 for S3 # PSRAM (if available on your board) # CONFIG_ESP32S3_SPIRAM_SUPPORT: y ``` -------------------------------- ### Install Core Dependencies Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/README.md Installs essential Python libraries for data manipulation and visualization, sufficient for running the notebooks. ```bash # Core dependencies (enough for both notebooks) pip install numpy matplotlib scipy ``` -------------------------------- ### Verify Firmware Installation Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Verifies that the MicroPython firmware has been successfully installed on the ESP32 device using the `me` CLI. ```bash ./me verify ``` -------------------------------- ### Launch Micro-ESPectre from CLI Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Start the interactive mode or open the web monitor directly from the command line. This is the recommended way to launch the tool. ```bash ./me # Start interactive mode webui # Open web monitor in browser ``` -------------------------------- ### Control Command Examples Source: https://github.com/francescopace/espectre/blob/main/docs/game/README.md Examples of control commands that can be sent from a client to the ESP32 for requesting system info or setting the detection threshold. ```text REQ_SYSINFO SET_THRESHOLD:1.80 ``` -------------------------------- ### Micro-ESPectre CLI Example Workflow Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Demonstrates a typical workflow for setting up and running the Micro-ESPectre application, including flashing, deploying, and running the code, as well as streaming CSI data and performing ML inference. ```bash ./me flash --erase # Flash firmware (first time only) ./me deploy # Deploy code ./me run # Run application ./me # Interactive MQTT control # For real-time CSI streaming (gesture detection, research) ./me stream --ip 192.168.1.100 # Stream to PC # On the PC, inspect live ML motion inference ./me detect --log-turbulence ``` -------------------------------- ### Micro-ESPectre CLI Main Commands Overview Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Provides a table summarizing the essential commands of the `me` CLI tool, their descriptions, and usage examples. ```markdown | Command | Description | |---------|-------------| | `flash` | Flash MicroPython firmware to device | | `deploy` | Deploy Python code to device | | `run` | Run the application | | `stream` | Stream raw CSI data via UDP | | `detect` | Run live ML motion detection on the PC | | `collect` | Collect labeled CSI data for ML training | | `verify` | Verify firmware installation | | `ui` | Open web monitoring interface in browser | | *(interactive)* | Interactive MQTT control | ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/README.md Creates a Python virtual environment and activates it for installing dependencies. Use the appropriate command for your operating system. ```bash cd espectre/micro-espectre # Create and activate virtual environment python3 -m venv venv source venv/bin/activate # macOS/Linux # venv\Scripts\activate # Windows ``` -------------------------------- ### Install Jupyter Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/README.md Installs the Jupyter Notebook environment, which is required to run the interactive notebooks. ```bash pip install jupyter ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Installs the necessary Python packages for the project using pip, assuming the virtual environment is active. ```bash # Install Python dependencies (venv should be active) pip install -r requirements.txt ``` -------------------------------- ### Setup and Imports for CSI Analysis Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/02_feature_extraction_and_ml.ipynb Imports necessary libraries and sets up paths for data and source directories. Ensures the environment is ready for data loading and analysis. ```python %matplotlib inline import numpy as np import matplotlib.pyplot as plt import json import os import math from pathlib import Path from collections import deque # Setup paths to data and source (relative to notebook location) NOTEBOOK_DIR = Path('.') DATA_DIR = NOTEBOOK_DIR / '..' / 'data' SRC_DIR = NOTEBOOK_DIR / '..' / 'src' print(f"Notebook directory: ./notebooks/") print(f"Data directory: ../data/") print(f"Source directory: ../src/") print() print("✓ Setup complete. Ready to load datasets.") import src.config as config ``` -------------------------------- ### Get System Information via MQTT Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Publish an 'info' command to the MQTT topic to retrieve system information, including network, device, and configuration details. ```json {"cmd": "info"} ``` -------------------------------- ### Initialize Web Audio API Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/espectre-theremin.html Initializes the Web Audio API context, gain node, and oscillator. Starts the oscillator and connects nodes. Handles potential initialization errors. ```javascript function initAudio() { if (isAudioInitialized) return; try { audioContext = new (window.AudioContext || window.webkitAudioContext)(); gainNode = audioContext.createGain(); oscillator = audioContext.createOscillator(); oscillator.type = 'sine'; oscillator.frequency.value = thereminConfig.baseFrequency; oscillator.connect(gainNode); gainNode.connect(audioContext.destination); gainNode.gain.value = 0; // Start muted oscillator.start(); isAudioInitialized = true; console.log('Audio initialized'); } catch (err) { console.error('Failed to initialize audio:', err); showNotification('Audio initialization failed. Click to enable.', 'error'); } } ``` -------------------------------- ### Get Runtime Statistics via MQTT Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Publish a 'stats' command to the MQTT topic to get runtime statistics such as memory usage, current state, and performance metrics. ```json {"cmd": "stats"} ``` -------------------------------- ### Run Jupyter Notebook Server Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/README.md Starts the Jupyter Notebook server from the 'notebooks' directory. This allows you to access and run the notebooks through your web browser. ```bash # From the micro-espectre directory cd notebooks jupyter notebook ``` -------------------------------- ### Start CSI Streaming Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/ML_DATA_COLLECTION.md Begin streaming CSI data from the ESP32 device to your PC. This enables data collection and real-time analysis. ```bash ./me stream --ip ``` -------------------------------- ### Load Libraries and Configure Plotting Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/01_csi_data_explorer.ipynb Imports necessary Python libraries for data analysis and visualization, and sets up the plotting style. This is a standard setup for data exploration notebooks. ```python import numpy as np import matplotlib.pyplot as plt import os import json from pathlib import Path # Configure plotting %matplotlib inline plt.style.use('seaborn-v0_8-whitegrid') print("Libraries loaded successfully.") ``` -------------------------------- ### Setup Real-time Listeners for Detection Parameters Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/espectre-monitor.html Attaches event listeners to UI elements for 'Segmentation Threshold' and 'Window Size'. Changes to these elements trigger debounced commands to update the device configuration. ```javascript // Setup real-time listeners for Detection Parameters function setupDetectionListeners() { // Segmentation Threshold document.getElementById('segThreshold').addEventListener('change', (e) => { debouncedSendCommand('segmentation_threshold', { value: parseFloat(e.target.value) }); }); document.getElementById('segThresholdValue').addEventListener('change', (e) => { debouncedSendCommand('segmentation_threshold', { value: parseFloat(e.target.value) }); }); // Window Size document.getElementById('windowSize').addEventListener('change', (e) => { debouncedSendCommand('segmentation_window_size', { value: parseInt(e.target.value) }); }); document.getElementById('windowSizeValue').addEventListener('change', (e) => { debouncedSendCommand('segmentation_window_size', { value: parseInt(e.target.value) }); }); } ``` -------------------------------- ### Load and Inspect a Sample Baseline Dataset Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/01_csi_data_explorer.ipynb Loads a specific baseline CSI dataset file using the `load_csi_dataset` function and prints its metadata and the shape of the CSI data. This is a practical example of using the loading function. ```python # Load a sample baseline dataset sample_baseline_file = BASELINE_DIR / 'baseline_s3_64sc_20260117_222606.npz' baseline_data = load_csi_dataset(sample_baseline_file) print(f"Loaded: {sample_baseline_file.name}") print(f"\nMetadata:") print(f" Chip: {baseline_data['chip']}") print(f" Label: {baseline_data['label']}") print(f" Gain locked: {baseline_data['gain_locked']}") print(f" Duration: {baseline_data['duration_ms']:.2f} ms ({baseline_data['duration_ms']/1000:.2f} s)") print(f"\nCSI data shape: {baseline_data['csi_data'].shape}") ``` -------------------------------- ### Deploy and Run Micro-ESPectre Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Use the `me` CLI tool to deploy the code to the device and then run the application. The tool automatically detects the necessary ports. ```bash # Deploy code (auto-detect port) ./me deploy # Run application (auto-detect port) ./me run ``` -------------------------------- ### System Tuning for MVS Parameters Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/tools/README.md Perform a grid search for optimal MVS parameters, including subcarrier clusters, thresholds, and window sizes. Shows the confusion matrix for the best configuration. Use --quick for a reduced parameter space. ```bash python 2_analyze_system_tuning.py ``` ```bash python 2_analyze_system_tuning.py --chip S3 ``` ```bash python 2_analyze_system_tuning.py --quick ``` -------------------------------- ### Telemetry Notification Example Source: https://github.com/francescopace/espectre/blob/main/docs/game/README.md Example of a telemetry notification containing movement and threshold values, represented in hexadecimal bytes for float32 values. ```text 00 00 40 3F 9A 99 99 3F ``` -------------------------------- ### Get Scale Ratios Function Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/espectre-theremin.html Returns the frequency ratio array for a given musical scale name. ```javascript function getScaleRatios(scale) { switch (scale) { case 'pentatonic': return PENTATONIC_RATIOS; case 'major': return MAJOR_RATIOS; case 'minor': return MINOR_RATIOS; case 'chromatic': return CHROMATIC_RATIOS; default: return PENTATONIC_RATIOS; } } ``` -------------------------------- ### ESPectre Calibration Logs Source: https://github.com/francescopace/espectre/blob/main/TUNING.md View logs during manual recalibration. This indicates the start, progress, and completion of the calibration process. ```text [I][espectre]: Manual recalibration triggered [I][espectre]: Starting band calibration... [I][espectre]: Calibration completed successfully ``` -------------------------------- ### Activate Virtualenv and Run All Tests Source: https://github.com/francescopace/espectre/blob/main/test/README.md Activate the virtual environment and navigate to the test directory to run all tests using PlatformIO. Native environment is the default. ```bash # Activate virtualenv source ../venv/bin/activate # Run all tests (native is the default environment) cd test && pio test ``` -------------------------------- ### Build and Flash ESPectre for ESP32 (Development) Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Build and flash the ESPectre device using the development configuration file for the original ESP32 platform. This enables debug sensors and uses local component paths. ```bash # For ESP32 (original) esphome run examples/espectre-esp32-dev.yaml ``` -------------------------------- ### Example MQTT Payload Structure Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Illustrates the JSON payload structure published by the system, including movement metrics, state, packet counts, and timestamps. ```json { "movement": 0.0234, # Current moving variance "threshold": 1.0, # Current threshold "state": "idle", # "idle" or "motion" "packets_processed": 100, # Packets since last publish "packets_dropped": 0, # Packets dropped since last publish "pps": 105, # Packets per second (calculated with ms precision) "timestamp": 1700000000 # Unix timestamp } ``` -------------------------------- ### Load Baseline Files for Cross-Chip Comparison Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/notebooks/01_csi_data_explorer.ipynb Placeholder comment indicating the intention to load baseline files for comparing CSI patterns across different Wi-Fi chips, considering gain-locked-aware turbulence. ```python # Load baseline files for each chip WITH gain_locked-aware turbulence ``` -------------------------------- ### Start Audio Interpolation Loop Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/espectre-theremin.html Initiates a continuous loop for audio interpolation at a specified rate (INTERPOLATION_RATE). The loop continues as long as 'interpolationActive' is true. ```javascript function startInterpolationLoop() { if (interpolationActive) return; interpolationActive = true; const updateInterval = 1000 / INTERPOLATION_RATE; // ~16.67ms for 60Hz function interpolate() { if (!interpolationActive) return; const now = Date.now(); const timeSinceLastMQTT = (now - lastUpdateTime) / 1000; // seconds // ``` -------------------------------- ### Load NPZ Sample using csi_utils Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/ML_DATA_COLLECTION.md Loads an NPZ sample file using the `load_npz_as_packets` utility function and processes individual packets. Requires `pathlib` and `numpy`. Run from the `micro-espectre/` directory. ```python from tools.csi_utils import load_npz_as_packets from pathlib import Path import numpy as np # Load a sample file (run from micro-espectre/) packets = load_npz_as_packets(Path('data/baseline/baseline_c6_64sc_20251212_142443.npz')) for pkt in packets: csi_data = pkt['csi_data'] # Shape: (128,) - raw I/Q data label = pkt['label'] # Calculate amplitudes from I/Q pairs Q = csi_data[0::2].astype(float) # Imaginary (odd indices) I = csi_data[1::2].astype(float) # Real (even indices) amplitudes = np.sqrt(I**2 + Q**2) # Shape: (64,) # Process... ``` -------------------------------- ### Run Interactive CLI Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Execute the interactive command-line interface for advanced device control and monitoring. Ensure your virtual environment is active. ```bash # Make sure virtual environment is active # (your prompt should show (venv) prefix) # If not: source venv/bin/activate # On macOS/Linux # Run the interactive CLI: ./me ``` -------------------------------- ### Build and Flash ESPectre for ESP32-C6 (Development) Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Build and flash the ESPectre device using the development configuration file for the ESP32-C6 platform. This enables debug sensors and uses local component paths. ```bash # For ESP32-C6 esphome run examples/espectre-c6-dev.yaml ``` -------------------------------- ### Flash MicroPython Firmware (Auto-detect) Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Flashes the MicroPython firmware with CSI support to the ESP32 device using the `me` CLI in auto-detect mode. This is required for first-time setup. ```bash ./me flash --erase ``` -------------------------------- ### Connect Interactive CLI with Authentication Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Connect the interactive CLI to an MQTT broker using authentication credentials (username and password). ```bash # With authentication ./me --broker homeassistant.local --username mqtt --password mqtt ``` -------------------------------- ### ESPectre ESPHome Configuration Source: https://github.com/francescopace/espectre/blob/main/docs/index.html Add this configuration to your ESPHome YAML file to integrate ESPectre into your Home Assistant setup. Ensure your ESP32 variant is correctly specified. ```yaml esp32: variant: ESP32C6 # or S3, C3, C5... framework: type: esp-idf external_components: - source: github://francescopace/espectre components: [espectre] espectre: ``` -------------------------------- ### Run ESPHome C++ Tests Source: https://github.com/francescopace/espectre/blob/main/CONTRIBUTING.md Navigate to the test directory and execute C++ tests for the ESPHome component using PlatformIO. ```bash cd test && pio test ``` -------------------------------- ### Connect to MQTT Broker Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/espectre-monitor.html Establishes a WebSocket connection to an MQTT broker using provided credentials and subscribes to the main and response topics. Requests initial configuration upon successful connection. ```javascript function connect() { const broker = document.getElementById('broker').value; const port = document.getElementById('port').value; const topic = document.getElementById('topic').value; const username = document.getElementById('username').value; const password = document.getElementById('password').value; if (!broker || !port || !topic) { alert('Please fill in all required fields!'); return; } const connectUrl = `ws://${broker}:${port}/mqtt`; const options = { clean: true, connectTimeout: 4000, clientId: 'espectre_monitor_' + Math.random().toString(16).substr(2, 8) }; if (username) options.username = username; if (password) options.password = password; try { client = mqtt.connect(connectUrl, options); client.on('connect', () => { console.log('Connected to MQTT broker'); updateStatus(true); document.getElementById('configContent').classList.add('collapsed'); document.getElementById('configArrow').classList.add('rotate'); // Subscribe to main topic client.subscribe(topic, (err) => { if (err) { console.error('Subscribe error:', err); alert('Error subscribing to topic!'); } else { console.log('Subscribed to:', topic); } }); // Also subscribe to response topic const responseTopic = topic + '/response'; client.subscribe(responseTopic, (err) => { if (err) { console.error('Subscribe error for response topic:', err); } else { console.log('Subscribed to:', responseTopic); // Request current configuration after successful connection setTimeout(() => { console.log('Requesting initial configuration...'); requestInfo(); }, 500); // Small delay to ensure subscriptions are ready } }); }); client.on('message', (topic, message) => { // Text message - parse as JSON handleMess ``` -------------------------------- ### Increase Threshold for Unstable Detection Source: https://github.com/francescopace/espectre/blob/main/TUNING.md Increase the segmentation threshold to reduce rapid flickering between IDLE and MOTION states. A value of 2.0 is suggested as a starting point. ```yaml espectre: segmentation_threshold: 2.0 ``` -------------------------------- ### Request System Info Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/espectre-monitor.html Sends an 'info' command to the device via MQTT to request system information. ```javascript function requestInfo() { sendCommand('info'); } ``` -------------------------------- ### Uncomment BSSID in ESPectre WiFi Configuration Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Uncomment the `bssid` line in your ESPectre configuration file to use the specified WiFi BSSID. This is part of the setup for mesh networks. ```yaml wifi: networks: - ssid: !secret wifi_ssid password: !secret wifi_password bssid: !secret wifi_bssid ``` -------------------------------- ### Initialize Espectre Theremin on Load Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/espectre-theremin.html Sets up initial slider synchronization, event listeners for configuration changes, and feature modulation toggles when the window loads. It also initializes audio on the first user click. ```javascript window.addEventListener('load', () => { // Sync sliders syncSlider('baseFreq', 'baseFreqValue'); syncSlider('freqRange', 'freqRangeValue'); syncSlider('smoothing', 'smoothingValue'); syncSlider('volume', 'volumeValue'); syncSlider('maxMovement', 'maxMovementValue'); syncSlider('tremoloSpeed', 'tremoloSpeedValue'); syncSlider('tremoloDepth', 'tremoloDepthValue'); syncSlider('vibratoSpeed', 'vibratoSpeedValue'); syncSlider('vibratoDepth', 'vibratoDepthValue'); syncSlider('filterCutoff', 'filterCutoffValue'); syncSlider('filterResonance', 'filterResonanceValue'); // Setup event listeners document.getElementById('thereminMode').addEventListener('change', updateConfig); document.getElementById('thereminScale').addEventListener('change', updateConfig); document.getElementById('logarithmicMapping').addEventListener('change', updateConfig); // Feature modulation event listeners document.getElementById('waveformModEnable').addEventListener('change', updateConfig); document.getElementById('vibratoModEnable').addEventListener('change', updateConfig); document.getElementById('filterModEnable').addEventListener('change', updateConfig); document.getElementById('stereoPanEnable').addEventListener('change', updateConfig); document.getElementById('autoScaleEnable').addEventListener('change', updateConfig); document.getElementById('tremoloEnable').addEventListener('change', updateConfig); document.getElementById('effectsModEnable').addEventListener('change', updateConfig); // Initialize audio on user interaction document.addEventListener('click', () => { if (!isAudioInitialized) { initAudio(); } }, { once: true }); // Initialize config updateConfig(); }); ``` -------------------------------- ### ML Detector Inference Pipeline Flow Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/ALGORITHMS.md This diagram shows the inference pipeline for the ML detector, starting from CSI packet reception to motion score calculation and thresholding. ```text ┌──────────────┐ ┌──────────────┐ ┌───────────────────┐ ┌──────────────┐ │ CSI Packet │───▶│ Turbulence │───▶│ Optional Filters │───▶│ Buffer (100) │ │ │ │ σ (raw std) │ │ Hampel + LowPass │ │ │ └──────────────┘ └──────────────┘ └───────────────────┘ └──────┬───────┘ │ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ IDLE/MOTION │◀───│ Threshold │◀───│ Motion Score │◀───│ 9 Features │ │ │ │ > 5.0 │ │ [0.0-10.0] │ │ → Neural Net │ └──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ ``` -------------------------------- ### Connect to MQTT Broker Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/espectre-theremin.html Establishes a WebSocket connection to an MQTT broker using provided configuration. Handles connection events, subscriptions, and error reporting. ```javascript function connect() { const broker = document.getElementById('broker').value; const port = document.getElementById('port').value; const topic = document.getElementById('topic').value; const username = document.getElementById('username').value; const password = document.getElementById('password').value; if (!broker || !port || !topic) { alert('Please fill in all required fields!'); return; } const connectUrl = `ws://${broker}:${port}/mqtt`; const options = { clean: true, connectTimeout: 4000, clientId: 'espectre_theremin_' + Math.random().toString(16).substr(2, 8) }; if (username) options.username = username; if (password) options.password = password; try { client = mqtt.connect(connectUrl, options); client.on('connect', () => { console.log('Connected to MQTT broker'); updateStatus(true); document.getElementById('configContent').classList.add('collapsed'); document.getElementById('configArrow').classList.add('rotate'); // Subscribe to main topic client.subscribe(topic, (err) => { if (err) { console.error('Subscribe error:', err); alert('Error subscribing to topic!'); } else { console.log('Subscribed to:', topic); resumeAudio(); startInterpolationLoop(); } }); }); client.on('message', (topic, message) => { try { const data = JSON.parse(message.toString()); handleMessage(data); } catch (err) { console.error('Error parsing message:', err); } }); client.on('error', (err) => { console.error('Connection error:', err); alert('Connection error: ' + err.message); updateStatus(false); }); client.on('close', () => { console.log('Connection closed'); updateStatus(false); }); } catch (err) { console.error('Connection error:', err); alert('Connection error: ' + err.message); } } ``` -------------------------------- ### Custom Partition Table for 8MB Flash (No OTA) Source: https://github.com/francescopace/espectre/blob/main/SETUP.md An example of a custom partition table for an 8MB flash device when OTA updates are not required. This configuration provides a large application partition. ```csv # Name, Type, SubType, Offset, Size nvs, data, nvs, 0x9000, 0x5000, phy_init, data, phy, 0xe000, 0x1000, app0, app, factory, 0x10000, 0x7C0000, spiffs, data, spiffs, 0x7D0000, 0x30000, ``` -------------------------------- ### Factory Reset via MQTT Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Publish a 'factory_reset' command to reset the device to its default configuration and re-calibrate it. This action is irreversible. ```json {"cmd": "factory_reset"} ``` -------------------------------- ### Custom Partition Table for 4MB Flash (No OTA) Source: https://github.com/francescopace/espectre/blob/main/SETUP.md An example of a custom partition table for a 4MB flash device when OTA updates are not required. This configuration maximizes the space available for the application. ```csv # Name, Type, SubType, Offset, Size nvs, data, nvs, 0x9000, 0x5000, phy_init, data, phy, 0xe000, 0x1000, app0, app, factory, 0x10000, 0x3C0000, spiffs, data, spiffs, 0x3D0000,0x30000, ``` -------------------------------- ### Build and Flash ESPectre Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Builds and flashes the ESPectre firmware to your ESP32 device using a specified YAML configuration file. Replace 'espectre-c6.yaml' with the appropriate file for your hardware. ```bash esphome run espectre-c6.yaml # replace with your platform's file ``` -------------------------------- ### Connect Interactive CLI to Specific Broker Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/README.md Run the interactive CLI and connect to a specific MQTT broker by providing its IP address and port. ```bash # Connect to specific broker ./me --broker 192.168.1.100 --port-mqtt 1883 ``` -------------------------------- ### Train ML Model Source: https://github.com/francescopace/espectre/blob/main/micro-espectre/ML_DATA_COLLECTION.md Initiate the training process for the machine learning model using the collected and preprocessed data. Default parameters are used unless specified. ```bash python tools/10_train_ml_model.py ``` -------------------------------- ### Clone ESPectre Repository Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Clone the ESPectre repository and navigate into the project directory to begin development. ```bash git clone https://github.com/francescopace/espectre.git cd spectre ``` -------------------------------- ### Run External Traffic Generator Script (Bash) Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Commands to manage the standalone Python script for generating external traffic. Use 'run' for foreground execution, 'start' for background daemon, 'stop' to halt, and 'status' to check if it's running. ```bash python3 espectre_traffic_generator.py run # Foreground (Ctrl+C to stop) python3 espectre_traffic_generator.py start # Background daemon python3 espectre_traffic_generator.py stop # Stop daemon python3 espectre_traffic_generator.py status # Check if running ``` -------------------------------- ### Build and Flash ESPectre for ESP32-S3 (Development) Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Build and flash the ESPectre device using the development configuration file for the ESP32-S3 platform. This enables debug sensors and uses local component paths. ```bash # For ESP32-S3 esphome run examples/espectre-s3-dev.yaml ``` -------------------------------- ### Customize Espectre Sensors Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Configure custom names, icons, and filters for Espectre sensors. This example shows how to hide the movement sensor from Home Assistant while making the motion sensor visible, and apply filters for scaling, clamping, and rounding the movement score. ```yaml espectre: movement_sensor: name: "Living Room Movement" internal: true # Hide from Home Assistant icon: "mdi:sine-wave" filters: - multiply: 100 # Scale 0-1 to 0-100 - clamp: min_value: 0 max_value: 100 # Cap at 100% - round: 1 # Round to 1 decimal motion_sensor: name: "Living Room Motion" icon: "mdi:motion-sensor" threshold_number: name: "Living Room Threshold" ``` -------------------------------- ### Home Assistant Command Line Integration for Traffic Generator Source: https://github.com/francescopace/espectre/blob/main/SETUP.md Integrate the ESPectre traffic generator script into Home Assistant using the command_line integration. This creates a switch entity to start, stop, and check the status of the background traffic generation process. ```yaml command_line: - switch: name: "ESPectre Traffic Generator" command_on: "python3 /config/python_scripts/espectre_traffic_generator.py start" command_off: "python3 /config/python_scripts/espectre_traffic_generator.py stop" command_state: "python3 /config/python_scripts/espectre_traffic_generator.py status" value_template: '{{ "Running" in value }}' unique_id: espectre_traffic_generator ```