chore: import KXKM Batterie Parallelator
ESP-IDF CI / Host Tests (Unity) (push) Successful in 1m8s
CI / firmware-native (push) Successful in 2m57s
Rust Protection Tests / Cargo test (host) (push) Failing after 3m21s
ESP-IDF CI / ESP-IDF Build (v5.4) (push) Failing after 6m55s
ESP-IDF CI / Memory Budget Gate (push) Has been skipped
qa-cicd-environments / qa-kxkm-s3-build (push) Successful in 8m53s
qa-cicd-environments / qa-sim-host (push) Successful in 2m2s
qa-cicd-environments / qa-kxkm-s3-memory-budget (push) Successful in 11m17s

Context: the project archive (KXKM_Batterie_Parallelator-main) had
no git history locally; a fresh repository is needed to host it on
git.saillant.cc (electron/KXKM_Batterie_Parallelator).

Approach: initialize a new repo on branch main, stage the archive
content, and harden .gitignore before the first commit.

Changes:
- Import the full project tree: firmware/, firmware-idf/,
  firmware-rs/, iosApp/, kxkm-bmu-app/, kxkm-api/, hardware/,
  docs/, specs/, scripts/, models/, tests/
- Keep project dotfiles tracked despite the trailing '.*' ignore
  rule: .github/, .claude/, .superpowers/, .gitattributes,
  .markdownlint.json
- Extend .gitignore: firmware/src/credentials.h (local secrets,
  template kept), kxkm-bmu-app/**/build/ (66 MB compiled iOS
  framework), .remember/ (session data)

