Skip to content

Addraw#64

Open
javierbrk wants to merge 142 commits into
AlterMundi-MonitoreoyControl:mainfrom
javierbrk:addraw
Open

Addraw#64
javierbrk wants to merge 142 commits into
AlterMundi-MonitoreoyControl:mainfrom
javierbrk:addraw

Conversation

@javierbrk
Copy link
Copy Markdown
Collaborator

Add raw values to grafana messages to simplify moisture sensor calibration process

Pablomonte and others added 30 commits November 11, 2025 16:27
Support for multiple sensor types via build flags:
- SCD30 (CO2 + temp + humidity) - original, backward compatible
- Capacitive soil moisture (analog ADC pin 34)
- BME280 (temp + humidity + pressure)
- Simulated (random data for testing)

Key changes:
- Abstract ISensor interface for sensor independence
- SensorFactory for compile-time sensor selection
- Updated Grafana messages to include sensor type tag
- Modified endpoints to work with any sensor type
- Calibration endpoint supports sensors that implement it

Build environments:
- esp32dev: SCD30 (default, backward compatible)
- esp32dev_capacitive: Capacitive soil moisture sensor
- esp32dev_bme280: BME280 environmental sensor
- esp32dev_simu: Simulated sensor data

Sensor abstraction layer maintains compatibility with
existing Grafana/WiFi/OTA infrastructure.

AI-assisted development
- RS485Manager class for UART2 communication
- DE/RE pin control for half-duplex (optional, puenteado por defecto)
- Dual output: Grafana (WiFi) + RS485 (local bus)
- Build flag ENABLE_RS485 para habilitar funcionalidad
- Compatible with modular sensor architecture

Hardware: ESP32 + MAX485/similar transceiver
Default pins: GPIO16(RX), GPIO17(TX), 9600 baud
DE/RE: Opcional (puentear para TX permanente)

New build environment: esp32dev_rs485
- Sensor capacitivo + RS485 enabled
- Transmite datos por WiFi/Grafana Y por RS485

Use cases:
- Monitoreo remoto sin WiFi (solo RS485)
- Dual mode: WiFi para Grafana + RS485 para displays locales
- Compatible con infraestructura AlterMundi

AI-assisted development
Implements SensorManager for simultaneous multi-sensor operation and
adds web-based configuration interface for runtime parameter changes.

Multi-sensor features:
- SensorManager class handles multiple sensors (SCD30, BME280, Capacitive, OneWire)
- OneWire auto-detection for DS18B20 temperature sensor chains
- Individual sensor enable/disable via config.json
- All sensors propagate to both Grafana and RS485 outputs
- Unique sensor IDs for proper Grafana tagging
- Backward compatible with single-sensor builds via #ifdef SENSOR_MULTI

Web configuration features:
- GET /settings endpoint serves HTML configuration form
- Edit all config parameters: sensors, RS485, WiFi, thresholds
- POST /config now saves complete configuration (not just WiFi)
- POST /restart endpoint for remote device restart
- No recompilation needed for config changes
- Changes persist to SPIFFS config.json

Technical changes:
- Added SensorManager.h for multi-sensor orchestration
- Added SensorOneWire.h for DS18B20 OneWire support
- Added webConfigPage.cpp/h with embedded HTML/CSS/JS form
- Updated configFile with updateConfig() for SPIFFS persistence
- Expanded endpoints.cpp with handleSettings() and handleRestart()
- Updated platformio.ini with esp32dev_multi environment
- Fixed SCD30 calibration method name (forceRecalibrationWithReference)
- Fixed ArduinoJson deprecated containsKey() usage

Build environments:
- esp32dev_multi: All sensors + RS485 + web config (RAM: 15%, Flash: 87%)
- Single-sensor builds remain unchanged (backward compatible)

AI-assisted development
Adds AlterMundi visual identity to serial output and web interface
with official branding and improved user experience.

Serial logging improvements:
- ASCII art banner with AlterMundi mesh network design
- Official slogan: "La pata tecnológica de ese otro mundo posible"
- Structured logging with [INFO], [OK], [ERROR] prefixes
- Visual separators and tree-style sensor listing
- Detailed system status on boot

Web interface improvements:
- CSS variables with AlterMundi color palette
  - Primary green: #55d400
  - Orange accent: #F39100
  - Blue highlights: #0198fe
- Modern gradient background
- Enhanced button styles with hover effects and shadows
- Smooth transitions and animations
- AlterMundi slogan in page header
- Improved form element styling with focus states
- Better visual hierarchy with updated typography

Design philosophy:
- Accessible and clean (community-focused)
- Professional yet approachable
- Vibrant colors reflecting open-source energy
- Consistent branding across serial and web

Build stats:
- RAM: 15.0% (49KB) - unchanged
- Flash: 87.1% (1.14MB) - minimal increase (+0.3%)

AI-assisted development
Implementa ESP-NOW con auto-discovery y auto-detección de rol:

Core Features:
- Auto-role detection: gateway (WiFi+Grafana) vs sensor (sin conectividad)
- Beacon-based discovery protocol (2s interval)
- RSSI-based gateway selection con failover automático
- Multi-gateway support con hysteresis (10 dBm)
- Unified firmware: un solo binary se adapta según conectividad

Architecture:
- ESPNowManager: clase completa para manejo de ESP-NOW
- Discovery: broadcast beacons → pairing request → ACK
- Data flow: sensor → unicast → gateway → Grafana
- Message structures: DiscoveryMessage (37 bytes), SensorDataMessage (29 bytes)

Configuration:
- Web UI con selector de modo (auto/gateway/sensor)
- Channel validation (1-13)
- Gateway usa canal WiFi actual, sensor usa canal configurado
- Configurable: beacon interval, discovery timeout, send interval

Bug Fixes:
- Fixed field name inconsistency (espnow_mode → espnow_force_mode)
- Fixed channel initialization order (after WiFiManager)
- Safe beacon broadcast con fallback para WiFi desconectado
- Loop optimizado: usa getMode() en vez de recargar config

Technical Details:
- Gateway: AP_STA mode, SoftAP MAC para beacons
- Sensor: STA mode sin conexión, bajo consumo
- Max 20 peers simultáneos
- Peer cleanup cada 60s (timeout: 5 min)
- Static callback pattern con inline instance pointer

Testing: Compilado OK (90.4% flash, 15.1% RAM)
Pendiente: Verificar comunicación beacon gateway→sensor

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Fixes critical ESP-NOW pairing problems between sensor and gateway:

ESP-NOW Handshake Fixes:
- Force WiFi channel in sensor mode using esp_wifi_set_channel()
  Without explicit channel setting, sensor in STA mode without connection
  has no active channel and cannot receive gateway beacons
- Change pairing request from unicast to broadcast
  Gateway MAC not in sensor's peer list before pairing, causing send failures
  Broadcast allows gateway to receive and respond with ACK

UI Improvements:
- Add AlterMundi branding to WiFi portal (portal cautivo)
- UTF-8 charset support for emojis and accented characters
- CSS variables for consistent AlterMundi color scheme
- Enhanced visual design with gradients, shadows, transitions
- Navigation buttons between WiFi config and settings pages

Technical Details:
- Sensor now properly operates on configured channel (e.g., ch 11)
- Gateway receives pairing requests via broadcast
- Eliminates "device or resource busy" during discovery phase
- Maintains backward compatibility with existing configurations

Testing: Confirmed handshake success between two ESP32 devices
- Gateway: Connected to WiFi, broadcasts beacons
- Sensor: Receives beacons, sends pairing requests, receives ACK

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Mejora la estética y legibilidad de los mensajes del monitor serial:

Formato Estandarizado:
- [✓ OK  ] Mensajes de éxito (8 chars width)
- [✗ ERR ] Mensajes de error (8 chars width)
- [⚠ WARN] Advertencias (8 chars width)
- [→ INFO] Información general (8 chars width)
- [ESP-NOW] Mensajes ESP-NOW (mantiene prefijo descriptivo)
  └─ Submensajes con indentación consistente (5 chars)

Archivos Modificados:
- src/main.cpp: Setup, WiFi Manager, ESP-NOW auto-detection
- include/ESPNowManager.h: Pairing, discovery, data transfer

Beneficios:
- Alineación vertical consistente en terminal
- Jerarquía visual clara con símbolos y indentación
- Más fácil de leer logs largos
- Símbolos Unicode descriptivos (✓ ✗ ⚠ →)
- Mensajes más concisos en español

Antes: [OK]    ✓ ESP-NOW inicializado
       [ERROR] ✗ Error...
Después: [✓ OK  ] ESP-NOW inicializado
         [✗ ERR ] Error...
         └─ Sensor: WiFi STA forzado a canal 11

Testing: Compilado OK (90.4% flash, 15.1% RAM)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Adds AlterMundi logo as favicon for better branding consistency.

- Add favicon.svg to SPIFFS data directory
- Add favicon link tags to both WiFi portal and settings pages
- Add /favicon.svg endpoint handler to serve from SPIFFS

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Separates sensitive credentials from public code for better security.

- Move URL, TOKEN_GRAFANA, FIRMWARE_BIN_URL to constants_private.h
- Add constants_private.h to .gitignore
- Create constants_private.h.example as template
- Update constants.cpp to include private constants

Users must create their own constants_private.h from the example template.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Comprehensive dashboard for visualizing all sensor data in Grafana.

Features:
- Auto-discovery of all connected sensors (gateway + mesh)
- Dynamic filtering by device and sensor type
- Real-time monitoring with 30s refresh
- Temperature, humidity, and CO₂ visualization
- Color-coded thresholds for all metrics
- Current state table with background colors
- CO₂ alert (>1000 ppm for 5 minutes)
- Heatmap for CO₂ distribution patterns

Dashboard Panels:
- Summary stats (devices, avg temp/hum/co2)
- Time series graphs per device
- Live sensor status table
- Temporal heatmap

