FiWiManager/reflex/inrush.reflex

69 lines
2.5 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Current inrush observer for USBHub3+ — runs on the hub (Reflex), not the host.
//
// Sampling uses Timer[0] in repeat mode (setExpiration in microseconds), not every_1ms(),
// so the hub schedules ticks on the RTOS timer — not the host sleep loop.
//
// Default sample grid: **100 µs** per tick (10 kHz). Time axis:
// elapsed_us ≈ ticks * sample_period_us
// time above threshold ≈ above_threshold_ticks * sample_period_us
//
// Compile: fiwi.py reflex compile reflex/inrush.reflex reflex/inrush.map
// or: ./scripts/compile_inrush_reflex.sh
// Load: ReflexLoader / HubTool (.map into module store).
// Readout: tests/check_inrush.py (default on-hub: re-arm slot, wait, scratchpad via pointer).
// Arm: map / mapEnable — zeros scratchpad, starts Timer[0] at 100 µs per tick.
// Stop: mapDisable — setExpiration(0) on Timer[0].
//
// Tune: port index in getPortCurrent(0) — 0..7 downstream on USBHub3+.
// Tune: 100 in mapEnable setExpiration + sample_period_us (keep them equal).
// Tune: threshold 50000 = 50 mA in µA.
//
// If arc rejects ``reflex hub.timer[0].expiration()``, try ``reflex timer[0].expiration()``
// (depends on your BrainStem / arc version).
#include <aUSBHub3p.reflex>
aUSBHub3p hub;
// Timer repeat period: 100 µs per sample (10 kHz). Change both setExpiration(...) and
// sample_period_us assignment in mapEnable if you retune. (BrainStem allows ~1 µss range;
// very fast rates increase CPU load; hub current readings may not update faster than hardware.)
// Scratchpad (host reads via pointer / HubTool)
// peak_ua — max port current since mapEnable (microamps)
// ticks — timer expiration count since mapEnable
// above_threshold_ticks — ticks where current > 50 mA
// sample_period_us — µs per tick (same as SAMPLE_PERIOD_US; for host scaling)
pad[0:4] signed int peak_ua;
pad[4:4] signed int ticks;
pad[8:4] signed int above_threshold_ticks;
pad[12:4] signed int sample_period_us;
reflex hub.timer[0].expiration() {
signed int current = hub.usb.getPortCurrent(0);
ticks++;
if (current > peak_ua) {
peak_ua = current;
}
if (current > 50000) {
above_threshold_ticks++;
}
}
reflex mapEnable() {
hub.timer[0].setExpiration(0);
peak_ua = 0;
ticks = 0;
above_threshold_ticks = 0;
sample_period_us = 100;
hub.timer[0].setMode(1);
hub.timer[0].setExpiration(100);
}
reflex mapDisable() {
hub.timer[0].setExpiration(0);
}