Impact: the project can now be maintained on the self-hosted Gitea
forge with a clean, secret-free initial history.
This commit is contained in:
L'électron rare
2026-07-04 12:32:28 +02:00
commit f55093d6fe
1056 changed files with 4403534 additions and 0 deletions
+28
View File
@@ -0,0 +1,28 @@
{
"permissions": {
"allow": [
"Bash(pio test:*)",
"Bash(git log:*)",
"WebFetch(domain:github.com)",
"WebFetch(domain:circuitdigest.com)",
"WebFetch(domain:www.ti.com)",
"Bash(system_profiler SPUSBDataType)",
"Bash(xcrun xcodebuild:*)",
"Bash(instruments -s devices)",
"Bash(ios-deploy --detect)",
"Bash(cfgutil list:*)",
"Bash(bash -c 'source ~/esp/esp-idf/export.sh && idf.py build')",
"Bash(./gradlew :shared:linkDebugFrameworkIosArm64)",
"Bash(/usr/libexec/java_home)",
"Read(//opt/homebrew/Cellar/openjdk@17/17.0.18/libexec/openjdk.jdk/Contents/Home/bin/**)",
"Bash(/opt/homebrew/opt/openjdk@17/bin/java -version)",
"Bash(export JAVA_HOME=/opt/homebrew/opt/openjdk@17)",
"Bash(./gradlew :shared:linkDebugFrameworkIosArm64 --stacktrace)",
"Bash(./gradlew :shared:generateCommonMainBmuDatabaseInterface)",
"Bash(./gradlew :shared:compileKotlinIosArm64)",
"Bash(xcodebuild -list)",
"Bash(xcodebuild build:*)",
"Bash(ruby -e ':*)"
]
}
}
+100
View File
@@ -0,0 +1,100 @@
---
name: ql-debug
description: >
Two-phase diagnostic system combining rapid root-cause identification with
residual sweep verification. Prevents cascading AI debugging damage by
enforcing four mandatory analysis layers before any code change.
user-invocable: true
allowed-tools: Read, Glob, Grep, Edit, Write, Bash
---
# /ql-debug - Diagnostic Fixer
<skill>
<trigger>/ql-debug</trigger>
<phase>IMPLEMENT / SUBSTANTIATE / GATE</phase>
<persona>Fixer</persona>
<dispatch>
<phase1>ql-fixer — Rapid root-cause (4-layer analysis on reported symptoms)</phase1>
<phase2>ql-fixer — Residual sweep (4-layer analysis on fixed state)</phase2>
</dispatch>
<output>Two-phase diagnosis: root-cause fix + residual sweep report</output>
</skill>
## Purpose
Bring surgical precision to debugging. AI coding agents typically pull a thread and watch the codebase unravel — guessing at fixes, introducing regressions, chasing cascading failures. The Fixer enforces a formal methodology: **prove the root cause first, then propose the minimal fix.** No code changes until the cause-effect chain is established with evidence.
## When to Use
- Runtime errors with unclear origin or misleading stack traces
- Non-deterministic failures (works sometimes, fails others)
- Cascading failures after refactoring
- Proactive verification after significant logic changes
- Test failures requiring formal root-cause analysis
- Structural defects blocking phase transitions
## Execution Protocol
### Step 1: Describe the Problem
Provide the Fixer with:
- **Symptom**: What is failing? Error message, unexpected behavior, test output.
- **Context**: What changed recently? Which files are involved?
- **Reproduction**: How to trigger the failure (if known).
If invoking proactively (no specific failure), state which files or logic paths were changed.
### Step 2: Two-Phase Agent Dispatch
**Phase 1 — Rapid Root-Cause (ql-fixer)**
Launch the `ql-fixer` agent (use `subagent_type: "ql-fixer"`) with the problem description. The fixer runs all four layers (Dijkstra, Hamming/Shannon, Turing/Hopper, Zeller) focused on the REPORTED symptoms. It identifies root causes and proposes fixes.
Apply the proposed fixes.
**Phase 2 — Residual Sweep (ql-fixer, resumed)**
After Phase 1 fixes are applied, launch the `ql-fixer` agent again to:
- Verify the fixes are complete and correct
- Sweep for residual issues introduced or exposed by the fixes
- Check for similar patterns elsewhere in the codebase
- Validate build artifacts match source (dist/out staleness check)
Phase 2 uses the same four-layer methodology but scoped to the FIXED state, not the original symptoms.
### Step 3: Diagnosis & Handoff
The Fixer produces a final diagnosis with:
- Root cause location and explanation
- Cause-effect chain
- Recommended fix with regression risk assessment
- Related issues discovered during analysis
**Handoff rules:**
- Straightforward fix: Fixer proposes exact code changes
- Architectural changes needed: hand off to `/ql-plan` for Governor review
- Implementation ready: hand off to `/ql-implement` for the Specialist
- Test validation needed: hand off to `/ql-substantiate` for the Judge
## Constraints
- **NEVER** apply a fix without completing at least Layers 1-3
- **NEVER** propose a fix that only addresses the symptom
- **ALWAYS** distinguish symptom from root cause
- **ALWAYS** check for similar patterns elsewhere in the codebase
- **ALWAYS** document findings with line numbers and evidence
- **ALWAYS** use `subagent_type: "ql-fixer"` (not `ultimate-debugger`)
## Integration with QoreLogic
This skill implements:
- **S.H.I.E.L.D. Diagnostic Service**: On-demand across IMPLEMENT, SUBSTANTIATE, and GATE phases
- **Two-Phase Architecture**: Root-cause first, then residual sweep
- **Four-Layer Methodology**: Dijkstra, Hamming/Shannon, Turing/Hopper, Zeller
- **Evidence-Based Fixes**: Every conclusion backed by code evidence
- **Cross-Agent Handoff**: Routes results to appropriate next agent/skill
+281
View File
@@ -0,0 +1,281 @@
---
name: ql-implement
description: >
Implementation Pass
user-invocable: true
allowed-tools: Read, Glob, Grep, Edit, Write, Bash
---
---
name: ql-implement
description: Specialist Implementation Pass that translates gated blueprint into reality using Section 4 Simplicity Razor and TDD-Light methodology. Use when: (1) Implementing after PASS verdict from /ql-audit, (2) Building features from approved architecture plans, or (3) Creating code under KISS constraints.
---
# /ql-implement - Implementation Pass
<skill>
<trigger>/ql-implement</trigger>
<phase>IMPLEMENT</phase>
<persona>Specialist</persona>
<output>Source code in src/, tests in tests/</output>
</skill>
## Purpose
Translate the gated blueprint into maintainable reality using strict Section 4 Simplicity Razor constraints and TDD-Light methodology.
## Execution Protocol
### Step 1: Identity Activation
You are now operating as **The QoreLogic Specialist**.
Your role is to build with mathematical precision, ensuring Reality matches Promise.
### Step 2: Gate Verification
```
Read: .failsafe/governance/AUDIT_REPORT.md
```
**INTERDICTION**: If verdict is NOT "PASS":
```
ABORT
Report: "Gate locked. Tribunal audit required. Run /ql-audit first."
```
**INTERDICTION**: If AUDIT_REPORT.md does not exist:
```
ABORT
Report: "No audit record found. Run /ql-audit to unlock implementation."
```
### Step 3: Blueprint Alignment
```
Read: docs/ARCHITECTURE_PLAN.md
Read: docs/CONCEPT.md
```
Extract:
- File tree (what to create)
- Interface contracts (how it should work)
- Risk grade (level of caution required)
### Step 4: Build Path Trace
Before creating ANY file:
```
Read: [entry point - main.tsx, index.ts, package.json]
```
Verify the target file will be connected to the build path.
**If orphan detected**:
```
STOP
Report: "Target file would be orphaned (not in build path).
Verify import chain or update blueprint."
```
### Step 5: TDD-Light
**Before writing any core logic**, create a minimal failing test.
Template: `.claude/commands/references/ql-implement-patterns.md`.
**Constraint**: Define exactly ONE success condition that proves Reality matches Promise.
### Step 5.6: Intent Lock Interdiction (B51)
> Deferred — `INTENT_LOCK.json` not yet implemented. This step is a no-op until `tools/reliability/` scripts are created.
### Step 5.7: Skill Admission Interdiction (B49)
> Deferred — `admit-skill.ps1` not yet implemented. This step is a no-op until `tools/reliability/` scripts are created.
### Step 5.8: Gate-to-Skill Matrix Interdiction (B50)
> Deferred — `gate-skill-matrix.json` not yet implemented. This step is a no-op until `tools/reliability/` scripts are created.
### Step 6: Precision Build
Apply the Section 4 Razor to EVERY function and file.
Checklist: `.claude/commands/references/ql-implement-patterns.md`.
#### Code Patterns
Reference code patterns:
`.claude/commands/references/ql-implement-patterns.md`.
### Step 7: Visual Silence (Frontend)
For UI examples, see:
`.claude/commands/references/ql-implement-patterns.md`.
### Step 8: Post-Build Cleanup
Final pass checklist:
`.claude/commands/references/ql-implement-patterns.md`.
### Step 9: Complexity Self-Check
Before declaring completion:
```
For each file modified/created:
- Count function lines
- Count nesting levels
- Check for nested ternaries
- Verify naming conventions
```
If ANY violation found:
```
PAUSE
Report: "Section 4 violation detected. Running self-refactor before completion."
Apply: Automatic splitting/flattening
```
### Step 10: Handoff
Template:
`.claude/commands/references/ql-implement-patterns.md`.
### Step 10.5: Mark Blockers Complete
If implementation addressed any blockers in BACKLOG.md:
```
Read: docs/BACKLOG.md
Edit: docs/BACKLOG.md
```
For each addressed blocker:
- Change: `- [ ] [ID]` -> `- [x] [ID]`
- Append: ` (v[version] - Complete)`
Example:
```markdown
- [x] [D4] V1: Ghost UI - toggleGuide handler missing (v1.2.0 - Complete)
```
### Step 11: Update Ledger
Edit: docs/META_LEDGER.md
Add entry:
```markdown
---
### Entry #[N]: IMPLEMENTATION
**Timestamp**: [ISO 8601]
**Phase**: IMPLEMENT
**Author**: Specialist
**Risk Grade**: [from blueprint]
**Files Modified**:
- [list of files]
**Content Hash**:
```
SHA256(modified files content)
= [hash]
```
**Previous Hash**: [from entry N-1]
**Chain Hash**:
```
SHA256(content_hash + previous_hash)
= [calculated]
```
**Decision**: Implementation complete. Section 4 Razor applied.
```
### Step 12.5: Implementation Staging
**Verify Reality = Blueprint**:
1. Read docs/ARCHITECTURE_PLAN.md file tree
2. Glob src/** and tests/**
3. Compare: every planned file exists
4. Verify: no unplanned orphans in src/
IF verification FAILS:
```
ABORT: "Implementation incomplete"
REPORT: Missing/unexpected files
DO NOT STAGE
```
IF verification PASSES:
**Auto-Stage**:
```bash
git add src/**
git add tests/**
git add docs/META_LEDGER.md
git add docs/BACKLOG.md
```
**CHANGELOG Check** (if user-facing changes):
IF CHANGELOG.md not updated AND changes are user-facing:
- WARN: "Consider updating CHANGELOG.md for user-facing changes"
REPORT: "Implementation verified. X files staged. Ready for commit."
## Constraints
- **NEVER** implement without PASS verdict
- **NEVER** exceed Section 4 limits - split/refactor instead
- **NEVER** skip TDD-Light for logic functions
- **NEVER** leave console.log in code
- **NEVER** create files not in blueprint without Governor approval
- **NEVER** add dependencies without proving necessity
- **ALWAYS** verify build path before creating files
- **ALWAYS** mark addressed blockers as complete in BACKLOG.md
- **ALWAYS** handoff to Judge for substantiation
- **ALWAYS** update ledger with implementation hash
## Success Criteria
Implementation succeeds when:
- [ ] AUDIT_REPORT.md shows PASS verdict
- [ ] All files from ARCHITECTURE_PLAN.md created
- [ ] All files connected to build path (no orphans)
- [ ] Section 4 Razor applied to all functions (<=40 lines)
- [ ] Section 4 Razor applied to all files (<=250 lines)
- [ ] Nesting depth <=3 levels for all code
- [ ] No nested ternaries in any code
- [ ] TDD-Light tests written for all logic functions
- [ ] No console.log statements in production code
- [ ] META_LEDGER.md updated with implementation hash
- [ ] Handoff to Judge for substantiation
## Integration with QoreLogic
This skill implements:
- **Precision Build**: Mathematical precision matching Reality to Promise
- **Section 4 Razor**: Strict simplicity constraints on all code
- **TDD-Light**: Test-driven development for logic functions
- **Build Path Verification**: Ensures no orphan files created
- **Hash Chain Continuation**: Updates META_LEDGER with cryptographic linkage
---
**Remember**: Reality must match Promise. If you find yourself exceeding Section 4 limits, stop and refactor. Split functions, flatten nesting, remove complexity. Never compromise on simplicity for speed.
+271
View File
@@ -0,0 +1,271 @@
---
name: ql-repo-release
description: >
Delivery Gate Orchestration
user-invocable: true
allowed-tools: Read, Glob, Grep, Edit, Write, Bash
---
---
name: ql-repo-release
description: /ql-repo-release - Delivery Gate Orchestration
---
# /ql-repo-release - Delivery Gate Orchestration
<skill>
<trigger>/ql-repo-release</trigger>
<phase>DELIVER</phase>
<persona>Governor</persona>
<output>Version bump, metadata sync, git tag, release pipeline trigger</output>
</skill>
## Purpose
Orchestrate the full local release workflow after `/ql-substantiate` seals a session. Transitions substantiated deliverables to production-ready releases with confirmation gates at every irreversible step.
## Execution Protocol
### Step 1: Verify Branch and Seal
#### Branch Gate
```bash
git branch --show-current
```
The release branch must follow the naming convention `hotfix/vX.Y.Z` or `release/vX.Y.Z`.
If on a feature branch (e.g., `feat/*`, `plan/*`):
```
ABORT
Report: "Cannot release from a feature branch. Create a release or hotfix branch first:
git checkout -b hotfix/vX.Y.Z (from the branch with all changes)
git checkout -b release/vX.Y.Z (from main after merging)"
```
If on `main`:
```
WARN: "Direct push to main is blocked by pre-push policy. Switching to release branch."
git checkout -b release/vX.Y.Z
```
#### Pull Latest
```bash
git pull --rebase
```
**Note**: After release, create a PR to merge the release/hotfix branch into `main`.
#### Seal Check
```
Read: docs/SYSTEM_STATE.md
Read: docs/META_LEDGER.md (last entry)
```
Confirm the latest ledger entry is a SUBSTANTIATE seal. If not:
```
ABORT
Report: "No seal found. Run /ql-substantiate before releasing."
```
### Step 2: Run Pre-Flight
Execute `release-gate.cjs --preflight` from `FailSafe/extension/`:
```bash
node scripts/release-gate.cjs --preflight
```
Additionally, verify:
#### Skill files uncommitted check
```bash
git diff --name-only -- .claude/commands/ql-*.md
```
If any skill files are modified but not committed, warn:
> Skill files modified but uncommitted: [list]. Include in release commit or stash before proceeding.
#### Help doc version markers
Read `FailSafe/extension/docs/COMPONENT_HELP.md` and `FailSafe/extension/docs/PROCESS_GUIDE.md`. Verify version markers match the target release version. If stale, flag for update in Step 5.
#### Backlog coherence
```
Read: docs/BACKLOG.md
```
Verify:
1. **No duplicate B-item numbers** — scan all `[B###]` references for collisions
2. **Version summary table is current** — the latest released version appears in the table with correct status
3. **No backlog items reference a version older than the current release as PLANNED/IN PROGRESS** — flag stale version targets
Report any issues. If any pre-flight check fails, report which checks need attention and STOP.
### Step 3: Confirm Version Bump
Read current version from `FailSafe/extension/package.json`.
Ask the user:
> Current version is **vX.Y.Z**. What bump level? (patch / minor / major)
Wait for response before proceeding.
### Step 4: Apply Version Bump
Execute:
```bash
node scripts/release-gate.cjs --bump <level>
```
Report: `vX.Y.Z -> vA.B.C (<level> bump)`
### Step 5: Author Release Metadata
Invoke `/ql-document` in RELEASE_METADATA mode with the target version:
1. Read recent META_LEDGER entries (from last DELIVER or SUBSTANTIATE to current)
2. Read SYSTEM_STATE.md for implementation summary
3. Author the 3 required files:
- `FailSafe/extension/CHANGELOG.md``## [A.B.C] - YYYY-MM-DD`
- `FailSafe/extension/README.md` — Current Release + What's New
- Root `CHANGELOG.md``## [A.B.C]`
4. Present authored content to user for review before writing
**Confirmation gate** — Show authored content. User approves or edits before files are written.
### Step 6: Documentation Gate (HARD STOP)
**INTERDICTION**: Documentation versioning MUST be verified complete before any commit or tag. This gate cannot be bypassed.
Execute `release-gate.cjs --preflight`:
```bash
node scripts/release-gate.cjs --preflight
```
**INTERDICTION**: If ANY check shows [FAIL]:
```
ABORT
Report: "Documentation versioning incomplete. The following markers must be resolved:
[list each [FAIL] check with its message]
Required files for vA.B.C:
- FailSafe/extension/CHANGELOG.md → ## [A.B.C]
- CHANGELOG.md (root) → ## [A.B.C]
- FailSafe/extension/README.md → Current Release: vA.B.C
- README.md (root) → Current Release: vA.B.C + Socket badge
- FailSafe/extension/docs/COMPONENT_HELP.md → vA.B.C
- FailSafe/extension/docs/PROCESS_GUIDE.md → vA.B.C
- docs/BACKLOG.md version summary → vA.B.C row
Return to Step 5 and complete all missing documentation before proceeding."
```
Only when all checks show [PASS] may you proceed to Step 7.
### Step 7: Stage and Commit
**Confirmation gate** — Show the user the diff:
```bash
git diff --stat
```
Ask: "Stage and commit these changes as `[RELEASE] vA.B.C`? (y/n)"
If confirmed:
```bash
git add -f FailSafe/extension/package.json FailSafe/extension/CHANGELOG.md FailSafe/extension/README.md FailSafe/extension/docs/COMPONENT_HELP.md FailSafe/extension/docs/PROCESS_GUIDE.md CHANGELOG.md README.md docs/BACKLOG.md
git commit -m "[RELEASE] vA.B.C"
```
Note: `-f` is required because `FailSafe/extension/docs/` is in `.gitignore` but tracked.
### Step 8: Create Tag
Execute:
```bash
node scripts/release-gate.cjs --tag
```
This runs preflight internally and creates an annotated git tag.
### Step 9: Confirm Push
**Confirmation gate** — Present:
> Tag **vA.B.C** created locally. Push to origin to trigger the release pipeline?
>
> Remote: origin
> Branch: current branch
> Tag: vA.B.C
>
> Proceed? (y/n)
If confirmed:
```bash
git push && git push --tags
```
### Step 10: Record Ledger
Add META_LEDGER entry:
```markdown
### Entry #[N]: DELIVER — vA.B.C
**Timestamp**: [ISO 8601]
**Phase**: DELIVER
**Author**: Governor
**Version**: A.B.C
**Tag**: vA.B.C
**Commit**: [short hash]
**Decision**: Release vA.B.C delivered. Tag pushed to trigger release pipeline.
```
Calculate and record content hash and chain hash per standard Merkle chain protocol.
## Confirmation Gates
Two irreversible actions require explicit user confirmation:
1. **Before commit** — Shows diff summary
2. **Before push** — Shows tag + remote target
## Constraints
- **NEVER** push without user confirmation
- **NEVER** write metadata without user review of authored content
- **NEVER** release without a preceding SUBSTANTIATE seal
- **NEVER** skip the pre-flight validation
- **NEVER** proceed past Step 6 if preflight has ANY [FAIL] — Step 6 is a hard ABORT gate
- **NEVER** commit `[RELEASE] vX.Y.Z` without confirmed preflight PASS (the commit-msg hook enforces this at the git layer)
- **NEVER** release from a feature branch — must be on `main`
- **NEVER** tag without pulling latest `main` first
- **ALWAYS** use `/ql-document` for release metadata authoring
- **ALWAYS** run pre-flight twice (before and after metadata authoring)
- **ALWAYS** use `[RELEASE] vX.Y.Z` commit message format
- **ALWAYS** record the delivery in META_LEDGER
- **ALWAYS** update version markers in `docs/COMPONENT_HELP.md` and `docs/PROCESS_GUIDE.md`
- **ALWAYS** update `README.md` (root) Current Release marker and Socket badge version
- **ALWAYS** update `docs/BACKLOG.md` version summary table: mark previous version RELEASED, add new version row
- **ALWAYS** use `git add -f` for gitignored-but-tracked paths (e.g., `FailSafe/extension/docs/`)
+310
View File
@@ -0,0 +1,310 @@
---
name: ql-substantiate
description: >
Session Seal
user-invocable: true
allowed-tools: Read, Glob, Grep, Edit, Write, Bash
---
---
name: ql-substantiate
description: S.H.I.E.L.D. Substantiation and Session Seal that verifies implementation against blueprint and cryptographically seals the session. Use when: (1) Implementation is complete, (2) Ready to verify Reality matches Promise, (3) Need to seal session with Merkle hash, or (4) Preparing to hand off completed work.
---
# /ql-substantiate - Session Seal
<skill>
<trigger>/ql-substantiate</trigger>
<phase>SUBSTANTIATE</phase>
<persona>Judge</persona>
<output>Updated META_LEDGER.md with final seal, SYSTEM_STATE.md snapshot</output>
</skill>
## Purpose
The final phase of the S.H.I.E.L.D. lifecycle. Verify that implementation matches the encoded blueprint (Reality = Promise), then cryptographically seal the session.
## Execution Protocol
### Step 1: Identity Activation
You are now operating as **The QoreLogic Judge** in substantiation mode.
Your role is to prove, not to improve. Verify what was built matches what was promised.
### Step 2: State Verification
```
Read: docs/META_LEDGER.md
Read: docs/ARCHITECTURE_PLAN.md
Read: .failsafe/governance/AUDIT_REPORT.md
```
**INTERDICTION**: If no PASS verdict exists:
```
ABORT
Report: "Cannot substantiate without PASS verdict. Run /ql-audit first."
```
**INTERDICTION**: If no implementation exists:
```
ABORT
Report: "No implementation found. Run /ql-implement first."
```
### Step 2.5: Version Validation (MANDATORY)
**Verify version consistency** between plan and current state:
```bash
git tag --sort=-v:refname | head -1
```
```
Read: Plan file (docs/Planning/plan-*.md or docs/ARCHITECTURE_PLAN.md)
Extract: Target Version from plan header
```
**INTERDICTION**: If Target Version ≤ Current Tag:
```
ABORT
Report: "Version mismatch: Target v[X.Y.Z] already shipped (current tag: v[A.B.C]).
Bump version in plan before substantiating."
```
**INTERDICTION**: If SYSTEM_STATE.md or META_LEDGER.md reference wrong version:
```
PAUSE
Report: "Version drift detected in governance files.
Expected: v[Target]
Found: v[Wrong]
Fix version references before sealing."
```
**Log validation**:
```
"Version validated: Current tag v[A.B.C] → Target v[X.Y.Z] (change type: [hotfix|feature|breaking])"
```
### Step 3: Reality Audit
Compare implementation against blueprint:
```
Read: All files in src/
Compare: Against docs/ARCHITECTURE_PLAN.md file tree
```
Template: `.claude/commands/references/ql-substantiate-templates.md`.
**Findings**:
- **MISSING**: Planned but not created -> FAIL
- **UNPLANNED**: Created but not in blueprint -> WARNING (document in ledger)
- **EXISTS**: Matches -> PASS
### Step 3.5: Blocker Verification
```
Read: docs/BACKLOG.md
```
Check for open Security Blockers:
```
IF any unchecked Security Blockers exist:
WARNING: "Open security blockers detected. Consider addressing before seal."
List: [unchecked S# items]
```
Check for open Development Blockers related to current implementation:
```
IF related Dev Blockers exist:
WARNING: "Implementation may have unresolved blockers."
List: [related D# items]
```
### Step 4: Functional Verification
#### Test Audit
```
Glob: tests/**/*.test.{ts,tsx,js}
Read: Test files
```
Template: `.claude/commands/references/ql-substantiate-templates.md`.
#### Visual Silence Verification (if frontend)
```
Grep: "color:" in src/**/*.{css,tsx}
Grep: "background:" in src/**/*.{css,tsx}
```
Check for violations:
Template: `.claude/commands/references/ql-substantiate-templates.md`.
#### Console.log Artifacts
```
Grep: "console.log" in src/**/*
```
Template: `.claude/commands/references/ql-substantiate-templates.md`.
### Step 4.5: Skill File Integrity Check
If any skill files (`.claude/commands/ql-*.md`) were modified during this session:
1. List modified skill files from git diff
2. For each modified skill:
- Verify it still has required sections: `<skill>` block, `## Execution Protocol`, `## Constraints`, `## Next Step`
- Verify the `## Next Step` section references valid successor skills
- Log in ledger: "Skill file [name] modified — structure verified"
If any skill is missing required sections after modification:
```
PAUSE
Report: "Skill [name] missing required section: [section]. Fix before sealing."
```
### Step 4.6: Skill Admission Evidence Check (B49)
> Deferred — `validate-skill-admission.ps1` not yet implemented. This step is a no-op until `tools/reliability/` scripts are created.
### Step 4.7: Gate-to-Skill Matrix Evidence Check (B50)
> Deferred — `validate-gate-skill-matrix.ps1` not yet implemented. This step is a no-op until `tools/reliability/` scripts are created.
### Step 4.8: Reliability Integrity Gate
> Deferred — `validate-reliability-run.ps1` not yet implemented. This step is a no-op until `tools/reliability/` scripts are created.
### Step 5: Section 4 Razor Final Check
Template: `.claude/commands/references/ql-substantiate-templates.md`.
### Step 6: Sync System State
Map the final physical tree:
```
Glob: src/**/*
Glob: tests/**/*
Glob: docs/**/*
```
Create/Update `docs/SYSTEM_STATE.md`:
Template: `.claude/commands/references/ql-substantiate-templates.md`.
### Step 7: Final Merkle Seal
Calculate session seal:
Reference implementation: `.claude/commands/scripts/calculate-session-seal.py`.
Update `docs/META_LEDGER.md`:
Template: `.claude/commands/references/ql-substantiate-templates.md`.
### Step 8: Cleanup Staging
Clear: .failsafe/governance/
Preserve only the final AUDIT_REPORT.md (or archive it).
### Step 9: Final Report
Template: `.claude/commands/references/ql-substantiate-templates.md`.
### Step 9.5: Final Commit & Push
**Stage All Artifacts**:
```bash
git add docs/CONCEPT.md
git add docs/ARCHITECTURE_PLAN.md
git add docs/META_LEDGER.md
git add docs/SYSTEM_STATE.md
git add docs/BACKLOG.md
git add src/
```
**Commit Session Seal**:
```bash
git commit -m "seal: [plan-slug] - Session substantiated
Merkle seal: [chain-hash]
Verdict: PASS
Files: [file-count]"
```
**Push to Remote**:
```bash
git push origin [current-branch]
```
REPORT: "Session committed and pushed to [current-branch]"
### Step 9.6: Merge Options
PROMPT user:
```
Session sealed. Ready to complete workflow.
Options:
1. Merge to main (if on feature branch)
git checkout main && git merge --no-ff [branch] -m "Merge [branch]: [summary]"
2. Create PR (if remote available)
gh pr create --title "[summary]" --body "[from META_LEDGER decision]"
3. Skip (stay on branch)
Select option [1/2/3]:
```
IF option 1 (Merge):
```bash
git checkout main
git merge --no-ff [branch] -m "Merge [branch]: [summary]"
```
IF option 2 (Create PR):
```bash
gh pr create --title "[summary]" --body "[from META_LEDGER decision]"
```
**Tag Prompt** (if version changed in SYSTEM_STATE.md):
```
Version changed: [old] -> [new]
Create tag v[new_version]?
Options:
1. Yes - git tag -a v[X.Y.Z] -m "Release [X.Y.Z]"
2. No - skip tagging
```
IF yes:
```bash
git tag -a v[X.Y.Z] -m "Release [X.Y.Z]: [summary]"
```
REPORT: "Session sealed. [Action taken: merged/PR created/branch only]"
## Failure Scenarios
### If Reality != Promise:
Template: `.claude/commands/references/ql-substantiate-templates.md`.
## Constraints
- **NEVER** seal a session with Reality != Promise
- **NEVER** skip any verification step
- **NEVER** seal with Section 4 violations present
- **NEVER** seal with version mismatch (Target ≤ Current Tag)
- **ALWAYS** validate version before sealing
- **ALWAYS** update SYSTEM_STATE.md before sealing
- **ALWAYS** calculate proper chain hash
- **ALWAYS** document any unplanned files in ledger
- **ALWAYS** verify chain integrity before sealing
+2
View File
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
@@ -0,0 +1,36 @@
---
description: "Use when reviewing battery protection thresholds, reconnect logic, topology validation, battery switching safety, I2C access discipline, or FreeRTOS concurrency around protection state."
name: "Battery Protection Review"
tools: [read, search]
argument-hint: "Portée cible (ex: firmware/src/BatteryParallelator.cpp, firmware/src/main.cpp)"
user-invocable: true
---
Tu es un agent de revue spécialisé dans la logique de protection batterie du BMU.
Ta mission est de trouver les risques de sûreté, de cohérence métier et de concurrence autour des décisions de commutation batterie, sans implémenter de correctif.
## Contraintes
- N'écris pas de code et ne modifie aucun fichier.
- Ne recommande jamais de relâcher un seuil, un délai de reconnexion ou une règle fail-safe.
- Traite comme prioritaires les incohérences entre config.h, BatteryParallelator, BatteryManager et main.cpp.
- Vérifie que les accès I2C restent sérialisés via I2CLockGuard lorsque la logique de protection dépend de lectures capteur.
## Approche
1. Scanner la portée fournie : ${input:Portée cible (ex: firmware/src/BatteryParallelator.cpp, firmware/src/main.cpp)}.
2. Reconstituer la chaîne de décision de protection : lecture capteur, validation, seuils, coupure, reconnexion, verrouillage.
3. Identifier les risques de seuil erroné, d'index hors borne, de topologie invalide, de concurrence FreeRTOS, ou de commutation non sûre.
4. Classer les findings par sévérité avec preuve vérifiable.
5. Proposer un plan de mitigation minimal et les tests de non-régression à ajouter.
## Format de sortie
1. Findings (Critique -> Faible)
2. Hypothèses / questions ouvertes
3. Mitigations prioritaires
4. Tests recommandés
## Références
- [AGENTS](../../AGENTS.md)
- [Firmware Safety Instructions](../instructions/firmware-safety.instructions.md)
- [CLAUDE](../../CLAUDE.md)
- [config](../../firmware/src/config.h)
- [BatteryParallelator](../../firmware/src/BatteryParallelator.h)
View File
+33
View File
@@ -0,0 +1,33 @@
---
description: "Use when reviewing BMU firmware safety, battery protection logic, I2C concurrency, FreeRTOS task robustness, and web control attack surface."
name: "BMU Safety Review"
tools: [read, search]
argument-hint: "Portée cible (ex: firmware/src/** ou fichiers précis)"
user-invocable: true
---
Tu es un spécialiste de revue sécurité/fiabilité firmware BMU (ESP32 + FreeRTOS).
Ta mission: produire une revue technique orientée risques concrets, sans implémenter de patch.
## Contraintes
- N'écris pas de code et ne modifie pas de fichier.
- Ne propose jamais de relâcher les seuils/protections de batterie.
- Traite en priorité les chemins de mutation batterie via WebServer et la sûreté des commutations.
- Vérifie que les accès I2C sont sérialisés (I2CLockGuard).
## Approche
1. Scanner la portée fournie: ${input:Portée cible (ex: firmware/src/** ou fichiers précis)}.
2. Identifier les risques de sécurité, concurrence, robustesse runtime, et cohérence des protections.
3. Hiérarchiser les findings avec preuve (fichier + localisation).
4. Donner un plan de mitigation minimal et des tests de non-régression.
## Format de sortie
1. Findings (Critique -> Faible)
2. Questions / hypothèses
3. Mitigations prioritaires
4. Tests recommandés (bornes, concurrence, fault injection, long-run)
## Références
- [AGENTS](../../AGENTS.md)
- [Firmware Safety Instructions](../instructions/firmware-safety.instructions.md)
- [CLAUDE](../../CLAUDE.md)
@@ -0,0 +1,33 @@
---
description: "Use when reviewing ESP-IDF display/touch changes (ILI9341/ILI934x + GT911), LVGL locking, UI non-blocking behavior, and UI/protection safety boundaries before merge."
name: "Display Safety Review"
tools: [read, search]
argument-hint: "Portée cible (ex: firmware-idf/components/bmu_display/** ou fichiers précis)"
user-invocable: true
---
Tu es un spécialiste de revue sécurité/fiabilité UI embarquée ESP-IDF (display + touch) pour BMU.
Ta mission: produire une revue orientée risques concrets avant merge, sans implémenter de patch.
## Contraintes
- N'écris pas de code et ne modifie pas de fichier.
- Ne recommande jamais de déplacer une logique de protection batterie vers la couche UI.
- Vérifie en priorité la discipline de lock LVGL et les chemins de callbacks/timers.
- Vérifie les frontières bus BSP (display/touch) vs bus BMU (I2C métier).
## Approche
1. Scanner la portée fournie: ${input:Portée cible (ex: firmware-idf/components/bmu_display/** ou fichiers précis)}.
2. Identifier les risques de concurrence, blocage runtime, régression UX tactile/wake-dim, et confusion de responsabilités UI/protection.
3. Prioriser les findings avec preuve (fichier + localisation).
4. Donner des mitigations minimales et des tests de non-régression.
## Format de sortie
1. Findings (Critique -> Faible)
2. Questions / hypothèses
3. Mitigations prioritaires
4. Tests recommandés (callbacks non bloquants, lock coverage, wake/dim, robustesse tactile)
## Références
- [AGENTS](../../AGENTS.md)
- [CLAUDE](../../CLAUDE.md)
- [ESP-IDF Display Safety Rules](../instructions/firmware-idf-display-safety.instructions.md)
+36
View File
@@ -0,0 +1,36 @@
---
description: "Use when running an AI QA gate focused only on tests, gates, and evidence before merge or release."
name: "QA Gate"
tools: [read, search]
argument-hint: "Portée QA (ex: firmware/test/**, scripts/check_memory_budget.sh, artefacts de build)"
user-invocable: true
---
Tu es un agent QA spécialisé gate de validation.
Mission:
- Vérifier uniquement la qualité des tests, des gates et des preuves.
## Interdictions
- Ne pas implémenter de code produit.
- Ne pas proposer d'architecture ou de refactor hors périmètre QA.
- Ne pas valider un item sans preuve traçable.
## Périmètre d'analyse
1. Tests: présence, couverture fonctionnelle minimale, cas limites, cas erreur.
2. Gates: build, lint, tests, budget mémoire/perf/sécurité selon le repo.
3. Evidence: logs, artefacts, résultats de commandes, fichiers de sortie.
## Critères de verdict
- PASS: preuves complètes et gates toutes vertes.
- FAIL: au moins un gate rouge ou preuve critique manquante.
- CONDITIONAL PASS: gates vertes mais dette documentaire/evidence mineure à corriger.
## Format de sortie
1. Verdict global: PASS | CONDITIONAL PASS | FAIL
2. Findings prioritaires (High, Medium, Low)
3. Evidence map (preuve -> fichier/commande)
4. Gaps restants
5. Checklist Go/No-Go finale
Portée à auditer: ${input:Portée QA (ex: firmware/test/**, scripts/check_memory_budget.sh, artefacts de build)}.
+11
View File
@@ -0,0 +1,11 @@
{
"hooks": {
"PreToolUse": [
{
"type": "command",
"command": "python3 .github/hooks/workflow_guard.py",
"timeout": 15
}
]
}
}
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
import json
import sys
from typing import Any
CONFIRM_TOKEN = "CONFIRM_WORKFLOW_CHANGE"
WORKFLOW_PATH = ".github/workflows/"
MUTATING_TOOLS = {
"apply_patch",
"create_file",
"edit_notebook_file",
"run_in_terminal",
"mcp_gitkraken_git_add_or_commit",
}
def _find_first_value(obj: Any, keys: set[str]) -> str:
if isinstance(obj, dict):
for k, v in obj.items():
if k in keys and isinstance(v, str):
return v
nested = _find_first_value(v, keys)
if nested:
return nested
elif isinstance(obj, list):
for item in obj:
nested = _find_first_value(item, keys)
if nested:
return nested
return ""
def _contains_mutation_hint(command: str) -> bool:
lowered = command.lower()
mutation_markers = [
"mv ", "cp ", "rm ", "sed ", "perl ", "tee ", "cat >", "> .github/workflows/",
"echo ", "python ", "touch ", "git add", "git commit"
]
return any(marker in lowered for marker in mutation_markers)
def main() -> int:
try:
payload = json.load(sys.stdin)
except Exception:
# If payload is unreadable, don't break the workflow.
print(json.dumps({"continue": True}))
return 0
payload_text = json.dumps(payload, ensure_ascii=False)
tool_name = _find_first_value(payload, {"toolName", "tool_name", "tool", "name"})
command = _find_first_value(payload, {"command", "input", "args", "parameters"})
targets_workflow = WORKFLOW_PATH in payload_text
has_confirmation = (
CONFIRM_TOKEN in payload_text
or "confirmation explicite" in payload_text.lower()
or "workflow confirmé" in payload_text.lower()
)
mutating_attempt = False
if tool_name in MUTATING_TOOLS:
mutating_attempt = True
if tool_name == "run_in_terminal" and not _contains_mutation_hint(command):
mutating_attempt = False
if targets_workflow and mutating_attempt and not has_confirmation:
out = {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "ask",
"permissionDecisionReason": (
"Modification de .github/workflows détectée. Confirmation explicite requise. "
"Ajoutez le token CONFIRM_WORKFLOW_CHANGE dans la demande pour autoriser."
),
}
}
print(json.dumps(out, ensure_ascii=False))
return 0
out = {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "Aucune modification workflow non confirmée détectée.",
}
}
print(json.dumps(out, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
import json
import sys
from typing import Any
CONFIRM_TOKEN = "CONFIRM_WORKFLOW_CHANGE"
WORKFLOW_PATH = ".github/workflows/"
MUTATING_TOOLS = {
"apply_patch",
"create_file",
"edit_notebook_file",
"run_in_terminal",
"mcp_gitkraken_git_add_or_commit",
}
def _find_first_value(obj: Any, keys: set[str]) -> str:
if isinstance(obj, dict):
for k, v in obj.items():
if k in keys and isinstance(v, str):
return v
nested = _find_first_value(v, keys)
if nested:
return nested
elif isinstance(obj, list):
for item in obj:
nested = _find_first_value(item, keys)
if nested:
return nested
return ""
def _contains_mutation_hint(command: str) -> bool:
lowered = command.lower()
mutation_markers = [
"mv ", "cp ", "rm ", "sed ", "perl ", "tee ", "cat >", "> .github/workflows/",
"echo ", "python ", "touch ", "git add", "git commit"
]
return any(marker in lowered for marker in mutation_markers)
def main() -> int:
try:
payload = json.load(sys.stdin)
except Exception:
# If payload is unreadable, don't break the workflow.
print(json.dumps({"continue": True}))
return 0
payload_text = json.dumps(payload, ensure_ascii=False)
tool_name = _find_first_value(payload, {"toolName", "tool_name", "tool", "name"})
command = _find_first_value(payload, {"command", "input", "args", "parameters"})
targets_workflow = WORKFLOW_PATH in payload_text
has_confirmation = (
CONFIRM_TOKEN in payload_text
or "confirmation explicite" in payload_text.lower()
or "workflow confirmé" in payload_text.lower()
)
mutating_attempt = False
if tool_name in MUTATING_TOOLS:
mutating_attempt = True
if tool_name == "run_in_terminal" and not _contains_mutation_hint(command):
mutating_attempt = False
if targets_workflow and mutating_attempt and not has_confirmation:
out = {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "ask",
"permissionDecisionReason": (
"Modification de .github/workflows détectée. Confirmation explicite requise. "
"Ajoutez le token CONFIRM_WORKFLOW_CHANGE dans la demande pour autoriser."
),
}
}
print(json.dumps(out, ensure_ascii=False))
return 0
out = {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "Aucune modification workflow non confirmée détectée.",
}
}
print(json.dumps(out, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,30 @@
---
description: "Use when editing ESP-IDF display/touch UI code (ILI9341/ILI934x + GT911) in firmware-idf/components/bmu_display. Enforces LVGL lock discipline, non-blocking UI, and strict separation from battery protection logic."
name: "ESP-IDF Display Safety Rules"
applyTo: "firmware-idf/components/bmu_display/**"
---
# ESP-IDF Display Safety Rules
- Keep UI initialization on BSP path (`bsp_display_start()` and related BSP helpers). Do not add alternate direct panel init in BMU display code.
- Keep touch active via BSP input-device wiring (`bsp_display_get_input_dev`) and preserve `LV_EVENT_PRESSING` wake/dim behavior.
- Keep LVGL calls protected with BSP lock discipline (`bsp_display_lock()` / `bsp_display_unlock()`).
- Keep refresh callbacks and periodic UI updates non-blocking. Do not introduce long waits, busy loops, or blocking network/I2C calls in display callbacks/timers.
- Treat UI as advisory only: never move battery protection or switching decisions into display handlers.
- Preserve bus ownership boundaries on BOX-3: internal display/touch bus remains BSP-owned; BMU custom I2C flows stay on BMU bus path.
- Keep panel compatibility in the existing ILI934x-class path; do not hardcode alternate display drivers in BMU component code.
- For UI state reads, avoid unsafe cross-task mutation of shared battery state.
## Validation Checklist
- Build passes: `cd firmware-idf && idf.py build`
- No direct battery switch mutation from UI callbacks
- No lockless LVGL write paths
- No new long blocking operations in display update path
## References
- [AGENTS](../../AGENTS.md)
- [CLAUDE](../../CLAUDE.md)
- [ESP-IDF migration design](../../docs/superpowers/specs/2026-03-30-esp-idf-migration-design.md)
- [Display dashboard spec](../../docs/superpowers/specs/2026-03-30-phase6-display-dashboard.md)
- [Display enhancement spec](../../docs/superpowers/specs/2026-03-31-phase8-display-enhanced.md)
@@ -0,0 +1,20 @@
---
description: "Use when modifying BMU firmware safety logic, battery switching, FreeRTOS tasks, INA/TCA I2C access, or WebServer battery control endpoints. Enforces fail-safe rules and safety checks."
name: "Firmware Safety Rules"
applyTo: ["firmware/src/**/*.cpp", "firmware/src/**/*.h"]
---
# Firmware Safety Rules
- Keep protection behavior fail-safe by default: never weaken voltage/current thresholds, reconnect delays, or topology guards.
- Do not bypass INA/TCA topology validation in firmware/src/main.cpp.
- Any I2C access (Wire, INA/TCA operations) must use I2CLockGuard from firmware/src/I2CMutex.h.
- Validate battery/sensor indexes before array or driver access (isValidIndex/bounds checks).
- Preserve existing NAN/early-return fault semantics for sensor and bus failures.
- Keep periodic FreeRTOS tasks non-blocking; avoid long blocking calls inside task loops.
- For WebServer mutation routes, require explicit safety review and avoid unauthenticated ON/OFF control paths.
- For Influx/cloud code, do not use insecure TLS mode in production.
- Prefer DebugLogger categories over ad-hoc Serial.print for diagnostics.
- If safety behavior changes, include test updates for bounds, fault injection, and regression of protection transitions.
See: AGENTS.md, CLAUDE.md, README.md.
@@ -0,0 +1,18 @@
---
description: "Use when editing ML battery health scripts, feature extraction, training, quantization, or SOH/RUL evaluation artifacts in scripts/ml, docs/ML_BATTERY_HEALTH_SPEC.md, and models."
name: "ML Pipeline Governance"
applyTo: ["scripts/ml/**/*.py", "docs/ML_BATTERY_HEALTH_SPEC.md", "models/**"]
---
# ML Pipeline Governance
- Keep ML advisory: model outputs must assist operators, never replace hard safety guards in firmware.
- Prefer compact edge models with predictable runtime and memory (INT8 quantization for MCU deployment paths).
- Preserve reproducibility: version datasets, features, training config, and model artifact names.
- Track both in-domain and out-of-domain metrics; do not report a single global score without split context.
- Include drift checks and calibration/confidence reporting when proposing SOH/RUL claims.
- Clearly separate high-confidence results (validated on project data) from exploratory results (literature-only).
- Avoid embedding secrets or credentials in scripts/config.
- When updating docs/ML_BATTERY_HEALTH_SPEC.md, link existing repo docs rather than duplicating architecture details.
See: docs/ML_BATTERY_HEALTH_SPEC.md, AGENTS.md, CLAUDE.md.
@@ -0,0 +1,24 @@
---
description: "Use when implementing roadmap plans, daily TODO lists, or execution tracking in plan/** and docs/plans/**. Enforce execution-first behavior, status/evidence synchronization, and completion discipline."
name: "Plan & TODO Implementation Rules"
applyTo: ["plan/**/*.md", "docs/plans/**/*.md", "**/*todo*.md"]
---
# Plan & TODO Implementation Rules
- If the user asks to implement, start execution immediately on the highest-priority actionable task.
- Do not stop at planning when code or file changes are expected.
- Keep TODO status synchronized with real work: not-started, in-progress, blocked, completed.
- For each completed TODO, record evidence (test/build command, artifact, or file diff).
- If a task is blocked, document blocker + next concrete action in the same update.
- Update plan checkboxes or status lines when implementation state changes.
- Prefer small, verifiable increments over large unverified batches.
- Run relevant validations before closing (tests, build, budget/security gates when available).
- Do not mark work complete while open blockers remain.
- Before task completion, provide a short summary of what changed and why.
- Never claim success without verifiable outputs (passing command results or produced artifacts).
## Output Expectations
- Execution updates should include: changed files, validation run, and remaining work.
- Final update should include: implemented items, evidence, and any residual risk.
@@ -0,0 +1,18 @@
---
description: "Use when writing or modifying Python tests in firmware/test/*.py or firmware/test/**. Enforce deterministic pytest style, clear evidence, and CI-friendly assertions."
name: "Python Test Rules"
applyTo: ["firmware/test/**/*.py", "**/firmware/test/**/*.py"]
---
# Python Test Rules
- Framework: utiliser pytest.
- Nommage: fichiers test_*.py, fonctions test_*.
- Structure: Arrange / Act / Assert, un scénario principal par test.
- Déterminisme: pas d'accès réseau, pas de dépendance horloge non contrôlée, pas d'aléatoire sans seed.
- I/O: utiliser tmp_path et fixtures, ne pas écrire hors répertoire temporaire.
- Assertions: messages explicites sur les écarts attendus.
- Paramétrage: préférer @pytest.mark.parametrize pour les variations d'entrée.
- Evidence: chaque test doit valider un comportement observable et vérifiable.
- Gates: ajouter au moins un cas nominal, un cas limite, un cas erreur.
- Performance CI: éviter les tests lents; isoler les tests lourds avec un marqueur explicite.
@@ -0,0 +1,25 @@
---
description: "Use when modifying BMU web routes, WebSocket handlers, battery switch HTTP endpoints, route validation, auth token checks, or mutation rate limiting. Covers WebServerHandler, WebRouteSecurity, WebMutationRateLimit, and BatteryRouteValidation."
name: "WebServer Safety Rules"
applyTo: ["firmware/src/WebServerHandler.*", "firmware/src/WebRouteSecurity.*", "firmware/src/WebMutationRateLimit.*", "firmware/src/BatteryRouteValidation.*"]
---
# WebServer Safety Rules
- Treat every battery switch route and WebSocket mutation path as safety-sensitive.
- Do not add unauthenticated battery ON/OFF paths; keep token checks centralized through WebRouteSecurity.
- Do not bypass or weaken mutation throttling; reuse WebMutationRateLimit instead of rolling a second rate limiter.
- Keep request parsing and battery index validation centralized in BatteryRouteValidation.
- Reject malformed, out-of-range, or missing inputs explicitly before touching battery state.
- If a WebSocket path can mutate state, enforce the same auth, validation, and rate-limit guarantees as HTTP routes.
- Avoid duplicating security checks across handlers; refactor toward shared helpers when behavior changes.
- Preserve fail-safe behavior on validation/auth failure: deny the request, log through existing logging paths, and do not partially apply mutations.
- Add or update sim-host tests for auth, rate limiting, malformed indexes, and unauthorized mutation attempts when changing these flows.
## References
- [AGENTS](../../AGENTS.md)
- [Firmware Safety Instructions](./firmware-safety.instructions.md)
- [WebServerHandler](../../firmware/src/WebServerHandler.h)
- [WebRouteSecurity](../../firmware/src/WebRouteSecurity.h)
- [WebMutationRateLimit](../../firmware/src/WebMutationRateLimit.h)
- [BatteryRouteValidation](../../firmware/src/BatteryRouteValidation.h)
View File
+27
View File
@@ -0,0 +1,27 @@
---
description: "Lancer un audit sécurité/fiabilité BMU sur firmware ESP32, FreeRTOS, WebServer, Influx et I2C avec findings priorisés."
name: "Audit BMU Safety"
argument-hint: "Portée de l'audit (ex: firmware/src/WebServerHandler.cpp, firmware/src/main.cpp)"
agent: "agent"
---
Réalise un audit ciblé BMU sur la portée suivante: ${input:Portée de l'audit (fichiers/dossiers ou 'firmware/src/**')}.
Objectif: identifier les risques de sécurité, fiabilité et régression fonctionnelle dans un firmware batterie parallèle ESP32.
Contraintes audit:
- Prioriser les findings par sévérité: Critique, Haute, Moyenne, Faible.
- Inclure des références de fichiers précises et vérifiables.
- Se concentrer sur: routes web mutantes, validation des index, I2C mutex, tâches FreeRTOS non bloquantes, cohérence des seuils de protection, mode TLS cloud.
- Ne pas proposer de weakening des protections batterie.
Format de sortie attendu:
1. Findings ordonnés par sévérité (avec impact + preuve).
2. Hypothèses / questions ouvertes.
3. Plan de correction minimal par ordre de priorité.
4. Tests à ajouter (bornes, concurrence, fault injection, soak test).
Contexte utile:
- [AGENTS](../../AGENTS.md)
- [Firmware Safety Instructions](../instructions/firmware-safety.instructions.md)
- [ML Pipeline Instructions](../instructions/ml-pipeline.instructions.md)
@@ -0,0 +1,37 @@
---
description: "Créer un plan d'implémentation actionnable puis lancer immédiatement l'implémentation avec validations et preuves."
name: "Create Implementation Plan + Lancer Implementation"
argument-hint: "Portée et objectif (ex: plan/refactor-safety-core-web-remote-1.md + TASK-010..014)"
agent: "agent"
---
Tu vas exécuter un workflow en 2 étapes sur: ${input:Portée et objectif (ex: plan/refactor-safety-core-web-remote-1.md + TASK-010..014)}.
## Étape 1 — Plan d'implémentation exécutable
- Produire un mini-plan orienté exécution (pas de brainstorming long).
- Identifier les TODO actionnables immédiatement.
- Définir pour chaque item: action, fichier cible, validation, preuve attendue.
- Marquer les dépendances et bloqueurs.
## Étape 2 — Lancer l'implémentation maintenant
- Implémenter tout de suite le premier lot prioritaire.
- Mettre à jour les statuts TODO/plan au fur et à mesure.
- Exécuter les validations pertinentes (build/tests/gates).
- Capturer les preuves (commande, résultat, artefact/fichier).
## Format de sortie attendu
1. Plan court (3 à 7 items max)
2. Exécution réalisée (fichiers modifiés + pourquoi)
3. Validations exécutées et résultats
4. Preuves collectées
5. Reste à faire priorisé
## Règles
- Si l'utilisateur dit "start implementation" ou "lancer l'implémentation", ne pas rester en mode plan-only.
- Ne pas déclarer terminé tant qu'il reste des bloqueurs critiques non traités.
- Ne pas inventer de preuves.
- Préférer des incréments petits et vérifiables.
## Références
- [Prompt audit quotidien](./plan-audit-quotidien.prompt.md)
- [Instruction Plan TODO](../instructions/plan-todo-implementation.instructions.md)
@@ -0,0 +1,36 @@
---
description: "Normaliser les TODO journaliers dans docs/plans avec statut, priorité, preuves et prochaines actions."
name: "Plan Audit Quotidien"
argument-hint: "Chemin du fichier plan (ex: docs/plans/2026-03-28.md)"
agent: "agent"
---
Analyse et normalise le plan journalier situé ici: ${input:Chemin du fichier plan (ex: docs/plans/2026-03-28.md)}.
Objectif:
- Standardiser tous les TODO pour une revue quotidienne rapide et actionnable.
Règles de normalisation:
- Créer un identifiant stable par item: TODO-001, TODO-002, etc.
- Uniformiser les statuts: not-started, in-progress, blocked, completed.
- Ajouter une priorité: P0, P1, P2, P3.
- Ajouter une colonne Evidence avec preuve vérifiable (fichier, commande, sortie, artefact).
- Ajouter une colonne Next Action avec une action concrète, unique et immédiatement exécutable.
- Dédupliquer les TODO équivalents.
- Signaler toute ambiguïté dans une section Hypothèses.
Format de sortie attendu:
1. Résumé journalier (5 lignes max)
2. Tableau TODO normalisé
3. Blocages et dépendances
4. Check de cohérence (manques de preuve, statuts incohérents, TODO sans prochaine action)
5. Proposition de patch du fichier cible
Contraintes:
- Ne pas inventer de preuves.
- Si une information manque, marquer explicitement UNKNOWN.
- Préserver le sens métier original.
Références utiles:
- [Plan principal](../../plan/refactor-safety-core-web-remote-1.md)
- [Workflow firmware](../instructions/firmware-workflow.instructions.md)
@@ -0,0 +1,41 @@
---
description: "Gate pre-merge sécurité firmware: exécute tests sim-host, build ciblé, budget mémoire et audit rapide des routes mutables."
name: "Pre-Merge Safety Gate"
argument-hint: "Portée optionnelle (ex: firmware/src/**, firmware-idf/**)"
agent: "agent"
model: "GPT-5 (copilot)"
---
Exécute une gate pre-merge sécurité sur la portée: ${input:Portée optionnelle (ex: firmware/src/**, firmware-idf/**)}.
Objectif:
- empêcher une régression de sécurité/sûreté avant PR.
Routine minimale à lancer:
1. Tests hôte: pio test -e sim-host.
2. Build firmware cible: pio run -e kxkm-s3-16MB.
3. Budget mémoire: scripts/check_memory_budget.sh --env kxkm-s3-16MB --ram-max 75 --flash-max 85.
4. Audit routes mutables: vérifier que les endpoints de mutation batterie appliquent auth token, rate-limit et validation dindex.
Checklist danalyse routes mutables:
- Vérifier lenregistrement des routes de mutation (switch_on/switch_off, HTTP et WebSocket si mutation).
- Vérifier lusage de WebRouteSecurity::isMutationTokenAuthorized.
- Vérifier lusage de WebMutationRateLimit::mutationRateLimitExceeded.
- Vérifier lusage de BatteryRouteValidation pour index et préconditions tension.
Format de sortie attendu:
1. Verdict global: PASS | CONDITIONAL PASS | FAIL
2. Résultat des commandes (succès/échec + points saillants)
3. Findings sécurité/sûreté (Critique -> Faible)
4. Risques résiduels
5. Go/No-Go merge
Contraintes:
- Ne pas modifier les seuils de protection ni relâcher les contrôles fail-safe.
- Sappuyer sur les règles de AGENTS et les instructions sécurité firmware/web.
Références:
- [AGENTS](../../AGENTS.md)
- [Firmware Safety Instructions](../instructions/firmware-safety.instructions.md)
- [WebServer Safety Instructions](../instructions/webserver-safety.instructions.md)
- [CI README](../../scripts/ci/README.md)
@@ -0,0 +1,31 @@
---
description: "Pré-vol avant modification sensible du BMU: lire les fichiers critiques, rappeler les garde-fous safety et proposer un plan court avant implémentation."
name: "Preflight BMU Change"
argument-hint: "Portée du changement (ex: firmware/src/WebServerHandler.cpp ou firmware/src/**)"
agent: "agent"
model: "GPT-5 (copilot)"
---
Réalise un pré-vol de modification sur la portée suivante : ${input:Portée du changement (ex: firmware/src/WebServerHandler.cpp ou firmware/src/**)}.
Objectif : préparer une intervention sûre et minimale avant toute édition dans ce dépôt BMU ESP32.
Consignes :
- Lire d'abord [AGENTS](../../AGENTS.md) et les instructions ciblées pertinentes dans [instructions](../instructions/).
- Identifier les fichiers critiques, les dépendances proches et les tests existants à consulter avant changement.
- Rappeler les garde-fous non négociables : topologie INA/TCA, protections batterie, I2CLockGuard, routes web mutantes authentifiées, tâches non bloquantes.
- Repérer les risques de régression probables pour la portée fournie.
- Ne pas écrire de code dans cette étape.
Format de sortie attendu :
1. Périmètre utile à lire.
2. Garde-fous à préserver.
3. Risques principaux.
4. Plan court d'implémentation.
5. Tests et validations à exécuter avant et après modification.
Références de départ :
- [AGENTS](../../AGENTS.md)
- [CLAUDE](../../CLAUDE.md)
- [Firmware Safety Instructions](../instructions/firmware-safety.instructions.md)
- [README](../../README.md)
@@ -0,0 +1,37 @@
---
description: "Pré-vol avant modification ESP-IDF display/touch (ILI9341/ILI934x + GT911): checklist lock LVGL, callbacks non bloquantes, séparation UI/protection, et frontières bus BSP/BMU."
name: "Preflight Display Change"
argument-hint: "Portée du changement (ex: firmware-idf/components/bmu_display/**)"
agent: "agent"
model: "GPT-5 (copilot)"
---
Réalise un pré-vol de modification UI display/touch sur la portée suivante : ${input:Portée du changement (ex: firmware-idf/components/bmu_display/**)}.
Objectif : vérifier les garde-fous critiques avant toute édition de code ESP-IDF UI/UX.
Consignes :
- Lire d'abord [AGENTS](../../AGENTS.md), [CLAUDE](../../CLAUDE.md), et [ESP-IDF Display Safety Rules](../instructions/firmware-idf-display-safety.instructions.md).
- Identifier les fichiers critiques à lire avant implémentation (init BSP, callbacks LVGL, input touch, pont vers état batterie).
- Produire une checklist pré-modif explicite sur les points suivants :
- discipline de lock LVGL (`bsp_display_lock` / `bsp_display_unlock`)
- UI non bloquante (callbacks/timers courts, pas de wait long)
- séparation stricte UI vs protection batterie
- frontière bus BSP (display/touch) vs bus BMU (I2C capteurs/actionneurs)
- Identifier les régressions probables sur wake/dim et interaction tactile.
- Ne pas écrire de code dans cette étape.
Format de sortie attendu :
1. Périmètre utile à lire
2. Checklist pré-modif (go/no-go)
3. Risques principaux
4. Plan court d'implémentation
5. Tests et validations avant/après
Références :
- [AGENTS](../../AGENTS.md)
- [CLAUDE](../../CLAUDE.md)
- [ESP-IDF Display Safety Rules](../instructions/firmware-idf-display-safety.instructions.md)
- [ESP-IDF migration design](../../docs/superpowers/specs/2026-03-30-esp-idf-migration-design.md)
- [Display dashboard spec](../../docs/superpowers/specs/2026-03-30-phase6-display-dashboard.md)
- [Display enhancement spec](../../docs/superpowers/specs/2026-03-31-phase8-display-enhanced.md)
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/env bash
# collect-evidence.sh — Assemble les preuves de qualité BMU pour une PR ou release.
# Usage: .github/skills/release-evidence/scripts/collect-evidence.sh [version-label]
# Exemple: .github/skills/release-evidence/scripts/collect-evidence.sh v1.2.0
set -euo pipefail
VERSION_LABEL="${1:-snapshot}"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
COMMIT_SHA="$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')"
REPORT="release-evidence-${TIMESTAMP}.md"
# Résoudre pio (compatibilité macOS + CI)
if command -v pio &>/dev/null; then
PIO="pio"
elif [ -x "/Users/electron/.local/bin/pio" ]; then
PIO="/Users/electron/.local/bin/pio"
elif python3 -m platformio --version &>/dev/null 2>&1; then
PIO="python3 -m platformio"
else
echo "ERROR: pio introuvable. Installe PlatformIO CLI avant de continuer." >&2
exit 1
fi
RUN_OK=0
RUN_FAIL=1
# ── Helpers ─────────────────────────────────────────────────────────────────
run_gate() {
local name="$1"
shift
local cmd="$*"
local tmpout
tmpout="$(mktemp)"
echo "→ [${name}] ${cmd}"
if eval "${cmd}" >"${tmpout}" 2>&1; then
echo " ✅ PASS"
echo "${tmpout}"
return ${RUN_OK}
else
echo " ❌ FAIL"
echo "${tmpout}"
return ${RUN_FAIL}
fi
}
tail_lines() {
tail -n 20 "$1" 2>/dev/null || true
}
extract_memory() {
# Extrait RAM% et Flash% du rapport check_memory_budget
grep -E 'RAM:|Flash:' "$1" | head -4 || echo "(non disponible)"
}
# ── Exécution des gates ──────────────────────────────────────────────────────
GATE_SIM_RESULT="FAIL"
GATE_BUILD_RESULT="FAIL"
GATE_MEM_RESULT="FAIL"
TMP_SIM="$(mktemp)"
TMP_BUILD="$(mktemp)"
TMP_MEM="$(mktemp)"
echo "=== BMU Release Evidence: ${VERSION_LABEL} (${COMMIT_SHA}) ==="
echo ""
# Gate 1: sim-host tests
if ${PIO} test -e sim-host >"${TMP_SIM}" 2>&1; then
GATE_SIM_RESULT="PASS"
echo "✅ sim-host tests: PASS"
else
echo "❌ sim-host tests: FAIL"
fi
# Gate 2: build S3
if ${PIO} run -e kxkm-s3-16MB >"${TMP_BUILD}" 2>&1; then
GATE_BUILD_RESULT="PASS"
echo "✅ S3 build: PASS"
else
echo "❌ S3 build: FAIL"
fi
# Gate 3: memory budget
if bash scripts/check_memory_budget.sh --env kxkm-s3-16MB --ram-max 75 --flash-max 85 >"${TMP_MEM}" 2>&1; then
GATE_MEM_RESULT="PASS"
echo "✅ Memory budget: PASS"
else
echo "❌ Memory budget: FAIL"
fi
# ── Verdict ──────────────────────────────────────────────────────────────────
if [ "${GATE_SIM_RESULT}" = "PASS" ] && [ "${GATE_BUILD_RESULT}" = "PASS" ] && [ "${GATE_MEM_RESULT}" = "PASS" ]; then
VERDICT="✅ PASS — Prêt pour merge"
else
VERDICT="❌ FAIL — Gates rouges, merge bloqué"
fi
# ── Génération du rapport Markdown ───────────────────────────────────────────
cat >"${REPORT}" <<MDEOF
## Release Evidence — ${VERSION_LABEL} (commit \`${COMMIT_SHA}\`)
Date: $(date +%Y-%m-%d\ %H:%M:%S)
| Gate | Résultat | Commande |
|------|----------|----------|
| sim-host tests | ${GATE_SIM_RESULT} | \`pio test -e sim-host\` |
| S3 build | ${GATE_BUILD_RESULT} | \`pio run -e kxkm-s3-16MB\` |
| Memory budget | ${GATE_MEM_RESULT} | \`scripts/check_memory_budget.sh --env kxkm-s3-16MB --ram-max 75 --flash-max 85\` |
**Verdict: ${VERDICT}**
---
### sim-host tests (dernières lignes)
\`\`\`
$(tail_lines "${TMP_SIM}")
\`\`\`
### S3 build (dernières lignes)
\`\`\`
$(tail_lines "${TMP_BUILD}")
\`\`\`
### Memory budget
\`\`\`
$(extract_memory "${TMP_MEM}")
\`\`\`
MDEOF
echo ""
echo "Rapport généré: ${REPORT}"
echo "Verdict: ${VERDICT}"
# Nettoyage des fichiers temporaires
rm -f "${TMP_SIM}" "${TMP_BUILD}" "${TMP_MEM}"
# Code de sortie: 0 si tout PASS, 1 sinon
if [ "${VERDICT#*PASS}" != "${VERDICT}" ] && [ "${GATE_SIM_RESULT}" = "PASS" ] && [ "${GATE_BUILD_RESULT}" = "PASS" ] && [ "${GATE_MEM_RESULT}" = "PASS" ]; then
exit 0
else
exit 1
fi
+37
View File
@@ -0,0 +1,37 @@
name: CI
on:
push:
branches:
- main
- master
pull_request:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
firmware-native:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install PlatformIO
run: pip install platformio
- name: Run Unity tests (sim-host)
run: pio test -e sim-host
# Build ESP32 non inclus en CI : dépendances locales (K32-lib) + libs Arduino-ESP32 3.x
# Valider localement avec : pio run -e kxkm-s3-16MB
+77
View File
@@ -0,0 +1,77 @@
name: ESP-IDF CI
on:
push:
branches: [main, victron]
paths: ['firmware-idf/**', '.github/workflows/esp-idf-ci.yml']
pull_request:
paths: ['firmware-idf/**', '.github/workflows/esp-idf-ci.yml']
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
host-tests:
name: Host Tests (Unity)
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- name: Run host tests
run: |
cd firmware-idf/test
make all
build:
name: ESP-IDF Build (v5.4)
runs-on: ubuntu-latest
container: espressif/idf:v5.4
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Build firmware
shell: bash
run: |
# Le conteneur espressif/idf fournit idf.py mais l'entrypoint qui
# source l'env est court-circuité par les run-steps GitHub Actions :
# il faut sourcer export.sh nous-mêmes (sinon "idf.py: not found").
. "${IDF_PATH}/export.sh"
cd firmware-idf
idf.py set-target esp32s3
idf.py build
- name: Upload binary
uses: actions/upload-artifact@v4
with:
name: kxkm-bmu-firmware
path: |
firmware-idf/build/kxkm-bmu.bin
firmware-idf/build/bootloader/bootloader.bin
firmware-idf/build/partition_table/partition-table.bin
memory-budget:
name: Memory Budget Gate
needs: build
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: kxkm-bmu-firmware
path: firmware-idf/build/
- name: Check binary size
run: |
BIN="firmware-idf/build/kxkm-bmu.bin"
PARTITION_SIZE=$((0x200000))
BIN_SIZE=$(stat -c%s "$BIN")
PERCENT=$(( BIN_SIZE * 100 / PARTITION_SIZE ))
echo "Binary: $BIN_SIZE bytes ($PERCENT% of 2MB partition)"
if [ "$PERCENT" -gt 85 ]; then
echo "::error::Flash usage ${PERCENT}% exceeds 85% threshold"
exit 1
fi
echo "Flash: ${PERCENT}% (max 85%)"
+36
View File
@@ -0,0 +1,36 @@
name: Rust Protection Tests
on:
push:
branches: [main]
paths:
- 'firmware-rs/**'
- '.github/workflows/rust-tests.yml'
pull_request:
paths:
- 'firmware-rs/**'
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
name: Cargo test (host)
runs-on: ubuntu-latest
defaults:
run:
working-directory: firmware-rs
steps:
- uses: actions/checkout@v4
- name: Install Rust stable (for host tests)
uses: dtolnay/rust-toolchain@stable
- name: Run protection tests
run: |
cd crates/bmu-protection
cargo test --target x86_64-unknown-linux-gnu
+46
View File
@@ -0,0 +1,46 @@
name: qa-cicd-environments
on:
workflow_dispatch:
pull_request:
push:
branches:
- main
jobs:
qa-by-environment:
runs-on: ubuntu-latest
name: qa-${{ matrix.id }}
strategy:
fail-fast: false
matrix:
include:
- id: sim-host
- id: kxkm-s3-build
- id: kxkm-s3-memory-budget
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Cache PlatformIO
uses: actions/cache@v4
with:
path: |
~/.platformio/.cache
~/.platformio/packages
~/.platformio/platforms
key: pio-${{ runner.os }}-${{ hashFiles('platformio.ini') }}
restore-keys: |
pio-${{ runner.os }}-
- name: Install Tooling
run: scripts/ci/install_tooling.sh
- name: Run QA for target environment
run: scripts/ci/run_qa_env.sh ${{ matrix.id }}
+136
View File
@@ -0,0 +1,136 @@
.vscode/
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
.DS_Store
### KiCad ###
# For PCBs designed using KiCad: http://www.kicad-pcb.org/
# Format documentation: http://kicad-pcb.org/help/file-formats/
# Temporary files
*.000
*.bak
*.bck
*.kicad_pcb-bak
*~
_autosave-*
*.tmp
*-rescue.lib
*-save.pro
*-save.kicad_pcb
# Netlist files (exported from Eeschema)
*.net
# Autorouter files (exported from Pcbnew)
*.dsn
*.ses
# Exported BOM files
*.xml
*.csv
# Exception: PlatformIO partition tables
!partitions*.csv
### KiCad Patch ###
rescue-backup/
*.tsv
bom/
# Gerber export output
out/
### Linux ###
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
# End of https://www.gitignore.io/api/kicad,linux
.pio/
# KiCad backups et fichiers de production (non versionnés)
**/*-backups/
**/jlcpcb/production_files/
# Credentials locaux
src/credentials.h
# Données terrain et modèles ML (binaires lourds)
data/
!firmware-idf/data/
models/*.pt
models/*.onnx
.failsafe/
firmware-idf/managed_components/
firmware-idf/build/
firmware-idf/sdkconfig
firmware-idf/sdkconfig.old
firmware-idf/.cache/
external/
models/consolidated.parquet
models/features_adapted_v2.parquet
models/features_v2.parquet
kxkm-bmu-app/.gradle/
kxkm-bmu-app/build/
.venv-ml/
# Xcode local user state
**/xcuserdata/
**/*.xcuserstate
# Local accidental duplicates seen in this workspace
firmware/test/test_tca_ina 2/
iosApp/KXKMBmu 2.xcodeproj/
**/* [0-9]
**/* [0-9].*
**/~*.lck
scripts/llm/__pycache__/
services/soh-llm/__pycache__/
tests/llm/__pycache__/
firmware/src/credentials.h
kxkm-bmu-app/**/build/
.remember/
.*
+12
View File
@@ -0,0 +1,12 @@
{
"default": true,
"overrides": [
{
"files": [
"plan/*.md"
],
"MD060": false,
"MD047": false
}
]
}
@@ -0,0 +1,50 @@
<h2>UI actuelle — Quel est le problème principal ?</h2>
<p class="subtitle">L'écran BOX-3 fait 320×240 px (2.4"). Actuellement 6 onglets, font 14px uniquement.</p>
<div class="options" data-multiselect>
<div class="option" data-choice="a" onclick="toggleSelect(this)">
<div class="letter">A</div>
<div class="content">
<h3>Trop d'onglets</h3>
<p>6 onglets sur 2.4" — difficile à naviguer, tab bar trop petite</p>
</div>
</div>
<div class="option" data-choice="b" onclick="toggleSelect(this)">
<div class="letter">B</div>
<div class="content">
<h3>Infos critiques peu lisibles</h3>
<p>Tensions et courants trop petits, pas assez de contraste, couleurs ternes</p>
</div>
</div>
<div class="option" data-choice="c" onclick="toggleSelect(this)">
<div class="letter">C</div>
<div class="content">
<h3>Fonctionnalités manquantes</h3>
<p>Pas de climat AHT30, pas de status BLE/WiFi, pas de config runtime, courant toujours 0A</p>
</div>
</div>
<div class="option" data-choice="d" onclick="toggleSelect(this)">
<div class="letter">D</div>
<div class="content">
<h3>Look trop brut</h3>
<p>Design technique/développeur, pas assez pro pour un produit terrain KXKM</p>
</div>
</div>
<div class="option" data-choice="e" onclick="toggleSelect(this)">
<div class="letter">E</div>
<div class="content">
<h3>Tout ça à la fois</h3>
<p>Refonte complète : navigation, lisibilité, fonctionnalités, esthétique</p>
</div>
</div>
</div>
<div class="section">
<h3>Bugs critiques actuels</h3>
<ul>
<li>⚠️ Courant batterie toujours <strong>0.0A</strong> (INA237 pas intégré dans l'UI)</li>
<li>⚠️ Navigation detail cassée (<code>s_nav_ref</code> jamais initialisé)</li>
<li>⚠️ Pas de confirmation pour Switch ON/OFF (dangereux)</li>
<li>⚠️ Plage chart hardcodée (20-32V) — échoue hors spec</li>
</ul>
</div>
@@ -0,0 +1,29 @@
<h2>Navigation — combien d'écrans ?</h2>
<p class="subtitle">Actuellement 6 onglets. Avec le climat AHT30 et le status connexion, ça fait encore plus. Comment organiser ?</p>
<div class="options">
<div class="option" data-choice="a" onclick="toggleSelect(this)">
<div class="letter">A</div>
<div class="content">
<h3>3 onglets principaux + sous-menus</h3>
<p><strong>Batteries</strong> (grille + détail) | <strong>Système</strong> (WiFi, BLE, climat, solar, debug) | <strong>Config</strong> (seuils, device name)</p>
<p style="color:#888">Moins de tabs = plus gros boutons, navigation plus claire</p>
</div>
</div>
<div class="option" data-choice="b" onclick="toggleSelect(this)">
<div class="letter">B</div>
<div class="content">
<h3>4 onglets (regroupement intelligent)</h3>
<p><strong>⚡ Batt</strong> | <strong>📊 Sys</strong> (WiFi+BLE+climat+solar) | <strong>⚠ Alert</strong> | <strong>⚙ Config</strong></p>
<p style="color:#888">Bon équilibre — debug/SOH intégrés dans les écrans existants</p>
</div>
</div>
<div class="option" data-choice="c" onclick="toggleSelect(this)">
<div class="letter">C</div>
<div class="content">
<h3>Dashboard unique + swipe vertical</h3>
<p>Un seul écran scrollable verticalement avec sections : batteries en haut, puis système, puis alertes</p>
<p style="color:#888">Pas de tabs du tout — tout visible en scrollant. Plus moderne mais moins structuré</p>
</div>
</div>
</div>
@@ -0,0 +1,80 @@
<h2>Grille batteries — quel style ?</h2>
<p class="subtitle">320×210px de contenu (240 - 30px tab bar). Jusqu'à 16 batteries, typiquement 4-8.</p>
<div class="split">
<div class="mockup" data-choice="a" onclick="toggleSelect(this)" style="cursor:pointer">
<div class="mockup-header">A — Grille compacte (actuel amélioré)</div>
<div class="mockup-body" style="background:#1E1E1E; padding:8px; font-family:monospace; font-size:11px;">
<div style="color:#4FC3F7; font-size:13px; margin-bottom:6px;">⚡ KXKM-BMU-kryole</div>
<div style="display:grid; grid-template-columns:repeat(4,1fr); gap:4px;">
<div style="background:#2D2D2D; border-left:3px solid #00C853; padding:4px; border-radius:4px;">
<div style="color:#888; font-size:9px;">B1</div>
<div style="color:white; font-size:13px; font-weight:bold;">26.4V</div>
<div style="color:#aaa; font-size:10px;">1.2A</div>
</div>
<div style="background:#2D2D2D; border-left:3px solid #00C853; padding:4px; border-radius:4px;">
<div style="color:#888; font-size:9px;">B2</div>
<div style="color:white; font-size:13px; font-weight:bold;">26.3V</div>
<div style="color:#aaa; font-size:10px;">0.8A</div>
</div>
<div style="background:#2D2D2D; border-left:3px solid #FF1744; padding:4px; border-radius:4px;">
<div style="color:#888; font-size:9px;">B3</div>
<div style="color:#FF1744; font-size:13px; font-weight:bold;">0.0V</div>
<div style="color:#aaa; font-size:10px;">OFF</div>
</div>
<div style="background:#2D2D2D; border-left:3px solid #00C853; padding:4px; border-radius:4px;">
<div style="color:#888; font-size:9px;">B4</div>
<div style="color:white; font-size:13px; font-weight:bold;">26.5V</div>
<div style="color:#aaa; font-size:10px;">2.1A</div>
</div>
</div>
<div style="color:#666; font-size:10px; margin-top:6px; text-align:center;">4 batt · moy 26.4V · 4.1A total · 23°C 45%</div>
</div>
</div>
<div class="mockup" data-choice="b" onclick="toggleSelect(this)" style="cursor:pointer">
<div class="mockup-header">B — Liste avec barres de progression</div>
<div class="mockup-body" style="background:#1E1E1E; padding:8px; font-family:monospace; font-size:11px;">
<div style="color:#4FC3F7; font-size:13px; margin-bottom:6px;">⚡ KXKM-BMU-kryole</div>
<div style="display:flex; flex-direction:column; gap:4px;">
<div style="background:#2D2D2D; padding:4px 8px; border-radius:4px; display:flex; align-items:center; gap:8px;">
<span style="color:#00C853; font-size:10px;"></span>
<span style="color:white; width:20px;">B1</span>
<div style="flex:1; background:#333; height:8px; border-radius:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#00C853,#4CAF50); width:88%; height:100%; border-radius:4px;"></div>
</div>
<span style="color:white; font-size:12px; font-weight:bold; width:45px; text-align:right;">26.4V</span>
<span style="color:#aaa; font-size:10px; width:35px; text-align:right;">1.2A</span>
</div>
<div style="background:#2D2D2D; padding:4px 8px; border-radius:4px; display:flex; align-items:center; gap:8px;">
<span style="color:#00C853; font-size:10px;"></span>
<span style="color:white; width:20px;">B2</span>
<div style="flex:1; background:#333; height:8px; border-radius:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#00C853,#4CAF50); width:87%; height:100%; border-radius:4px;"></div>
</div>
<span style="color:white; font-size:12px; font-weight:bold; width:45px; text-align:right;">26.3V</span>
<span style="color:#aaa; font-size:10px; width:35px; text-align:right;">0.8A</span>
</div>
<div style="background:#2D2D2D; padding:4px 8px; border-radius:4px; display:flex; align-items:center; gap:8px;">
<span style="color:#FF1744; font-size:10px;"></span>
<span style="color:#888; width:20px;">B3</span>
<div style="flex:1; background:#333; height:8px; border-radius:4px;"></div>
<span style="color:#FF1744; font-size:12px; font-weight:bold; width:45px; text-align:right;">OFF</span>
<span style="color:#666; font-size:10px; width:35px; text-align:right;"></span>
</div>
<div style="background:#2D2D2D; padding:4px 8px; border-radius:4px; display:flex; align-items:center; gap:8px;">
<span style="color:#00C853; font-size:10px;"></span>
<span style="color:white; width:20px;">B4</span>
<div style="flex:1; background:#333; height:8px; border-radius:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#00C853,#4CAF50); width:88%; height:100%; border-radius:4px;"></div>
</div>
<span style="color:white; font-size:12px; font-weight:bold; width:45px; text-align:right;">26.5V</span>
<span style="color:#aaa; font-size:10px; width:35px; text-align:right;">2.1A</span>
</div>
</div>
<div style="color:#666; font-size:10px; margin-top:6px; text-align:center;">moy 26.4V · 4.1A total · 🌡23°C 💧45%</div>
</div>
</div>
</div>
<p class="subtitle" style="margin-top:16px;">La grille (A) montre plus de batteries d'un coup. La liste (B) est plus lisible avec les barres visuelles. Tap sur une batterie → écran détail dans les deux cas.</p>
@@ -0,0 +1,89 @@
<h2>Écran Système — quelles infos regrouper ?</h2>
<p class="subtitle">Cet onglet fusionne : WiFi, BLE, climat AHT30, solar VE.Direct, debug I2C. Quel layout ?</p>
<div class="mockup">
<div class="mockup-header">Proposition — Écran Sys avec sections pliables</div>
<div class="mockup-body" style="background:#1E1E1E; padding:8px; font-family:monospace; font-size:11px;">
<div style="color:#4FC3F7; font-size:13px; margin-bottom:8px;">📊 Système</div>
<!-- Connexion -->
<div style="background:#252525; border-radius:4px; padding:6px; margin-bottom:4px;">
<div style="display:flex; justify-content:space-between; align-items:center;">
<span style="color:#aaa; font-size:10px;">CONNEXION</span>
<div style="display:flex; gap:8px;">
<span style="color:#00C853; font-size:10px;">● BLE</span>
<span style="color:#00C853; font-size:10px;">● WiFi 192.168.0.250</span>
<span style="color:#FF9100; font-size:10px;">○ MQTT</span>
</div>
</div>
</div>
<!-- Climat -->
<div style="background:#252525; border-radius:4px; padding:6px; margin-bottom:4px;">
<div style="display:flex; justify-content:space-between;">
<span style="color:#aaa; font-size:10px;">CLIMAT</span>
<div style="display:flex; gap:12px;">
<span style="color:white;">🌡 <strong>23.5°C</strong></span>
<span style="color:white;">💧 <strong>45%</strong></span>
</div>
</div>
</div>
<!-- Solar -->
<div style="background:#252525; border-radius:4px; padding:6px; margin-bottom:4px;">
<div style="display:flex; justify-content:space-between; margin-bottom:2px;">
<span style="color:#aaa; font-size:10px;">SOLAIRE</span>
<span style="color:#FFD600; font-size:10px;">☀ Float</span>
</div>
<div style="display:flex; gap:12px; font-size:11px;">
<span style="color:white;">PV <strong>35.2V</strong></span>
<span style="color:white;"><strong>120W</strong></span>
<span style="color:white;">Bat <strong>26.8V</strong></span>
<span style="color:#aaa;">Jour <strong>450Wh</strong></span>
</div>
</div>
<!-- Firmware -->
<div style="background:#252525; border-radius:4px; padding:6px; margin-bottom:4px;">
<div style="display:flex; justify-content:space-between; margin-bottom:2px;">
<span style="color:#aaa; font-size:10px;">FIRMWARE</span>
<span style="color:#888; font-size:10px;">v0.5.0</span>
</div>
<div style="display:flex; gap:12px; font-size:10px; color:#888;">
<span>Heap 16.1MB</span>
<span>Up 2h34m</span>
<span>INA:4 TCA:1</span>
</div>
</div>
<!-- I2C Debug (compact) -->
<div style="background:#252525; border-radius:4px; padding:6px;">
<div style="display:flex; justify-content:space-between; margin-bottom:2px;">
<span style="color:#aaa; font-size:10px;">I2C BUS</span>
<span style="color:#888; font-size:10px;">5 devices · 0 err</span>
</div>
<div style="font-size:9px; color:#666; max-height:40px; overflow:hidden;">
20:15:42 AHT30 read OK<br>
20:15:41 INA237 scan OK<br>
20:15:40 TCA9535 init OK
</div>
</div>
</div>
</div>
<div class="options" style="margin-top:16px;">
<div class="option" data-choice="ok" onclick="toggleSelect(this)">
<div class="letter"></div>
<div class="content">
<h3>Ce layout me va</h3>
<p>Sections compactes, toutes les infos en un écran sans scroll</p>
</div>
</div>
<div class="option" data-choice="more" onclick="toggleSelect(this)">
<div class="letter">+</div>
<div class="content">
<h3>J'aimerais des modifications</h3>
<p>Dis-moi quoi changer dans le terminal</p>
</div>
</div>
</div>
@@ -0,0 +1,56 @@
<h2>Palette de couleurs — quel style ?</h2>
<p class="subtitle">L'écran est petit (2.4") et souvent en plein soleil sur les événements KXKM. Le contraste est critique.</p>
<div class="split">
<div class="mockup" data-choice="a" onclick="toggleSelect(this)" style="cursor:pointer">
<div class="mockup-header">A — Dark Pro (actuel amélioré)</div>
<div class="mockup-body" style="background:#1E1E1E; padding:12px; font-family:monospace;">
<div style="display:flex; gap:6px; margin-bottom:8px;">
<span style="background:#00C853; color:black; padding:2px 8px; border-radius:10px; font-size:10px;">OK</span>
<span style="background:#FF9100; color:black; padding:2px 8px; border-radius:10px; font-size:10px;">WARN</span>
<span style="background:#FF1744; color:white; padding:2px 8px; border-radius:10px; font-size:10px;">ERR</span>
<span style="background:#9E9E9E; color:white; padding:2px 8px; border-radius:10px; font-size:10px;">OFF</span>
</div>
<div style="display:flex; flex-direction:column; gap:3px;">
<div style="background:#2D2D2D; padding:4px 8px; border-radius:4px; display:flex; align-items:center; gap:8px;">
<span style="color:#00C853;"></span>
<span style="color:white; font-weight:bold;">26.4V</span>
<span style="color:#aaa;">1.2A</span>
</div>
<div style="background:#2D2D2D; padding:4px 8px; border-radius:4px; display:flex; align-items:center; gap:8px;">
<span style="color:#FF1744;"></span>
<span style="color:#FF1744; font-weight:bold;">OFF</span>
<span style="color:#666;"></span>
</div>
</div>
<div style="color:#4FC3F7; font-size:10px; margin-top:8px;">Fond sombre, texte blanc, accents vifs</div>
</div>
</div>
<div class="mockup" data-choice="b" onclick="toggleSelect(this)" style="cursor:pointer">
<div class="mockup-header">B — High Contrast (plein soleil)</div>
<div class="mockup-body" style="background:#000000; padding:12px; font-family:monospace;">
<div style="display:flex; gap:6px; margin-bottom:8px;">
<span style="background:#00FF66; color:black; padding:2px 8px; border-radius:10px; font-size:10px; font-weight:bold;">OK</span>
<span style="background:#FFAA00; color:black; padding:2px 8px; border-radius:10px; font-size:10px; font-weight:bold;">WARN</span>
<span style="background:#FF0044; color:white; padding:2px 8px; border-radius:10px; font-size:10px; font-weight:bold;">ERR</span>
<span style="background:#666666; color:white; padding:2px 8px; border-radius:10px; font-size:10px; font-weight:bold;">OFF</span>
</div>
<div style="display:flex; flex-direction:column; gap:3px;">
<div style="background:#111; border:1px solid #333; padding:4px 8px; border-radius:4px; display:flex; align-items:center; gap:8px;">
<span style="color:#00FF66; font-size:14px;"></span>
<span style="color:#FFFFFF; font-weight:bold; font-size:14px;">26.4V</span>
<span style="color:#CCCCCC; font-size:12px;">1.2A</span>
</div>
<div style="background:#1A0000; border:1px solid #440000; padding:4px 8px; border-radius:4px; display:flex; align-items:center; gap:8px;">
<span style="color:#FF0044; font-size:14px;"></span>
<span style="color:#FF4466; font-weight:bold; font-size:14px;">OFF</span>
<span style="color:#664444; font-size:12px;"></span>
</div>
</div>
<div style="color:#00AAFF; font-size:10px; margin-top:8px;">Noir pur, couleurs saturées, gros texte</div>
</div>
</div>
</div>
<p class="subtitle" style="margin-top:12px;">A = élégant en intérieur. B = lisible en plein soleil. Les deux sont dark mode.</p>
@@ -0,0 +1,3 @@
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
<p class="subtitle">Préparation du design final...</p>
</div>
@@ -0,0 +1,142 @@
<h2>Dashboard avec icônes — quel style ?</h2>
<p class="subtitle">Tu veux un dashboard type "home screen" avec des icônes au lieu de tabs ? Ou des icônes dans les tabs ?</p>
<div class="split">
<div class="mockup" data-choice="a" onclick="toggleSelect(this)" style="cursor:pointer">
<div class="mockup-header">A — Home Dashboard avec tuiles icônes</div>
<div class="mockup-body" style="background:#000; padding:8px; font-family:sans-serif; font-size:11px;">
<!-- Header -->
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
<span style="color:#00AAFF; font-weight:bold; font-size:13px;">KXKM-BMU-kryole</span>
<div style="display:flex; gap:4px;">
<span style="color:#00FF66; font-size:9px;">● BLE</span>
<span style="color:#00FF66; font-size:9px;">● WiFi</span>
</div>
</div>
<!-- Tuiles 2x3 -->
<div style="display:grid; grid-template-columns:repeat(3,1fr); gap:6px;">
<!-- Batteries -->
<div style="background:#111; border:1px solid #00FF66; border-radius:8px; padding:8px; text-align:center;">
<div style="font-size:28px;"></div>
<div style="color:white; font-weight:bold; font-size:14px;">4 / 4</div>
<div style="color:#00FF66; font-size:9px;">BATTERIES</div>
<div style="color:#aaa; font-size:9px;">moy 26.4V</div>
</div>
<!-- Climat -->
<div style="background:#111; border:1px solid #444; border-radius:8px; padding:8px; text-align:center;">
<div style="font-size:28px;">🌡</div>
<div style="color:white; font-weight:bold; font-size:14px;">23.5°C</div>
<div style="color:#888; font-size:9px;">CLIMAT</div>
<div style="color:#aaa; font-size:9px;">45% HR</div>
</div>
<!-- Solar -->
<div style="background:#111; border:1px solid #FFD600; border-radius:8px; padding:8px; text-align:center;">
<div style="font-size:28px;">☀️</div>
<div style="color:white; font-weight:bold; font-size:14px;">120W</div>
<div style="color:#FFD600; font-size:9px;">SOLAIRE</div>
<div style="color:#aaa; font-size:9px;">Float</div>
</div>
<!-- Courant total -->
<div style="background:#111; border:1px solid #444; border-radius:8px; padding:8px; text-align:center;">
<div style="font-size:28px;"></div>
<div style="color:white; font-weight:bold; font-size:14px;">4.1A</div>
<div style="color:#888; font-size:9px;">COURANT</div>
<div style="color:#aaa; font-size:9px;">total</div>
</div>
<!-- Alertes -->
<div style="background:#111; border:1px solid #FF0044; border-radius:8px; padding:8px; text-align:center;">
<div style="font-size:28px;">⚠️</div>
<div style="color:#FF0044; font-weight:bold; font-size:14px;">2</div>
<div style="color:#FF0044; font-size:9px;">ALERTES</div>
<div style="color:#aaa; font-size:9px;">actives</div>
</div>
<!-- Config -->
<div style="background:#111; border:1px solid #444; border-radius:8px; padding:8px; text-align:center;">
<div style="font-size:28px;">⚙️</div>
<div style="color:white; font-weight:bold; font-size:14px;">v0.5</div>
<div style="color:#888; font-size:9px;">CONFIG</div>
<div style="color:#aaa; font-size:9px;">2h34m up</div>
</div>
</div>
<div style="color:#444; font-size:9px; text-align:center; margin-top:6px;">Tap une tuile pour ouvrir le détail</div>
</div>
</div>
<div class="mockup" data-choice="b" onclick="toggleSelect(this)" style="cursor:pointer">
<div class="mockup-header">B — Dashboard compact + tabs icônes en bas</div>
<div class="mockup-body" style="background:#000; padding:8px; font-family:sans-serif; font-size:11px; display:flex; flex-direction:column; min-height:260px;">
<!-- Header stats -->
<div style="display:flex; gap:4px; margin-bottom:6px;">
<div style="flex:1; background:#111; border-radius:6px; padding:4px; text-align:center;">
<div style="color:#00FF66; font-size:18px; font-weight:bold;">4/4</div>
<div style="color:#666; font-size:8px;">BATT OK</div>
</div>
<div style="flex:1; background:#111; border-radius:6px; padding:4px; text-align:center;">
<div style="color:white; font-size:18px; font-weight:bold;">26.4V</div>
<div style="color:#666; font-size:8px;">MOY</div>
</div>
<div style="flex:1; background:#111; border-radius:6px; padding:4px; text-align:center;">
<div style="color:white; font-size:18px; font-weight:bold;">4.1A</div>
<div style="color:#666; font-size:8px;">TOTAL</div>
</div>
<div style="flex:1; background:#111; border-radius:6px; padding:4px; text-align:center;">
<div style="color:#FFAA00; font-size:18px; font-weight:bold;">23°C</div>
<div style="color:#666; font-size:8px;">TEMP</div>
</div>
</div>
<!-- Battery list -->
<div style="flex:1; display:flex; flex-direction:column; gap:2px; overflow:hidden;">
<div style="background:#111; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px;">B1</span>
<div style="flex:1; background:#222; height:6px; border-radius:3px;"><div style="background:#00FF66; width:88%; height:100%; border-radius:3px;"></div></div>
<span style="color:white; font-size:11px; font-weight:bold; width:40px; text-align:right;">26.4V</span>
<span style="color:#aaa; font-size:9px; width:30px; text-align:right;">1.2A</span>
</div>
<div style="background:#111; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px;">B2</span>
<div style="flex:1; background:#222; height:6px; border-radius:3px;"><div style="background:#00FF66; width:87%; height:100%; border-radius:3px;"></div></div>
<span style="color:white; font-size:11px; font-weight:bold; width:40px; text-align:right;">26.3V</span>
<span style="color:#aaa; font-size:9px; width:30px; text-align:right;">0.8A</span>
</div>
<div style="background:#0A0000; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px; border-left:3px solid #FF0044;">
<span style="color:#664444; width:18px; font-size:10px;">B3</span>
<div style="flex:1; background:#220000; height:6px; border-radius:3px;"></div>
<span style="color:#FF4466; font-size:11px; font-weight:bold; width:40px; text-align:right;">OFF</span>
<span style="color:#442222; font-size:9px; width:30px; text-align:right;"></span>
</div>
<div style="background:#111; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px;">B4</span>
<div style="flex:1; background:#222; height:6px; border-radius:3px;"><div style="background:#00FF66; width:88%; height:100%; border-radius:3px;"></div></div>
<span style="color:white; font-size:11px; font-weight:bold; width:40px; text-align:right;">26.5V</span>
<span style="color:#aaa; font-size:9px; width:30px; text-align:right;">2.1A</span>
</div>
</div>
<!-- Tab bar -->
<div style="display:flex; background:#0A0A0A; border-top:1px solid #222; margin:6px -8px -8px -8px; padding:4px 0;">
<div style="flex:1; text-align:center; color:#00FF66;">
<div style="font-size:16px;"></div>
<div style="font-size:7px;">BATT</div>
</div>
<div style="flex:1; text-align:center; color:#666;">
<div style="font-size:16px;">📊</div>
<div style="font-size:7px;">SYS</div>
</div>
<div style="flex:1; text-align:center; color:#FF0044; position:relative;">
<div style="font-size:16px;">⚠️</div>
<div style="font-size:7px;">ALERT</div>
<div style="position:absolute; top:-2px; right:20%; background:#FF0044; color:white; font-size:7px; width:12px; height:12px; border-radius:6px; display:flex; align-items:center; justify-content:center;">2</div>
</div>
<div style="flex:1; text-align:center; color:#666;">
<div style="font-size:16px;">⚙️</div>
<div style="font-size:7px;">CONFIG</div>
</div>
</div>
</div>
</div>
</div>
<p class="subtitle" style="margin-top:12px;">A = Home screen avec tuiles cliquables, chaque tuile ouvre un écran. B = Dashboard direct avec tabs icônes en bas et stats en haut.</p>
@@ -0,0 +1,138 @@
<h2>Dashboard B raffiné — top bar avec stats clés</h2>
<p class="subtitle">Top bar : Vmoy, Itotal, Ah In, Ah Out, Climat. Puis liste batteries. Tab bar icônes en bas.</p>
<div class="mockup">
<div class="mockup-header">Dashboard final — 320×240 High Contrast</div>
<div class="mockup-body" style="background:#000; padding:0; font-family:sans-serif; font-size:11px; display:flex; flex-direction:column; height:300px; overflow:hidden;">
<!-- TOP BAR - Stats clés -->
<div style="background:#0A0A0A; border-bottom:1px solid #222; padding:4px 6px;">
<!-- Row 1: device name + connexion -->
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:3px;">
<span style="color:#00AAFF; font-weight:bold; font-size:11px;">⚡ kryole</span>
<div style="display:flex; gap:4px;">
<span style="color:#00FF66; font-size:8px;">● BLE</span>
<span style="color:#00FF66; font-size:8px;">● WiFi</span>
<span style="color:#FF4444; font-size:8px;">○ MQTT</span>
</div>
</div>
<!-- Row 2: stats -->
<div style="display:flex; gap:2px;">
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:#00FF66; font-size:14px; font-weight:bold; line-height:1.1;">26.4V</div>
<div style="color:#555; font-size:7px;">V MOY</div>
</div>
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:white; font-size:14px; font-weight:bold; line-height:1.1;">4.1A</div>
<div style="color:#555; font-size:7px;">I TOTAL</div>
</div>
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:#4FC3F7; font-size:14px; font-weight:bold; line-height:1.1;">12.3</div>
<div style="color:#555; font-size:7px;">Ah IN</div>
</div>
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:#FF9100; font-size:14px; font-weight:bold; line-height:1.1;">8.2</div>
<div style="color:#555; font-size:7px;">Ah OUT</div>
</div>
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:#FFAA00; font-size:12px; font-weight:bold; line-height:1.3;">23°C</div>
<div style="color:#555; font-size:7px;">45% HR</div>
</div>
</div>
</div>
<!-- BATTERY LIST -->
<div style="flex:1; padding:4px 6px; display:flex; flex-direction:column; gap:2px; overflow-y:auto;">
<!-- B1 OK -->
<div style="background:#0A0A0A; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px; font-weight:bold;">B1</span>
<div style="flex:1; background:#1A1A1A; height:8px; border-radius:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#00CC44,#00FF66); width:88%; height:100%; border-radius:4px;"></div>
</div>
<span style="color:#FFFFFF; font-size:12px; font-weight:bold; width:44px; text-align:right;">26.4V</span>
<span style="color:#CCCCCC; font-size:10px; width:32px; text-align:right;">1.2A</span>
</div>
<!-- B2 OK -->
<div style="background:#0A0A0A; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px; font-weight:bold;">B2</span>
<div style="flex:1; background:#1A1A1A; height:8px; border-radius:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#00CC44,#00FF66); width:87%; height:100%; border-radius:4px;"></div>
</div>
<span style="color:#FFFFFF; font-size:12px; font-weight:bold; width:44px; text-align:right;">26.3V</span>
<span style="color:#CCCCCC; font-size:10px; width:32px; text-align:right;">0.8A</span>
</div>
<!-- B3 OFF -->
<div style="background:#0A0000; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #FF0044;">
<span style="color:#884444; width:18px; font-size:10px; font-weight:bold;">B3</span>
<div style="flex:1; background:#1A0000; height:8px; border-radius:4px;"></div>
<span style="color:#FF4466; font-size:12px; font-weight:bold; width:44px; text-align:right;">OFF</span>
<span style="color:#553333; font-size:10px; width:32px; text-align:right;"></span>
</div>
<!-- B4 OK -->
<div style="background:#0A0A0A; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px; font-weight:bold;">B4</span>
<div style="flex:1; background:#1A1A1A; height:8px; border-radius:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#00CC44,#00FF66); width:88%; height:100%; border-radius:4px;"></div>
</div>
<span style="color:#FFFFFF; font-size:12px; font-weight:bold; width:44px; text-align:right;">26.5V</span>
<span style="color:#CCCCCC; font-size:10px; width:32px; text-align:right;">2.1A</span>
</div>
<!-- B5 WARN -->
<div style="background:#0A0800; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #FFAA00;">
<span style="color:#AA8800; width:18px; font-size:10px; font-weight:bold;">B5</span>
<div style="flex:1; background:#1A1800; height:8px; border-radius:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#FF8800,#FFAA00); width:82%; height:100%; border-radius:4px;"></div>
</div>
<span style="color:#FFCC44; font-size:12px; font-weight:bold; width:44px; text-align:right;">24.8V</span>
<span style="color:#AA9944; font-size:10px; width:32px; text-align:right;">0.3A</span>
</div>
<!-- B6 OK -->
<div style="background:#0A0A0A; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px; font-weight:bold;">B6</span>
<div style="flex:1; background:#1A1A1A; height:8px; border-radius:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#00CC44,#00FF66); width:86%; height:100%; border-radius:4px;"></div>
</div>
<span style="color:#FFFFFF; font-size:12px; font-weight:bold; width:44px; text-align:right;">26.1V</span>
<span style="color:#CCCCCC; font-size:10px; width:32px; text-align:right;">1.5A</span>
</div>
</div>
<!-- TAB BAR -->
<div style="display:flex; background:#0A0A0A; border-top:1px solid #222; padding:4px 0; flex-shrink:0;">
<div style="flex:1; text-align:center; color:#00FF66;">
<div style="font-size:16px;"></div>
<div style="font-size:7px; font-weight:bold;">BATT</div>
</div>
<div style="flex:1; text-align:center; color:#666;">
<div style="font-size:16px;">📊</div>
<div style="font-size:7px;">SYS</div>
</div>
<div style="flex:1; text-align:center; color:#FF0044; position:relative;">
<div style="font-size:16px;">⚠️</div>
<div style="font-size:7px;">ALERT</div>
<div style="position:absolute; top:-2px; right:22%; background:#FF0044; color:white; font-size:7px; width:12px; height:12px; border-radius:6px; display:flex; align-items:center; justify-content:center; font-weight:bold;">2</div>
</div>
<div style="flex:1; text-align:center; color:#666;">
<div style="font-size:16px;">⚙️</div>
<div style="font-size:7px;">CONFIG</div>
</div>
</div>
</div>
</div>
<div class="options" style="margin-top:16px;">
<div class="option" data-choice="ok" onclick="toggleSelect(this)">
<div class="letter"></div>
<div class="content">
<h3>C'est bon, on part là-dessus</h3>
<p>Top bar stats + liste batteries + tab bar icônes</p>
</div>
</div>
<div class="option" data-choice="change" onclick="toggleSelect(this)">
<div class="letter"></div>
<div class="content">
<h3>Modifications à faire</h3>
<p>Dis-moi quoi changer dans le terminal</p>
</div>
</div>
</div>
@@ -0,0 +1,122 @@
<h2>5 onglets avec SOH IA — où le mettre ?</h2>
<p class="subtitle">On ajoute l'onglet State of Health (prédiction IA TFLite). 5 onglets sur 320px = 64px par tab.</p>
<div class="mockup">
<div class="mockup-header">Tab bar 5 onglets — 320px</div>
<div class="mockup-body" style="background:#000; padding:0; font-family:sans-serif;">
<!-- Spacer -->
<div style="height:220px; display:flex; align-items:center; justify-content:center; color:#333;">
(contenu écran)
</div>
<!-- Tab bar 5 -->
<div style="display:flex; background:#0A0A0A; border-top:1px solid #222; padding:4px 0;">
<div style="flex:1; text-align:center; color:#00FF66;">
<div style="font-size:15px;"></div>
<div style="font-size:7px; font-weight:bold;">BATT</div>
</div>
<div style="flex:1; text-align:center; color:#666;">
<div style="font-size:15px;">🧠</div>
<div style="font-size:7px;">SOH</div>
</div>
<div style="flex:1; text-align:center; color:#666;">
<div style="font-size:15px;">📊</div>
<div style="font-size:7px;">SYS</div>
</div>
<div style="flex:1; text-align:center; color:#FF0044; position:relative;">
<div style="font-size:15px;">⚠️</div>
<div style="font-size:7px;">ALERT</div>
<div style="position:absolute; top:-2px; right:16%; background:#FF0044; color:white; font-size:7px; width:12px; height:12px; border-radius:6px; display:flex; align-items:center; justify-content:center; font-weight:bold;">2</div>
</div>
<div style="flex:1; text-align:center; color:#666;">
<div style="font-size:15px;">⚙️</div>
<div style="font-size:7px;">CONFIG</div>
</div>
</div>
</div>
</div>
<h3 style="margin-top:20px;">Écran SOH — State of Health IA</h3>
<div class="mockup">
<div class="mockup-header">🧠 SOH — Prédiction santé batteries (TFLite)</div>
<div class="mockup-body" style="background:#000; padding:8px; font-family:sans-serif; font-size:11px; display:flex; flex-direction:column; gap:4px;">
<!-- Header -->
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
<span style="color:#00FFCC; font-weight:bold; font-size:13px;">🧠 State of Health</span>
<span style="color:#555; font-size:9px;">Dernière pred: il y a 10s</span>
</div>
<!-- SOH Avg -->
<div style="background:#0A1A1A; border:1px solid #00FFCC; border-radius:6px; padding:6px; text-align:center; margin-bottom:4px;">
<div style="color:#00FFCC; font-size:9px;">SOH MOYEN</div>
<div style="color:white; font-size:24px; font-weight:bold;">78%</div>
<div style="background:#1A1A1A; height:8px; border-radius:4px; margin-top:4px; overflow:hidden;">
<div style="background:linear-gradient(90deg,#00AA88,#00FFCC); width:78%; height:100%; border-radius:4px;"></div>
</div>
</div>
<!-- Per battery -->
<div style="display:flex; flex-direction:column; gap:2px;">
<div style="background:#0A0A0A; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#ccc; width:18px; font-size:10px;">B1</span>
<div style="flex:1; background:#1A1A1A; height:6px; border-radius:3px; overflow:hidden;">
<div style="background:#00FF66; width:92%; height:100%; border-radius:3px;"></div>
</div>
<span style="color:#00FF66; font-size:11px; font-weight:bold; width:32px; text-align:right;">92%</span>
</div>
<div style="background:#0A0A0A; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#ccc; width:18px; font-size:10px;">B2</span>
<div style="flex:1; background:#1A1A1A; height:6px; border-radius:3px; overflow:hidden;">
<div style="background:#00FF66; width:85%; height:100%; border-radius:3px;"></div>
</div>
<span style="color:#00FF66; font-size:11px; font-weight:bold; width:32px; text-align:right;">85%</span>
</div>
<div style="background:#0A0A0A; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#ccc; width:18px; font-size:10px;">B3</span>
<div style="flex:1; background:#1A1A1A; height:6px; border-radius:3px; overflow:hidden;">
<div style="background:#FFAA00; width:58%; height:100%; border-radius:3px;"></div>
</div>
<span style="color:#FFAA00; font-size:11px; font-weight:bold; width:32px; text-align:right;">58%</span>
</div>
<div style="background:#0A0A0A; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#ccc; width:18px; font-size:10px;">B4</span>
<div style="flex:1; background:#1A1A1A; height:6px; border-radius:3px; overflow:hidden;">
<div style="background:#00FF66; width:78%; height:100%; border-radius:3px;"></div>
</div>
<span style="color:#00FF66; font-size:11px; font-weight:bold; width:32px; text-align:right;">78%</span>
</div>
<div style="background:#0A0000; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#884444; width:18px; font-size:10px;">B5</span>
<div style="flex:1; background:#1A0000; height:6px; border-radius:3px; overflow:hidden;">
<div style="background:#FF3333; width:22%; height:100%; border-radius:3px;"></div>
</div>
<span style="color:#FF3333; font-size:11px; font-weight:bold; width:32px; text-align:right;">22%</span>
<span style="color:#FF3333; font-size:8px;">⚠ REMPLACER</span>
</div>
</div>
<!-- Legend -->
<div style="display:flex; gap:8px; justify-content:center; margin-top:4px;">
<span style="color:#00FF66; font-size:8px;">● >70% OK</span>
<span style="color:#FFAA00; font-size:8px;">● 40-70% USURE</span>
<span style="color:#FF3333; font-size:8px;"><40% REMPLACER</span>
</div>
</div>
</div>
<div class="options" style="margin-top:16px;">
<div class="option" data-choice="ok" onclick="toggleSelect(this)">
<div class="letter"></div>
<div class="content">
<h3>5 onglets c'est bon</h3>
<p>⚡BATT | 🧠SOH | 📊SYS | ⚠ALERT | ⚙CONFIG</p>
</div>
</div>
<div class="option" data-choice="change" onclick="toggleSelect(this)">
<div class="letter"></div>
<div class="content">
<h3>Modifications</h3>
<p>Dis-moi dans le terminal</p>
</div>
</div>
</div>
@@ -0,0 +1,314 @@
<h2>Preview complète — 5 écrans LVGL refonte</h2>
<p class="subtitle">320×240px · High Contrast · Noir pur · Font 14px</p>
<!-- ═══════════════════════════════════════════════════════ -->
<h3>⚡ Onglet 1 — BATT (Dashboard principal)</h3>
<!-- ═══════════════════════════════════════════════════════ -->
<div class="mockup">
<div class="mockup-header">⚡ BATT — Top bar + Liste batteries</div>
<div class="mockup-body" style="background:#000; padding:0; font-family:sans-serif; font-size:11px; display:flex; flex-direction:column; height:320px; overflow:hidden;">
<!-- TOP BAR -->
<div style="background:#0A0A0A; border-bottom:1px solid #222; padding:4px 6px;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:3px;">
<span style="color:#00AAFF; font-weight:bold; font-size:11px;">⚡ kryole</span>
<div style="display:flex; gap:4px;">
<span style="color:#00FF66; font-size:8px;">● BLE</span>
<span style="color:#00FF66; font-size:8px;">● WiFi</span>
<span style="color:#FF4444; font-size:8px;">○ MQTT</span>
</div>
</div>
<div style="display:flex; gap:2px;">
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:#00FF66; font-size:14px; font-weight:bold; line-height:1.1;">26.4V</div>
<div style="color:#555; font-size:7px;">V MOY</div>
</div>
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:white; font-size:14px; font-weight:bold; line-height:1.1;">4.1A</div>
<div style="color:#555; font-size:7px;">I TOTAL</div>
</div>
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:#4FC3F7; font-size:14px; font-weight:bold; line-height:1.1;">12.3</div>
<div style="color:#555; font-size:7px;">Ah IN</div>
</div>
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:#FF9100; font-size:14px; font-weight:bold; line-height:1.1;">8.2</div>
<div style="color:#555; font-size:7px;">Ah OUT</div>
</div>
<div style="flex:1; background:#111; border-radius:3px; padding:2px 4px; text-align:center;">
<div style="color:#FFAA00; font-size:12px; font-weight:bold; line-height:1.3;">23°C</div>
<div style="color:#555; font-size:7px;">45% HR</div>
</div>
</div>
</div>
<!-- BATTERY LIST -->
<div style="flex:1; padding:4px 6px; display:flex; flex-direction:column; gap:2px; overflow-y:auto;">
<div style="background:#0A0A0A; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px; font-weight:bold;">B1</span>
<div style="flex:1; background:#1A1A1A; height:8px; border-radius:4px; overflow:hidden;"><div style="background:linear-gradient(90deg,#00CC44,#00FF66); width:88%; height:100%; border-radius:4px;"></div></div>
<span style="color:#FFF; font-size:12px; font-weight:bold; width:44px; text-align:right;">26.4V</span>
<span style="color:#CCC; font-size:10px; width:32px; text-align:right;">1.2A</span>
</div>
<div style="background:#0A0A0A; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px; font-weight:bold;">B2</span>
<div style="flex:1; background:#1A1A1A; height:8px; border-radius:4px; overflow:hidden;"><div style="background:linear-gradient(90deg,#00CC44,#00FF66); width:87%; height:100%; border-radius:4px;"></div></div>
<span style="color:#FFF; font-size:12px; font-weight:bold; width:44px; text-align:right;">26.3V</span>
<span style="color:#CCC; font-size:10px; width:32px; text-align:right;">0.8A</span>
</div>
<div style="background:#0A0000; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #FF0044;">
<span style="color:#884444; width:18px; font-size:10px; font-weight:bold;">B3</span>
<div style="flex:1; background:#1A0000; height:8px; border-radius:4px;"></div>
<span style="color:#FF4466; font-size:12px; font-weight:bold; width:44px; text-align:right;">OFF</span>
<span style="color:#553333; font-size:10px; width:32px; text-align:right;"></span>
</div>
<div style="background:#0A0A0A; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px; font-weight:bold;">B4</span>
<div style="flex:1; background:#1A1A1A; height:8px; border-radius:4px; overflow:hidden;"><div style="background:linear-gradient(90deg,#00CC44,#00FF66); width:88%; height:100%; border-radius:4px;"></div></div>
<span style="color:#FFF; font-size:12px; font-weight:bold; width:44px; text-align:right;">26.5V</span>
<span style="color:#CCC; font-size:10px; width:32px; text-align:right;">2.1A</span>
</div>
<div style="background:#0A0800; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #FFAA00;">
<span style="color:#AA8800; width:18px; font-size:10px; font-weight:bold;">B5</span>
<div style="flex:1; background:#1A1800; height:8px; border-radius:4px; overflow:hidden;"><div style="background:linear-gradient(90deg,#FF8800,#FFAA00); width:82%; height:100%; border-radius:4px;"></div></div>
<span style="color:#FFCC44; font-size:12px; font-weight:bold; width:44px; text-align:right;">24.8V</span>
<span style="color:#AA9944; font-size:10px; width:32px; text-align:right;">0.3A</span>
</div>
<div style="background:#0A0A0A; padding:4px 6px; border-radius:4px; display:flex; align-items:center; gap:6px; border-left:3px solid #00FF66;">
<span style="color:#ccc; width:18px; font-size:10px; font-weight:bold;">B6</span>
<div style="flex:1; background:#1A1A1A; height:8px; border-radius:4px; overflow:hidden;"><div style="background:linear-gradient(90deg,#00CC44,#00FF66); width:86%; height:100%; border-radius:4px;"></div></div>
<span style="color:#FFF; font-size:12px; font-weight:bold; width:44px; text-align:right;">26.1V</span>
<span style="color:#CCC; font-size:10px; width:32px; text-align:right;">1.5A</span>
</div>
</div>
<!-- TAB BAR -->
<div style="display:flex; background:#0A0A0A; border-top:1px solid #222; padding:4px 0; flex-shrink:0;">
<div style="flex:1; text-align:center; color:#00FF66;"><div style="font-size:15px;"></div><div style="font-size:7px; font-weight:bold;">BATT</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">🧠</div><div style="font-size:7px;">SOH</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">📊</div><div style="font-size:7px;">SYS</div></div>
<div style="flex:1; text-align:center; color:#FF0044; position:relative;"><div style="font-size:15px;">⚠️</div><div style="font-size:7px;">ALERT</div><div style="position:absolute; top:-2px; right:16%; background:#FF0044; color:white; font-size:7px; width:12px; height:12px; border-radius:6px; display:flex; align-items:center; justify-content:center; font-weight:bold;">2</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">⚙️</div><div style="font-size:7px;">CONFIG</div></div>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════════════════ -->
<h3 style="margin-top:24px;">🧠 Onglet 2 — SOH (State of Health IA)</h3>
<!-- ═══════════════════════════════════════════════════════ -->
<div class="mockup">
<div class="mockup-header">🧠 SOH — Prédiction santé batteries TFLite</div>
<div class="mockup-body" style="background:#000; padding:8px; font-family:sans-serif; font-size:11px; display:flex; flex-direction:column; height:280px;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
<span style="color:#00FFCC; font-weight:bold; font-size:13px;">🧠 State of Health</span>
<span style="color:#555; font-size:9px;">il y a 10s</span>
</div>
<div style="background:#0A1A1A; border:1px solid #00FFCC; border-radius:6px; padding:6px; text-align:center; margin-bottom:6px;">
<div style="color:#00FFCC; font-size:9px;">SOH MOYEN</div>
<div style="color:white; font-size:24px; font-weight:bold;">78%</div>
<div style="background:#1A1A1A; height:8px; border-radius:4px; margin-top:4px; overflow:hidden;"><div style="background:linear-gradient(90deg,#00AA88,#00FFCC); width:78%; height:100%; border-radius:4px;"></div></div>
</div>
<div style="flex:1; display:flex; flex-direction:column; gap:3px; overflow-y:auto;">
<div style="background:#0A0A0A; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#ccc; width:18px; font-size:10px;">B1</span>
<div style="flex:1; background:#1A1A1A; height:6px; border-radius:3px; overflow:hidden;"><div style="background:#00FF66; width:92%; height:100%;"></div></div>
<span style="color:#00FF66; font-size:11px; font-weight:bold; width:32px; text-align:right;">92%</span>
</div>
<div style="background:#0A0A0A; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#ccc; width:18px; font-size:10px;">B2</span>
<div style="flex:1; background:#1A1A1A; height:6px; border-radius:3px; overflow:hidden;"><div style="background:#00FF66; width:85%; height:100%;"></div></div>
<span style="color:#00FF66; font-size:11px; font-weight:bold; width:32px; text-align:right;">85%</span>
</div>
<div style="background:#0A0A0A; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#ccc; width:18px; font-size:10px;">B3</span>
<div style="flex:1; background:#1A1A1A; height:6px; border-radius:3px; overflow:hidden;"><div style="background:#FFAA00; width:58%; height:100%;"></div></div>
<span style="color:#FFAA00; font-size:11px; font-weight:bold; width:32px; text-align:right;">58%</span>
</div>
<div style="background:#0A0A0A; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#ccc; width:18px; font-size:10px;">B4</span>
<div style="flex:1; background:#1A1A1A; height:6px; border-radius:3px; overflow:hidden;"><div style="background:#00FF66; width:78%; height:100%;"></div></div>
<span style="color:#00FF66; font-size:11px; font-weight:bold; width:32px; text-align:right;">78%</span>
</div>
<div style="background:#0A0000; padding:3px 6px; border-radius:3px; display:flex; align-items:center; gap:6px;">
<span style="color:#884444; width:18px; font-size:10px;">B5</span>
<div style="flex:1; background:#1A0000; height:6px; border-radius:3px; overflow:hidden;"><div style="background:#FF3333; width:22%; height:100%;"></div></div>
<span style="color:#FF3333; font-size:11px; font-weight:bold; width:32px; text-align:right;">22%</span>
<span style="color:#FF3333; font-size:8px;"></span>
</div>
</div>
<div style="display:flex; gap:8px; justify-content:center; margin-top:4px;">
<span style="color:#00FF66; font-size:8px;">● >70% OK</span>
<span style="color:#FFAA00; font-size:8px;">● 40-70% USURE</span>
<span style="color:#FF3333; font-size:8px;"><40% REMPLACER</span>
</div>
<!-- Tab bar -->
<div style="display:flex; background:#0A0A0A; border-top:1px solid #222; padding:4px 0; margin:6px -8px -8px -8px;">
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;"></div><div style="font-size:7px;">BATT</div></div>
<div style="flex:1; text-align:center; color:#00FFCC;"><div style="font-size:15px;">🧠</div><div style="font-size:7px; font-weight:bold;">SOH</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">📊</div><div style="font-size:7px;">SYS</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">⚠️</div><div style="font-size:7px;">ALERT</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">⚙️</div><div style="font-size:7px;">CONFIG</div></div>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════════════════ -->
<h3 style="margin-top:24px;">📊 Onglet 3 — SYS (Système)</h3>
<!-- ═══════════════════════════════════════════════════════ -->
<div class="mockup">
<div class="mockup-header">📊 SYS — Connexion, Climat, Solar, Firmware, I2C</div>
<div class="mockup-body" style="background:#000; padding:8px; font-family:sans-serif; font-size:11px; display:flex; flex-direction:column; height:280px;">
<div style="color:#00AAFF; font-size:13px; margin-bottom:6px; font-weight:bold;">📊 Système</div>
<div style="background:#111; border-radius:4px; padding:5px; margin-bottom:3px;">
<div style="display:flex; justify-content:space-between;"><span style="color:#666; font-size:9px;">CONNEXION</span><div style="display:flex; gap:6px;"><span style="color:#00FF66; font-size:9px;">● BLE</span><span style="color:#00FF66; font-size:9px;">● WiFi 192.168.0.250</span><span style="color:#FF4444; font-size:9px;">○ MQTT</span></div></div>
</div>
<div style="background:#111; border-radius:4px; padding:5px; margin-bottom:3px;">
<div style="display:flex; justify-content:space-between;"><span style="color:#666; font-size:9px;">CLIMAT</span><div style="display:flex; gap:10px;"><span style="color:white;">🌡 <strong>23.5°C</strong></span><span style="color:white;">💧 <strong>45%</strong></span></div></div>
</div>
<div style="background:#111; border-radius:4px; padding:5px; margin-bottom:3px;">
<div style="display:flex; justify-content:space-between; margin-bottom:2px;"><span style="color:#666; font-size:9px;">SOLAIRE</span><span style="color:#FFD600; font-size:9px;">☀ Float</span></div>
<div style="display:flex; gap:10px; font-size:10px;"><span style="color:white;">PV <strong>35.2V</strong></span><span style="color:white;"><strong>120W</strong></span><span style="color:white;">Bat <strong>26.8V</strong></span><span style="color:#888;">Jour <strong>450Wh</strong></span></div>
</div>
<div style="background:#111; border-radius:4px; padding:5px; margin-bottom:3px;">
<div style="display:flex; justify-content:space-between; margin-bottom:2px;"><span style="color:#666; font-size:9px;">FIRMWARE</span><span style="color:#888; font-size:9px;">v0.5.0</span></div>
<div style="display:flex; gap:10px; font-size:9px; color:#888;"><span>Heap 16.1MB</span><span>Up 2h34m</span><span>INA:4 TCA:1</span></div>
</div>
<div style="background:#111; border-radius:4px; padding:5px;">
<div style="display:flex; justify-content:space-between; margin-bottom:2px;"><span style="color:#666; font-size:9px;">I2C BUS</span><span style="color:#888; font-size:9px;">5 dev · 0 err</span></div>
<div style="font-size:8px; color:#555;">20:15:42 AHT30 OK · 20:15:41 INA scan · 20:15:40 TCA init</div>
</div>
<div style="flex:1;"></div>
<!-- Tab bar -->
<div style="display:flex; background:#0A0A0A; border-top:1px solid #222; padding:4px 0; margin:6px -8px -8px -8px;">
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;"></div><div style="font-size:7px;">BATT</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">🧠</div><div style="font-size:7px;">SOH</div></div>
<div style="flex:1; text-align:center; color:#00AAFF;"><div style="font-size:15px;">📊</div><div style="font-size:7px; font-weight:bold;">SYS</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">⚠️</div><div style="font-size:7px;">ALERT</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">⚙️</div><div style="font-size:7px;">CONFIG</div></div>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════════════════ -->
<h3 style="margin-top:24px;">⚠ Onglet 4 — ALERT</h3>
<!-- ═══════════════════════════════════════════════════════ -->
<div class="mockup">
<div class="mockup-header">⚠ ALERT — Journal chronologique</div>
<div class="mockup-body" style="background:#000; padding:8px; font-family:sans-serif; font-size:11px; display:flex; flex-direction:column; height:280px;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px;">
<span style="color:#FF0044; font-weight:bold; font-size:13px;">⚠ Alertes</span>
<div style="background:#222; color:#888; padding:2px 10px; border-radius:10px; font-size:9px; cursor:pointer;">CLEAR</div>
</div>
<div style="flex:1; display:flex; flex-direction:column; gap:2px; overflow-y:auto;">
<div style="background:#1A0000; padding:4px 6px; border-radius:3px; border-left:3px solid #FF0044;">
<div style="display:flex; justify-content:space-between;"><span style="color:#FF4466; font-size:10px; font-weight:bold;">B3 Undervoltage</span><span style="color:#553333; font-size:9px;">20:14:32</span></div>
<div style="color:#884444; font-size:9px;">V=23.2V < seuil 24.0V batterie déconnectée</div>
</div>
<div style="background:#1A0800; padding:4px 6px; border-radius:3px; border-left:3px solid #FFAA00;">
<div style="display:flex; justify-content:space-between;"><span style="color:#FFCC44; font-size:10px; font-weight:bold;">B5 Low voltage</span><span style="color:#665500; font-size:9px;">20:12:15</span></div>
<div style="color:#AA8844; font-size:9px;">V=24.8V proche du seuil 24.0V</div>
</div>
<div style="background:#0A0A0A; padding:4px 6px; border-radius:3px; border-left:3px solid #00FF66;">
<div style="display:flex; justify-content:space-between;"><span style="color:#00FF66; font-size:10px;">WiFi connecté</span><span style="color:#555; font-size:9px;">20:10:03</span></div>
<div style="color:#666; font-size:9px;">IP 192.168.0.250 — SSID "Les cils"</div>
</div>
<div style="background:#0A0A0A; padding:4px 6px; border-radius:3px; border-left:3px solid #00FF66;">
<div style="display:flex; justify-content:space-between;"><span style="color:#00FF66; font-size:10px;">BLE advertising</span><span style="color:#555; font-size:9px;">20:09:58</span></div>
<div style="color:#666; font-size:9px;">KXKM-BMU-kryole — NimBLE OK</div>
</div>
<div style="background:#0A0A0A; padding:4px 6px; border-radius:3px; border-left:3px solid #00AAFF;">
<div style="display:flex; justify-content:space-between;"><span style="color:#00AAFF; font-size:10px;">Boot</span><span style="color:#555; font-size:9px;">20:09:55</span></div>
<div style="color:#666; font-size:9px;">KXKM BMU v0.5.0 — 4 INA, 1 TCA</div>
</div>
</div>
<!-- Tab bar -->
<div style="display:flex; background:#0A0A0A; border-top:1px solid #222; padding:4px 0; margin:6px -8px -8px -8px;">
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;"></div><div style="font-size:7px;">BATT</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">🧠</div><div style="font-size:7px;">SOH</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">📊</div><div style="font-size:7px;">SYS</div></div>
<div style="flex:1; text-align:center; color:#FF0044;"><div style="font-size:15px;">⚠️</div><div style="font-size:7px; font-weight:bold;">ALERT</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">⚙️</div><div style="font-size:7px;">CONFIG</div></div>
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════════════════ -->
<h3 style="margin-top:24px;">⚙ Onglet 5 — CONFIG</h3>
<!-- ═══════════════════════════════════════════════════════ -->
<div class="mockup">
<div class="mockup-header">⚙ CONFIG — NVS runtime settings</div>
<div class="mockup-body" style="background:#000; padding:8px; font-family:sans-serif; font-size:11px; display:flex; flex-direction:column; height:280px;">
<div style="color:#888; font-weight:bold; font-size:13px; margin-bottom:6px;">⚙ Configuration</div>
<div style="flex:1; display:flex; flex-direction:column; gap:3px; overflow-y:auto;">
<!-- Device -->
<div style="background:#111; border-radius:4px; padding:5px;">
<div style="color:#666; font-size:9px; margin-bottom:2px;">NOM DEVICE</div>
<div style="display:flex; gap:4px; align-items:center;">
<div style="flex:1; background:#1A1A1A; border:1px solid #333; border-radius:3px; padding:2px 6px; color:white; font-size:11px;">kryole</div>
<div style="background:#222; color:#888; padding:2px 8px; border-radius:3px; font-size:9px;"></div>
</div>
</div>
<!-- WiFi -->
<div style="background:#111; border-radius:4px; padding:5px;">
<div style="display:flex; justify-content:space-between;"><span style="color:#666; font-size:9px;">WIFI</span><span style="color:#00FF66; font-size:8px;">● Connecté</span></div>
<div style="display:flex; gap:4px; margin-top:2px;">
<div style="flex:1; background:#1A1A1A; border:1px solid #333; border-radius:3px; padding:2px 6px; color:white; font-size:10px;">Les cils</div>
<div style="flex:1; background:#1A1A1A; border:1px solid #333; border-radius:3px; padding:2px 6px; color:#555; font-size:10px;">••••••••</div>
</div>
</div>
<!-- Seuils -->
<div style="background:#111; border-radius:4px; padding:5px;">
<div style="color:#666; font-size:9px; margin-bottom:2px;">SEUILS PROTECTION</div>
<div style="display:grid; grid-template-columns:1fr 1fr; gap:3px;">
<div style="display:flex; align-items:center; gap:4px;">
<span style="color:#888; font-size:9px; width:36px;">V min</span>
<div style="background:#222; color:#FFAA00; padding:1px 4px; border-radius:2px; font-size:9px; cursor:pointer;"></div>
<span style="color:white; font-size:10px; font-weight:bold;">24.0V</span>
<div style="background:#222; color:#FFAA00; padding:1px 4px; border-radius:2px; font-size:9px; cursor:pointer;">+</div>
</div>
<div style="display:flex; align-items:center; gap:4px;">
<span style="color:#888; font-size:9px; width:36px;">V max</span>
<div style="background:#222; color:#FFAA00; padding:1px 4px; border-radius:2px; font-size:9px;"></div>
<span style="color:white; font-size:10px; font-weight:bold;">30.0V</span>
<div style="background:#222; color:#FFAA00; padding:1px 4px; border-radius:2px; font-size:9px;">+</div>
</div>
<div style="display:flex; align-items:center; gap:4px;">
<span style="color:#888; font-size:9px; width:36px;">I max</span>
<div style="background:#222; color:#FFAA00; padding:1px 4px; border-radius:2px; font-size:9px;"></div>
<span style="color:white; font-size:10px; font-weight:bold;">10.0A</span>
<div style="background:#222; color:#FFAA00; padding:1px 4px; border-radius:2px; font-size:9px;">+</div>
</div>
<div style="display:flex; align-items:center; gap:4px;">
<span style="color:#888; font-size:9px; width:36px;">V diff</span>
<div style="background:#222; color:#FFAA00; padding:1px 4px; border-radius:2px; font-size:9px;"></div>
<span style="color:white; font-size:10px; font-weight:bold;">1.0V</span>
<div style="background:#222; color:#FFAA00; padding:1px 4px; border-radius:2px; font-size:9px;">+</div>
</div>
</div>
</div>
<!-- Options -->
<div style="background:#111; border-radius:4px; padding:5px;">
<div style="color:#666; font-size:9px; margin-bottom:2px;">OPTIONS</div>
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:2px;">
<span style="color:#ccc; font-size:10px;">BLE</span>
<div style="width:36px; height:18px; background:#00FF66; border-radius:9px; position:relative;"><div style="width:14px; height:14px; background:white; border-radius:7px; position:absolute; right:2px; top:2px;"></div></div>
</div>
<div style="display:flex; justify-content:space-between; align-items:center;">
<span style="color:#ccc; font-size:10px;">Luminosité</span>
<div style="width:120px; height:6px; background:#333; border-radius:3px; overflow:hidden;"><div style="width:70%; height:100%; background:#FFD600; border-radius:3px;"></div></div>
<span style="color:#888; font-size:9px;">70%</span>
</div>
</div>
</div>
<!-- Save button -->
<div style="background:#00CC44; color:black; text-align:center; padding:6px; border-radius:6px; font-weight:bold; font-size:12px; margin-top:4px; cursor:pointer;">💾 SAUVEGARDER</div>
<!-- Tab bar -->
<div style="display:flex; background:#0A0A0A; border-top:1px solid #222; padding:4px 0; margin:6px -8px -8px -8px;">
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;"></div><div style="font-size:7px;">BATT</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">🧠</div><div style="font-size:7px;">SOH</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">📊</div><div style="font-size:7px;">SYS</div></div>
<div style="flex:1; text-align:center; color:#666;"><div style="font-size:15px;">⚠️</div><div style="font-size:7px;">ALERT</div></div>
<div style="flex:1; text-align:center; color:#888;"><div style="font-size:15px;">⚙️</div><div style="font-size:7px; font-weight:bold;">CONFIG</div></div>
</div>
</div>
</div>
@@ -0,0 +1 @@
{"reason":"owner process exited","timestamp":1775079179687}
@@ -0,0 +1,27 @@
{"type":"server-started","port":49322,"host":"127.0.0.1","url_host":"localhost","url":"http://localhost:49322","screen_dir":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content","state_dir":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/state"}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/01-current-issues.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/01-current-issues.html"}
{"source":"user-event","type":"click","text":"C\n \n Fonctionnalités manquantes\n Pas de climat AHT30, pas de status BLE/WiFi, pas de config runtime, courant toujours 0A","choice":"c","id":null,"timestamp":1775076679371}
{"source":"user-event","type":"click","text":"D\n \n Look trop brut\n Design technique/développeur, pas assez pro pour un produit terrain KXKM","choice":"d","id":null,"timestamp":1775076685508}
{"source":"user-event","type":"click","text":"C\n \n Fonctionnalités manquantes\n Pas de climat AHT30, pas de status BLE/WiFi, pas de config runtime, courant toujours 0A","choice":"c","id":null,"timestamp":1775076702824}
{"source":"user-event","type":"click","text":"C\n \n Fonctionnalités manquantes\n Pas de climat AHT30, pas de status BLE/WiFi, pas de config runtime, courant toujours 0A","choice":"c","id":null,"timestamp":1775076703036}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/02-navigation.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/02-navigation.html"}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/03-battery-grid.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/03-battery-grid.html"}
{"source":"user-event","type":"click","text":"B — Liste avec barres de progression\n \n ⚡ KXKM-BMU-kryole\n \n \n ●\n B1\n \n \n \n 26.4V\n 1.2A\n \n \n ●\n B2\n \n \n \n 26.3V\n 0.8A\n \n \n ●\n B3\n \n OFF\n —\n \n \n ●\n B4\n \n \n \n 26.5V\n 2.1A\n \n \n moy 26.4V · 4.1A total · 🌡23°C 💧45%","choice":"b","id":null,"timestamp":1775076781666}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/04-system-screen.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/04-system-screen.html"}
{"source":"user-event","type":"click","text":"✓\n \n Ce layout me va\n Sections compactes, toutes les infos en un écran sans scroll","choice":"ok","id":null,"timestamp":1775076871777}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/05-color-theme.html"}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/06-waiting.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/06-waiting.html"}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/07-dashboard-icons.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/07-dashboard-icons.html"}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/08-topbar-refined.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/08-topbar-refined.html"}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/09-tabs-with-soh.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/09-tabs-with-soh.html"}
{"type":"screen-added","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/10-full-preview.html"}
{"type":"screen-updated","file":"/Users/electron/Documents/Lelectron_rare/1-KXKM/KXKM_Batterie_Parallelator/.superpowers/brainstorm/41015-1775076599/content/10-full-preview.html"}
{"type":"server-stopped","reason":"owner process exited"}
@@ -0,0 +1 @@
41024
+76
View File
@@ -0,0 +1,76 @@
# Project Guidelines
## Scope
- This AGENTS.md is the workspace-wide instruction source. Do not add a second global .github/copilot-instructions.md unless intentionally replacing this file.
- Repository focus: BMU firmware for parallelized battery packs (up to 16 channels), with PlatformIO/Arduino code in firmware/ and ESP-IDF code in firmware-idf/.
- Safety is mandatory: do not weaken battery protection logic, topology checks, authentication checks, or reconnect behavior.
- Prefer focused diffs in firmware/src/ and firmware-idf/. Avoid unrelated edits in hardware folders unless explicitly requested.
## Code Style
- Keep naming/comment language consistent with surrounding files (French-first in legacy firmware paths).
- Preserve existing API shapes and file-local style; avoid unrelated refactors.
- Prefer small, reviewable patches and reuse existing helpers before introducing new abstractions.
- For diagnostics, use DebugLogger categories over ad-hoc Serial.print.
## Build and Test
- Quick validation before substantial firmware edits:
- pio test -e sim-host
- Additional checks when scope grows:
- pio run -e kxkm-s3-16MB
- scripts/check_memory_budget.sh --env kxkm-s3-16MB --ram-max 75 --flash-max 85
- cd firmware-idf && idf.py build
- PlatformIO gotcha:
- Keep framework=arduino in [arduino_base] only; do not move it to global [env] (breaks sim-host/native tests).
- Canonical command references:
- [CLAUDE.md](CLAUDE.md)
- [README.md](README.md)
- [scripts/ci/README.md](scripts/ci/README.md)
## Architecture
- Safety core:
- firmware/src/main.cpp (orchestration + fail-safe topology behavior)
- firmware/src/BatteryParallelator.* (protection state machine)
- firmware/src/BatteryManager.* (aggregated state/metrics)
- I2C and peripherals:
- firmware/src/I2CMutex.h (global I2C mutex + I2CLockGuard)
- firmware/src/INAHandler.* (INA237 path)
- firmware/src/TCAHandler.* (TCA9535 path)
- Web mutation surface:
- firmware/src/WebServerHandler.*
- firmware/src/WebRouteSecurity.*
- firmware/src/WebMutationRateLimit.*
- firmware/src/BatteryRouteValidation.*
## Conventions
- Keep French comments/identifiers consistent with surrounding code.
- All I2C access must go through I2CLockGuard.
- Keep I2C recovery semantics intact (kI2CRecoveryThreshold = 5 consecutive failures).
- Validate battery/sensor indexes before any array/driver access.
- Preserve NAN/early-return semantics for sensor and bus faults.
- Keep periodic FreeRTOS tasks non-blocking.
- Maintain topology constraint Nb_TCA * 4 == Nb_INA; mismatch must remain fail-safe (all batteries OFF).
- Keep thresholds centralized in firmware/src/config.h (mV/mA conventions).
- Prefer DebugLogger categories (KxLogger.h) over ad-hoc Serial.print.
## Copilot Workflow
- Start by loading the scoped instruction file for the area being edited:
- [.github/instructions/firmware-safety.instructions.md](.github/instructions/firmware-safety.instructions.md)
- [.github/instructions/webserver-safety.instructions.md](.github/instructions/webserver-safety.instructions.md)
- [.github/instructions/firmware-idf-display-safety.instructions.md](.github/instructions/firmware-idf-display-safety.instructions.md)
- [.github/instructions/tests-python.instructions.md](.github/instructions/tests-python.instructions.md)
- [.github/instructions/ml-pipeline.instructions.md](.github/instructions/ml-pipeline.instructions.md)
- [.github/instructions/plan-todo-implementation.instructions.md](.github/instructions/plan-todo-implementation.instructions.md)
- For firmware safety changes, inspect the relevant code path and the closest sim-host tests before proposing edits.
- Reuse existing validation/security helpers and keep diffs minimal.
- Update nearby tests when behavior changes (especially protection, routes, auth, rate limiting).
- For risk-focused review work, prefer narrow agents in .github/agents/ over broad generic reviews.
- Link to existing documentation rather than embedding long duplicated guidance in code changes.
## Link-First References
- Safety and implementation context: [CLAUDE.md](CLAUDE.md)
- Project overview and setup: [README.md](README.md)
- Kill_LIFE specs and gates: [specs/00_intake.md](specs/00_intake.md), [specs/01_spec.md](specs/01_spec.md), [specs/02_arch.md](specs/02_arch.md), [specs/03_plan.md](specs/03_plan.md), [specs/04_validation.md](specs/04_validation.md)
- Current execution plan and safety refactor tracking: [plan/refactor-safety-core-web-remote-1.md](plan/refactor-safety-core-web-remote-1.md)
- CI/QA orchestration: [scripts/ci/README.md](scripts/ci/README.md), [.github/workflows](.github/workflows)
- ML governance and artifacts: [docs/ML_BATTERY_HEALTH_SPEC.md](docs/ML_BATTERY_HEALTH_SPEC.md), [models](models)
- QA environments and remote proof flow: [docs/QA_CICD_ENVIRONNEMENTS.md](docs/QA_CICD_ENVIRONNEMENTS.md), [docs/QA_REMOTE_PROOF_LATEST.md](docs/QA_REMOTE_PROOF_LATEST.md)
+9
View File
@@ -0,0 +1,9 @@
// ...existing code...
#define ARDUINOJSON_CONCAT_(a, b) a##b
#define ARDUINOJSON_CONCAT(a, b) ARDUINOJSON_CONCAT_(a, b)
#define ARDUINOJSON_BEGIN_PUBLIC_NAMESPACE \
namespace ARDUINOJSON_CONCAT(ARDUINOJSON_NAMESPACE, _NS) {
// ...existing code...
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 420 KiB

+53
View File
@@ -0,0 +1,53 @@
# KXKM Batterie Parallelator
BMU (Battery Management Unit) ESP32 — gestion sécurisée de batteries en parallèle 24-30V pour scénographie hors-réseau.
Client : KompleX KapharnaüM (Villeurbanne) — contact `[email protected]`
## Where to Look
| Tâche | Location |
|-------|----------|
| Modifier le firmware ESP-IDF (production) | `firmware-idf/` |
| Toucher l'Arduino legacy (sim-host tests) | `firmware/` |
| App iOS native (CoreBluetooth) | `iosApp/` |
| KMP Shared Kotlin | `kxkm-bmu-app/` |
| Stack cloud Docker (Mosquitto, InfluxDB, FastAPI) | `kxkm-api/` |
| Schémas/PCB KiCad | `hardware/` |
| Specs Kill_LIFE (S0-S3) | `specs/` |
| Plans + designs superpowers | `docs/superpowers/` |
## Project Status
- Kill_LIFE gates : S0-S2 ✅, S3 ⬜ (validation terrain)
- Tests : 13 PlatformIO sim-host + 13 ESP-IDF host = 26 ✅
- Memory budget : 81% flash (19% headroom sur 2MB OTA)
- iOS ↔ firmware GATT : 100% parité (audit 2026-04-08)
## Safety-Critical Rules
- Ne **jamais** affaiblir les seuils protection (V/I/délai/topology)
- Toute lecture I2C passe par `I2CLockGuard` (firmware/) ou `bmu_i2c_lock()` (firmware-idf/)
- Topology constraint : `Nb_TCA × 4 == Nb_INA` — mismatch → fail-safe (all OFF)
- Tâches FreeRTOS non-bloquantes
- Routes web mutation : token auth obligatoire
## Conventions
- Commentaires + identifiants en **français** (cohérence avec le legacy)
- Seuils dans `firmware/src/config.h` (mV/mA) ou Kconfig ESP-IDF
- Secrets WiFi/MQTT : `credentials.h.example` template (jamais commit credentials.h)
- Python via `uv` (pas pip/venv)
## Agent Workflow
Explore finds → Librarian reads → You plan → Worker implements → Validator checks
- Tâches indépendantes : lancer Task() en parallèle (un seul message, plusieurs calls)
- Avant grosse modif firmware : vérifier `pio test -e sim-host` et `idf.py build`
- Memory budget : `scripts/check_memory_budget.sh --env kxkm-s3-16MB --ram-max 75 --flash-max 85`
## Guidance
Context-specific guidance lives in nested `CLAUDE.md` files (firmware-idf/, iosApp/, kxkm-api/, etc.).
Closest CLAUDE.md to the file being edited takes precedence.
+190
View File
@@ -0,0 +1,190 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Projet
- Client : KompleX KapharnaüM (Villeurbanne) — contact : [email protected]
- BMU (Battery Management Unit) ESP32 — gestion sécurisée de batteries en parallèle 2430 V
- Intégré au workflow Kill_LIFE (spec-first, gates S0S3)
## Build & Test Commands
```bash
# === ESP-IDF firmware (production, firmware-idf/) ===
source ~/esp/esp-idf/export.sh
cd firmware-idf && idf.py build
idf.py -p /dev/cu.usbmodem* flash monitor
# === PlatformIO (legacy Arduino, firmware/) ===
pio run -e kxkm-s3-16MB # build
pio run -e kxkm-s3-16MB --target upload # flash
pio device monitor -e kxkm-s3-16MB --baud 115200
# === Tests (no hardware needed) ===
pio test -e sim-host # 13 PlatformIO tests
pio test -e sim-host -f test_protection # single suite
pio test -e sim-host -vv # verbose
cd firmware-idf/test && make all # 13 ESP-IDF host tests (Unity, g++)
cd firmware-idf/test && make test_protection # single ESP-IDF test suite
# === Rust firmware (firmware-rs/) ===
cd firmware-rs && cargo build
cargo test # unit tests (no hardware)
# === ML / LLM tests ===
uv run python -m pytest tests/llm/
# === Memory budget (required before large changes) ===
scripts/check_memory_budget.sh --env kxkm-s3-16MB --ram-max 75 --flash-max 85
# === Cloud stack (kxkm-api/) ===
cd kxkm-api && cp .env.example .env && docker compose up -d
# === SOH services (services/) ===
cd services/soh-scoring && uv run uvicorn soh_api:app # scoring API
cd services/soh-llm && uv run uvicorn app:app # LLM diagnostic
# === ML pipeline (scripts/ml/) ===
uv run python scripts/ml/extract_features.py
uv run python scripts/ml/train_fpnn.py
uv run python scripts/ml/quantize_tflite.py
```
**PlatformIO gotchas:**
- `[arduino_base]` in platformio.ini holds `framework=arduino`. Do NOT put `framework=arduino` in the global `[env]` — it breaks the `native`/`sim-host` test environments.
- `[env:sim-host]` has `build_src_filter` listing which `.cpp` files are compiled for host tests. When adding a new testable module, you must add its `.cpp` to this filter or it won't link.
## Architecture
### Three Firmware Tracks
| Track | Directory | Framework | Status |
|-------|-----------|-----------|--------|
| ESP-IDF | `firmware-idf/` | ESP-IDF 5.4, 25 components | **Production** (ESP32-S3-BOX-3) |
| Arduino | `firmware/` | PlatformIO/Arduino | Legacy (sim-host tests still active) |
| Rust | `firmware-rs/` | Cargo workspace, 5 crates | Experimental (FFI bridge to ESP-IDF) |
### ESP-IDF Execution Flow (firmware-idf/)
Boot sequence (14 stages): NVS → SPIFFS → Display → WiFi → BLE → FAT → SNTP → I2C scan → topology → protection → cloud → web → VE.Direct → OTA
Key components: `bmu_protection` (state machine), `bmu_balancer` (duty-cycling), `bmu_ble` (NimBLE 4 GATT services), `bmu_display` (LVGL), `bmu_influx` + `bmu_influx_store` (offline persistence), `bmu_web` + `bmu_web_security`. See component READMEs and Kconfig files for details.
### Arduino Execution Flow (firmware/)
1. `main.cpp` setup: Serial → Wire (SDA=32, SCL=33, 50kHz) → i2cMutexInit → INAHandler.begin → TCAHandler.begin → topology check → BattParallelator config
2. `main.cpp` loop (500ms): iterates all INAs via `BattParallelator.check_battery_connected_status(i)`. If topology invalid, forces all batteries OFF (fail-safe).
### Rust Firmware (firmware-rs/)
Cargo workspace with 5 crates: `bmu-i2c` (bus abstraction), `bmu-ina237` (sensor driver), `bmu-tca9535` (GPIO expander), `bmu-protection` (state machine), `bmu-ffi` (C FFI bridge with cbindgen). Hybrid C/Rust: I2C initialized by ESP-IDF C, passed to Rust via FFI. `no_std` compatible.
### Protection Thresholds (configurable via Kconfig + NVS)
| Threshold | Default |
|-----------|---------|
| Min voltage | 24,000 mV |
| Max voltage | 30,000 mV |
| Max current | 10,000 mA |
| Imbalance | 1,000 mV |
| Reconnect delay | 10,000 ms |
| Switch limit | 5 (>5 = permanent lock until reboot) |
### Topology Constraint
Hard validation: `Nb_TCA * 4 == Nb_INA`. Mismatch → fail-safe (all batteries OFF). Typical: 4 TCA + 16 INA.
### Thread Safety
- `I2CLockGuard` (RAII) wraps ALL I2C operations — INAHandler, TCAHandler, WebServerHandler
- `stateMutex` in BatteryParallelator and BatteryManager for shared state across FreeRTOS tasks
- `reconnect_time[]` access is mutex-protected
- `i2cBusRecovery()` triggered on 5+ consecutive I2C failures
### Offline Data Persistence
When WiFi/InfluxDB is unreachable, telemetry persists to FAT internal flash:
- Primary: `/fatfs/influx/current.lp` → rotates to `rotated.lp` at 512 KB (max 1 MB)
- Fallback: `/sdcard/influx/` if SD card present
- Replay: automatic on WiFi reconnection (cloud_telemetry_task, every 10s)
## ML Pipeline
SOH (State of Health) prediction deployed on ESP32 as TFLite INT8 (12.2 KB):
- **Pipeline**: `train_fpnn.py` → `quantize_tflite.py` → INT8 model (MAPE ~10%)
- **Models**: `models/` (`.pt`, `.onnx`, `.tflite`), features in `.parquet`
- **Remote training**: `scripts/ml/remote_kxkm_ai_pipeline.sh` on kxkm-ai (RTX 4090)
- **Services**: `services/soh-scoring/` (PyTorch API) + `services/soh-llm/` (Qwen2.5-7B diagnostics, port 8401)
## Test Suites (26 total, no hardware needed)
### PlatformIO sim-host (`pio test -e sim-host`)
| Suite | Covers |
|-------|--------|
| `test_protection` (10) | V/I/imbalance/lock state machine |
| `test_battery_route_validation` | Index bounds + state checks |
| `test_influx_buffer_codec` | InfluxDB line-protocol encoding |
| `test_web_mutation_rate_limit` (3) | Sliding window + multi-IP |
| `test_web_route_security` (9) | Constant-time token + Bearer |
| `test_ws_auth_flow` (7) | Combined auth + rate limit |
| `test_mqtt_influx_codec` (3) | JSON MQTT + topic parsing |
### ESP-IDF host (`cd firmware-idf/test && make all`)
| Suite | Covers |
|-------|--------|
| `test_protection` (13) | Full state machine (ESP-IDF) |
| `test_victron_gatt` (8) | GATT encoding (V, SOC, alarm, TTG, T) |
| `test_victron_scan` (5) | Payload parsing, expiry, MAC, CID |
| `test_ble_victron` | Battery/solar payload encoding |
| `test_vedirect_parser` | VE.Direct frame parsing |
| `test_rint` | R_int calculation |
| `test_config_labels` | Battery label management |
| `test_vrm_topics` | VRM topic generation |
## Safety-Critical Rules
- **Never** weaken voltage/current thresholds, reconnect delays, or topology guards
- **Never** bypass INA/TCA topology validation in main.cpp
- **All** I2C access must use `I2CLockGuard` from I2CMutex.h
- Validate sensor/battery indexes before array or driver access
- Preserve NAN/early-return fault semantics for sensor failures
- Keep FreeRTOS tasks non-blocking — no long blocking calls in periodic tasks
- Web mutation routes require auth token — no unauthenticated ON/OFF paths
## Conventions
- French comments and identifiers throughout — maintain consistency with surrounding code
- Arduino/ESP32 C++ style, fixed-size arrays where already used
- Use `DebugLogger` categories (KxLogger.h) instead of ad-hoc `Serial.print`
- CSV logging uses `;` separator — keep unchanged
- Config thresholds in `firmware/src/config.h` (values in mV/mA)
- WiFi/MQTT secrets go in `firmware/src/credentials.h` (template: `credentials.h.example`)
- Python projects use `uv` (not pip/venv)
## iOS App (iosApp/)
See `iosApp/CLAUDE.md` for full details. Key points:
- SwiftUI + CoreBluetooth, no external dependencies
- BLE polls every 2s (firmware notification bug workaround)
- Custom 128-bit UUID GATT protocol (battery/system/control/Victron services)
- 3 roles: Admin, Technician, Viewer (PIN + Face ID)
- Source of truth: `project.yml` → regenerate after target changes: `xcodegen generate`
- **Never** edit `project.pbxproj` manually
- Build: `xcodebuild build -scheme KXKMBmu -destination "platform=iOS,id=<DEVICE_ID>"`
## KMP Shared (kxkm-bmu-app/shared/)
Kotlin Multiplatform module — compiles for iOS arm64.
- Build requires JDK 17: `export JAVA_HOME=/opt/homebrew/opt/openjdk@17`
- Build framework: `./gradlew :shared:linkDebugFrameworkIosArm64`
- Gradle wrapper: 8.5 (not 9.x — AGP 8.2.0 incompatible)
- SKIE disabled (Gradle 9.x incompatible) — use manual callback bridges
## CI/CD
- `ci.yml`: PlatformIO `pio test -e sim-host` on push/PR (13 tests)
- `sim-host-tests.yml`: sim-host + S3 build + memory budget (RAM ≤75%, Flash ≤85%)
- Current flash usage: 81% (19% headroom on 2MB OTA)
## Gates Kill_LIFE
- S0 ✅ intake + specs
- S1 ✅ tests natifs 13/13 + bug fix `find_max_voltage`
- S2 ✅ KiCad BMU v2 review (ERC 0 violations)
- S3 ⬜ validation terrain (batteries réelles)
## Known Technical Debt
- Web UI assets are embedded as string literals in headers — consider SPIFFS/LittleFS migration
- KMP Shared framework not yet integrated in Xcode project (types prefixed `Shared*` need bridge layer)
- NVS config overrides sdkconfig defaults — erase NVS partition to reset: `esptool erase_region 0x9000 0x6000`
+11
View File
@@ -0,0 +1,11 @@
{
"folders": [
{
"path": "."
}
],
"settings": {
"stm32-for-vscode.openOCDPath": false,
"stm32-for-vscode.armToolchainPath": false
}
}
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+379
View File
@@ -0,0 +1,379 @@
<p align="center">
<img src="BMU.jpeg" alt="BMU PCB" width="480" />
</p>
<h1 align="center">KXKM Batterie Parallelator</h1>
<p align="center">
<strong>Battery Management Unit for parallel 24-30V packs</strong><br>
Up to 32 batteries &middot; ESP32-S3 &middot; BLE + MQTT + InfluxDB &middot; iOS companion app
</p>
<p align="center">
<a href="https://github.com/KomplexKapharnaum/KXKM_Batterie_Parallelator/actions/workflows/ci.yml">
<img src="https://github.com/KomplexKapharnaum/KXKM_Batterie_Parallelator/actions/workflows/ci.yml/badge.svg" alt="CI" />
</a>
<a href="https://github.com/KomplexKapharnaum/KXKM_Batterie_Parallelator/actions/workflows/sim-host-tests.yml">
<img src="https://github.com/KomplexKapharnaum/KXKM_Batterie_Parallelator/actions/workflows/sim-host-tests.yml/badge.svg" alt="QA" />
</a>
<img src="https://img.shields.io/badge/ESP--IDF-v5.4-blue" alt="ESP-IDF" />
<img src="https://img.shields.io/badge/license-GPLv3-green" alt="License" />
<img src="https://img.shields.io/badge/tests-26%20passed-brightgreen" alt="Tests" />
</p>
---
## Overview
The **KXKM Batterie Parallelator** is an embedded Battery Management Unit (BMU) that safely parallels multiple battery packs (24-30V) for off-grid stage installations. Each battery is individually monitored (voltage, current, temperature) and can be disconnected in microseconds via MOSFET switches.
Built by [L'Electron Rare](https://lelectronrare.fr) for [KompleX KapharnaüM](https://komplex-kapharnaum.net) (Villeurbanne, France) — a live arts company deploying digital scenography in public spaces without grid power.
### Key Features
| Feature | Description |
|---------|-------------|
| Per-battery protection | Under/over-voltage, over-current, imbalance detection |
| Auto-reconnection | Exponential backoff with permanent lock after 5 faults |
| Soft-balancing | Duty-cycling with opportunistic R_int measurement |
| Victron integration | BLE Instant Readout + GATT SmartShunt emulation + device scanner |
| Touchscreen UI | 320x240 LVGL display with battery grid, SOH, charts |
| iOS companion app | BLE real-time monitoring, offline cache, role-based access |
| Cloud telemetry | MQTT + InfluxDB + Grafana with offline persistence |
| OTA updates | Dual-partition with automatic rollback |
---
## Quick Start
```bash
# ESP-IDF firmware (production)
cd firmware-idf
source ~/esp/esp-idf/export.sh
idf.py build
idf.py -p /dev/cu.usbmodem* flash monitor
# PlatformIO (legacy Arduino)
pio run -e kxkm-s3-16MB --target upload
# Run all tests (no hardware needed)
pio test -e sim-host # 13 PlatformIO tests
cd firmware-idf && idf.py build # 13 ESP-IDF host tests
# Cloud stack (kxkm-ai server)
cd kxkm-api && cp .env.example .env && docker compose up -d
```
---
## Architecture
```
┌──────────────────────────┐
│ ESP32-S3-BOX-3 │
│ 320x240 LVGL display │
│ NimBLE + WiFi │
└─────────┬────────────────┘
│ I2C 50kHz
┌───────────────┼───────────────┐
│ │ │
┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐
│ TCA9535 │ │ TCA9535 │ │ ...×8 │
│ 4× MOSFET │ │ 4× LED │ │ │
└─────┬─────┘ └───────────┘ └───────────┘
┌─────▼─────┐
│ INA237 ×4 │ ← per TCA (voltage + current)
└───────────┘
┌──────────────────────────────────────────────────────┐
│ Cloud Stack │
│ BMU ──MQTT──► Mosquitto ──► Telegraf ──► InfluxDB │
│ │ │
│ iPhone ◄──BLE──► BMU Grafana ◄───────────┘ │
│ iPhone ◄──REST──► FastAPI ◄─────────────────┘ │
└──────────────────────────────────────────────────────┘
```
### Firmware Components (ESP-IDF, 25 modules)
| Component | Role |
|-----------|------|
| `bmu_protection` | State machine: 5 states, 5 criteria, permanent lock |
| `bmu_balancer` | Soft-balancing duty-cycling + R_int measurement |
| `bmu_ina237` | 16× INA237 power monitors (2mΩ shunt) |
| `bmu_tca9535` | 8× GPIO expanders (switches + LEDs) |
| `bmu_ble` | NimBLE 4 GATT services + Victron SmartShunt |
| `bmu_ble_victron` | Victron Instant Readout (AES-CTR encrypted ads) |
| `bmu_ble_victron_scan` | BLE central scanner for Victron devices |
| `bmu_display` | LVGL: battery grid, pack info, SOH, charts, swipe |
| `bmu_influx` + `_store` | InfluxDB client + offline FAT/SD persistence |
| `bmu_mqtt` | ESP-MQTT with auth credentials |
| `bmu_vedirect` | Victron VE.Direct UART parser (solar charger) |
| `bmu_rint` | Internal resistance pulse measurement |
| `bmu_web` | HTTP + WebSocket with token auth + rate limiting |
| `bmu_config` | NVS runtime config + Victron device keys |
| `bmu_storage` | NVS, FAT, SPIFFS, SD card, USB MSC |
| `bmu_ota` | OTA firmware update with rollback |
### Protection Logic
```
Nb_switch < 5 → Reconnect immediately when condition clears
Nb_switch == 5 → 10-second delay before reconnection
Nb_switch > 5 → Permanent lock (blinking red LED) until reboot
```
| Threshold | Default | Configurable |
|-----------|---------|:------------:|
| Min voltage | 24,000 mV | via Kconfig + NVS |
| Max voltage | 30,000 mV | via Kconfig + NVS |
| Max current | 10,000 mA | via Kconfig + NVS |
| Imbalance | 1,000 mV | via Kconfig + NVS |
| Reconnect delay | 10,000 ms | via Kconfig |
| Switch limit | 5 | via Kconfig |
### LED Behavior
| State | LED |
|-------|-----|
| Connected | Solid green |
| Disconnected | Solid red |
| Error | **Blinking red** (~1 Hz) |
| Locked | Solid red |
---
## iOS Companion App
<p align="center">
<strong>KXKM BMU</strong> &mdash; SwiftUI + CoreBluetooth
</p>
| Feature | Transport |
|---------|-----------|
| Real-time battery dashboard | BLE (2s poll) |
| Battery detail + voltage chart | BLE |
| Switch ON/OFF + reset | BLE (role-gated) |
| Protection config (0.025V/A step) | BLE |
| WiFi config for BMU | BLE |
| Audit trail + filtering | Local SQLDelight |
| Offline mode with cache indicator | Auto-fallback |
| SOH dashboard + R_int | BLE + REST |
| Victron device scanning | BLE passive |
**3 roles**: Admin (full), Technician (control), Viewer (read-only) — PIN + Face ID.
**Code**: `iosApp/` (Xcode, CoreBluetooth) + `kxkm-bmu-app/` (KMP Shared Kotlin)
---
## Victron BLE Integration
The BMU interacts with the Victron ecosystem via three mechanisms:
| Mechanism | Direction | Protocol |
|-----------|-----------|----------|
| Instant Readout | BMU → VictronConnect | AES-CTR encrypted advertising (PID 0xA389) |
| GATT SmartShunt | BMU → any BLE client | 9 read-only characteristics (V, I, SOC, Ah, TTG, T, alarm) |
| Device Scanner | Victron devices → BMU | Passive BLE scan, AES decrypt, 8 device cache |
Supported Victron record types: Solar (0x01), Battery (0x02), Inverter (0x03), DC-DC (0x04).
---
## Cloud Infrastructure
Docker stack on `kxkm-ai` server:
| Service | Port | Role |
|---------|------|------|
| Mosquitto | 1883, 9001 | MQTT broker (authenticated) |
| InfluxDB 2.7 | 8086 | Time-series storage (org=kxkm, bucket=bmu) |
| Telegraf | - | MQTT → InfluxDB bridge |
| FastAPI | 8400 | REST API (sync, history, audit) |
| Grafana 11 | 3001 | 3 dashboards (live, fleet, solar) |
**Setup**: `cp .env.example .env` — fill all secrets (API key, InfluxDB token, MQTT credentials, Grafana password, CORS origins). All secrets via `${...}` env vars, `chmod 600 .env`.
**Offline resilience**: when WiFi/InfluxDB is unreachable, telemetry is persisted to internal FAT flash (`/fatfs/influx/`) with 2-file rotation (512KB each). Automatic replay on reconnection.
---
## Testing
**26 tests total** — no hardware required.
### PlatformIO sim-host (13 tests)
```bash
pio test -e sim-host
```
| Suite | Tests | Covers |
|-------|:-----:|--------|
| `test_protection` | 10 | V/I/imbalance/lock state machine |
| `test_battery_route_validation` | - | Index bounds + state checks |
| `test_influx_buffer_codec` | - | InfluxDB line-protocol encoding |
| `test_web_mutation_rate_limit` | 3 | Sliding window + multi-IP |
| `test_web_route_security` | 9 | Constant-time token + Bearer |
| `test_ws_auth_flow` | 7 | Combined auth + rate limit |
| `test_mqtt_influx_codec` | 3 | JSON MQTT + topic parsing |
| `test_emulation_bench` | - | Emulation benchmark |
### ESP-IDF Host Tests (13 tests)
```bash
cd firmware-idf && idf.py build
```
| Suite | Tests | Covers |
|-------|:-----:|--------|
| `test_protection` | 13 | Full state machine (ESP-IDF) |
| `test_victron_gatt` | 8 | GATT encoding (V, SOC, alarm, TTG, T) |
| `test_victron_scan` | 5 | Payload parsing, expiry, MAC, CID |
| `test_ble_victron` | - | Battery/solar payload encoding |
| `test_vedirect_parser` | - | VE.Direct frame parsing |
| `test_rint` | - | R_int calculation |
| `test_config_labels` | - | Battery label management |
| `test_vrm_topics` | - | VRM topic generation |
### CI/CD Pipelines
| Pipeline | Trigger | Gate |
|----------|---------|------|
| `ci.yml` | push/PR | sim-host 13 tests pass |
| `sim-host-tests.yml` | push/PR | + S3 build + RAM ≤75% + Flash ≤85% |
| `esp-idf-ci.yml` | push/PR | + ESP-IDF host tests + flash ≤85% of 2MB OTA |
**Current flash usage**: 81% (1.69 MB / 2 MB OTA partition) — 19% headroom.
---
## Security Audit
**All findings resolved** as of 2026-04-07.
<details>
<summary><strong>Phase 1 — Migration (March 2026): 7/7 resolved</strong></summary>
| ID | Finding | Status |
|----|---------|--------|
| CRIT-001 | Obsolete function calls | ✅ |
| CRIT-002 | Unreliable global Nb_INA | ✅ |
| CRIT-003 | I2C access without mutex | ✅ |
| CRIT-004 | Missing mutex init | ✅ |
| HIGH-005 | WebSocket V/I race | ✅ |
| HIGH-006 | reconnect_time race | ✅ |
| HIGH-007 | Uninitialized globals | ✅ |
</details>
<details>
<summary><strong>Phase 2 — Deep audit (March-April 2026): 13/13 resolved</strong></summary>
| ID | Severity | Finding | Fix |
|----|----------|---------|-----|
| CRIT-A | Critical | mV/V unit mismatch | ESP-IDF: mV everywhere |
| CRIT-B | Critical | Imbalance vs config instead of fleet max | bmu_protection |
| CRIT-C | Critical | Deadlock in web switch | bmu_web |
| CRIT-D | Critical | Unauthenticated routes | bmu_web_security |
| HIGH-1 | High | Negative overcurrent ignored | Bidirectional factor |
| HIGH-2 | High | Unauthenticated WebSocket | Token on first frame |
| HIGH-3 | High | XSS in /log | cJSON null check |
| HIGH-4 | High | MQTT plaintext | Mosquitto auth + .env |
| HIGH-5 | High | I2C speed change unguarded | I2CLockGuard |
| HIGH-7 | High | Public battery_voltages[] | state_mutex |
| HIGH-8 | High | Influx task crash on SD fail | influx_store fallback |
| MED-1 | Medium | No permanent lock (F08) | BMU_STATE_LOCKED |
| MED-010 | Medium | mV/V harmonization | mV throughout |
</details>
<details>
<summary><strong>Infrastructure audit (April 2026): 5/5 resolved</strong></summary>
| Finding | Fix |
|---------|-----|
| Mosquitto anonymous access | Auth + password file |
| Hardcoded secrets in docker-compose | All via .env (chmod 600) |
| Default InfluxDB token | Rotated (44-char random) |
| CORS allow_origins=["*"] | Restricted via env var |
| Offline data loss | FAT/SD persistence + replay |
</details>
---
## Hardware
### PCB Revisions
| Version | Status | Files |
|---------|--------|-------|
| BMU v1 | Manufactured | `hardware/PCB/` |
| BMU v2 | Production-ready (ERC 0, BOM 107) | `hardware/pcb-bmu-v2/` |
### Key ICs
| IC | Package | Role | I2C Address |
|----|---------|------|-------------|
| INA237 | VSSOP-10 | Power monitor (V/I/P) | 0x40-0x4F (16 max) |
| TCA9535 | TSSOP-24 | GPIO expander (switches + LEDs) | 0x20-0x27 (8 max) |
| ISO1540 | SOIC-8 | Galvanic I2C isolator | - |
| IRF4905 | D2PAK | P-channel MOSFET (55V, 74A) | - |
### I2C Mapping
```
TCA_0 (0x20) → INA 0x40-0x43 → Batteries 1-4
TCA_1 (0x21) → INA 0x44-0x47 → Batteries 5-8
TCA_2 (0x22) → INA 0x48-0x4B → Batteries 9-12
TCA_3 (0x23) → INA 0x4C-0x4F → Batteries 13-16
```
Topology constraint: `Nb_TCA × 4 == Nb_INA` — mismatch triggers fail-safe (all OFF).
---
## Project Structure
```
KXKM_Batterie_Parallelator/
├── firmware-idf/ # ESP-IDF 5.4 firmware (25 components)
│ ├── components/ # Modular ESP-IDF components
│ ├── main/ # app_main entry point
│ └── test/ # Unity host tests (13 suites)
├── firmware/ # Legacy PlatformIO/Arduino firmware
│ ├── src/ # Source modules
│ ├── test/ # sim-host tests (8 suites, 13 tests)
│ └── lib/INA237/ # Local INA237 driver fork
├── iosApp/ # iOS SwiftUI app (CoreBluetooth)
├── kxkm-bmu-app/ # KMP shared Kotlin module
│ └── shared/ # Cross-platform domain logic
├── kxkm-api/ # Docker stack (Mosquitto, InfluxDB, FastAPI, Grafana)
├── hardware/ # KiCad schematics + Gerbers (v1 + v2)
├── specs/ # Kill_LIFE gates (S0-S3)
├── docs/ # Specs, plans, governance, research
├── grafana/dashboards/ # 3 Grafana dashboard JSONs
└── scripts/ # CI, QA, ML pipeline
```
---
## About KompleX KapharnaüM
[KompleX KapharnaüM](https://komplex-kapharnaum.net) is a live arts company based in Villeurbanne (Lyon, France), active for 20+ years in street arts, live performance, and digital creation. The company develops its own embedded hardware platform (K32, ESP32-based) and maintains open-source tools on [GitHub](https://github.com/KomplexKapharnaum).
---
## License
[GNU General Public License v3.0](LICENSE)
---
<p align="center">
<sub>Built with ESP-IDF, LVGL, NimBLE, SwiftUI, FastAPI, InfluxDB, and Grafana.</sub><br>
<sub>Developed by <a href="https://lelectronrare.fr">L'Electron Rare</a> for <a href="https://komplex-kapharnaum.net">KompleX KapharnaüM</a></sub>
</p>
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,75 @@
# TinyML & Edge AI Literature Library
**Project:** KXKM Batterie Parallelator — Battery Health Prediction
**Date Created:** 2026-03-30
**Total Papers:** 12 (20202026)
---
## Overview
This folder contains peer-reviewed research papers and technical reports relevant to:
- **Edge inference optimization** for battery SOH/RUL prediction on MCUs
- **Quantization strategies** for neural network deployment
- **SOTA techniques** for TinyML and embedded AI systems
All papers have been classified by priority based on relevance to KXKM project goals (FPNN quantization on ESP32 + cloud SambaMixer).
---
## Organization by Priority
### 01-HIGH-PRIORITY
**Papers to read first for FPNN/quantization understanding:**
- `MCUNet_ImageNet_on_MCU_MIT_2020.pdf` — Memory-efficient architecture design
- `Lightweight_DL_Survey_TinyML_2024-04.pdf` — Quantization taxonomy & benchmarks
**Why:** Direct applicability to edge FPNN deployment. Validates current quantization approach (stratified calibration + per-channel + QDQ format).
### 02-MEDIUM-PRIORITY
**Papers for SOTA 2026 exploration (Q2Q3 roadmap):**
- `Fine-Tuning_Small_Language_Models_*_2025-03.pdf` — SLM domain adaptation
- `Shakti_SLMs_Edge_AI_2025-03.pdf` — SLM benchmarks on edge
- `EmbedAgent_LLM_Benchmark_Embedded_Systems_2025-06.pdf` — LLM inference metrics
- `TinyAgent_Function_Calling_Edge_2024-09.pdf` and `_Lutfi_Eren_Erdogan_*.pdf` — Local task execution
- `TinyNav_*_2026-03.pdf` (x2) — Autonomous inference patterns
**Why:** Potential expansion of KXKM health prediction to multi-modal (advisory LLM, local decision-making). Not critical for baseline, but inform longer roadmap.
### 03-LOW-PRIORITY
**Context & future-use papers:**
- `Securing_LLM_Embedded_Firmware_Validation_2025-09.pdf` — Security considerations (if future LLM adoption)
- `Tiny_Transformers_Audio_Edge_MCU_2021-03.pdf` — Attention mechanisms (techniques transfer)
- `WakeMod_UltraLowPower_IoT_WakeUp_Radio_2025-05.pdf` — Ultra-low-power circuits (future)
**Why:** Useful for understanding landscape; lower immediate applicability.
---
## How to Use
1. **For immediate work:** Start with HIGH-PRIORITY papers (34 hours reading + synthesis)
2. **For planning:** Review SOTA roadmap table in [../ml-battery-health-spec.md](../ml-battery-health-spec.md#5-literature-review--sota-baseline) section 5
3. **For deep dives:** See `_priority-matrix.json` for detailed scoring and reading time estimates
---
## Related Documentation
- **ML Spec:** [../ml-battery-health-spec.md](../ml-battery-health-spec.md) — Integration spec with Literature Review section
- **Phase 1 Findings:** Strategy Notes (internal) — Technical synthesis of MCUNet + TinyML Survey
- **PDF Analysis:** [../pdf-library-analysis.md](../pdf-library-analysis.md) — Detailed classification and relevance matrix
---
## Metadata
- **Total papers:** 12
- **Date span:** 20202026
- **Domains:** TinyML, quantization, edge AI, embedded inference, battery health
- **Priority breakdown:** 2 HIGH, 7 MEDIUM, 3 LOW
Last updated: 2026-03-30
@@ -0,0 +1,148 @@
{
"metadata": {
"project": "KXKM Batterie Parallelator",
"date_created": "2026-03-30",
"total_papers": 12,
"scoring_version": "v1.0"
},
"scoring_criteria": {
"relevance_to_fpnn_quantization": {
"weight": 0.4,
"description": "How directly applicable to FPNN edge inference on ESP32"
},
"sota_2026_importance": {
"weight": 0.3,
"description": "Relevance to roadmap expansion (LLM advisory, multi-modal)"
},
"read_priority": {
"weight": 0.2,
"description": "Urgency for team to review (baseline vs. future)"
},
"practical_techniques": {
"weight": 0.1,
"description": "Number of actionable code/config changes"
}
},
"papers": [
{
"id": "HIGH-1",
"filename": "01-HIGH-PRIORITY/MCUNet_ImageNet_on_MCU_MIT_2020.pdf",
"title": "MCUNet: Memory-Efficient Convolutional Neural Networks for Embedded Vision",
"year": 2020,
"priority": "HIGH",
"score": 0.94,
"applicability_to_kxkm": "Direct \u2014 validates current quantization + memory strategy",
"status": "Read (Phase 1)"
},
{
"id": "HIGH-2",
"filename": "01-HIGH-PRIORITY/Lightweight_DL_Survey_TinyML_2024-04.pdf",
"title": "Lightweight Deep Learning: A Survey on Efficient Deep Neural Networks",
"year": 2024,
"priority": "HIGH",
"score": 0.92,
"applicability_to_kxkm": "Direct \u2014 all 5 techniques mapped to Phase 2 baseline",
"status": "Read (Phase 1)"
},
{
"id": "MEDIUM-1",
"filename": "02-MEDIUM-PRIORITY/Fine-Tuning_Small_Language_Models_for_Domain-Specific_AI_An_Edge_AI_Perspective_Rakshit_2025-03.pdf",
"title": "Fine-Tuning Small Language Models for Domain-Specific AI",
"year": 2025,
"priority": "MEDIUM",
"score": 0.68,
"applicability_to_kxkm": "Future \u2014 informs hybrid FPNN + LLM advisory architecture",
"status": "Queued for Phase 3"
},
{
"id": "MEDIUM-2",
"filename": "02-MEDIUM-PRIORITY/Shakti_SLMs_Edge_AI_2025-03.pdf",
"title": "Shakti: Small Language Models on Edge Devices",
"year": 2025,
"priority": "MEDIUM",
"score": 0.65,
"applicability_to_kxkm": "Future \u2014 validates SLM feasibility on hardware",
"status": "Queued for Phase 3"
},
{
"id": "MEDIUM-3",
"filename": "02-MEDIUM-PRIORITY/TinyAgent_Function_Calling_Edge_2024-09.pdf",
"title": "TinyAgent: Function Calling on Edge Devices",
"year": 2024,
"priority": "MEDIUM",
"score": 0.62,
"applicability_to_kxkm": "Future \u2014 enables battery advisor on edge",
"status": "Queued for Phase 3"
},
{
"id": "MEDIUM-4",
"filename": "02-MEDIUM-PRIORITY/TinyAgent_Function_Calling_at_the_Edge_Lutfi_Eren_Erdogan_1_Nicholas_Lee_2024-09.pdf",
"title": "TinyAgent: Function Calling at the Edge (Extended)",
"year": 2024,
"priority": "MEDIUM",
"score": 0.6,
"applicability_to_kxkm": "Future \u2014 design phase Q2 2026",
"status": "Queued for Phase 3"
},
{
"id": "MEDIUM-5",
"filename": "02-MEDIUM-PRIORITY/TinyNav_ESP32_Navigation_2026-03.pdf",
"title": "TinyNav: Real-Time Autonomous Navigation on ESP32",
"year": 2026,
"priority": "MEDIUM",
"score": 0.7,
"applicability_to_kxkm": "Immediate reference \u2014 FPNN could use pipeline patterns",
"status": "Queued for Phase 3"
},
{
"id": "MEDIUM-6",
"filename": "02-MEDIUM-PRIORITY/TinyNav_End-to-End_TinyML_for_Real-Time_Autonomous_Navigation_on_Microcontrollers_2026-03.pdf",
"title": "TinyNav: End-to-End TinyML for Real-Time Autonomous Navigation",
"year": 2026,
"priority": "MEDIUM",
"score": 0.72,
"applicability_to_kxkm": "Immediate reference \u2014 systems design for Phase 2",
"status": "Queued for Phase 3"
},
{
"id": "MEDIUM-7",
"filename": "02-MEDIUM-PRIORITY/EmbedAgent_LLM_Benchmark_Embedded_Systems_2025-06.pdf",
"title": "EmbedAgent: LLM Benchmarking on Embedded Systems",
"year": 2025,
"priority": "MEDIUM",
"score": 0.64,
"applicability_to_kxkm": "Future \u2014 validation framework for Phase 3",
"status": "Queued for Phase 3"
},
{
"id": "LOW-1",
"filename": "03-LOW-PRIORITY/Securing_LLM_Embedded_Firmware_Validation_2025-09.pdf",
"title": "Securing LLM Embeddings: Firmware Validation Techniques",
"year": 2025,
"priority": "LOW",
"score": 0.45,
"applicability_to_kxkm": "Future (Q3 2026+) \u2014 consider only if LLM chosen",
"status": "Low priority archive"
},
{
"id": "LOW-2",
"filename": "03-LOW-PRIORITY/Tiny_Transformers_Audio_Edge_MCU_2021-03.pdf",
"title": "Tiny Transformers: Audio Processing on Edge MCUs",
"year": 2021,
"priority": "LOW",
"score": 0.4,
"applicability_to_kxkm": "Theoretical interest \u2014 attention techniques transfer",
"status": "Low priority archive"
},
{
"id": "LOW-3",
"filename": "03-LOW-PRIORITY/WakeMod_UltraLowPower_IoT_WakeUp_Radio_2025-05.pdf",
"title": "WakeMod: Ultra-Low-Power Wake-Up Radio for IoT",
"year": 2025,
"priority": "LOW",
"score": 0.38,
"applicability_to_kxkm": "Future (Phase 4, 2027+) \u2014 power optimization if critical",
"status": "Low priority archive"
}
]
}
View File
File diff suppressed because it is too large Load Diff
View File
+524
View File
@@ -0,0 +1,524 @@
# ML Battery Health Prediction -- Integration Spec
**Project**: KXKM Batterie Parallelator
**Repository**: [KomplexKapharnaum/KXKM_Batterie_Parallelator](https://github.com/KomplexKapharnaum/KXKM_Batterie_Parallelator) (branch: `object-orriented`)
**Author**: Clement Saillant / Komplex Kapharnaum
**Date**: 2026-03-27
**Status**: Draft
---
## 1. Objective
Predict **State of Health (SOH)** and **Remaining Useful Life (RUL)** for up to 16 lead-acid or LiFePO4 batteries managed by the Parallelator, using telemetry already collected by INA226 sensors and logged to SD card / InfluxDB.
**Success criteria**:
- SOH estimation within 5% accuracy (MAPE < 5%) on held-out Parallelator data
- Real-time SOH inference on target MCU (ESP32, Teensy 4.1, STM32, etc.) in under 100 ms per channel
- RUL prediction (cycle-level) via cloud model with MAPE < 3%
- Zero impact on existing firmware timing (INA read loop, SD logging, WebSocket serving)
---
## 2. Data Pipeline
### 2.1 Existing Data Sources
| Source | Format | Fields per channel | Count |
|--------|--------|--------------------|-------|
| SD card logs | CSV (`;` separator) | Temps, Volt_N, Current_N, Switch_N, AhCons_N, AhCharge_N, TotCurrent, TotCharge, TotCons | 43 files |
| InfluxDB | Line protocol | voltage, current, temperature (per batteryId) | Continuous |
**Log file naming**: `datalog_{device}_{seq}.csv` -- devices: `gocab` (12 files), `k-led1` (11), `k-led2` (11), `tender` (9).
**Sample rate**: ~1 second intervals (observed from timestamps).
### 2.2 Feature Extraction
From raw voltage/current time series, extract per-channel features:
| Feature | Description | Derivation |
|---------|-------------|------------|
| `V_mean`, `V_std` | Mean/std voltage over sliding window | Rolling stats on Volt_N |
| `I_mean`, `I_std` | Mean/std current over sliding window | Rolling stats on Current_N |
| `dV/dt` | Voltage rate of change | Finite difference on Volt_N |
| `dI/dt` | Current rate of change | Finite difference on Current_N |
| `R_internal` | Estimated internal resistance | delta_V / delta_I at load transitions |
| `Ah_discharge` | Cumulative discharge capacity | AhCons_N (already logged) |
| `Ah_charge` | Cumulative charge capacity | AhCharge_N (already logged) |
| `coulombic_eff` | Charge/discharge efficiency | AhCharge / AhCons ratio per cycle |
| `capacity_fade` | Capacity loss vs nominal | (nominal_Ah - measured_Ah) / nominal_Ah |
| `V_under_load` | Voltage sag under load | Min voltage during discharge bursts |
| `rest_voltage` | Open-circuit voltage after rest | Volt_N when Current_N ~ 0 for > 60s |
| `cycle_count` | Number of charge/discharge cycles | Zero-crossing detection on current |
| `temperature` | Battery temperature (if available via InfluxDB) | Direct from InfluxDB |
### 2.3 Processing Pipeline
```raw
SD CSV files (43)
|
v
[scripts/ml/parse_csv.py] -- Parse semicolon-separated CSVs, align timestamps
|
v
[scripts/ml/extract_features.py] -- Sliding window features, cycle detection
|
v
features.parquet -- Tabular dataset, one row per (device, channel, window)
|
v
[Merge with NASA Battery Dataset] -- Augment with public degradation data
|
v
train.parquet / val.parquet / test.parquet -- 70/15/15 split by device
```
---
## 3. Model Selection
### 3.1 Candidates
| Model | Architecture | Params (est.) | MAPE (literature) | ESP32 viable | Notes |
|-------|-------------|---------------|--------------------|--------------|----|
| **FPNN** | Feature-based polynomial neural net | ~5K | 0.88% | Yes (INT8, any MCU with I2C) | Best accuracy-to-size ratio for SOH |
| **SambaMixer** | Mamba SSM blocks | ~500K-2M | SOTA on NASA | Cloud only | Best for RUL |
| **LSTM** | 2-layer LSTM | ~50K-200K | 1-3% | Teensy 4.1 / STM32H7 only | Baseline, well-understood |
| **1D-CNN** | Temporal convolutions | ~10K-50K | 1-5% | Yes (INT8, most MCUs) | Good for fixed-window patterns |
| **Linear regression** | OLS on engineered features | ~20 | 5-10% | Yes (any MCU) | Absolute baseline |
### 3.2 Recommendation
**Two-tier architecture**:
1. **Edge (MCU via I2C)**: Start with **FPNN** (Feature-based Polynomial Neural Network)
- Tiny parameter count (~5K params = ~10 KB INT8)
- Operates on pre-computed features from INA226 I2C sensors, not raw sequences
- Literature MAPE of 0.88% on standard benchmarks
- MCU-agnostic: runs on ESP32, Teensy 4.1, STM32F4/H7, or any MCU with I2C + ~50KB free RAM
- The I2C bus (INA226 sensors + TCA9535 GPIO expanders) is the common hardware layer across all board revisions
- Fallback: 1D-CNN if FPNN proves too sensitive to feature engineering quality
2. **Cloud (mascarade on KXKM-AI)**: **SambaMixer** for lifecycle prediction
- Mamba SSM architecture handles long sequences efficiently (O(n) vs O(n^2))
- Full historical data from InfluxDB, not constrained by ESP32 memory
- Anomaly detection via reconstruction error
- RUL prediction with confidence intervals
---
## 4. Edge vs Cloud Split
### 4.1 Edge -- MCU (I2C as common hardware layer)
The intelligence layer is **MCU-agnostic**. The INA226 current/voltage sensors and TCA9535/TCA9555 GPIO expanders communicate over I2C, which is available on all target platforms. The ML model consumes features extracted from I2C sensor readings.
**Supported MCU targets**:
| MCU | RAM | FPU | Inference lib | Notes |
|-----|-----|-----|--------------|-------|
| ESP32-WROVER | 520 KB SRAM + 4MB PSRAM | Soft-float (S3: vector) | TFLite Micro / ESP-DL | Current production board |
| Teensy 4.1 | 1 MB SRAM + 8 MB PSRAM | ARM Cortex-M7 FPU | TFLite Micro / CMSIS-NN | Fastest inference, K32-lib native |
| STM32F4/H7 | 192 KB - 1 MB | ARM Cortex-M4/M7 FPU | TFLite Micro / STM32Cube.AI | V3 boards have STM32F070 coprocessor |
| RP2040 | 264 KB | Soft-float | TFLite Micro | Budget option, dual-core |
**Common constraints across all targets**:
- Available RAM budget for ML: ~50-80 KB (after firmware overhead)
- Must not block INA I2C read loop (current: ~1s cycle for 16 channels)
- I2C bus shared with INA226 (0x40-0x4F) + TCA9535 (0x20-0x27) — ML task must yield during sensor reads
**Edge model responsibilities**:
- Real-time SOH estimation per channel (run every 60s or on-demand)
- Simple anomaly flag: voltage/current outside learned bounds
- Publish SOH + flags via WebSocket/MQTT to mascarade mesh
**Deployment format**: TFLite Micro (portable) or platform-specific (ESP-DL, STM32Cube.AI, CMSIS-NN)
**Memory budget** (same across all targets):
```raw
Model weights (INT8): ~10 KB
Inference scratch buffer: ~15 KB
Feature buffer (16 ch): ~8 KB
Total ML footprint: ~33 KB
```
### 4.2 Cloud -- mascarade on KXKM-AI
**Resources**: RTX 4090 (24 GB VRAM), 62 GB RAM, Unsloth venv
**Cloud model responsibilities**:
- Full lifecycle RUL prediction (days/cycles remaining)
- Fleet-level anomaly detection across all Parallelator devices
- Capacity fade trend analysis and alerting
- Model retraining on new data (incremental)
- Serve predictions via MCP tool interface
---
## 5. Integration Architecture
### 5.1 MCU Firmware Changes (I2C-based, platform-agnostic)
New files to add to `src/`:
```raw
src/
SOHEstimator.h -- SOH inference wrapper (TFLite Micro or ESP-DL)
SOHEstimator.cpp -- Feature computation + model inference
models/
soh_fpnn_int8.tflite -- Quantized model binary (included as PROGMEM)
```
**Integration points in existing code**:
```cpp
// In BatteryParallelator main loop (or dedicated FreeRTOS task):
// Every 60 seconds:
// 1. Collect last 60 samples of (voltage, current) per channel from ring buffer
// 2. Compute features: V_mean, V_std, I_mean, I_std, dV/dt, R_internal
// 3. Run SOHEstimator::predict(channel, features) -> float soh_percent
// 4. Publish via WebSocket: {"type":"soh","ch":N,"soh":XX.X,"anomaly":false}
// 5. Log to InfluxDB: battery_soh,channel=N value=XX.X
// New ring buffer in INA_NRJ_lib (or BatteryManager):
struct SampleRing {
float voltage[60];
float current[60];
uint8_t head;
};
SampleRing channelSamples[16];
```
**FreeRTOS task** (pinned to core 0, low priority):
```cpp
void sohEstimationTask(void* pvParameters) {
SOHEstimator estimator;
estimator.loadModel(); // Load from PROGMEM
while (true) {
for (int ch = 0; ch < nbBatteries; ch++) {
float soh = estimator.predict(ch, channelSamples[ch]);
// Publish result
}
vTaskDelay(pdMS_TO_TICKS(60000)); // Every 60s
}
}
```
### 5.2 mascarade MCP Integration
New MCP tool registered in mascarade-core:
```typescript
// tools/battery_health.ts
{
name: "battery_health",
description: "Query battery SOH predictions and RUL for Parallelator fleet",
inputSchema: {
type: "object",
properties: {
device: { type: "string", description: "Device name (gocab, k-led1, k-led2, tender)" },
channel: { type: "integer", minimum: 1, maximum: 16 },
query: {
type: "string",
enum: ["soh", "rul", "anomalies", "fleet_summary", "capacity_trend"]
},
time_range: { type: "string", description: "ISO 8601 duration, e.g. P7D for last 7 days" }
},
required: ["query"]
}
}
```
**Data flow**:
```raw
ESP32 Parallelator
|-- WebSocket/MQTT --> mascarade P2P mesh
| |
| v
| InfluxDB (Tower)
| |
| v
| SambaMixer model (KXKM-AI)
| |
| v
| battery_health MCP tool
| |
v v
SD card logs crazy_life dashboard
```
### 5.3 crazy_life Dashboard Widget
New component in the cockpit:
```raw
BatteryFleetHealth/
FleetOverview.tsx -- Grid of 16 cells with SOH color coding
ChannelDetail.tsx -- Time series chart for selected channel
RULForecast.tsx -- Remaining life prediction with confidence band
AnomalyLog.tsx -- Recent anomaly events
```
**Color coding**: SOH > 80% green, 60-80% yellow, < 60% red.
---
## 6. Training Pipeline
### 6.1 Seed Data
- **43 CSV log files** from Parallelator SD cards
- 4 device classes: gocab (6-8 channels), k-led1 (8 ch), k-led2 (8 ch), tender (8 ch)
- Fields: Voltage, Current, Switch state, Ah consumption, Ah charge, totals
- Sampling: ~1 Hz
- Limitation: no ground-truth SOH labels (must derive from capacity fade)
### 6.2 Data Augmentation
**NASA Battery Dataset** (public, PCoE):
- 28 Li-ion cells, charge/discharge/impedance cycles until failure
- Ground-truth capacity measurements per cycle
- Download: https://www.nasa.gov/content/prognostics-center-of-excellence-data-set-repository
- Use for: pre-training the SambaMixer model, validating feature extraction pipeline
**Synthetic augmentation**:
- Add Gaussian noise to voltage/current (simulate sensor noise)
- Time-stretch/compress cycles (simulate different load profiles)
- Inject synthetic degradation curves (linear, knee-point, sudden)
### 6.3 Training on KXKM-AI
```bash
# On KXKM-AI (RTX 4090, 62 GB RAM)
ssh kxkm@kxkm-ai
# Activate environment
source ~/venv/bin/activate
# Install dependencies (one-time)
pip install pytorch-lightning tensorboard scikit-learn pandas pyarrow
# Step 1: Parse and extract features
python scripts/ml/parse_csv.py --input "log SD/" --output data/raw.parquet
python scripts/ml/extract_features.py --input data/raw.parquet --output data/features.parquet
# Step 2: Train edge model (FPNN)
python scripts/ml/train_fpnn.py \
--data data/features.parquet \
--epochs 200 \
--batch-size 64 \
--lr 1e-3 \
--output models/soh_fpnn.pt
# Step 3: Train cloud model (SambaMixer)
python scripts/ml/train_sambamixer.py \
--data data/features.parquet \
--nasa-data data/nasa_battery/ \
--epochs 100 \
--batch-size 32 \
--output models/rul_sambamixer.pt
# Step 4: Quantize edge model
python scripts/ml/quantize.py \
--model models/soh_fpnn.pt \
--format tflite \
--quantization int8 \
--output models/soh_fpnn_int8.tflite
# Step 5: Convert to C header for ESP32
xxd -i models/soh_fpnn_int8.tflite > src/models/soh_fpnn_int8.h
```
### 6.4 Quantization Strategy
| Step | Tool | Input | Output | Target |
|------|------|-------|--------|--------|
| Float32 training | PyTorch | features.parquet | soh_fpnn.pt | KXKM-AI |
| Post-training quantization | TFLite converter | soh_fpnn.pt | soh_fpnn_int8.tflite | ESP32 |
| C array embedding | xxd | .tflite | .h (PROGMEM) | ESP32 flash |
Alternative path: ESP-DL (Espressif's framework) with `esp-dl` quantization tools if TFLite Micro proves too heavy on ESP32 classic.
---
## 7. Milestones
### Phase 1: Data Collection + Feature Extraction (2 weeks)
- [ ] Write `scripts/ml/parse_csv.py` -- parse all 43 CSV files, handle missing channels, normalize timestamps
- [ ] Write `scripts/ml/extract_features.py` -- sliding window features, cycle detection, internal resistance estimation
- [ ] Download and preprocess NASA PCoE battery dataset
- [ ] Validate feature distributions, produce exploratory analysis notebook
- [ ] Define pseudo-SOH labels from capacity fade in Parallelator data
- **Deliverable**: `data/features.parquet` with labeled training data
### Phase 2: Train Baseline Model (2 weeks)
- [ ] Implement FPNN architecture in PyTorch (`scripts/ml/train_fpnn.py`)
- [ ] Implement SambaMixer architecture (`scripts/ml/train_sambamixer.py`)
- [ ] Train FPNN on combined Parallelator + NASA data
- [ ] Train SambaMixer for RUL prediction
- [ ] Evaluate: MAPE, RMSE, R^2 on held-out test set
- [ ] Compare against linear regression and simple LSTM baselines
- **Deliverable**: Trained models + evaluation report
### Phase 3: Quantize + Deploy on ESP32 (2 weeks)
- [ ] Quantize FPNN to INT8 via TFLite or ESP-DL
- [ ] Validate quantized model accuracy (< 1% degradation from float32)
- [ ] Implement `SOHEstimator.h/.cpp` firmware module
- [ ] Add ring buffer to INA read loop for feature computation
- [ ] Add FreeRTOS SOH estimation task
- [ ] Add WebSocket publish for SOH results
- [ ] Memory budget validation: `scripts/check_memory_budget.sh --env kxkm-v3-16MB --ram-max 75 --flash-max 85`
- **Deliverable**: Firmware with embedded SOH inference, tested on hardware
### Phase 4: mascarade MCP + Dashboard (2 weeks)
- [ ] Deploy SambaMixer model as inference service on KXKM-AI
- [ ] Implement `battery_health` MCP tool in mascarade-core
- [ ] Wire ESP32 SOH data into InfluxDB via existing `InfluxDBHandler`
- [ ] Build `BatteryFleetHealth` widget in crazy_life dashboard
- [ ] End-to-end integration test: ESP32 -> mascarade -> dashboard
- [ ] Documentation and operational runbook
- **Deliverable**: Full pipeline live, fleet health visible in cockpit
### Timeline Summary
```raw
Week 1-2: Phase 1 -- Data pipeline
Week 3-4: Phase 2 -- Model training
Week 5-6: Phase 3 -- Edge deployment
Week 7-8: Phase 4 -- Cloud integration + dashboard
```
---
## 8. References
### Battery ML Research
1. **FPNN** -- Feature-based Polynomial Neural Network for battery SOH estimation. MAPE 0.88% on benchmark datasets. Lightweight architecture suitable for edge deployment.
2. **SambaMixer** -- Mamba State Space Model for battery RUL prediction. Current SOTA on NASA PCoE dataset. Selective state space layers with O(n) sequence modeling.
3. **GPT4Battery** -- LLM-based approach for State of Health estimation. Demonstrates transfer learning from language models to battery time series. Interesting for few-shot adaptation.
4. **BatteryML** -- Open-source platform for battery lifecycle prediction. Standardized benchmarks, feature extraction utilities, and model comparison framework. GitHub: https://github.com/microsoft/BatteryML
5. **NASA PCoE Battery Dataset** -- 28 Li-ion cells cycled to failure with impedance, charge, and discharge measurements. Standard benchmark for RUL prediction. Public domain.
6. **Attention-based CNN-LSTM** -- Hybrid architecture combining spatial feature extraction (CNN) with temporal modeling (LSTM) and attention mechanism for SOH prediction.
7. **Transfer Learning for Battery Degradation** -- Domain adaptation techniques for applying models trained on lab data (NASA) to field data (Parallelator). Critical for bridging the lab-to-field gap.
8. **TinyML for Predictive Maintenance** -- Survey of quantization and pruning techniques for deploying neural networks on microcontrollers. INT8 quantization typically preserves > 99% accuracy.
9. **Electrochemical Impedance Spectroscopy (EIS) features** -- Extracting internal resistance and diffusion coefficients from voltage/current transients without dedicated EIS hardware.
10. **Incremental Capacity Analysis (ICA)** -- dQ/dV analysis for detecting degradation modes (SEI growth, lithium plating, active material loss) from standard charge/discharge curves.
### Framework and Tools
- **TensorFlow Lite Micro**: https://www.tensorflow.org/lite/microcontrollers
- **ESP-DL** (Espressif Deep Learning): https://github.com/espressif/esp-dl
- **Unsloth**: Training acceleration on KXKM-AI RTX 4090
- **InfluxDB Client for Arduino**: Already integrated in firmware
- **mascarade MCP**: Tool registration and P2P mesh communication
---
## Appendix A: CSV Schema
From `datalog_{device}_{seq}.csv` (semicolon-separated):
```raw
Temps;Volt_1;...;Volt_N;Current_1;...;Current_N;Switch_1;...;Switch_N;
AhCons_1;...;AhCons_N;AhCharge_1;...;AhCharge_N;TotCurrent;TotCharge;TotCons
```
- `Temps`: ISO 8601 timestamp (e.g., `2025-05-23 16:27:34`)
- `Volt_N`: Bus voltage in volts (float, ~28-30V for 24V lead-acid systems)
- `Current_N`: Current in amps (float, positive = discharge, negative = charge)
- `Switch_N`: Relay state (`ON` / `OFF`)
- `AhCons_N`: Cumulative amp-hour discharge (float)
- `AhCharge_N`: Cumulative amp-hour charge (float)
- `TotCurrent`: Total instantaneous current across all channels
- `TotCharge`: Total charge across all channels
- `TotCons`: Total consumption across all channels
Channels vary by device: gocab uses 6-8 channels, k-led and tender use up to 8.
## Appendix B: ESP32 Memory Map (with ML)
```raw
Flash (16 MB):
Firmware: ~1.5 MB
SPIFFS: ~1.0 MB
Model (INT8): ~0.01 MB
OTA partition: ~1.5 MB
Free: ~12 MB
SRAM (520 KB):
FreeRTOS + WiFi: ~180 KB
INA + TCA drivers: ~20 KB
WebSocket server: ~40 KB
SD Logger: ~16 KB
InfluxDB client: ~30 KB
Ring buffers (16ch): ~8 KB
ML inference: ~25 KB
Stack + heap: ~200 KB
--------------------------------
Total used: ~519 KB (estimate, tight)
```
Note: Memory budget is tight on ESP32-WROVER. If ML inference exceeds 30 KB, consider offloading entirely to mascarade cloud. The `check_memory_budget.sh` script must pass with `--ram-max 75`.
---
## 11. ML Governance 2026 Addendum
### 11.1 Reproducibility and Versioning
- Every training run must record: dataset hash, feature extraction script commit, training script commit, hyperparameters, random seed, and produced model artifact name.
- Use explicit model naming: `soh_<arch>_v<major>.<minor>_<YYYYMMDD>`.
- Store a run metadata artifact (`training_metadata.json`) alongside each exported model.
- Keep a feature schema version (`feature_schema_version`) and increment it on any feature definition change.
### 11.2 In-Domain vs Out-of-Domain Evaluation
- Report metrics separately for in-domain Parallelator field logs and out-of-domain public PHM datasets.
- Do not merge in-domain and out-of-domain scores into a single headline metric.
- Minimum reporting set: MAPE, MAE, calibration error, and confidence coverage by domain.
- Track generalization gap explicitly: `OOD_MAPE - ID_MAPE`.
### 11.3 Confidence, Uncertainty, and OOD Signals
- Edge and cloud predictions must include confidence metadata (interval or calibrated score).
- Add an `is_in_distribution` or equivalent OOD flag for each inference result.
- If confidence is below threshold or OOD flag is active, classify prediction as advisory-low-confidence.
- Prediction payloads must include both value and confidence context in dashboards/API outputs.
### 11.4 Drift Monitoring and Retraining Triggers
- Monitor feature drift in production (rolling statistics vs training baseline).
- Define explicit thresholds for drift alerts and retraining triggers.
- Log drift indicators to time-series storage and review periodically.
- Retraining decisions must be based on measured degradation and drift evidence, not ad-hoc intuition.
### 11.5 Safety Policy: Advisory-Only ML
- ML outputs must never override hard protection logic (voltage/current thresholds, topology checks, reconnect protections).
- On inference failure (timeout, NAN, model load error), system behavior falls back to deterministic protection logic only.
- Safety-critical switching decisions remain firmware state-machine responsibilities.
- Any future control-loop coupling with ML requires a dedicated safety review and test campaign.
### 11.6 Governance Checklist Before Deployment
- Reproducibility artifacts generated and archived.
- In-domain and out-of-domain metrics reported separately.
- Confidence/OOD outputs validated on representative scenarios.
- Drift detection verified with synthetic and real replay traces.
- Advisory-only safety fallback tested end-to-end.
- Memory and latency budgets validated on target hardware.
### 11.7 CI/Validation Recommendations
- Add automated checks for metadata completeness in model artifacts.
- Fail CI if domain-split metrics or confidence fields are missing in evaluation reports.
- Keep a regression benchmark set derived from field logs to detect silent quality drift.
- Version and review evaluation notebooks/scripts as part of model PRs.
View File
View File
+51
View File
@@ -0,0 +1,51 @@
# QA CI/CD par environnement
> Statut: local OK, preuve distante en attente dactivation/présence du workflow sur la branche par défaut.
## Objectif
- Exécuter QA de manière déterministe par environnement (`sim-host`, `kxkm-s3-build`, `kxkm-v3-build`, `kxkm-s3-memory-budget`).
- Capturer des preuves exploitables localement et côté GitHub Actions.
## Exécution locale
```bash
bash scripts/ci/run_qa_all.sh
```
Commande équivalente par environnement:
```bash
bash scripts/ci/run_qa_env.sh sim-host
bash scripts/ci/run_qa_env.sh kxkm-s3-build
bash scripts/ci/run_qa_env.sh kxkm-v3-build
bash scripts/ci/run_qa_env.sh kxkm-s3-memory-budget
```
## Preuve distante GitHub Actions
1. Vérifier les workflows disponibles:
```bash
gh workflow list --repo KomplexKapharnaum/KXKM_Batterie_Parallelator
```
2. Si le workflow `qa-cicd-environments` existe et expose `workflow_dispatch`, le déclencher:
```bash
gh workflow run qa-cicd-environments --ref object-orriented --repo KomplexKapharnaum/KXKM_Batterie_Parallelator
```
3. Exporter une table de preuves:
```bash
bash scripts/ci/collect_remote_qa_evidence.sh qa-cicd-environments object-orriented 10
```
## Blocage connu (2026-03-29)
- Le fichier `.github/workflows/sim-host-tests.yml` nexiste pas encore sur la branche par défaut distante.
- Le workflow `CI` distant ne possède pas de trigger `workflow_dispatch`.
- Prochaine action: pousser/ouvrir PR contenant le workflow `qa-cicd-environments`, puis relancer la collecte de preuves.
## Automatisation de preuve distante (nouveau)
Commande:
```bash
bash scripts/ci/request_remote_qa_proof.sh \
KomplexKapharnaum/KXKM_Batterie_Parallelator \
object-orriented \
qa-cicd-environments \
docs/QA_REMOTE_PROOF_LATEST.md
```
Résultat actuel: un snapshot horodaté est produit dans `docs/QA_REMOTE_PROOF_LATEST.md` avec inventaire workflows, runs disponibles, diagnostic dispatch, et prochaine action.
+26
View File
@@ -0,0 +1,26 @@
# QA Remote Proof Snapshot
- Timestamp (UTC): 2026-03-29T01:00:36Z
- Repository: KomplexKapharnaum/KXKM_Batterie_Parallelator
- Branch: object-orriented
- Target workflow: qa-cicd-environments
- Dispatch status: blocked
## Workflow inventory
```text
CI active 251386236
Copilot code review active 243076938
Copilot coding agent active 243074488
```
## Recent runs (target workflow + branch)
UNKNOWN
## Dispatch diagnostic
```text
workflow 'qa-cicd-environments' absent from remote workflow list
```
## Next action
- Ensure .github/workflows/sim-host-tests.yml is available on default branch, then re-run this script.
- If dispatch is unavailable, open/update a PR to trigger pull_request CI and collect run URLs.
@@ -0,0 +1,76 @@
# Note de conception — refactor concurrence hotplug (H3 / H4 / H13)
> Statut : **conception** (aucun code). Implémentation à réaliser **avec le matériel au banc** (ajout/retrait à chaud de modules INA237 / TCA9535). Réf. audit : `docs/audit/firmware-safety-audit-2026-06-13.md`.
## 1. Problème
Deux tâches FreeRTOS partagent l'état de topologie et les tableaux de devices I2C :
- **Tâche protection** (prio 8) — lit en continu `ctx->ina_devices[idx]` / `ctx->tca_devices[idx]`, `ctx->nb_ina`, `ctx->nb_tca`, et écrit l'état batterie sous `state_mutex`.
- **Tâche hotplug** (prio 3) — détecte les modules ajoutés/retirés et **mute directement** les mêmes tableaux.
Trois défauts en découlent :
| # | Défaut | Détail |
|---|--------|--------|
| **H3** | **use-after-free** | `remove_gone_ina/tca` font `i2c_master_bus_rm_device()` puis `memmove` (compaction) des structs `bmu_ina237_t`/`bmu_tca9535_handle_t` pendant que la tâche protection peut lire `&ctx->ina_devices[idx]` dans `bmu_ina237_read_voltage_current`. Le handle peut être supprimé/déplacé sous les pieds de la protection. `nb_ina_mutex` ne protège que le **compteur**, pas le contenu du tableau ni les handles. |
| **H4** | **écritures non protégées** | `*s_cfg.nb_tca` (l.189/277) et `*s_cfg.topology_ok` (l.359) sont écrits **sans mutex**, alors que `publish_snapshot` les lit (`nb_tca*4==nb_ina`). Lecture/écriture concurrente → lecture déchirée d'un drapeau qui pilote le fail-safe. |
| **H13** | **double source de vérité** | `nb_ina` existe en deux exemplaires : le `nb_ina` global de `main` (pointé par `ctx->nb_ina` côté cloud) et `prot->nb_ina`. Le hotplug met à jour les deux séparément ; la tâche cloud lit l'un avec un **fallback non protégé** si le mutex échoue. |
**Cause racine commune** : *deux écrivains* mutent un état partagé via *pointeurs directs*, avec une granularité de verrou incohérente (mutex sur le compteur, pas sur le contenu ; mutex différents entre écrivain et lecteur). C'est pourquoi un correctif partiel (ex. juste un mutex autour de `nb_tca`) donnerait une fausse assurance : il ne couvre pas la compaction des handles (H3) ni l'unification des sources (H13).
## 2. Principe de la solution : propriétaire unique + queue de commandes
**Un seul propriétaire mute le contexte de topologie : la tâche protection.** Le hotplug ne fait que *détecter* et *notifier*.
```
Tâche hotplug (prio 3) Tâche protection (prio 8)
───────────────────── ─────────────────────────
scan I2C (probe add/remove)
construit un "set cible" ──CMD_TOPOLOGY_SET──▶ applique TOUTES les
(adresses présentes) (queue) mutations sous state_mutex :
NE TOUCHE PLUS aux - add/remove device
tableaux partagés - compaction tableaux
- nb_ina / nb_tca / topology_ok
```
- Le hotplug n'appelle plus `bmu_protection_update_topology()` directement (l'appel direct ET la CMD coexistent aujourd'hui — double application, M2 de l'audit). **Un seul chemin : la queue.**
- La compaction des tableaux `ina_devices[]` / `tca_devices[]` et les `i2c_master_bus_rm_device()` se font **dans la tâche protection**, donc jamais concurremment avec une lecture de handle par cette même tâche → H3 éliminé.
- `nb_ina`, `nb_tca`, `topology_ok` deviennent des champs du **seul** `ctx`, écrits/lus sous `state_mutex` → H4 + H13 éliminés. Le `nb_ina` global de `main` est supprimé ; tout le monde lit `prot->nb_ina` via un accesseur mutexé `bmu_protection_get_nb_ina()`.
### Payload de la commande
`CMD_TOPOLOGY_SET` doit décrire l'état I2C cible de façon autoportante (pas de pointeur vers un tableau muté par le hotplug). Deux options :
- **(A) bitmap d'adresses présentes** : `uint16_t ina_present_mask`, `uint8_t tca_present_mask` + adresses de base. La protection diff par rapport à son état courant et applique add/remove. Compact, pas d'allocation.
- **(B) snapshot complet** : tableau d'adresses (≤ BMU_MAX_BATTERIES). Plus simple à raisonner, payload plus gros mais borné.
Recommandation : **(A) bitmap** — minimal, sans allocation, idempotent (le hotplug peut renvoyer l'état complet à chaque scan, la protection ne fait rien si pas de delta).
### Création/suppression des devices I2C
`i2c_master_bus_add_device` / `_rm_device` ne sont **pas** garantis thread-safe vis-à-vis des transactions en cours. En les déplaçant dans la tâche protection (qui est aussi celle qui fait les transactions), on sérialise naturellement add/remove et lecture — plus besoin de verrou inter-tâches sur le bus pour ce cas.
## 3. Étapes d'implémentation (incrémentales, build entre chaque)
1. **Accesseur unique `nb_ina`** : ajouter `bmu_protection_get_nb_ina()` (sous `state_mutex`), migrer tous les lecteurs (`cloud_telemetry_task`, BLE, VRM, balancer) dessus. Supprimer le `nb_ina` global de `main` et le fallback non protégé. *(H13)*
2. **Champs topologie dans `ctx`** : déplacer `nb_tca` / `topology_ok` dans `ctx`, accès sous `state_mutex` partout (y compris `publish_snapshot` et le gate C2 déjà en place). *(H4)*
3. **Commande unique** : remplacer l'appel direct `bmu_protection_update_topology()` du hotplug par l'unique envoi `CMD_TOPOLOGY_SET` (bitmap). Supprimer la double application. *(M2)*
4. **Déplacer la compaction** : implémenter dans la tâche protection un `apply_topology(mask)` qui fait add/remove device + compaction + maj compteurs, sous `state_mutex`. Le hotplug ne mute plus aucun tableau. *(H3)*
5. **Nettoyage** : retirer `nb_ina_mutex` (remplacé par `state_mutex` comme verrou unique de topologie) ou le renommer `topology_mutex` et l'utiliser de façon cohérente.
## 4. Plan de validation (banc matériel requis)
- **Fonctionnel** : retirer puis réinsérer à chaud un module INA237, puis un TCA9535 ; vérifier `nb_ina`/`nb_tca`/`topology_ok` cohérents, pas de batterie « fantôme », fail-safe sur mismatch.
- **Stress** : insertions/retraits répétés sous charge (batteries connectées, balancer actif) ; surveiller l'absence de crash (use-after-free), de `LoadProhibited`, de WDT.
- **Concurrence** : logs horodatés protection vs hotplug ; confirmer qu'aucune mutation de tableau n'a lieu hors tâche protection.
- **Non-régression** : 14 tests host + `qa-kxkm-s3-*` verts ; `idf.py build` OK ; budget mémoire < 85 %.
- **Durée** : prévoir un run d'endurance (≥ 1 h) hotplug aléatoire.
## 5. Risques & points d'attention
- **Latence topologie** : un module retiré n'est « vu » qu'au prochain cycle protection (≤ période boucle). Acceptable (le fail-safe coupe déjà sur lecture I2C en échec).
- **Taille de queue** : `CMD_TOPOLOGY_SET` est idempotent et écrasable → utiliser `xQueueOverwrite` sur une file de profondeur 1 dédiée, pour ne pas saturer la file de commandes générale.
- **Ordre d'init** : au boot, la topologie initiale doit être posée avant le démarrage de la tâche hotplug pour éviter une première CMD redondante.
- **Compat tests** : les tests `test_protection` / `test_snapshot` devront simuler `apply_topology` ; prévoir un point d'entrée testable en host.
## 6. Effort estimé
Moyen. ~1-2 j de dev + **0,5-1 j de validation au banc** (indispensable : ces bugs ne se reproduisent qu'avec du hotplug réel). À faire en un PR dédié, séparé de la remédiation déjà mergée.
@@ -0,0 +1,63 @@
# Audit sécurité firmware-idf — 2026-06-13
Audit multi-dimensions (4 axes : logique safety, concurrence FreeRTOS/I2C, sûreté mémoire, sécurité BLE/cloud) du firmware ESP-IDF du BMU. Méthodo : skill `bmu-firmware-safety-audit`. Statuts de remédiation : skill `tracked-remediation`.
Légende statut : ✅ corrigé · doing · ⬜ à faire · 🧪 décision politique (validation requise) · ❌ écarté (faux positif)
## 🔴 CRITICAL
| # | Finding | Fichier:ligne | Statut |
|---|---------|---------------|--------|
| C1 | Sur-tension ne déclenche jamais ERROR/LOCKED → reconnexion en boucle d'une batterie défaillante | bmu_protection.cpp:231 | ✅ sur-tension → ERROR (`v_mv > MAX`) |
| C2 | Fail-safe topologie cosmétique : la tâche rallume malgré `all_off()` ; batteries sans canal TCA non coupables | bmu_protection.cpp:42, main.cpp:640 | ✅ gate `Nb_TCA×4≠Nb_INA` dans check_battery_ex |
| C3 | Write BLE R_int (0x0038) sans WRITE_ENC → action physique non authentifiée | bmu_ble_battery_svc.cpp:423 | ✅ `+ WRITE_ENC` |
| C4 | INA237 : sorties non initialisées sur échec lecture → donnée capteur fantôme | bmu_ina237.cpp:378 | ✅ init NAN en tête |
| C5 | INA237 bitbang : cast `(int16_t)` sur VBUS non signé → tension négative aberrante | bmu_ina237.cpp:528 | ✅ cast retiré |
## 🟠 HIGH
| # | Finding | Fichier:ligne | Statut |
|---|---------|---------------|--------|
| H1 | `publish_snapshot()` lit l'état sécurité SANS state_mutex (race avec hotplug) | bmu_protection.cpp:540 | ✅ copie sous state_mutex |
| H2 | `switch_battery()` (I2C + vTaskDelay) appelée en tenant state_mutex | bmu_protection.cpp:156,606 | ✅ commute hors mutex (health + balance) |
| H3 | Hotplug compacte tableaux/handles I2C partagés sans synchro → use-after-free | bmu_i2c_hotplug.cpp:131 | ⬜ **refactor dédié (validation HW requise)** |
| H4 | Topologie mutée par 2 tâches ; `topology_ok`/`nb_tca` écrits sans mutex | bmu_i2c_hotplug.cpp:189,286,359 | ⬜ **refactor dédié (validation HW requise)** |
| H5 | `web_switch` contourne le lock à 5 (pas de check nb_switch avant ON) | bmu_protection.cpp:435 | ✅ refus si nb_switch>MAX |
| H6 | Balancer rallume une batterie en défaut sans revalidation | bmu_protection.cpp:601 | ✅ guard ON (lock+plage) |
| H7 | Sur-courant : fenêtre 1020 A réversible (facteur 2.0 large) | Kconfig + :229 | ✅ facteur 2.0→1.4 (défaut sûr, à valider) |
| H8 | TCA9535 : cache OUTPUT mis à jour AVANT confirmation I2C | bmu_tca9535.cpp:240 | ✅ cache après succès I2C |
| H9 | Cloud non-TLS : token Influx en clair (HTTP), MQTT clair, VRM TLS sans vérif cert | bmu_influx/mqtt/vrm | ✅ VRM vérifie le cert (bundle CA). Influx/MQTT restent clairs **par design** (LAN/Tailscale, cf. CLAUDE.md) — durcissement TLS = option future si exposition publique |
| H10 | Clé Victron BLE par défaut commitée | bmu_ble_victron/Kconfig:9 | ✅ défaut vidé |
| H11 | Retours ignorés : publish MQTT/VRM, fputc/fclose store offline (corruption replay) | bmu_vrm/mqtt, bmu_influx_store.cpp:127 | ✅ fputc/fclose + VRM publish |
| H12 | Priorités tâches doc(5/4) ⇄ code(protection=8/balancer=3) | main.cpp:606,646 | ⬜ Vague 4 (dette) |
| H13 | Double source de vérité `nb_ina` + fallback non protégé | main.cpp:128 | ⬜ Vague 2 |
## 🟡 MEDIUM / 🟢 LOW (extraits)
- Injection line-protocol/MQTT via device name modifiable BLE (`device=%s` non échappé) — `main.cpp:264` ✅ device name restreint à `[A-Za-z0-9_-]` à la source
- Pairing : `min_key_size=0`→16 ✅. Just Works + re-pairing auto-accepté — ⬜ requiert un design de confirmation UI (écran LVGL), différé
- NUL terminator manquant sur défauts Kconfig (device/wifi/mqtt) — `bmu_config.cpp:130`
- `fgets(512)` tronque lignes longues au replay — `bmu_influx_store.cpp:144` ✅ ligne tronquée drainée+ignorée
- `esp_timer_create()` non vérifié (×5) — ✅ retour vérifié (battery/system/control/victron_gatt/victron_scan)
- Ah comptés sur batteries OFF — `bmu_battery_manager.cpp:34` ⬜ (mineur, non bloquant)
- Clamp `BMU_MAX_BATTERIES` manquant sur GATT rint/soh — ✅ clamp ajouté
## 🧹 Dette technique / incohérences
- Code mort non-mutexé : `find_fleet_max_mv()`, `bmu_influx_write_battery()` ✅ supprimés (+ décls header)
- Doc ⇄ code : priorités tâches ✅ CLAUDE.md aligné (protection=8…) ; commentaire bus-recover bitbang obsolète ⬜ (cosmétique)
- Patterns incohérents : cache TCA ✅ (H8) ; NUL terminator ✅ (M2) ; clamp GATT ✅. Reste : `set_led` vs `switch` ✅ aligné par H8.
## ❌ Faux positifs écartés (vérifiés contre le code)
- influx.cpp:203 « overflow memcpy après flush échoué » → return avant le memcpy.
- influx_store « fwrite non vérifié » → l'est (comparé à len).
- ble_victron_scan « buffer over-read déchiffrement » (×2) → lectures bornées (≥15, raw[10]).
- ble_gatt arrays sans terminateur → terminateurs présents dans toutes les branches.
## Politique safety à valider (🧪)
Valeurs par défaut sûres proposées (à confirmer en revue) :
- **Sur-tension** → ERROR (fait, C1). Option future : ERROR répété N fois → LOCKED.
- **Sur-courant** : réduire `BMU_OVERCURRENT_FACTOR` 2.0 → ~1.3-1.5 (coupure ferme plus tôt).
- **Pairing BLE** : `min_key_size=16` + refuser re-pairing auto (confirmation écran).
View File
+39
View File
@@ -0,0 +1,39 @@
# Project Context Snapshot
- generated_at_utc: 2026-03-30T11:08:18Z
- branch: main
- head: 9193987
- origin_main: 9193987
## Git Status
```
## main
M .github/workflows/sim-host-tests.yml
M README.md
D docs/AGENT_TASK_ASSIGNMENT.md
D docs/ARCHITECTURE_DIAGRAMS.md
D docs/FEATURE_MAP.md
D docs/GOVERNANCE_INTEGRATION.md
D docs/PRODUCT_GATES_VARIANTS.md
D docs/PROJECT_CONTEXT_SNAPSHOT.md
M plan/process-cicd-environments-1.md
M plan/refactor-safety-core-web-remote-1.md
M platformio.ini
M scripts/ci/run_qa_env.sh
D scripts/project/update_project_context.sh
?? docs/context/
?? docs/governance/
?? include/
?? scripts/project/update-context-snapshot.sh
```
## Plans
- plan/process-cicd-environments-1.md
- plan/refactor-safety-core-web-remote-1.md
## Governance Docs
- docs/governance/integration.md
- docs/governance/architecture-diagrams.md
- docs/governance/feature-map.md
- docs/governance/agent-task-assignment.md
- docs/governance/product-gates-variants.md

Some files were not shown because too many files have changed in this diff Show More