Included:
- grafana-dashboard.json: Importable dashboard configuration
- DASHBOARD_GRAFANA.md: Complete documentation
- tools/test_grafana.sh: Connectivity and data verification script

Import: Dashboards → Import → Upload grafana-dashboard.json

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Adds automatic sensor configuration with management buttons.

Features:
- Auto-load default sensors (SCD30, BME280, Capacitive, OneWire) when config is empty
- Button "Por Defecto": Load default sensor configuration
- Button "Olvidar WiFi": Clear WiFi credentials and return to AP mode
- Button "Limpiar Todo": Reset all configuration to factory defaults
- Automatic migration: detects old configs without sensors and adds defaults
- New endpoint /config/reset for complete config reset

UI Improvements:
- Compact button design with concise labels
- All buttons in single line with appropriate colors
- Warning message when using default config

Backend:
- handleConfigReset() endpoint for factory reset
- loadConfig() auto-migration for backward compatibility
- Preserves existing config structure while adding missing sensors

Fixes issue where devices without sensor config showed no sensors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
ESP-NOW mesh was implemented but only printing sensor values to serial.
Now properly forwards data through mesh network to gateway, which sends
it to Grafana.

Technical details:
- Implement buffered mesh data processing (10-entry ring buffer)
- Move HTTP calls from WiFi interrupt to main loop context
- Gateway processes queued mesh data and forwards to Grafana
- Add DNS configuration for reliable gateway connectivity
- Improve debug logging with visual indicators

AI-assisted development
CI was failing due to:
1. Missing constants_private.h (excluded from repo via gitignore)
2. C++17 inline variable syntax in ESPNowManager.h

Changes:
- Generate constants_private.h from example template in CI workflow
- Add C++17 standard flag to all ESP-NOW environments in platformio.ini
- Resolve "inline variables require C++17" compilation warning

Build verified locally: SUCCESS (22.56s)

AI-assisted development
Prevent 403 permission error when running CI on PRs from forks.
Release creation now only runs on push to main branch.

Changes:
- Add conditional to "Create Release" step
- Condition: github.event_name == 'push' && github.ref == 'refs/heads/main'
- PRs will build successfully without attempting release creation

AI-assisted development
Adds two new sensor types with full integration:
- ModbusTHSensor: TH-MB-04S temperature/humidity via Modbus RTU
- HD38Sensor: Soil moisture with analog/digital outputs

Also includes complete documentation restructure:
- Rewritten README for clarity and concision
- Added API, configuration, data flow, ESP-NOW, and sensors docs

SensorManager updated to load new sensor types from config.json.
Added modbus-esp8266 dependency to platformio.ini.

AI-assisted development
…ure/add_sensor_id

add sensor id, device id, and measurement text, fixes  AlterMundi-MonitoreoyControl#3
- Add HD38 soil moisture sensor to web config interface
- Reorder UI sections: WiFi > Sistema > ESP-NOW > RS485 > Sensores
- Group sensors: buses (SCD30, BME280, Modbus, OneWire) then ADC (Capacitive, HD38)
- HD38 config includes: analog/digital pins, voltage divider, invert logic

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add modern card-based layout with Altermundi colors
- Support multi-sensor mode via SENSOR_MULTI
- Add color coding: green=ok, orange=warn, red=error
- Show sensor icons based on type
- Display WiFi RSSI and uptime in status bar
- Auto-refresh every 10 seconds
- Responsive design with flexbox
- Soil sensors (HD38, Capacitive) show only humidity, not temperature

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…ature/improved-data-page

Feature/improved data page
Interactive CLI tool for RS485 Modbus sensor diagnostics:
- Auto-detect USB serial ports
- Scan bus for sensors across multiple baudrates
- Real-time sensor monitoring
- Configure sensor address, baudrate, and calibration offsets
- Slicetex TH-MB-XXX-DS register mapping (0=2400, 1=4800, 2=9600)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
javierbrk and others added 30 commits April 30, 2026 17:40
…itoreoyControl/javi/feature/mediator-control

Javi/feature/mediator control
…itoreoyControl/altermundi-main

Altermundi main
…itoreoyControl/altermundi-main

create a new version
…itoreoyControl/altermundi-main

Refs/heads/altermundi main
- Add 9 missing endpoints: /api/status, /actuator/command,
  /actuator/status, /rules, /rules/save, /rules/reload,
  /rules-editor, /api/admin/info, /api/admin/password
- Rewrite /actual schema: structured sensors[]/actuators[]/uptime
  replacing the legacy flat format
- Document GPIO relay support in /api/relays and /api/relay/toggle
- Fix auth section: opt-in Basic Auth with protected endpoints marked
- Fix CORS: globally enabled (was documented as absent)
- Correct response bodies for /config POST, /restart, /config/reset
- Editorial pass: remove firmware internals, trim swagger descriptions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…itoreoyControl/docs/api-sync

docs: update and sync API reference to firmware v0.2.12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants