Skip to content

feat: support Hardware AAD feature and improve power consumption - #9048

Merged
mdmohsin7 merged 42 commits into
BasedHardware:mainfrom
TuEmb:hardware_aad
Jul 12, 2026
Merged

mdmohsin7 merged 42 commits into
BasedHardware:mainfrom
TuEmb:hardware_aad

Conversation

@TuEmb

@TuEmb TuEmb commented Jul 5, 2026 •

Copy link
Copy Markdown
Collaborator

This PR is to:

1. Hardware AAD (new t5838_aad.c/.h, mic.c; removes aad.c/aad.h)

On silence, the T5838 is clocked into its built-in AAD sleep (mic off, ~µA) and wakes on the WAKE pin (P1.02). Owned inside mic.c since it shares the PDM peripheral.
CLK + THSEL parked high during sleep so they don't fight the TXS0104 level-shifter's pull-ups (~1 mA leak).

2. Offline / idle power (sd_card.c, mic.c, main.c)

SD-NAND powered off during offline AAD sleep, remounted on wake (writes buffered across the remount); CS parked low; full bus disconnect at shutdown.
Status LED off during offline sleep.
Deep-sleep (system-off): mic_off() now cuts PDM_EN so mic + shifter fully power down → ~25 µA (IMU + OTA flash stay functional).

Review in cubic

TuEmb and others added 10 commits July 5, 2026 01:21
…ge into unpowered card

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@TuEmb
TuEmb marked this pull request as draft July 5, 2026 06:31
cubic-dev-ai[bot]

This comment was marked as outdated.

TuEmb and others added 15 commits July 5, 2026 13:46
…unt SD at connect start

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ad can drain (fixes no-log sync stall)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@TuEmb

TuEmb commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Jul 5, 2026

Copy link
Copy Markdown

@cubic-dev-ai review

@TuEmb I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 16 files

Confidence score: 5/5

  • Safe to merge after the addressed issues were fixed.

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread omi/firmware/omi/src/mic.c Resolved
@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge docs-accuracy Documentation or committed reports need accuracy fixes needs-tests PR introduces logic that should be covered by tests labels Jul 5, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @TuEmb — this is a substantial, well-scoped power-consumption improvement for the firmware (hardware AAD sleep on the T5838, SD power cycling, low-power BLE params). The power-state diagrams you attached are genuinely helpful for review. The overall architecture (AAD owned in mic.c since it shares the PDM peripheral; SD power tied to AAD/connect state) looks sound.

Because this changes power, mic bring-up, SD persistence, and BLE connection behavior across 16 files (~1670 lines), it needs human maintainer + on-device validation before merge — I've labeled it accordingly and will not approve it automatically. A few concrete things that came up in review:

SD data durability during power cycling (most important)

  • sd_request_power(false) uses k_msgq_put(..., K_NO_WAIT) and discards the return value. If the priority queue is full, the REQ_POWER_OFF is silently dropped and the SD stays powered (and sd_enabled is optimistically set true on the power-on path even if the put fails). Worth a retry/fallback like the other prio-queue callers.
  • REQ_POWER_OFF unmounts without first draining pending writes from sd_msgq, so audio queued just before idle can be lost. The shutdown path (app_sd_off) drains first — matching that here would make the idle path durable.
  • The wake-race fallback in REQ_WRITE_DATA drains sd_prio_msgq to find a REQ_POWER_ON; if that mount fails it can also drop unrelated priority requests (sync/read). Mounting directly and bailing on failure keeps those intact.

New t5838_aad.c driver

  • t5838_aad_init() returns success even if gpio_pin_configure_dt() for pdm_en/thsel fails, and doesn't gpio_is_ready_dt() the specs first. Propagating those errors would prevent a false-ready state that fails later during bit-bang. (You already do this correctly for the WAKE pin in aad_hw_start().)
  • The t5838_aad_init() call in mic_start() is now redundant with the one inside aad_hw_start() — your own follow-up commit message says you deduped it, so worth confirming the final diff only initializes once.

Minor

  • AAD_HARDWARE.md is referenced in a mic.c comment but isn't in this PR — either add the doc or drop the reference so it's not a dangling pointer.
  • imu.c shows ~492 changed lines but is entirely whitespace (tabs→spaces, no logic change). Harmless, but it inflates the diff and makes review/git blame noisier — consider reverting that file to keep the diff focused on the AAD/power work.
  • A disconnected device that is charging will turn its status LED off once the mic enters AAD sleep (main.c), hiding the charging indication. Excluding is_charging from that shortcut would keep charging feedback visible.

Really nice work on the power-state design overall. Once the SD-durability path and the driver error handling are tightened up, this should be in good shape for a maintainer to validate on hardware.

@Git-on-my-level

Copy link
Copy Markdown
Member

Following up on the earlier review with a few more targeted notes after a full pass over the final diff.

SD data durability during power cycling (highest impact)

  • REQ_POWER_OFF unmounts without first draining pending writes from sd_msgq, so audio queued just before idle can be lost. The full-shutdown path (app_sd_off) drains first — matching that here would make the idle power path durable too.
  • sd_request_power() uses k_msgq_put(..., K_NO_WAIT) and discards the return value. If the prio queue is full the REQ_POWER_OFF/REQ_POWER_ON is silently dropped (and sd_enabled is set true optimistically on the power-on path even if the put fails). A retry/fallback like the other prio-queue callers would be safer.
  • The wake-race fallback in REQ_WRITE_DATA drains sd_prio_msgq looking for a REQ_POWER_ON; if that mount fails it can also drop unrelated priority requests (sync/read). Mounting directly and bailing on failure keeps those intact.

New t5838_aad.c driver

  • t5838_aad_init() doesn't gpio_is_ready_dt() the pdm_en/thsel specs and ignores the return of gpio_pin_configure_dt() for them, so it can report success while the rail/config silently failed — later bit-bang calls would then be undefined. Propagating those errors (as you already do for the WAKE pin in aad_hw_start()) would prevent a false-ready state.
  • The t5838_aad_init() call in mic_start() looks redundant with the one referenced inside aad_hw_start() — worth confirming the final diff initializes exactly once.

Idle-thread wakeups

  • aad_thread_fn does k_sem_take(..., K_MSEC(100)), waking the thread every 100 ms even when idle — on a power-optimization PR that's a self-inflicted CPU wakeup. Switch to a blocking wait (or a much longer timeout) so the AAD thread stays asleep until the WAKE ISR / silence timer actually signals.

Minor

  • mic.c references AAD_HARDWARE.md in a comment but that file isn't in this PR — either add it or drop the reference so it isn't a dangling pointer.
  • imu.c is ~492 changed lines of pure whitespace (tabs→spaces, no logic change). Harmless, but it inflates the diff and makes git blame noisier — reverting it would keep the diff focused on the AAD/power work.
  • No tests cover the silence→sleep→WAKE→resume sequence or the SD power-cycle/remount path; needs-tests is warranted.

Still needs human maintainer review + on-device validation before merge (power, mic bring-up, SD persistence, and BLE params all change at once). The power-state design itself reads well.

@TuEmb

TuEmb commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

battery drops ~32% after 13 hours of continuous use.
image

@Git-on-my-level

Copy link
Copy Markdown
Member

Third-pass automated review. The power-state architecture (hardware AAD owned in mic.c, SD power tied to AAD/connect state, WAKE-pin ISR resume) reads well and the battery data is encouraging. A few items from the earlier passes are still open in the final diff:

Still open

  1. SD durability — sd_request_power() still discards the k_msgq_put(..., K_NO_WAIT) return; if the prio queue is full the REQ_POWER_OFF/ON is silently dropped (and sd_enabled is optimistically set true on the power-on path). REQ_POWER_OFF still unmounts without first draining pending writes from sd_msgq — the full-shutdown path (app_sd_off) drains first, and matching that here would make the idle path durable too.
  2. t5838_aad_init error propagation — gpio_pin_configure_dt() for pdm_en/thsel still doesn't check the return value or gpio_is_ready_dt() the specs. If the rail/config silently fails, later bit-bang calls would be undefined. (You already do this correctly for the WAKE pin in aad_hw_start().)
  3. AAD thread 100ms polling — k_sem_take(&aad_sem, K_MSEC(100)) wakes the thread every 100ms even when idle. On a power-optimization PR that's a self-inflicted CPU wakeup — a blocking K_FOREVER (or much longer timeout) would let it stay asleep until the WAKE ISR / silence timer actually signals.
  4. Dangling doc reference — mic.c:67 still says "See AAD_HARDWARE.md" but that file was deleted from the PR. Drop the reference so it isn't a dangling pointer.
  5. imu.c whitespace — 492 changed lines of tabs→spaces, no logic change. Reverting it would shrink the diff and keep git blame clean.

Resolved since last pass (good)

  • Init dedup confirmed: aad_hw_start() no longer re-inits, mic_start() calls t5838_aad_init() once.
  • Debug/test configs (AAD_TEST_MODE, FAKE_RTC) cleaned out of Kconfig/omi.conf.
  • mic_off() now properly cuts PDM_EN and aborts the AAD thread.
  • BLE low-power conn params and LED-off-during-AAD were iterated on and ultimately reverted — the final state is simpler.

No security concerns — no auth/secrets/data-handling/CI/dependency changes. The FAKE2C protocol and register writes are properly attributed to the Irnas/Brilliant-Labs driver.

Still needs human maintainer review + on-device validation before merge (power, mic bring-up, SD persistence, and sync path all change at once). Once the SD-durability path and driver error handling are tightened, this should be in good shape.

@Git-on-my-level

Copy link
Copy Markdown
Member

Fourth-pass automated review — the earlier items are all addressed in the current diff. Thank you for working through them.

Previously flagged — now resolved

  1. SD durability — sd_request_power() now checks the k_msgq_put return and logs/returns on failure instead of silently dropping. REQ_POWER_OFF now calls drain_pending_write_queue_for_shutdown() before unmounting, matching the shutdown path. Good.
  2. t5838_aad_init error propagation — now does gpio_is_ready_dt() on pdm_en/thsel and propagates gpio_pin_configure_dt() failures. The redundancy with aad_hw_start() is also resolved (aad_hw_start() no longer re-inits; the comment makes it clear init ran in mic_start()).
  3. AAD thread polling — k_sem_take(&aad_sem, K_FOREVER) with no timeout. Clean.
  4. Dangling AAD_HARDWARE.md reference — gone from mic.c.

The wake-race fallback in REQ_WRITE_DATA also changed to mount directly instead of draining sd_prio_msgq (which avoids dropping unrelated sync/read requests) — that was a good fix.

Architecture assessment

The power-state design is cohesive and sound: hardware AAD owned in mic.c (shares the PDM peripheral), SD power tied to AAD/connect state, WAKE-pin ISR resume, cooperative mic_pause()/mic_resume() to avoid interrupting in-flight dmic_read, shared BLE TX-throttle slot for battery/sync coexistence. The battery data (32% after 13h) is encouraging. The PR is well-scoped around one outcome (firmware power reduction) — not something to split.

Why this still needs human maintainer review before merge

  • No firmware CI build — the "Build" check is skipped for this path, so compilation and the nRF5340 build are only verified locally. On-device validation (power measurements, SD remount reliability across many cycles, BLE stability under AAD sleep) is not something automated review can certify.
  • SD power cycling is inherently data-risky — the mount/unmount/remount path is much improved over the earlier iterations, but repeated SD power cycles over a device lifetime are exactly where data-loss bugs surface. The sd_request_power(true) path still optimistically sets sd_enabled = true before the remount completes (writes buffer, which is reasonable, but the remount can still fail — REQ_POWER_ON logs the error but doesn't reset sd_enabled).
  • nrf_pdm_disable() bypasses the Zephyr DMIC driver — calling the HAL directly while the DMIC API thinks it owns the peripheral is a pragmatic root-cause fix (well-documented in the analysis), but it's the kind of low-level coupling that a firmware maintainer should sign off on.

These are judgment calls, not blockers I can resolve from a diff. Leaving needs-maintainer-review and needs-tests in place. This is a strong contribution — the remaining items are about validation, not the approach.

@TuEmb

TuEmb commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

Power profile:

1. Deepsleep Mode
image

2. Offline Silent Mode
image

3. Offline Recording Mode
image

4. Online Audio Streaming Mode
image

5. Online Audio Streaming + Sync Mode
image

6. Online Silent Mode
image

@Git-on-my-level

Copy link
Copy Markdown
Member

Fifth-pass automated review. The power-state design remains cohesive and all four earlier items (SD durability, t5838_aad_init error propagation, AAD thread K_FOREVER, dangling doc ref) are confirmed resolved in the current diff.

One new docs-accuracy item:

  • t5838_aad.h — the doc comment for t5838_aad_enter() says "Leaves PDMCLK idle low afterwards so the peripheral can reclaim it on resume." The implementation actually parks CLK HIGH (clk_set(1)) — which is correct and well-justified (avoids fighting the TXS0104 level-shifter pull-ups, ~1 mA leak), but the header text is stale from an earlier low-parking iteration. Updating the doc to match the code would help future readers.

Remaining judgment calls (unchanged from pass 4, not code defects):

  • No firmware CI build for this path — compilation and the nRF5340 build are only locally verified.
  • SD power cycling over a device lifetime is where remount/data-loss bugs surface — the path is much improved but needs on-device stress testing.
  • nrf_pdm_disable() bypasses the Zephyr DMIC driver HAL — a pragmatic root-cause fix that a firmware maintainer should sign off on.
  • No tests cover the silence→sleep→WAKE→resume sequence or the SD remount path.

No security concerns. Needs human maintainer review + on-device validation before merge.

@mdmohsin7
mdmohsin7 merged commit 22b1b46 into BasedHardware:main Jul 12, 2026
19 checks passed
Git-on-my-level added a commit that referenced this pull request Jul 13, 2026
## Summary

Review-swarm findings from a 10-agent code review of the last 2 days of
merged PRs (62 PRs / 1072 files). Seven isolated bugs were found and
fixed; no behavior change beyond the fixes. Each commit is independent
and reviewable on its own.

### High-severity correctness
- **`fix(chat)`: tz-aware `created_at` sort sentinel** —
`get_chat_files_desc` (>30 file_ids merge path) used naive
`datetime.min`, which TypeError-compares against tz-aware Firestore
dates and 500s. Last instance of the #9571 failure class; all four
`datetime.min` sort sentinels in `backend/` are now tz-aware.
- **`fix(agent-control)`: derive consent for `request_permission` in
PTT/voice mode** — both voice paths never built a
`PermissionRequestAuthorization`, so the consent gate always silently
denied `request_permission` while the system prompt told the model to
call it. The feature was non-functional in voice mode. Fixed by deriving
authorization from the spoken turn transcript (mirrors the text path;
fail-closed).

### Medium
- **`fix(translation)`: NLLB native-language-code case resolution** —
`_resolve_nllb_code` lowercased input before checking the mixed-case
`NLLB_TO_BCP47` keys, making the native-code passthrough dead. README
documents `eng_Latn` as valid input.
- **`fix(nllb)`: autoscale on active requests instead of CPU-only** —
the NLLB GPU HPA scaled only on CPU, which stays low during GPU
inference, so it never scaled past minReplicas. Added a
concurrency-based External metric on the existing `nllb_active_requests`
gauge (`requestsPerPod: 4` in prod), mirroring the parakeet pattern, and
wired the adapter rule into the cluster-wide prometheus-adapter
(dev+prod). CPU retained as a secondary floor.
- **`fix(firmware)`: propagate `t5838_aad_init` failure from
`mic_start`** — the init powers the 1.8V mic rail; on failure it only
logged and returned 0 (false-ready at the caller: mic "starts" but
captures silence). `main()` already handles a nonzero `mic_start` return
via `error_microphone()`, so propagate the failure. Closes the #9048
false-ready goal at the caller level.

### Low / defense-in-depth
- **`fix(tasks)`: re-add defensive newest-first sort for suggested
candidates** — #9591 removed the client-side sort, leaving the top-5
slice dependent on backend return order with no test. Re-added the sort
as defense-in-depth.
- **`fix(ci)`: drop duplicate isinstance-ratchet exempt entry** — two
commits registered the same script in the manifest `exempt:` list.

### Desktop changelog
Fragments added for the two user-visible desktop fixes (PTT permission
consent, suggested-tasks ordering).

## Product invariants affected
- INV-CHAT-1

## Verification
- Each fix reviewed hunk-by-hunk by a dedicated reviewer; the chat.py
fix was cross-confirmed by two reviewers (sync/memory found it, API
owner fixed it).
- Pre-push manifest checks pass (check-manifest-contract, diff-hygiene,
architecture-guardrails, product-invariants with this citation,
desktop-changelog-entry, brand-ui INV-UI-1, backend-import-purity,
backend-async-blockers).
- No new tests added in this PR; the underlying behavior is covered by
the existing suite for each touched area. The tz-sentinel and consent
fixes are the kind of regression a follow-up test should pin (noted
below).

## Notes / follow-ups
- The NLLB HPA active-requests metric requires the documented
prometheus-adapter helm upgrade (same manual step parakeet needs) before
it takes effect in-cluster.
- Reported-but-not-fixed concerns from the review (out of scope here):
NLLB model re-downloaded every pod restart (emptyDir), gateway 13-label
metrics cardinality monitoring, a static guard to prevent recurrence of
the naive-`datetime.min` sort class.

🤖 Generated with Claude Code


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/9600?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Jul 13, 2026
…ew swarm

t5838_aad_init() powers the 1.8V mic rail; if it fails the PDM mic is
unpowered and captures silence, but mic_start() only logged and returned
0 (false-ready at the caller level). main() already handles a nonzero
mic_start return via error_microphone(), so propagate the failure — the
device reports a mic fault instead of booting into a silent-capture
state. Closes the false-ready class BasedHardware#9048 targeted at the caller level;
aad_hw_start() remains non-fatal (mic already running by then).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs-accuracy Documentation or committed reports need accuracy fixes needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants