Compare commits
22 Commits
5c9aa62cda
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 4aa369ca73 | |||
| a7082c9022 | |||
| 14e9c96f55 | |||
| 0fc38a5e1b | |||
| 8ab07adfc6 | |||
| 2abc226652 | |||
| 5ab13a525a | |||
| 502ea786b0 | |||
| 1486fe13f2 | |||
| 395fd9b839 | |||
| 87fc2a3574 | |||
| 5f928d7c92 | |||
| 532ba4f719 | |||
| 19b96c9b21 | |||
| 94f38975bd | |||
| c325336508 | |||
| 953edd4065 | |||
| 8e9a3712ac | |||
| cb433f76c9 | |||
| 5c36aa041e | |||
| dcc50150b8 | |||
| 8f63d7c0b5 |
@@ -6,3 +6,4 @@
|
|||||||
*.vscode
|
*.vscode
|
||||||
web/version.js
|
web/version.js
|
||||||
samples/
|
samples/
|
||||||
|
firmware_dfu.zip
|
||||||
|
|||||||
@@ -5,17 +5,17 @@ A BLE HID mouse that uses the onboard IMU of a **Seeed XIAO nRF52840 Sense** to
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **6-DoF gyro + accelerometer** via LSM6DS3 with complementary filter
|
- **6-DoF gyro + accelerometer** via LSM6DS3 with complementary filter
|
||||||
- **Hardware tap detection** — single tap = left click, double tap = right click
|
- **Hardware tap detection** - single tap = left click, double tap = right click
|
||||||
- **BLE HID mouse** — works natively on Windows, macOS, Linux, Android, iOS
|
- **BLE HID mouse** - works natively on Windows, macOS, Linux, Android, iOS
|
||||||
- **BLE Battery Service** — charge level visible in OS Bluetooth settings
|
- **BLE Battery Service** - charge level visible in OS Bluetooth settings
|
||||||
- **Web config UI** (`web/index.html`) — configure over BLE from any Chrome/Edge browser, no app install
|
- **Web config UI** (`web/index.html`) - configure over BLE from any Chrome/Edge browser, no app install
|
||||||
- **Flash persistence** — config survives power cycles (LittleFS)
|
- **Flash persistence** - config survives power cycles (LittleFS)
|
||||||
- **Live IMU stream** — 20 Hz gyro/accel data streamed to the web UI visualiser
|
- **Live IMU stream** - 20 Hz gyro/accel data streamed to the web UI visualiser
|
||||||
- **Live telemetry** — temperature, uptime, click counts, gyro bias RMS, recal count
|
- **Live telemetry** - temperature, uptime, click counts, gyro bias RMS, recal count
|
||||||
- **Temperature compensation** — gyro drift correction by Δ temperature since last calibration
|
- **Temperature compensation** - gyro drift correction by Δ temperature since last calibration
|
||||||
- **Auto-recalibration** — recalibrates automatically after 5 minutes of idle
|
- **Auto-recalibration** - recalibrates automatically after 5 minutes of idle
|
||||||
- **Configurable charge rate** — OFF / 50 mA slow / 100 mA fast via BQ25100 HICHG pin
|
- **Configurable charge rate** - OFF / 50 mA slow / 100 mA fast via BQ25100 HICHG pin
|
||||||
- **Boot-loop detection** — 3 rapid reboots trigger safe mode (config service disabled, flash wiped)
|
- **Boot-loop detection** - 3 rapid reboots trigger safe mode (config service disabled, flash wiped)
|
||||||
|
|
||||||
## Hardware
|
## Hardware
|
||||||
|
|
||||||
@@ -26,22 +26,22 @@ A BLE HID mouse that uses the onboard IMU of a **Seeed XIAO nRF52840 Sense** to
|
|||||||
|
|
||||||
## LED Status
|
## LED Status
|
||||||
|
|
||||||
The XIAO has three user LEDs (active LOW — HIGH = off, LOW = on):
|
The XIAO has three user LEDs (active LOW - HIGH = off, LOW = on):
|
||||||
|
|
||||||
| LED | Pattern | Meaning |
|
| LED | Pattern | Meaning |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Blue | Single pulse every 10 s | BLE connected (heartbeat) |
|
| Blue | Single pulse every 10 s | BLE connected (heartbeat) |
|
||||||
| Green | Single pulse every 10 s | Advertising / not connected (heartbeat) |
|
| Green | Single pulse every 10 s | Advertising / not connected (heartbeat) |
|
||||||
| Green | Rapid flutter (~10 Hz) | Gyro calibration in progress |
|
| Green | Rapid flutter (~10 Hz) | Gyro calibration in progress |
|
||||||
| Red | Fast blink (continuous) | IMU init failed — hardware fault |
|
| Red | Fast blink (continuous) | IMU init failed - hardware fault |
|
||||||
| Red | 3 slow blinks on boot | Boot-loop detected — entered safe mode |
|
| Red | 3 slow blinks on boot | Boot-loop detected - entered safe mode |
|
||||||
| Red | 6 rapid blinks | Battery critically low (< 3.10 V) |
|
| Red | 6 rapid blinks | Battery critically low (< 3.10 V) |
|
||||||
|
|
||||||
> **Blue** = BLE-related state. **Green** = device activity. **Red** = fault only.
|
> **Blue** = BLE-related state. **Green** = device activity. **Red** = fault only.
|
||||||
|
|
||||||
## Web Config UI
|
## Web Config UI
|
||||||
|
|
||||||
Open `web/index.html` in Chrome or Edge (desktop). Requires Web Bluetooth — enable it at `chrome://flags/#enable-web-bluetooth` on Linux.
|
Open `web/index.html` in Chrome or Edge (desktop). Requires Web Bluetooth - enable it at `chrome://flags/#enable-web-bluetooth` on Linux.
|
||||||
|
|
||||||
**Configurable parameters:**
|
**Configurable parameters:**
|
||||||
|
|
||||||
@@ -56,8 +56,8 @@ Open `web/index.html` in Chrome or Edge (desktop). Requires Web Bluetooth — en
|
|||||||
|
|
||||||
**Commands:**
|
**Commands:**
|
||||||
|
|
||||||
- **Calibrate Gyro** — recalculates bias offset; hold the device still on a flat surface for ~1 s
|
- **Calibrate Gyro** - recalculates bias offset; hold the device still on a flat surface for ~1 s
|
||||||
- **Factory Reset** — wipes flash config, restores defaults
|
- **Factory Reset** - wipes flash config, restores defaults
|
||||||
|
|
||||||
## Building
|
## Building
|
||||||
|
|
||||||
|
|||||||
+152
-246
@@ -1,290 +1,196 @@
|
|||||||
# IMU Pointer Enclosure
|
"""
|
||||||
|
IMU Pointer Enclosure — v11.7 (Slimmed Corners & Rounded USB-C)
|
||||||
|
"""
|
||||||
|
|
||||||
import FreeCAD as App
|
import FreeCAD as App
|
||||||
import FreeCADGui as Gui
|
import FreeCADGui as Gui
|
||||||
import Part
|
import Part
|
||||||
from FreeCAD import Base
|
from FreeCAD import Base
|
||||||
|
|
||||||
doc = App.newDocument("pointer")
|
doc = App.newDocument("pointer_v11_7")
|
||||||
|
|
||||||
# Global dimensions
|
# ─── DIMENSIONS ───────────────────────────────────────────────────────────────
|
||||||
L = 115.0
|
L, W, H = 115.0, 36.0, 22.0
|
||||||
W = 36.0
|
|
||||||
H = 20.0
|
|
||||||
WALL = 3.5
|
WALL = 3.5
|
||||||
CR = 3.0
|
CR, CR_I = 8.0, 4.5
|
||||||
TOL = 0.25
|
TOL = 0.25
|
||||||
|
EDGE_FILLET = 3.0
|
||||||
|
|
||||||
# Rail and lid
|
USBC_W, USBC_H, USBC_Z = 12.0, 7.0, 5.0
|
||||||
RAIL_H = 4.5
|
SPLIT_Z = USBC_Z + USBC_H + 2.5
|
||||||
RAIL_D = 2.0
|
|
||||||
LIP_H = 2.0
|
|
||||||
LIP_OVER = 1.5
|
|
||||||
LIP_EMBED = 0.2
|
|
||||||
|
|
||||||
LID_H = RAIL_H - LIP_H - TOL - 0.55
|
# MICRO-DETENT Snap Logic
|
||||||
|
TONGUE_H, TONGUE_T = 2.5, 2.0
|
||||||
|
GROOVE_H, GROOVE_T = TONGUE_H + TOL, TONGUE_T + TOL
|
||||||
|
RIDGE_W = 12.0
|
||||||
|
RIDGE_H = 1.2
|
||||||
|
RIDGE_PROUD = 1.0 # Snap ridge protrusion
|
||||||
|
RIDGE_Z_OFF = (TONGUE_H - RIDGE_H) / 2.0
|
||||||
|
|
||||||
# Board dimensions
|
# ─── IMU BOARD (+1mm Spacing & Slim Corners) ──────────────────────────────────
|
||||||
PCB_T = 1.0
|
PCB_T, BRD_L, BRD_W = 3.0, 22.6, 19.6
|
||||||
BRD_L = 21.0
|
BRD_X, BRD_Y = WALL, (W - BRD_W) / 2.0
|
||||||
BRD_W = 17.5
|
PLATFORM_H, MIC_EXTRA = 1.5, 2.0
|
||||||
BRD_X = WALL
|
MIC_PCB_T = 2.5 # Thicker PCB section (MEMS mic), rounded up from 2.2
|
||||||
BRD_Y = (W - BRD_W) / 2
|
BUMP_PROUD = 0.3 # Press-fit nub protrusion into board cavity
|
||||||
|
BUMP_R = 0.6 # Nub radius (half-sphere)
|
||||||
PLATFORM_H = 0.5
|
|
||||||
BRD_Z = WALL + PLATFORM_H
|
BRD_Z = WALL + PLATFORM_H
|
||||||
|
|
||||||
# Clip arms
|
# ─── BUTTON & BATTERY ─────────────────────────────────────────────────────────
|
||||||
ARM_LEN = 5.0
|
BAT_L, BAT_W, BAT_H = 50.0, 12.0, 12.0
|
||||||
ARM_THICK = 1.6
|
BAT_X, BAT_Y = BRD_X + BRD_L + 8.0 + 5.0, (W - BAT_W) / 2.0
|
||||||
ARM_H = BRD_Z + PCB_T + 0.8
|
|
||||||
CLIP_TOL = 0.35
|
|
||||||
|
|
||||||
# USB-C cutout
|
|
||||||
USBC_W = 11.0
|
|
||||||
USBC_H = 7.0
|
|
||||||
USBC_Z = 4.5
|
|
||||||
|
|
||||||
# Battery section
|
|
||||||
BAT_L = 50.0
|
|
||||||
BAT_W = 12.0
|
|
||||||
BAT_H = 12.0
|
|
||||||
BAT_X = BRD_X + BRD_L + 8.0
|
|
||||||
BAT_Y = (W - BAT_W) / 2
|
|
||||||
BAT_CLIP_Y = 8.0
|
BAT_CLIP_Y = 8.0
|
||||||
|
BTN_X, BTN_CY, BTN_HOLE_R = 28.0, W / 2.0, 10.0
|
||||||
|
CAP_SHAFT_R, CAP_SHAFT_H = 9.6, WALL + 1.0 # +1mm taller shaft so cap sits flush
|
||||||
|
CAP_RIM_R, CAP_RIM_H = 12.0, 1.5
|
||||||
|
CAP_CAVITY_R, CAP_CAVITY_H = 5.2, 2.5 # Hollow cavity replaces nubbin — clears button dome
|
||||||
|
BTN_DOME_R, BTN_DOME_SAG = 14.0, 0.6
|
||||||
|
|
||||||
# Circular notch
|
PCB_BOT_Z = SPLIT_Z + 1.5
|
||||||
NOTCH_R = (USBC_W + TOL) / 2
|
POST_H = BRD_Z + PCB_T + MIC_EXTRA + 3.0 - 4.0 # Lowered 4mm for button PCB + button thickness
|
||||||
NOTCH_DEPTH = WALL + 2.0
|
POST_OFFS_X, POST_OFFS_Y = 4.0, 11.0
|
||||||
|
LH_R, LH_X, LH_Y_OFFS = 1.5, L - WALL - 3.0, 4.0
|
||||||
|
BPCB_L, BPCB_W = 16.0, 16.0
|
||||||
|
|
||||||
|
# ─── HELPERS ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
# Circular notch helper
|
|
||||||
def circular_notch(face_x, cy, cz, r, depth):
|
|
||||||
circle = Part.makeCircle(r, Base.Vector(face_x, cy, cz), Base.Vector(1, 0, 0))
|
|
||||||
face = Part.Face(Part.Wire(circle))
|
|
||||||
return face.extrude(Base.Vector(-depth, 0, 0))
|
|
||||||
|
|
||||||
|
|
||||||
# Rounded box helper
|
|
||||||
def rbox(lx, ly, lz, ox=0, oy=0, oz=0, r=CR):
|
|
||||||
b = Part.makeBox(lx, ly, lz, Base.Vector(ox, oy, oz))
|
|
||||||
try:
|
|
||||||
vert = [e for e in b.Edges
|
|
||||||
if abs(e.Vertexes[0].Z - e.Vertexes[1].Z) > lz * 0.9]
|
|
||||||
if vert:
|
|
||||||
b = b.makeFillet(r, vert)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return b
|
|
||||||
|
|
||||||
|
|
||||||
# Simple box helper
|
|
||||||
def box(lx, ly, lz, ox=0, oy=0, oz=0):
|
def box(lx, ly, lz, ox=0, oy=0, oz=0):
|
||||||
return Part.makeBox(lx, ly, lz, Base.Vector(ox, oy, oz))
|
return Part.makeBox(lx, ly, lz, Base.Vector(ox, oy, oz))
|
||||||
|
|
||||||
|
def rbox(lx, ly, lz, ox=0, oy=0, oz=0, r=CR):
|
||||||
|
b = box(lx, ly, lz, ox, oy, oz)
|
||||||
|
try:
|
||||||
|
edges = [e for e in b.Edges if abs(e.Vertexes[0].X - e.Vertexes[1].X) < 1e-3 and abs(e.Vertexes[0].Y - e.Vertexes[1].Y) < 1e-3]
|
||||||
|
return b.makeFillet(r, edges) if edges else b
|
||||||
|
except: return b
|
||||||
|
|
||||||
# Rounded slot helper
|
def cyl(r, h, cx=0, cy=0, cz=0):
|
||||||
def rounded_slot(depth, w, h, ox, oy, oz, r=None):
|
return Part.makeCylinder(r, h, Base.Vector(cx, cy, cz))
|
||||||
if r is None:
|
|
||||||
r = h / 2.0
|
|
||||||
|
|
||||||
r = min(r, h / 2.0, w / 2.0)
|
def fillet_horiz(solid, r, z_test):
|
||||||
|
try:
|
||||||
|
edges = [e for e in solid.Edges if abs(e.Vertexes[0].Z - e.Vertexes[1].Z) < 0.2 and abs((e.Vertexes[0].Z + e.Vertexes[1].Z)/2 - z_test) < 1.5]
|
||||||
|
return solid.makeFillet(r, edges) if edges else solid
|
||||||
|
except: return solid
|
||||||
|
|
||||||
import math
|
def make_slim_corner(cx, cy, ix, iy):
|
||||||
|
pw = 0.8 # Much slimmer wall thickness (was 1.5/1.6)
|
||||||
|
sl = 4.0 # Slightly shorter side length
|
||||||
|
h = PLATFORM_H + PCB_T + 0.5
|
||||||
|
|
||||||
cy = oy + w / 2.0
|
x0, y0 = (cx if ix>0 else cx-sl), (cy if iy>0 else cy-pw)
|
||||||
cz = oz + h / 2.0
|
w1 = box(sl, pw, h, x0, y0, WALL)
|
||||||
hw = w / 2.0 - r
|
|
||||||
|
|
||||||
def pt(cx, cy_v, cz_v, angle_deg, radius):
|
x1, y1 = (cx if ix>0 else cx-pw), (cy if iy>0 else cy-sl)
|
||||||
a = math.radians(angle_deg)
|
w2 = box(pw, sl, h, x1, y1, WALL)
|
||||||
return Base.Vector(
|
|
||||||
cx,
|
|
||||||
cy_v + radius * math.cos(a),
|
|
||||||
cz_v + radius * math.sin(a)
|
|
||||||
)
|
|
||||||
|
|
||||||
l_start = pt(ox, cy - hw, cz, 270, r)
|
px, py = (cx if ix>0 else cx-sl), (cy if iy>0 else cy-sl)
|
||||||
l_mid = pt(ox, cy - hw, cz, 180, r)
|
plat = box(sl, sl, PLATFORM_H, px, py, WALL)
|
||||||
l_end = pt(ox, cy - hw, cz, 90, r)
|
|
||||||
arc_left = Part.Arc(l_start, l_mid, l_end).toShape()
|
|
||||||
|
|
||||||
line_top = Part.makeLine(
|
return plat.fuse(w1).fuse(w2)
|
||||||
l_end,
|
|
||||||
pt(ox, cy + hw, cz, 90, r)
|
|
||||||
)
|
|
||||||
|
|
||||||
r_start = pt(ox, cy + hw, cz, 90, r)
|
# ═════════════════════════════════════════════════════════════════════════════
|
||||||
r_mid = pt(ox, cy + hw, cz, 0, r)
|
# CONSTRUCTION
|
||||||
r_end = pt(ox, cy + hw, cz, 270, r)
|
# ═════════════════════════════════════════════════════════════════════════════
|
||||||
arc_right = Part.Arc(r_start, r_mid, r_end).toShape()
|
|
||||||
|
|
||||||
line_bot = Part.makeLine(r_end, l_start)
|
# BOTTOM SHELL
|
||||||
|
bot_shell = fillet_horiz(rbox(L, W, SPLIT_Z + TONGUE_H), EDGE_FILLET, 0.0)
|
||||||
|
bot_shell = bot_shell.cut(rbox(L-WALL*2, W-WALL*2, SPLIT_Z, WALL, WALL, WALL, r=CR_I))
|
||||||
|
bot_shell = bot_shell.cut(rbox(L-TONGUE_T*2, W-TONGUE_T*2, TONGUE_H+2, TONGUE_T, TONGUE_T, SPLIT_Z, r=CR-TONGUE_T))
|
||||||
|
|
||||||
wire = Part.Wire([arc_left, line_top, arc_right, line_bot])
|
# Internal Fusions (Using Slim L-bracket style for MCU)
|
||||||
face = Part.Face(wire)
|
for cx, cy, ix, iy in [(BRD_X, BRD_Y, 1, 1), (BRD_X+BRD_L, BRD_Y, -1, 1), (BRD_X, BRD_Y+BRD_W, 1, -1), (BRD_X+BRD_L, BRD_Y+BRD_W, -1, -1)]:
|
||||||
|
bot_shell = bot_shell.fuse(make_slim_corner(cx, cy, ix, iy))
|
||||||
|
|
||||||
return face.extrude(Base.Vector(depth, 0, 0))
|
# Press-fit nubs — half-sphere on each L-bracket's inner Y-facing wall (w1)
|
||||||
|
bump_z = BRD_Z + 1.0 + BUMP_R # Bottom of nub sits 1mm above platform
|
||||||
|
pw = 0.8; sl = 4.0 # Must match make_slim_corner
|
||||||
|
for cx, cy, ix, iy in [(BRD_X, BRD_Y, 1, 1), (BRD_X+BRD_L, BRD_Y, -1, 1),
|
||||||
|
(BRD_X, BRD_Y+BRD_W, 1, -1), (BRD_X+BRD_L, BRD_Y+BRD_W, -1, -1)]:
|
||||||
|
# w1 wall centre X: midpoint of the sl-long wall extending from corner
|
||||||
|
mid_x = cx + ix * sl / 2.0
|
||||||
|
# w1 inner face Y: the face that looks toward the board centre
|
||||||
|
face_y = cy if iy > 0 else cy - pw # wall origin Y
|
||||||
|
inner_y = face_y + pw if iy > 0 else face_y # the side facing inward
|
||||||
|
# iy>0 → bump faces +Y (inward), iy<0 → bump faces -Y (inward)
|
||||||
|
# Actually: iy>0 means corner is at low-Y side, wall inner face = face_y+pw, bump goes +Y
|
||||||
|
# iy<0 means corner is at high-Y side, wall inner face = face_y, bump goes -Y
|
||||||
|
sph = Part.makeSphere(BUMP_R, Base.Vector(mid_x, inner_y, bump_z))
|
||||||
|
cs = BUMP_R + 0.5
|
||||||
|
# Clip: keep only the half protruding inward (toward board centre)
|
||||||
|
if iy > 0:
|
||||||
|
clip = box(cs*2, cs, cs*2, mid_x - cs, inner_y, bump_z - cs)
|
||||||
|
else:
|
||||||
|
clip = box(cs*2, cs, cs*2, mid_x - cs, inner_y - cs, bump_z - cs)
|
||||||
|
half_sph = sph.common(clip)
|
||||||
|
bot_shell = bot_shell.fuse(half_sph)
|
||||||
|
|
||||||
|
POST_R = 1.75
|
||||||
|
POST_TAPER_EXTRA = 0.3 # Extra radius at base
|
||||||
|
POST_TAPER_H = 6.0 # Height over which the taper blends to nominal radius
|
||||||
|
BACK_POST_SHIFT = POST_R # Shift back posts by half a post diameter
|
||||||
|
for ox in [-POST_OFFS_X, POST_OFFS_X]:
|
||||||
|
for oy in [-POST_OFFS_Y, POST_OFFS_Y]:
|
||||||
|
px = BTN_X + ox + (BACK_POST_SHIFT if ox > 0 else 0)
|
||||||
|
py = BTN_CY + oy
|
||||||
|
post = cyl(POST_R, POST_H, px, py, WALL)
|
||||||
|
# Tapered cone base: wider at bottom, blends to post radius at POST_TAPER_H
|
||||||
|
taper = Part.makeCone(POST_R + POST_TAPER_EXTRA, POST_R, POST_TAPER_H,
|
||||||
|
Base.Vector(px, py, WALL))
|
||||||
|
post = post.fuse(taper)
|
||||||
|
post = post.cut(cyl(0.5, POST_H + 1, px, py, WALL))
|
||||||
|
bot_shell = bot_shell.fuse(post)
|
||||||
|
|
||||||
# Board clip helper
|
# Rounded USB-C Cut (Pill Shape)
|
||||||
def make_clip(corner_x, corner_y, inward_x, inward_y):
|
usbc_r = USBC_H / 2.0
|
||||||
|
usbc_box = box(WALL*4, USBC_W - 2*usbc_r, USBC_H, -1, W/2 - USBC_W/2 + usbc_r, USBC_Z)
|
||||||
|
usbc_cyl1 = Part.makeCylinder(usbc_r, WALL*4, Base.Vector(-1, W/2 - USBC_W/2 + usbc_r, USBC_Z + usbc_r), Base.Vector(1, 0, 0))
|
||||||
|
usbc_cyl2 = Part.makeCylinder(usbc_r, WALL*4, Base.Vector(-1, W/2 + USBC_W/2 - usbc_r, USBC_Z + usbc_r), Base.Vector(1, 0, 0))
|
||||||
|
usbc_rounded = usbc_box.fuse(usbc_cyl1).fuse(usbc_cyl2)
|
||||||
|
bot_shell = bot_shell.cut(usbc_rounded)
|
||||||
|
|
||||||
plat_w = ARM_THICK + CLIP_TOL
|
# Battery bay + retaining tabs
|
||||||
|
bot_shell = bot_shell.cut(box(BAT_L, BAT_W, 3.0, BAT_X, BAT_Y, WALL))
|
||||||
|
bat_clip_cy = BAT_Y + BAT_W / 2.0 - BAT_CLIP_Y / 2.0
|
||||||
|
bot_shell = bot_shell.fuse(box(2.0, BAT_CLIP_Y, BAT_H * 0.55, BAT_X - 2.0, bat_clip_cy, WALL))
|
||||||
|
bot_shell = bot_shell.fuse(box(2.0, BAT_CLIP_Y, BAT_H * 0.55, BAT_X + BAT_L, bat_clip_cy, WALL))
|
||||||
|
|
||||||
plat_x = corner_x if inward_x > 0 else corner_x - plat_w
|
# MICRO-DETENT RIDGES: Buried deep, barely protruding
|
||||||
plat_y = corner_y if inward_y > 0 else corner_y - plat_w
|
rx0, rz0 = L/2 - RIDGE_W/2, SPLIT_Z + RIDGE_Z_OFF
|
||||||
|
ridge_bury = 1.5
|
||||||
|
ridge_total_t = ridge_bury + RIDGE_PROUD
|
||||||
|
bot_shell = bot_shell.fuse(box(RIDGE_W, ridge_total_t, RIDGE_H, rx0, TONGUE_T - ridge_bury, rz0))
|
||||||
|
bot_shell = bot_shell.fuse(box(RIDGE_W, ridge_total_t, RIDGE_H, rx0, W - TONGUE_T - RIDGE_PROUD, rz0))
|
||||||
|
|
||||||
platform = box(
|
# TOP SHELL
|
||||||
plat_w, plat_w,
|
top_shell = fillet_horiz(rbox(L, W, H-SPLIT_Z, 0, 0, SPLIT_Z), EDGE_FILLET, H)
|
||||||
PLATFORM_H + PCB_T,
|
top_shell = top_shell.cut(rbox(L-WALL*2, W-WALL*2, H-SPLIT_Z-WALL, WALL, WALL, SPLIT_Z, r=CR_I))
|
||||||
plat_x, plat_y, WALL
|
|
||||||
)
|
|
||||||
|
|
||||||
ax_ox = corner_x if inward_x > 0 else corner_x - ARM_LEN
|
# Groove and Matching Recesses
|
||||||
ax_oy = corner_y - ARM_THICK - CLIP_TOL if inward_y > 0 else corner_y + CLIP_TOL
|
g_band = rbox(L, W, GROOVE_H, 0, 0, SPLIT_Z, r=CR).cut(rbox(L-GROOVE_T*2, W-GROOVE_T*2, GROOVE_H+2, GROOVE_T, GROOVE_T, SPLIT_Z-1, r=CR-GROOVE_T))
|
||||||
arm_x = box(ARM_LEN, ARM_THICK, ARM_H, ax_ox, ax_oy, WALL)
|
top_shell = top_shell.cut(g_band)
|
||||||
|
|
||||||
ay_oy = corner_y if inward_y > 0 else corner_y - ARM_LEN
|
# Recesses in groove wall — bottom ridges click into these
|
||||||
ay_ox = corner_x - ARM_THICK - CLIP_TOL if inward_x > 0 else corner_x + CLIP_TOL
|
rec_w = RIDGE_W + TOL*2
|
||||||
arm_y = box(ARM_THICK, ARM_LEN, ARM_H, ay_ox, ay_oy, WALL)
|
rec_d = RIDGE_PROUD + TOL # Slightly deeper than ridge protrusion
|
||||||
|
top_shell = top_shell.cut(box(rec_w, rec_d, RIDGE_H+TOL, L/2-rec_w/2, GROOVE_T, rz0-TOL/2))
|
||||||
|
top_shell = top_shell.cut(box(rec_w, rec_d, RIDGE_H+TOL, L/2-rec_w/2, W-GROOVE_T-rec_d, rz0-TOL/2))
|
||||||
|
|
||||||
corner_block_w = ARM_THICK + CLIP_TOL
|
# Button & Cap
|
||||||
cb_ox = corner_x - corner_block_w if inward_x > 0 else corner_x
|
top_shell = top_shell.cut(cyl(BTN_HOLE_R, H, BTN_X, BTN_CY, SPLIT_Z))
|
||||||
cb_oy = corner_y - corner_block_w if inward_y > 0 else corner_y
|
top_shell = top_shell.cut(Part.makeSphere(BTN_DOME_R, Base.Vector(BTN_X, BTN_CY, H - WALL - BTN_DOME_R + BTN_DOME_SAG)))
|
||||||
|
cap = cyl(CAP_SHAFT_R, CAP_SHAFT_H).fuse(cyl(CAP_RIM_R, CAP_RIM_H, 0, 0, -CAP_RIM_H))
|
||||||
|
# Hollow cavity in bottom of shaft — button dome nests inside instead of a protruding nubbin
|
||||||
|
cap = cap.cut(cyl(CAP_CAVITY_R, CAP_CAVITY_H, 0, 0, -CAP_RIM_H))
|
||||||
|
cap_placed = cap.copy(); cap_placed.translate(Base.Vector(BTN_X, BTN_CY, H - CAP_SHAFT_H))
|
||||||
|
|
||||||
corner_block = box(
|
# ─── REGISTER ────────────────────────────────────────────────────────────────
|
||||||
corner_block_w, corner_block_w, ARM_H,
|
for name, shape, color in [("Shell_Bottom", bot_shell, (0.15, 0.15, 0.18)),
|
||||||
cb_ox, cb_oy, WALL
|
("Shell_Top", top_shell, (0.25, 0.25, 0.32)),
|
||||||
)
|
("Button_Cap", cap_placed, (0.7, 0.7, 0.7))]:
|
||||||
|
obj = doc.addObject("Part::Feature", name)
|
||||||
return platform.fuse(arm_x.fuse(arm_y).fuse(corner_block))
|
obj.Shape = shape
|
||||||
|
obj.ViewObject.ShapeColor = color
|
||||||
|
|
||||||
# Base outer body
|
|
||||||
base = rbox(L, W, H)
|
|
||||||
|
|
||||||
# Inner cavity
|
|
||||||
base = base.cut(
|
|
||||||
box(L - WALL * 2, W - WALL * 2, H - WALL,
|
|
||||||
WALL, WALL, WALL)
|
|
||||||
)
|
|
||||||
|
|
||||||
rail_z = H - RAIL_H
|
|
||||||
groove_h = RAIL_H - LIP_H
|
|
||||||
|
|
||||||
# Rail grooves
|
|
||||||
base = base.cut(
|
|
||||||
box(L - WALL * 2, RAIL_D, groove_h,
|
|
||||||
WALL, WALL - RAIL_D, rail_z)
|
|
||||||
)
|
|
||||||
|
|
||||||
base = base.cut(
|
|
||||||
box(L - WALL * 2, RAIL_D, groove_h,
|
|
||||||
WALL, W - WALL, rail_z)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Lid lips
|
|
||||||
lip_z = H - LIP_H
|
|
||||||
|
|
||||||
base = base.fuse(
|
|
||||||
box(L - WALL * 2, LIP_OVER, LIP_H,
|
|
||||||
WALL, WALL, lip_z)
|
|
||||||
)
|
|
||||||
|
|
||||||
base = base.fuse(
|
|
||||||
box(L - WALL * 2, LIP_OVER, LIP_H,
|
|
||||||
WALL, W - WALL - LIP_OVER, lip_z)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Back slot
|
|
||||||
slot_y0 = WALL - RAIL_D
|
|
||||||
slot_yw = W - WALL * 2 + RAIL_D * 2
|
|
||||||
|
|
||||||
base = base.cut(
|
|
||||||
box(WALL + 1.0, slot_yw, RAIL_H,
|
|
||||||
L - WALL, slot_y0, rail_z)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Entry bump
|
|
||||||
BUMP_H = 0.5
|
|
||||||
pad_raw = box(WALL, slot_yw, BUMP_H,
|
|
||||||
L - WALL, slot_y0, rail_z)
|
|
||||||
|
|
||||||
pad_trimmed = pad_raw.common(rbox(L, W, H))
|
|
||||||
base = base.fuse(pad_trimmed)
|
|
||||||
|
|
||||||
# Board clips
|
|
||||||
clip_corners = [
|
|
||||||
(BRD_X, BRD_Y, +1, +1),
|
|
||||||
(BRD_X + BRD_L, BRD_Y, -1, +1),
|
|
||||||
(BRD_X, BRD_Y + BRD_W, +1, -1),
|
|
||||||
(BRD_X + BRD_L, BRD_Y + BRD_W, -1, -1),
|
|
||||||
]
|
|
||||||
|
|
||||||
for cx, cy, ix, iy in clip_corners:
|
|
||||||
base = base.fuse(make_clip(cx, cy, ix, iy))
|
|
||||||
|
|
||||||
# USB-C opening
|
|
||||||
base = base.cut(
|
|
||||||
rounded_slot(
|
|
||||||
WALL * 3,
|
|
||||||
USBC_W,
|
|
||||||
USBC_H,
|
|
||||||
-WALL,
|
|
||||||
W / 2 - USBC_W / 2,
|
|
||||||
USBC_Z
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Battery recess
|
|
||||||
base = base.cut(
|
|
||||||
box(BAT_L, BAT_W, 3.0,
|
|
||||||
BAT_X, BAT_Y, WALL)
|
|
||||||
)
|
|
||||||
|
|
||||||
clip_y_start = BAT_Y + BAT_W / 2 - BAT_CLIP_Y / 2
|
|
||||||
|
|
||||||
base = base.fuse(
|
|
||||||
box(2.0, BAT_CLIP_Y, BAT_H * 0.55,
|
|
||||||
BAT_X - 2.0, clip_y_start, WALL)
|
|
||||||
)
|
|
||||||
|
|
||||||
base = base.fuse(
|
|
||||||
box(2.0, BAT_CLIP_Y, BAT_H * 0.55,
|
|
||||||
BAT_X + BAT_L, clip_y_start, WALL)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Circular notch in back wall — centred on base
|
|
||||||
notch_cz = rail_z + LID_H
|
|
||||||
base = base.cut(circular_notch(L, W / 2, notch_cz, NOTCH_R, NOTCH_DEPTH))
|
|
||||||
|
|
||||||
# Lid
|
|
||||||
TAB_W = RAIL_D - TOL + 0.5
|
|
||||||
LID_L = L - WALL * 2 - TOL
|
|
||||||
LID_EXTRA_TOL = 0.5
|
|
||||||
|
|
||||||
LID_W = (
|
|
||||||
W - WALL * 2
|
|
||||||
- (TOL + LID_EXTRA_TOL) * 2
|
|
||||||
+ TAB_W * 2
|
|
||||||
)
|
|
||||||
|
|
||||||
lid_y0 = WALL + TOL + LID_EXTRA_TOL - TAB_W
|
|
||||||
lid = box(LID_L, LID_W, LID_H, 0, lid_y0, 0)
|
|
||||||
|
|
||||||
lid.translate(Base.Vector(WALL + TOL, 0, rail_z))
|
|
||||||
|
|
||||||
# Final objects
|
|
||||||
base_obj = doc.addObject("Part::Feature", "Pointer_Base")
|
|
||||||
base_obj.Shape = base
|
|
||||||
base_obj.ViewObject.ShapeColor = (0.12, 0.12, 0.14)
|
|
||||||
|
|
||||||
lid_obj = doc.addObject("Part::Feature", "Pointer_Lid")
|
|
||||||
lid_obj.Shape = lid
|
|
||||||
lid_obj.ViewObject.ShapeColor = (0.28, 0.28, 0.34)
|
|
||||||
lid_obj.ViewObject.Transparency = 25
|
|
||||||
|
|
||||||
doc.recompute()
|
doc.recompute()
|
||||||
Gui.activeDocument().activeView().viewIsometric()
|
|
||||||
Gui.SendMsgToActiveView("ViewFit")
|
Gui.SendMsgToActiveView("ViewFit")
|
||||||
+10
-8
@@ -1,4 +1,4 @@
|
|||||||
; ── PlatformIO project configuration ─────────────────────────────────────────
|
; PlatformIO project configuration
|
||||||
; Board : Seeed XIAO nRF52840 Sense
|
; Board : Seeed XIAO nRF52840 Sense
|
||||||
; Core : Adafruit nRF52 Arduino (via Seeed platform-seeedboards)
|
; Core : Adafruit nRF52 Arduino (via Seeed platform-seeedboards)
|
||||||
; Flash : adafruit-nrfutil over USB serial (same as Arduino IDE)
|
; Flash : adafruit-nrfutil over USB serial (same as Arduino IDE)
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
; First-time setup:
|
; First-time setup:
|
||||||
; pip install adafruit-nrfutil <- upload tool (once, globally)
|
; pip install adafruit-nrfutil <- upload tool (once, globally)
|
||||||
; pio run -t upload <- build + flash
|
; pio run -t upload <- build + flash
|
||||||
; ──────────────────────────────────────────────────────────────────────────────
|
;
|
||||||
|
|
||||||
[platformio]
|
[platformio]
|
||||||
src_dir = source
|
src_dir = source
|
||||||
@@ -16,7 +16,7 @@ platform = https://github.com/Seeed-Studio/platform-seeedboards.git
|
|||||||
board = seeed-xiao-afruitnrf52-nrf52840
|
board = seeed-xiao-afruitnrf52-nrf52840
|
||||||
framework = arduino
|
framework = arduino
|
||||||
|
|
||||||
; ── Upload ────────────────────────────────────────────────────────────────────
|
; Upload
|
||||||
; The XIAO uses a UF2 bootloader that accepts firmware via adafruit-nrfutil.
|
; The XIAO uses a UF2 bootloader that accepts firmware via adafruit-nrfutil.
|
||||||
; Double-tap the reset button to enter bootloader (red LED pulses) before
|
; Double-tap the reset button to enter bootloader (red LED pulses) before
|
||||||
; flashing if the board isn't auto-reset by the tool.
|
; flashing if the board isn't auto-reset by the tool.
|
||||||
@@ -25,21 +25,23 @@ upload_speed = 115200
|
|||||||
; Uncomment and set the correct port if auto-detect fails:
|
; Uncomment and set the correct port if auto-detect fails:
|
||||||
; upload_port = COM3
|
; upload_port = COM3
|
||||||
|
|
||||||
; ── Build scripts ─────────────────────────────────────────────────────────────
|
; Build scripts
|
||||||
extra_scripts = pre:scripts/git_hash.py
|
; git_hash.py - injects short git hash into firmware + web/version.js
|
||||||
|
; generate_dfu.py - generates firmware_dfu.zip for OTA upload (requires adafruit-nrfutil)
|
||||||
|
extra_scripts = pre:scripts/git_hash.py, post:scripts/generate_dfu.py
|
||||||
|
|
||||||
; ── Build flags ───────────────────────────────────────────────────────────────
|
; Build flags
|
||||||
build_flags =
|
build_flags =
|
||||||
-DARDUINO_Seeed_XIAO_nRF52840_Sense
|
-DARDUINO_Seeed_XIAO_nRF52840_Sense
|
||||||
-DNRF52840_XXAA
|
-DNRF52840_XXAA
|
||||||
-DTARGET_SEEED_XIAO_NRF52840_SENSE
|
-DTARGET_SEEED_XIAO_NRF52840_SENSE
|
||||||
|
|
||||||
; ── Libraries ─────────────────────────────────────────────────────────────────
|
; Libraries
|
||||||
; bluefruit.h, Adafruit_LittleFS.h, InternalFileSystem.h are bundled with
|
; bluefruit.h, Adafruit_LittleFS.h, InternalFileSystem.h are bundled with
|
||||||
; the Adafruit nRF52 core and do NOT need to be listed here.
|
; the Adafruit nRF52 core and do NOT need to be listed here.
|
||||||
; Only external libraries are listed:
|
; Only external libraries are listed:
|
||||||
lib_deps =
|
lib_deps =
|
||||||
Seeed-Studio/Seeed Arduino LSM6DS3 @ ^2.0.3
|
Seeed-Studio/Seeed Arduino LSM6DS3 @ ^2.0.3
|
||||||
|
|
||||||
; ── Serial monitor ────────────────────────────────────────────────────────────
|
; Serial monitor
|
||||||
monitor_speed = 115200
|
monitor_speed = 115200
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""
|
||||||
|
PlatformIO post-build script: generates a Nordic DFU package (.zip) from the
|
||||||
|
built firmware .hex using adafruit-nrfutil.
|
||||||
|
|
||||||
|
The resulting firmware_dfu.zip can be uploaded to the device via:
|
||||||
|
- nRF Connect mobile app (iOS / Android) after triggering OTA mode
|
||||||
|
- nRF Connect for Desktop
|
||||||
|
- adafruit-nrfutil over BLE (advanced)
|
||||||
|
|
||||||
|
Trigger OTA mode on the device:
|
||||||
|
- Send BLE command 0x02 to cfgCommand (0x1236), OR
|
||||||
|
- Type 'o' in the serial monitor
|
||||||
|
|
||||||
|
Usage: referenced from platformio.ini as:
|
||||||
|
extra_scripts = pre:scripts/git_hash.py, post:scripts/generate_dfu.py
|
||||||
|
"""
|
||||||
|
import subprocess, os
|
||||||
|
|
||||||
|
Import("env") # noqa: F821 - PlatformIO injects this
|
||||||
|
|
||||||
|
def generate_dfu_package(source, target, env):
|
||||||
|
build_dir = env.subst("$BUILD_DIR")
|
||||||
|
project_dir = env.subst("$PROJECT_DIR")
|
||||||
|
hex_path = os.path.join(build_dir, "firmware.hex")
|
||||||
|
|
||||||
|
if not os.path.exists(hex_path):
|
||||||
|
print(f"[generate_dfu] firmware.hex not found at {hex_path}, skipping")
|
||||||
|
return
|
||||||
|
|
||||||
|
out_path = os.path.join(project_dir, "firmware_dfu.zip")
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
"adafruit-nrfutil", "dfu", "genpkg",
|
||||||
|
"--dev-type", "0x0052", # nRF52840
|
||||||
|
"--application", hex_path,
|
||||||
|
out_path,
|
||||||
|
],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
if result.returncode == 0:
|
||||||
|
size_kb = os.path.getsize(out_path) / 1024
|
||||||
|
print(f"[generate_dfu] DFU package ready: firmware_dfu.zip ({size_kb:.1f} KB)")
|
||||||
|
print(f"[generate_dfu] Upload with nRF Connect after sending OTA command (0x02) via BLE")
|
||||||
|
else:
|
||||||
|
print(f"[generate_dfu] adafruit-nrfutil error: {result.stderr.strip()}")
|
||||||
|
except FileNotFoundError:
|
||||||
|
print("[generate_dfu] adafruit-nrfutil not found - skipping DFU package generation")
|
||||||
|
print("[generate_dfu] Install with: pip install adafruit-nrfutil")
|
||||||
|
|
||||||
|
env.AddPostAction("$BUILD_DIR/firmware.hex", generate_dfu_package) # noqa: F821
|
||||||
+4
-4
@@ -8,7 +8,7 @@ Usage: referenced from platformio.ini as:
|
|||||||
"""
|
"""
|
||||||
import subprocess, os, re
|
import subprocess, os, re
|
||||||
|
|
||||||
Import("env") # noqa: F821 — PlatformIO injects this
|
Import("env") # noqa: F821 - PlatformIO injects this
|
||||||
|
|
||||||
def get_git_hash():
|
def get_git_hash():
|
||||||
try:
|
try:
|
||||||
@@ -27,14 +27,14 @@ def get_git_hash():
|
|||||||
git_hash = get_git_hash()
|
git_hash = get_git_hash()
|
||||||
print(f"[git_hash] short hash = {git_hash}")
|
print(f"[git_hash] short hash = {git_hash}")
|
||||||
|
|
||||||
# ── Inject into firmware build ────────────────────────────────────────────────
|
# Inject into firmware build
|
||||||
env.Append(CPPDEFINES=[("GIT_HASH", f'\\"{git_hash}\\"')]) # noqa: F821
|
env.Append(CPPDEFINES=[("GIT_HASH", f'\\"{git_hash}\\"')]) # noqa: F821
|
||||||
|
|
||||||
# ── Write web/version.js ──────────────────────────────────────────────────────
|
# Write web/version.js
|
||||||
web_dir = os.path.join(env.subst("$PROJECT_DIR"), "web") # noqa: F821
|
web_dir = os.path.join(env.subst("$PROJECT_DIR"), "web") # noqa: F821
|
||||||
ver_file = os.path.join(web_dir, "version.js")
|
ver_file = os.path.join(web_dir, "version.js")
|
||||||
os.makedirs(web_dir, exist_ok=True)
|
os.makedirs(web_dir, exist_ok=True)
|
||||||
with open(ver_file, "w") as f:
|
with open(ver_file, "w") as f:
|
||||||
f.write(f"// Auto-generated by scripts/git_hash.py — do not edit\n")
|
f.write(f"// Auto-generated by scripts/git_hash.py - do not edit\n")
|
||||||
f.write(f"const FIRMWARE_BUILD_HASH = '{git_hash}';\n")
|
f.write(f"const FIRMWARE_BUILD_HASH = '{git_hash}';\n")
|
||||||
print(f"[git_hash] wrote {ver_file}")
|
print(f"[git_hash] wrote {ver_file}")
|
||||||
|
|||||||
+6
-5
@@ -13,7 +13,7 @@ void initBatteryADC() {
|
|||||||
pinMode(PIN_VBAT_ENABLE, OUTPUT); digitalWrite(PIN_VBAT_ENABLE, LOW);
|
pinMode(PIN_VBAT_ENABLE, OUTPUT); digitalWrite(PIN_VBAT_ENABLE, LOW);
|
||||||
pinMode(PIN_VBAT_READ, INPUT);
|
pinMode(PIN_VBAT_READ, INPUT);
|
||||||
analogReference(AR_INTERNAL_3_0); analogReadResolution(12);
|
analogReference(AR_INTERNAL_3_0); analogReadResolution(12);
|
||||||
// Warm up with a few reads (no delay — just discard results)
|
// Warm up with a few reads (no delay - just discard results)
|
||||||
for (int i=0; i<8; i++) analogRead(PIN_VBAT_READ);
|
for (int i=0; i<8; i++) analogRead(PIN_VBAT_READ);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,17 +34,18 @@ void updateBattery() {
|
|||||||
float v = readBatteryVoltage(); int pct = batteryPercent(v);
|
float v = readBatteryVoltage(); int pct = batteryPercent(v);
|
||||||
bool chg = (digitalRead(PIN_CHG) == LOW);
|
bool chg = (digitalRead(PIN_CHG) == LOW);
|
||||||
ChargeStatus status = chg ? (pct >= 99 ? CHGSTAT_FULL : CHGSTAT_CHARGING) : CHGSTAT_DISCHARGING;
|
ChargeStatus status = chg ? (pct >= 99 ? CHGSTAT_FULL : CHGSTAT_CHARGING) : CHGSTAT_DISCHARGING;
|
||||||
// Only write BLE Battery Service when connected — blebas.write() blocks on the
|
// Only write BLE Battery Service when connected - blebas.write() blocks on the
|
||||||
// SoftDevice ATT layer and causes 30-40ms loop stalls when called during advertising.
|
// SoftDevice ATT layer and causes 30-40ms loop stalls when called during advertising.
|
||||||
if (Bluefruit.connected()) blebas.write(pct);
|
if (Bluefruit.connected()) blebas.notify(pct);
|
||||||
lastChargeStatus = status;
|
lastChargeStatus = status;
|
||||||
#ifdef FEATURE_TELEMETRY
|
#ifdef FEATURE_TELEMETRY
|
||||||
telem.chargeStatus = (uint8_t)status;
|
telem.chargeStatus = (uint8_t)status;
|
||||||
#endif
|
#endif
|
||||||
const char* st[] = {"discharging","charging","full"};
|
const char* st[] = {"discharging","charging","full"};
|
||||||
Serial.print("[BATT] "); Serial.print(v,2); Serial.print("V ");
|
Serial.print("[BATT] "); Serial.print(v,2); Serial.print("V ");
|
||||||
Serial.print(pct); Serial.print("% "); Serial.println(st[status]);
|
Serial.print(pct); Serial.print("% "); Serial.print(st[status]);
|
||||||
// Critical battery alert — only blink when not connected to avoid blocking BLE scheduler.
|
Serial.print(" (PIN_CHG="); Serial.print(digitalRead(PIN_CHG)); Serial.println(")");
|
||||||
|
// Critical battery alert - only blink when not connected to avoid blocking BLE scheduler.
|
||||||
// 6 × 160ms = 960ms hard block; skip during active connection.
|
// 6 × 160ms = 960ms hard block; skip during active connection.
|
||||||
if (status == CHGSTAT_DISCHARGING && v < BATT_CRITICAL && !Bluefruit.connected())
|
if (status == CHGSTAT_DISCHARGING && v < BATT_CRITICAL && !Bluefruit.connected())
|
||||||
for (int i=0; i<6; i++) { digitalWrite(LED_RED,LOW); delay(80); digitalWrite(LED_RED,HIGH); delay(80); }
|
for (int i=0; i<6; i++) { digitalWrite(LED_RED,LOW); delay(80); digitalWrite(LED_RED,HIGH); delay(80); }
|
||||||
|
|||||||
+22
-16
@@ -1,13 +1,14 @@
|
|||||||
#include "ble_config.h"
|
#include "ble_config.h"
|
||||||
#include "tap.h"
|
#include "tap.h"
|
||||||
#include "battery.h"
|
#include "battery.h"
|
||||||
|
#include "buttons.h"
|
||||||
#include <Adafruit_LittleFS.h>
|
#include <Adafruit_LittleFS.h>
|
||||||
#include <InternalFileSystem.h>
|
#include <InternalFileSystem.h>
|
||||||
|
|
||||||
using namespace Adafruit_LittleFS_Namespace;
|
using namespace Adafruit_LittleFS_Namespace;
|
||||||
extern File cfgFile;
|
extern File cfgFile;
|
||||||
|
|
||||||
// ─── BLE Config Service objects ───────────────────────────────────────────────
|
// BLE Config Service objects
|
||||||
#ifndef GIT_HASH
|
#ifndef GIT_HASH
|
||||||
#define GIT_HASH "unknown"
|
#define GIT_HASH "unknown"
|
||||||
#endif
|
#endif
|
||||||
@@ -25,18 +26,17 @@ BLECharacteristic cfgGitHash (0x1239); // GitHash R 8 bytes (7-char ha
|
|||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── Charge mode ──────────────────────────────────────────────────────────────
|
// Charge mode
|
||||||
void applyChargeMode(ChargeMode mode) {
|
void applyChargeMode(ChargeMode mode) {
|
||||||
switch (mode) {
|
switch (mode) {
|
||||||
case CHARGE_OFF: pinMode(PIN_HICHG, INPUT_PULLUP); break;
|
case CHARGE_SLOW: pinMode(PIN_HICHG, INPUT); break;
|
||||||
case CHARGE_SLOW: pinMode(PIN_HICHG, OUTPUT); digitalWrite(PIN_HICHG, HIGH); break;
|
|
||||||
case CHARGE_FAST: pinMode(PIN_HICHG, OUTPUT); digitalWrite(PIN_HICHG, LOW); break;
|
case CHARGE_FAST: pinMode(PIN_HICHG, OUTPUT); digitalWrite(PIN_HICHG, LOW); break;
|
||||||
}
|
}
|
||||||
const char* n[] = {"OFF (~0mA)", "SLOW (50mA)", "FAST (100mA)"};
|
const char* n[] = {"SLOW (50mA)", "FAST (100mA)"};
|
||||||
Serial.print("[CHG] "); Serial.println(n[mode]);
|
Serial.print("[CHG] "); Serial.println(n[mode]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Config persistence ───────────────────────────────────────────────────────
|
// Config persistence
|
||||||
void loadConfig() {
|
void loadConfig() {
|
||||||
InternalFS.begin();
|
InternalFS.begin();
|
||||||
cfgFile.open(CONFIG_FILENAME, FILE_O_READ);
|
cfgFile.open(CONFIG_FILENAME, FILE_O_READ);
|
||||||
@@ -56,11 +56,11 @@ void saveConfig() {
|
|||||||
cfgFile.open(CONFIG_FILENAME, FILE_O_WRITE);
|
cfgFile.open(CONFIG_FILENAME, FILE_O_WRITE);
|
||||||
if (cfgFile) { cfgFile.write((uint8_t*)&cfg, sizeof(cfg)); cfgFile.close(); }
|
if (cfgFile) { cfgFile.write((uint8_t*)&cfg, sizeof(cfg)); cfgFile.close(); }
|
||||||
unsigned long elapsed = millis() - t0;
|
unsigned long elapsed = millis() - t0;
|
||||||
if (elapsed > 5) { Serial.print("[CFG] Saved ("); Serial.print(elapsed); Serial.println("ms — flash block)"); }
|
if (elapsed > 5) { Serial.print("[CFG] Saved ("); Serial.print(elapsed); Serial.println("ms - flash block)"); }
|
||||||
else { Serial.println("[CFG] Saved"); }
|
else { Serial.println("[CFG] Saved"); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── ConfigBlob push ─────────────────────────────────────────────────────────
|
// ConfigBlob push
|
||||||
#ifdef FEATURE_CONFIG_SERVICE
|
#ifdef FEATURE_CONFIG_SERVICE
|
||||||
void pushConfigBlob() {
|
void pushConfigBlob() {
|
||||||
ConfigBlob b;
|
ConfigBlob b;
|
||||||
@@ -74,8 +74,9 @@ void pushConfigBlob() {
|
|||||||
b.tapAction = (uint8_t)cfg.tapAction;
|
b.tapAction = (uint8_t)cfg.tapAction;
|
||||||
b.tapKey = cfg.tapKey;
|
b.tapKey = cfg.tapKey;
|
||||||
b.tapMod = cfg.tapMod;
|
b.tapMod = cfg.tapMod;
|
||||||
b._pad = 0;
|
b.tapFreezeEnabled = cfg.tapFreezeEnabled;
|
||||||
b.jerkThreshold = cfg.jerkThreshold;
|
b.jerkThreshold = cfg.jerkThreshold;
|
||||||
|
b.featureFlags = cfg.featureFlags;
|
||||||
cfgBlob.write((uint8_t*)&b, sizeof(b));
|
cfgBlob.write((uint8_t*)&b, sizeof(b));
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -98,7 +99,7 @@ void factoryReset() {
|
|||||||
Serial.println("[CFG] Factory reset complete");
|
Serial.println("[CFG] Factory reset complete");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── BLE callbacks ────────────────────────────────────────────────────────────
|
// BLE callbacks
|
||||||
#ifdef FEATURE_CONFIG_SERVICE
|
#ifdef FEATURE_CONFIG_SERVICE
|
||||||
void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l) {
|
void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l) {
|
||||||
if (l != sizeof(ConfigBlob)) { Serial.println("[CFG] Bad blob length"); return; }
|
if (l != sizeof(ConfigBlob)) { Serial.println("[CFG] Bad blob length"); return; }
|
||||||
@@ -108,7 +109,7 @@ void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l)
|
|||||||
cfg.accelStrength = b->accelStrength;
|
cfg.accelStrength = b->accelStrength;
|
||||||
if (b->curve <= 2) cfg.curve = (CurveType)b->curve;
|
if (b->curve <= 2) cfg.curve = (CurveType)b->curve;
|
||||||
cfg.axisFlip = b->axisFlip;
|
cfg.axisFlip = b->axisFlip;
|
||||||
if (b->chargeMode <= 2) { cfg.chargeMode = (ChargeMode)b->chargeMode; applyChargeMode(cfg.chargeMode); }
|
if (b->chargeMode <= 1) { cfg.chargeMode = (ChargeMode)b->chargeMode; applyChargeMode(cfg.chargeMode); }
|
||||||
#ifdef FEATURE_TAP_DETECTION
|
#ifdef FEATURE_TAP_DETECTION
|
||||||
if (b->tapThreshold >= 1 && b->tapThreshold <= 31) {
|
if (b->tapThreshold >= 1 && b->tapThreshold <= 31) {
|
||||||
cfg.tapThreshold = b->tapThreshold;
|
cfg.tapThreshold = b->tapThreshold;
|
||||||
@@ -118,9 +119,11 @@ void onConfigBlobWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l)
|
|||||||
cfg.tapKey = b->tapKey;
|
cfg.tapKey = b->tapKey;
|
||||||
cfg.tapMod = b->tapMod;
|
cfg.tapMod = b->tapMod;
|
||||||
#endif
|
#endif
|
||||||
|
cfg.tapFreezeEnabled = b->tapFreezeEnabled ? 1 : 0;
|
||||||
if (b->jerkThreshold >= 100.0f && b->jerkThreshold <= 50000.0f) cfg.jerkThreshold = b->jerkThreshold;
|
if (b->jerkThreshold >= 100.0f && b->jerkThreshold <= 50000.0f) cfg.jerkThreshold = b->jerkThreshold;
|
||||||
|
cfg.featureFlags = b->featureFlags & (FLAG_TAP_ENABLED | FLAG_TEMP_COMP_ENABLED | FLAG_AUTO_RECAL_ENABLED);
|
||||||
saveConfig();
|
saveConfig();
|
||||||
Serial.print("[CFG] Written — sens="); Serial.print(cfg.sensitivity,0);
|
Serial.print("[CFG] Written - sens="); Serial.print(cfg.sensitivity,0);
|
||||||
Serial.print(" dz="); Serial.print(cfg.deadZone,3);
|
Serial.print(" dz="); Serial.print(cfg.deadZone,3);
|
||||||
Serial.print(" tapThr="); Serial.print(cfg.tapThreshold);
|
Serial.print(" tapThr="); Serial.print(cfg.tapThreshold);
|
||||||
Serial.print(" tapAction="); Serial.println(cfg.tapAction);
|
Serial.print(" tapAction="); Serial.println(cfg.tapAction);
|
||||||
@@ -130,6 +133,9 @@ void onCommandWrite(uint16_t h, BLECharacteristic* c, uint8_t* d, uint16_t l) {
|
|||||||
if (l < 1) return;
|
if (l < 1) return;
|
||||||
if (d[0] == 0x01) pendingCal = true;
|
if (d[0] == 0x01) pendingCal = true;
|
||||||
if (d[0] == 0xFF) pendingReset = true;
|
if (d[0] == 0xFF) pendingReset = true;
|
||||||
|
#ifdef FEATURE_OTA
|
||||||
|
if (d[0] == 0x02) pendingOTA = true;
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef FEATURE_IMU_STREAM
|
#ifdef FEATURE_IMU_STREAM
|
||||||
@@ -139,7 +145,7 @@ void onImuStreamCccd(uint16_t conn_hdl, BLECharacteristic* chr, uint16_t value)
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── BLE config service setup ─────────────────────────────────────────────────
|
// BLE config service setup
|
||||||
void setupConfigService() {
|
void setupConfigService() {
|
||||||
cfgService.begin();
|
cfgService.begin();
|
||||||
|
|
||||||
@@ -150,13 +156,13 @@ void setupConfigService() {
|
|||||||
cfgBlob.begin();
|
cfgBlob.begin();
|
||||||
pushConfigBlob();
|
pushConfigBlob();
|
||||||
|
|
||||||
cfgCommand.setProperties(CHR_PROPS_WRITE);
|
cfgCommand.setProperties(CHR_PROPS_WRITE | CHR_PROPS_WRITE_WO_RESP);
|
||||||
cfgCommand.setPermission(SECMODE_OPEN, SECMODE_OPEN);
|
cfgCommand.setPermission(SECMODE_OPEN, SECMODE_OPEN);
|
||||||
cfgCommand.setFixedLen(1);
|
cfgCommand.setFixedLen(1);
|
||||||
cfgCommand.setWriteCallback(onCommandWrite);
|
cfgCommand.setWriteCallback(onCommandWrite);
|
||||||
cfgCommand.begin();
|
cfgCommand.begin();
|
||||||
|
|
||||||
// Git hash — 8-byte fixed field (7 hex chars + NUL), read-only
|
// Git hash - 8-byte fixed field (7 hex chars + NUL), read-only
|
||||||
cfgGitHash.setProperties(CHR_PROPS_READ);
|
cfgGitHash.setProperties(CHR_PROPS_READ);
|
||||||
cfgGitHash.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
|
cfgGitHash.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
|
||||||
cfgGitHash.setFixedLen(8);
|
cfgGitHash.setFixedLen(8);
|
||||||
@@ -192,7 +198,7 @@ void setupConfigService() {
|
|||||||
}
|
}
|
||||||
#endif // FEATURE_CONFIG_SERVICE
|
#endif // FEATURE_CONFIG_SERVICE
|
||||||
|
|
||||||
// ─── Telemetry push ───────────────────────────────────────────────────────────
|
// Telemetry push
|
||||||
#ifdef FEATURE_TELEMETRY
|
#ifdef FEATURE_TELEMETRY
|
||||||
void pushTelemetry(unsigned long now) {
|
void pushTelemetry(unsigned long now) {
|
||||||
telem.uptimeSeconds = now / 1000;
|
telem.uptimeSeconds = now / 1000;
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#include "buttons.h"
|
||||||
|
|
||||||
|
#ifdef FEATURE_PHYSICAL_BUTTONS
|
||||||
|
#include <bluefruit.h>
|
||||||
|
|
||||||
|
extern BLEHidAdafruit blehid;
|
||||||
|
extern Config cfg;
|
||||||
|
|
||||||
|
static uint8_t physBtnMask = 0;
|
||||||
|
static uint8_t rawMaskPrev = 0;
|
||||||
|
static unsigned long debounceMs = 0;
|
||||||
|
static const unsigned long DEBOUNCE_MS = 20;
|
||||||
|
|
||||||
|
// Double-press detection for left button
|
||||||
|
static const unsigned long DOUBLE_PRESS_MS = 400; // max gap between two releases
|
||||||
|
static const unsigned long KEY_HOLD_MS = 60; // how long to hold the key down
|
||||||
|
static unsigned long lastLeftReleaseMs = 0;
|
||||||
|
static unsigned long keyDownUntil = 0;
|
||||||
|
|
||||||
|
// Setup
|
||||||
|
void setupPhysicalButtons() {
|
||||||
|
// Release any held physical buttons before reconfiguring
|
||||||
|
if (physBtnMask && Bluefruit.connected()) { blehid.mouseButtonRelease(); }
|
||||||
|
physBtnMask = 0;
|
||||||
|
|
||||||
|
if (BTN_LEFT_PIN != BTN_PIN_NONE) pinMode(BTN_LEFT_PIN, INPUT_PULLUP);
|
||||||
|
if (BTN_RIGHT_PIN != BTN_PIN_NONE) pinMode(BTN_RIGHT_PIN, INPUT_PULLUP);
|
||||||
|
if (BTN_MIDDLE_PIN != BTN_PIN_NONE) pinMode(BTN_MIDDLE_PIN, INPUT_PULLUP);
|
||||||
|
|
||||||
|
bool any = (BTN_LEFT_PIN != BTN_PIN_NONE) || (BTN_RIGHT_PIN != BTN_PIN_NONE)
|
||||||
|
|| (BTN_MIDDLE_PIN != BTN_PIN_NONE);
|
||||||
|
if (any) {
|
||||||
|
Serial.print("[BTN] L=");
|
||||||
|
BTN_LEFT_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_LEFT_PIN);
|
||||||
|
Serial.print(" R=");
|
||||||
|
BTN_RIGHT_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_RIGHT_PIN);
|
||||||
|
Serial.print(" M=");
|
||||||
|
BTN_MIDDLE_PIN == BTN_PIN_NONE ? Serial.print("--") : Serial.print(BTN_MIDDLE_PIN);
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Poll and report
|
||||||
|
// Called every loop iteration (before rate limiter) for immediate response.
|
||||||
|
// Uses active-low logic: INPUT_PULLUP, button connects pin to GND.
|
||||||
|
void processPhysicalButtons() {
|
||||||
|
if (!Bluefruit.connected()) return;
|
||||||
|
|
||||||
|
unsigned long now = millis();
|
||||||
|
|
||||||
|
// Release held key combo after KEY_HOLD_MS
|
||||||
|
if (keyDownUntil && now >= keyDownUntil) {
|
||||||
|
uint8_t noKeys[6] = {};
|
||||||
|
blehid.keyboardReport(0, noKeys);
|
||||||
|
keyDownUntil = 0;
|
||||||
|
Serial.println("[BTN] key release");
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t rawMask = 0;
|
||||||
|
if (BTN_LEFT_PIN != BTN_PIN_NONE && digitalRead(BTN_LEFT_PIN) == LOW) rawMask |= MOUSE_BUTTON_LEFT;
|
||||||
|
if (BTN_RIGHT_PIN != BTN_PIN_NONE && digitalRead(BTN_RIGHT_PIN) == LOW) rawMask |= MOUSE_BUTTON_RIGHT;
|
||||||
|
if (BTN_MIDDLE_PIN != BTN_PIN_NONE && digitalRead(BTN_MIDDLE_PIN) == LOW) rawMask |= MOUSE_BUTTON_MIDDLE;
|
||||||
|
|
||||||
|
if (rawMask != rawMaskPrev) { rawMaskPrev = rawMask; debounceMs = now; }
|
||||||
|
if (rawMask != physBtnMask && (now - debounceMs >= DEBOUNCE_MS)) {
|
||||||
|
uint8_t newMask = rawMask;
|
||||||
|
uint8_t pressed = newMask & ~physBtnMask;
|
||||||
|
uint8_t released = physBtnMask & ~newMask;
|
||||||
|
physBtnMask = newMask;
|
||||||
|
if (physBtnMask) blehid.mouseButtonPress(physBtnMask);
|
||||||
|
else blehid.mouseButtonRelease();
|
||||||
|
if (pressed & MOUSE_BUTTON_LEFT) Serial.println("[BTN] L press");
|
||||||
|
if (pressed & MOUSE_BUTTON_RIGHT) Serial.println("[BTN] R press");
|
||||||
|
if (pressed & MOUSE_BUTTON_MIDDLE) Serial.println("[BTN] M press");
|
||||||
|
if (released & MOUSE_BUTTON_LEFT) {
|
||||||
|
unsigned long gap = lastLeftReleaseMs ? (now - lastLeftReleaseMs) : 0;
|
||||||
|
Serial.print("[BTN] L release - gap="); Serial.print(gap);
|
||||||
|
Serial.print("ms (max="); Serial.print(DOUBLE_PRESS_MS); Serial.println("ms)");
|
||||||
|
// Double-press detection: two short presses → fire key combo
|
||||||
|
if (lastLeftReleaseMs && (gap <= DOUBLE_PRESS_MS)) {
|
||||||
|
uint8_t keys[6] = {cfg.tapKey, 0, 0, 0, 0, 0};
|
||||||
|
blehid.keyboardReport(cfg.tapMod, keys);
|
||||||
|
keyDownUntil = now + KEY_HOLD_MS;
|
||||||
|
lastLeftReleaseMs = 0;
|
||||||
|
Serial.print("[BTN] Double-press → key 0x"); Serial.print(cfg.tapKey, HEX);
|
||||||
|
Serial.print(" mod 0x"); Serial.println(cfg.tapMod, HEX);
|
||||||
|
} else {
|
||||||
|
lastLeftReleaseMs = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (released & MOUSE_BUTTON_RIGHT) Serial.println("[BTN] R release");
|
||||||
|
if (released & MOUSE_BUTTON_MIDDLE) Serial.println("[BTN] M release");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // FEATURE_PHYSICAL_BUTTONS
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "config.h"
|
||||||
|
|
||||||
|
#ifdef FEATURE_PHYSICAL_BUTTONS
|
||||||
|
void setupPhysicalButtons();
|
||||||
|
void processPhysicalButtons();
|
||||||
|
#endif
|
||||||
+42
-22
@@ -1,20 +1,22 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
|
||||||
// ─── Feature Flags ────────────────────────────────────────────────────────────
|
// Feature Flags
|
||||||
#define FEATURE_CONFIG_SERVICE
|
#define FEATURE_CONFIG_SERVICE
|
||||||
#define FEATURE_TELEMETRY
|
#define FEATURE_TELEMETRY
|
||||||
#define FEATURE_IMU_STREAM
|
#define FEATURE_IMU_STREAM
|
||||||
#define FEATURE_TAP_DETECTION
|
// #define FEATURE_TAP_DETECTION
|
||||||
#define FEATURE_TEMP_COMPENSATION
|
#define FEATURE_TEMP_COMPENSATION
|
||||||
#define FEATURE_AUTO_RECAL
|
#define FEATURE_AUTO_RECAL
|
||||||
#define FEATURE_BATTERY_MONITOR
|
#define FEATURE_BATTERY_MONITOR
|
||||||
#define FEATURE_BOOT_LOOP_DETECT
|
#define FEATURE_BOOT_LOOP_DETECT
|
||||||
|
#define FEATURE_PHYSICAL_BUTTONS
|
||||||
|
#define FEATURE_OTA
|
||||||
|
|
||||||
// ─── Debug ────────────────────────────────────────────────────────────────────
|
// Debug
|
||||||
// #define DEBUG
|
// #define DEBUG
|
||||||
|
|
||||||
// ─── ATT table size ───────────────────────────────────────────────────────────
|
// ATT table size
|
||||||
#define _ATT_BASE 900
|
#define _ATT_BASE 900
|
||||||
#ifdef FEATURE_CONFIG_SERVICE
|
#ifdef FEATURE_CONFIG_SERVICE
|
||||||
#define _ATT_CFG 100 // +20 for cfgGitHash characteristic
|
#define _ATT_CFG 100 // +20 for cfgGitHash characteristic
|
||||||
@@ -34,7 +36,7 @@
|
|||||||
#define ATT_TABLE_SIZE_CALC (_ATT_BASE + _ATT_CFG + _ATT_TELEM + _ATT_STREAM)
|
#define ATT_TABLE_SIZE_CALC (_ATT_BASE + _ATT_CFG + _ATT_TELEM + _ATT_STREAM)
|
||||||
#define ATT_TABLE_SIZE (ATT_TABLE_SIZE_CALC < 1536 ? 1536 : ATT_TABLE_SIZE_CALC)
|
#define ATT_TABLE_SIZE (ATT_TABLE_SIZE_CALC < 1536 ? 1536 : ATT_TABLE_SIZE_CALC)
|
||||||
|
|
||||||
// ─── IMU register addresses ───────────────────────────────────────────────────
|
// IMU register addresses
|
||||||
#define REG_CTRL1_XL 0x10
|
#define REG_CTRL1_XL 0x10
|
||||||
#define REG_TAP_CFG 0x58
|
#define REG_TAP_CFG 0x58
|
||||||
#define REG_TAP_THS_6D 0x59
|
#define REG_TAP_THS_6D 0x59
|
||||||
@@ -45,22 +47,37 @@
|
|||||||
#define REG_OUT_TEMP_L 0x20
|
#define REG_OUT_TEMP_L 0x20
|
||||||
#define REG_OUT_TEMP_H 0x21
|
#define REG_OUT_TEMP_H 0x21
|
||||||
|
|
||||||
// ─── Pins ─────────────────────────────────────────────────────────────────────
|
// Pins
|
||||||
#define PIN_VBAT_ENABLE (14)
|
#define PIN_VBAT_ENABLE (14)
|
||||||
#define PIN_VBAT_READ (32)
|
#define PIN_VBAT_READ (32)
|
||||||
#define PIN_CHG (23)
|
#define PIN_CHG (23)
|
||||||
#define PIN_HICHG (22)
|
#define PIN_HICHG (22)
|
||||||
|
|
||||||
// ─── Persistence ──────────────────────────────────────────────────────────────
|
// Persistence
|
||||||
#define CONFIG_FILENAME "/imu_mouse_cfg.bin"
|
#define CONFIG_FILENAME "/imu_mouse_cfg.bin"
|
||||||
#define CONFIG_MAGIC 0xDEAD123AUL
|
#define CONFIG_MAGIC 0xDEAD123EUL
|
||||||
|
|
||||||
// ─── Enums ────────────────────────────────────────────────────────────────────
|
// Physical button pin assignments (hardcoded - set to 0xFF to disable a button)
|
||||||
|
// Valid pin numbers: 0-10 (Arduino D0-D10 on XIAO nRF52840 Sense)
|
||||||
|
#define BTN_PIN_NONE 0xFF
|
||||||
|
#define BTN_LEFT_PIN 1 // D1, active-low to GND
|
||||||
|
#define BTN_RIGHT_PIN BTN_PIN_NONE // e.g. 1 for D1
|
||||||
|
#define BTN_MIDDLE_PIN BTN_PIN_NONE // e.g. 2 for D2
|
||||||
|
|
||||||
|
// Runtime feature-override flags (cfg.featureFlags bitmask)
|
||||||
|
// These mirror the compile-time FEATURE_* defines but can be toggled at runtime
|
||||||
|
// via the web UI and persisted in flash. Bits not listed here are reserved = 0.
|
||||||
|
#define FLAG_TAP_ENABLED 0x01 // Tap detection active (requires restart)
|
||||||
|
#define FLAG_TEMP_COMP_ENABLED 0x02 // Temperature gyro-drift compensation
|
||||||
|
#define FLAG_AUTO_RECAL_ENABLED 0x04 // Auto-recalibrate after long idle
|
||||||
|
#define FLAG_ALL_DEFAULT (FLAG_TAP_ENABLED | FLAG_TEMP_COMP_ENABLED | FLAG_AUTO_RECAL_ENABLED)
|
||||||
|
|
||||||
|
// Enums
|
||||||
enum CurveType : uint8_t { CURVE_LINEAR=0, CURVE_SQUARE=1, CURVE_SQRT=2 };
|
enum CurveType : uint8_t { CURVE_LINEAR=0, CURVE_SQUARE=1, CURVE_SQRT=2 };
|
||||||
enum ChargeMode : uint8_t { CHARGE_OFF=0, CHARGE_SLOW=1, CHARGE_FAST=2 };
|
enum ChargeMode : uint8_t { CHARGE_SLOW=0, CHARGE_FAST=1 };
|
||||||
enum ChargeStatus: uint8_t { CHGSTAT_DISCHARGING=0, CHGSTAT_CHARGING=1, CHGSTAT_FULL=2 };
|
enum ChargeStatus: uint8_t { CHGSTAT_DISCHARGING=0, CHGSTAT_CHARGING=1, CHGSTAT_FULL=2 };
|
||||||
|
|
||||||
// ─── Tap action types ─────────────────────────────────────────────────────────
|
// Tap action types
|
||||||
// TAP_ACTION_KEY: fires a raw HID keycode (tapKey) with optional modifier (tapMod).
|
// TAP_ACTION_KEY: fires a raw HID keycode (tapKey) with optional modifier (tapMod).
|
||||||
// Modifier byte: bit0=Ctrl, bit1=Shift, bit2=Alt, bit3=GUI (same as HID modifier byte).
|
// Modifier byte: bit0=Ctrl, bit1=Shift, bit2=Alt, bit3=GUI (same as HID modifier byte).
|
||||||
enum TapAction : uint8_t {
|
enum TapAction : uint8_t {
|
||||||
@@ -70,7 +87,7 @@ enum TapAction : uint8_t {
|
|||||||
TAP_ACTION_KEY = 3,
|
TAP_ACTION_KEY = 3,
|
||||||
};
|
};
|
||||||
|
|
||||||
// ─── Config (stored in flash) ─────────────────────────────────────────────────
|
// Config (stored in flash)
|
||||||
struct Config {
|
struct Config {
|
||||||
uint32_t magic;
|
uint32_t magic;
|
||||||
float sensitivity;
|
float sensitivity;
|
||||||
@@ -84,11 +101,13 @@ struct Config {
|
|||||||
uint8_t tapKey; // HID keycode (used when tapAction == TAP_ACTION_KEY)
|
uint8_t tapKey; // HID keycode (used when tapAction == TAP_ACTION_KEY)
|
||||||
uint8_t tapMod; // HID modifier byte (used when tapAction == TAP_ACTION_KEY)
|
uint8_t tapMod; // HID modifier byte (used when tapAction == TAP_ACTION_KEY)
|
||||||
float jerkThreshold; // jerk² threshold for tap-freeze detection
|
float jerkThreshold; // jerk² threshold for tap-freeze detection
|
||||||
|
uint8_t tapFreezeEnabled; // 1 = enable jerk-based cursor freeze during taps
|
||||||
|
uint8_t featureFlags; // bitmask of FLAG_* - runtime feature overrides
|
||||||
};
|
};
|
||||||
extern Config cfg;
|
extern Config cfg;
|
||||||
extern const Config CFG_DEFAULTS;
|
extern const Config CFG_DEFAULTS;
|
||||||
|
|
||||||
// ─── ConfigBlob (over BLE, 20 bytes) ─────────────────────────────────────────
|
// ConfigBlob (over BLE, 25 bytes)
|
||||||
struct __attribute__((packed)) ConfigBlob {
|
struct __attribute__((packed)) ConfigBlob {
|
||||||
float sensitivity; // [0]
|
float sensitivity; // [0]
|
||||||
float deadZone; // [4]
|
float deadZone; // [4]
|
||||||
@@ -100,12 +119,13 @@ struct __attribute__((packed)) ConfigBlob {
|
|||||||
uint8_t tapAction; // [16] TapAction enum
|
uint8_t tapAction; // [16] TapAction enum
|
||||||
uint8_t tapKey; // [17] HID keycode
|
uint8_t tapKey; // [17] HID keycode
|
||||||
uint8_t tapMod; // [18] HID modifier
|
uint8_t tapMod; // [18] HID modifier
|
||||||
uint8_t _pad; // [19]
|
uint8_t tapFreezeEnabled; // [19] 1 = enable jerk-based cursor freeze during taps
|
||||||
float jerkThreshold; // [20] jerk² tap-freeze threshold
|
float jerkThreshold; // [20] jerk² tap-freeze threshold
|
||||||
|
uint8_t featureFlags; // [24] FLAG_* bitmask - runtime feature overrides
|
||||||
};
|
};
|
||||||
static_assert(sizeof(ConfigBlob) == 24, "ConfigBlob must be 24 bytes");
|
static_assert(sizeof(ConfigBlob) == 25, "ConfigBlob must be 25 bytes");
|
||||||
|
|
||||||
// ─── TelemetryPacket (24 bytes) ───────────────────────────────────────────────
|
// TelemetryPacket (24 bytes)
|
||||||
#ifdef FEATURE_TELEMETRY
|
#ifdef FEATURE_TELEMETRY
|
||||||
struct __attribute__((packed)) TelemetryPacket {
|
struct __attribute__((packed)) TelemetryPacket {
|
||||||
uint32_t uptimeSeconds; // [0]
|
uint32_t uptimeSeconds; // [0]
|
||||||
@@ -122,7 +142,7 @@ static_assert(sizeof(TelemetryPacket) == 28, "TelemetryPacket must be 28 bytes")
|
|||||||
extern TelemetryPacket telem;
|
extern TelemetryPacket telem;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── ImuPacket (14 bytes) ─────────────────────────────────────────────────────
|
// ImuPacket (14 bytes)
|
||||||
#ifdef FEATURE_IMU_STREAM
|
#ifdef FEATURE_IMU_STREAM
|
||||||
struct __attribute__((packed)) ImuPacket {
|
struct __attribute__((packed)) ImuPacket {
|
||||||
int16_t gyroX_mDPS; // [0] pitch axis (nod up/down → cursor Y)
|
int16_t gyroX_mDPS; // [0] pitch axis (nod up/down → cursor Y)
|
||||||
@@ -138,8 +158,7 @@ struct __attribute__((packed)) ImuPacket {
|
|||||||
static_assert(sizeof(ImuPacket) == 14, "ImuPacket must be 14 bytes");
|
static_assert(sizeof(ImuPacket) == 14, "ImuPacket must be 14 bytes");
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── Tuning constants ─────────────────────────────────────────────────────────
|
// Tuning constants
|
||||||
extern const float ALPHA;
|
|
||||||
extern const int LOOP_RATE_MS;
|
extern const int LOOP_RATE_MS;
|
||||||
extern const int BIAS_SAMPLES;
|
extern const int BIAS_SAMPLES;
|
||||||
extern const int IDLE_FRAMES;
|
extern const int IDLE_FRAMES;
|
||||||
@@ -164,10 +183,8 @@ extern const float BATT_CRITICAL;
|
|||||||
extern const unsigned long AUTO_RECAL_MS;
|
extern const unsigned long AUTO_RECAL_MS;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── Global state ─────────────────────────────────────────────────────────────
|
// Global state
|
||||||
extern float angleX, angleY;
|
|
||||||
extern float accumX, accumY;
|
extern float accumX, accumY;
|
||||||
extern float gravX, gravY, gravZ;
|
|
||||||
extern float biasGX, biasGY, biasGZ;
|
extern float biasGX, biasGY, biasGZ;
|
||||||
extern float calTempC;
|
extern float calTempC;
|
||||||
extern float cachedTempC;
|
extern float cachedTempC;
|
||||||
@@ -186,6 +203,9 @@ extern float cachedTempC;
|
|||||||
|
|
||||||
extern bool pendingCal;
|
extern bool pendingCal;
|
||||||
extern bool pendingReset;
|
extern bool pendingReset;
|
||||||
|
#ifdef FEATURE_OTA
|
||||||
|
extern bool pendingOTA;
|
||||||
|
#endif
|
||||||
extern ChargeStatus lastChargeStatus;
|
extern ChargeStatus lastChargeStatus;
|
||||||
extern int idleFrames;
|
extern int idleFrames;
|
||||||
extern unsigned long idleStartMs;
|
extern unsigned long idleStartMs;
|
||||||
|
|||||||
+5
-7
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
LSM6DS3 imu(I2C_MODE, 0x6A);
|
LSM6DS3 imu(I2C_MODE, 0x6A);
|
||||||
|
|
||||||
// ─── I2C helpers ──────────────────────────────────────────────────────────────
|
// I2C helpers
|
||||||
void imuWriteReg(uint8_t reg, uint8_t val) {
|
void imuWriteReg(uint8_t reg, uint8_t val) {
|
||||||
// LSM6DS3 is on Wire1 (internal I2C, SDA=P0.17, SCL=P0.16), NOT Wire (external pins 4/5)
|
// LSM6DS3 is on Wire1 (internal I2C, SDA=P0.17, SCL=P0.16), NOT Wire (external pins 4/5)
|
||||||
Wire1.beginTransmission(0x6A); Wire1.write(reg); Wire1.write(val); Wire1.endTransmission();
|
Wire1.beginTransmission(0x6A); Wire1.write(reg); Wire1.write(val); Wire1.endTransmission();
|
||||||
@@ -16,13 +16,13 @@ uint8_t imuReadReg(uint8_t reg) {
|
|||||||
return Wire1.available() ? Wire1.read() : 0;
|
return Wire1.available() ? Wire1.read() : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Temperature ──────────────────────────────────────────────────────────────
|
// Temperature
|
||||||
float readIMUTemp() {
|
float readIMUTemp() {
|
||||||
int16_t raw = (int16_t)((imuReadReg(REG_OUT_TEMP_H) << 8) | imuReadReg(REG_OUT_TEMP_L));
|
int16_t raw = (int16_t)((imuReadReg(REG_OUT_TEMP_H) << 8) | imuReadReg(REG_OUT_TEMP_L));
|
||||||
return 25.0f + (float)raw / 256.0f;
|
return 25.0f + (float)raw / 256.0f;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Calibration ──────────────────────────────────────────────────────────────
|
// Calibration
|
||||||
void calibrateGyroBias() {
|
void calibrateGyroBias() {
|
||||||
Serial.println("[CAL] Hold still...");
|
Serial.println("[CAL] Hold still...");
|
||||||
double sx=0, sy=0, sz=0;
|
double sx=0, sy=0, sz=0;
|
||||||
@@ -34,9 +34,7 @@ void calibrateGyroBias() {
|
|||||||
biasGY = (float)(sy/BIAS_SAMPLES);
|
biasGY = (float)(sy/BIAS_SAMPLES);
|
||||||
biasGZ = (float)(sz/BIAS_SAMPLES);
|
biasGZ = (float)(sz/BIAS_SAMPLES);
|
||||||
calTempC = readIMUTemp();
|
calTempC = readIMUTemp();
|
||||||
angleX = angleY = accumX = accumY = 0.0f;
|
accumX = accumY = 0.0f;
|
||||||
// Seed gravity estimate from current accel so projection is correct immediately
|
|
||||||
gravX = imu.readFloatAccelX(); gravY = imu.readFloatAccelY(); gravZ = imu.readFloatAccelZ();
|
|
||||||
|
|
||||||
#ifdef FEATURE_TELEMETRY
|
#ifdef FEATURE_TELEMETRY
|
||||||
statRecalCount++;
|
statRecalCount++;
|
||||||
@@ -51,7 +49,7 @@ void calibrateGyroBias() {
|
|||||||
Serial.print(","); Serial.println(biasGZ,4);
|
Serial.print(","); Serial.println(biasGZ,4);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Motion curve ─────────────────────────────────────────────────────────────
|
// Motion curve
|
||||||
float applyCurve(float v) {
|
float applyCurve(float v) {
|
||||||
switch (cfg.curve) {
|
switch (cfg.curve) {
|
||||||
case CURVE_SQUARE: return (v >= 0 ? 1.f : -1.f) * v * v;
|
case CURVE_SQUARE: return (v >= 0 ? 1.f : -1.f) * v * v;
|
||||||
|
|||||||
+103
-129
@@ -1,27 +1,12 @@
|
|||||||
/*
|
/*
|
||||||
* IMU BLE Mouse — Seeed XIAO nRF52840 Sense (v3.4)
|
* IMU BLE Mouse - Seeed XIAO nRF52840 Sense (v3.4)
|
||||||
* ================================================================
|
* ================================================================
|
||||||
* Feature flags — comment out any line to disable that feature.
|
|
||||||
* ATT table size is computed automatically from enabled features.
|
|
||||||
* Start with minimal flags to isolate the SoftDevice RAM issue,
|
|
||||||
* then re-enable one at a time.
|
|
||||||
*
|
|
||||||
* MINIMUM (just working mouse, no BLE config):
|
* MINIMUM (just working mouse, no BLE config):
|
||||||
* leave only FEATURE_BATTERY_MONITOR + FEATURE_BOOT_LOOP_DETECT
|
* leave only FEATURE_BATTERY_MONITOR + FEATURE_BOOT_LOOP_DETECT
|
||||||
*
|
*
|
||||||
* RECOMMENDED first test:
|
* RECOMMENDED first test:
|
||||||
* enable FEATURE_CONFIG_SERVICE, keep TAP + STREAM + TELEMETRY off
|
* enable FEATURE_CONFIG_SERVICE, keep TAP + STREAM + TELEMETRY off
|
||||||
*
|
*
|
||||||
* ── Feature flag index ───────────────────────────────────────────
|
|
||||||
* FEATURE_CONFIG_SERVICE Custom GATT service (ConfigBlob + Command)
|
|
||||||
* FEATURE_TELEMETRY +24-byte notify characteristic, 1 Hz
|
|
||||||
* FEATURE_IMU_STREAM +14-byte notify characteristic, ~10 Hz
|
|
||||||
* FEATURE_TAP_DETECTION LSM6DS3 hardware tap engine → L/R clicks
|
|
||||||
* FEATURE_TEMP_COMPENSATION Gyro drift correction by temperature delta
|
|
||||||
* FEATURE_AUTO_RECAL Recalibrate after AUTO_RECAL_MS idle
|
|
||||||
* FEATURE_BATTERY_MONITOR ADC battery read + BLE Battery Service
|
|
||||||
* FEATURE_BOOT_LOOP_DETECT .noinit crash counter → safe mode
|
|
||||||
*
|
|
||||||
* Dependencies:
|
* Dependencies:
|
||||||
* FEATURE_TELEMETRY requires FEATURE_CONFIG_SERVICE
|
* FEATURE_TELEMETRY requires FEATURE_CONFIG_SERVICE
|
||||||
* FEATURE_IMU_STREAM requires FEATURE_CONFIG_SERVICE
|
* FEATURE_IMU_STREAM requires FEATURE_CONFIG_SERVICE
|
||||||
@@ -32,45 +17,46 @@
|
|||||||
#include "imu.h"
|
#include "imu.h"
|
||||||
#include "ble_config.h"
|
#include "ble_config.h"
|
||||||
#include "battery.h"
|
#include "battery.h"
|
||||||
#include "tap.h"
|
#include "buttons.h"
|
||||||
#include <bluefruit.h>
|
#include <bluefruit.h>
|
||||||
#include <Adafruit_LittleFS.h>
|
#include <Adafruit_LittleFS.h>
|
||||||
#include <InternalFileSystem.h>
|
#include <InternalFileSystem.h>
|
||||||
#include "Wire.h"
|
#include "Wire.h"
|
||||||
|
#include "sleep.h"
|
||||||
|
|
||||||
// ─── Boot-loop detection ──────────────────────────────────────────────────────
|
// Boot-loop detection
|
||||||
#ifdef FEATURE_BOOT_LOOP_DETECT
|
#ifdef FEATURE_BOOT_LOOP_DETECT
|
||||||
static uint32_t __attribute__((section(".noinit"))) bootCount;
|
static uint32_t __attribute__((section(".noinit"))) bootCount;
|
||||||
static uint32_t __attribute__((section(".noinit"))) bootMagic;
|
static uint32_t __attribute__((section(".noinit"))) bootMagic;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── BLE Standard Services ────────────────────────────────────────────────────
|
// BLE Standard Services
|
||||||
BLEDis bledis;
|
BLEDis bledis;
|
||||||
BLEHidAdafruit blehid;
|
BLEHidAdafruit blehid;
|
||||||
#ifdef FEATURE_BATTERY_MONITOR
|
#ifdef FEATURE_BATTERY_MONITOR
|
||||||
BLEBas blebas;
|
BLEBas blebas;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── Persistence ──────────────────────────────────────────────────────────────
|
// Persistence
|
||||||
using namespace Adafruit_LittleFS_Namespace;
|
using namespace Adafruit_LittleFS_Namespace;
|
||||||
File cfgFile(InternalFS);
|
File cfgFile(InternalFS);
|
||||||
|
|
||||||
// ─── Config definitions ───────────────────────────────────────────────────────
|
// Config definitions
|
||||||
Config cfg;
|
Config cfg;
|
||||||
const Config CFG_DEFAULTS = {
|
const Config CFG_DEFAULTS = {
|
||||||
CONFIG_MAGIC, 600.0f, 0.060f, 0.08f, CURVE_LINEAR, 0x00, CHARGE_SLOW,
|
CONFIG_MAGIC, 600.0f, 0.060f, 0.08f, CURVE_LINEAR, 0x00, CHARGE_SLOW,
|
||||||
/*tapThreshold=*/12, /*tapAction=*/TAP_ACTION_LEFT, /*tapKey=*/0, /*tapMod=*/0,
|
/*tapThreshold=*/12, /*tapAction=*/TAP_ACTION_KEY, /*tapKey=*/0x04, /*tapMod=*/0x03, // Ctrl+Shift+A
|
||||||
/*jerkThreshold=*/2000.0f
|
/*jerkThreshold=*/2000.0f, /*tapFreezeEnabled=*/1, /*featureFlags=*/FLAG_ALL_DEFAULT
|
||||||
};
|
};
|
||||||
|
|
||||||
// ─── Telemetry definition ─────────────────────────────────────────────────────
|
// Telemetry definition
|
||||||
#ifdef FEATURE_TELEMETRY
|
#ifdef FEATURE_TELEMETRY
|
||||||
TelemetryPacket telem = {};
|
TelemetryPacket telem = {};
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── Tuning constants ─────────────────────────────────────────────────────────
|
// Tuning constants
|
||||||
const float ALPHA = 0.96f;
|
|
||||||
const int LOOP_RATE_MS = 10;
|
const int LOOP_RATE_MS = 10;
|
||||||
|
const float SMOOTH_ALPHA = 0.65f; // single-pole low-pass for cursor smoothing
|
||||||
const int BIAS_SAMPLES = 200;
|
const int BIAS_SAMPLES = 200;
|
||||||
const int IDLE_FRAMES = 150;
|
const int IDLE_FRAMES = 150;
|
||||||
const unsigned long BATT_REPORT_MS = 20000;
|
const unsigned long BATT_REPORT_MS = 20000;
|
||||||
@@ -79,7 +65,7 @@ const unsigned long HEARTBEAT_MS = 10000;
|
|||||||
const int HEARTBEAT_DUR = 30;
|
const int HEARTBEAT_DUR = 30;
|
||||||
const unsigned long BOOT_SAFE_MS = 5000;
|
const unsigned long BOOT_SAFE_MS = 5000;
|
||||||
#ifdef FEATURE_IMU_STREAM
|
#ifdef FEATURE_IMU_STREAM
|
||||||
const unsigned long IMU_STREAM_RATE_MS = 100;
|
const unsigned long IMU_STREAM_RATE_MS = 20;
|
||||||
#endif
|
#endif
|
||||||
const float BATT_FULL = 4.20f;
|
const float BATT_FULL = 4.20f;
|
||||||
const float BATT_EMPTY = 3.00f;
|
const float BATT_EMPTY = 3.00f;
|
||||||
@@ -94,11 +80,8 @@ const float BATT_CRITICAL = 3.10f;
|
|||||||
const unsigned long AUTO_RECAL_MS = 5UL * 60UL * 1000UL;
|
const unsigned long AUTO_RECAL_MS = 5UL * 60UL * 1000UL;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// ─── Global state definitions ─────────────────────────────────────────────────
|
// Global state definitions
|
||||||
float angleX = 0, angleY = 0;
|
|
||||||
float accumX = 0, accumY = 0;
|
float accumX = 0, accumY = 0;
|
||||||
// Low-pass filtered gravity estimate in device frame (for roll-independent axis projection)
|
|
||||||
float gravX = 0, gravY = 0, gravZ = 1.0f;
|
|
||||||
float biasGX = 0, biasGY = 0, biasGZ = 0;
|
float biasGX = 0, biasGY = 0, biasGZ = 0;
|
||||||
float calTempC = 25.0f;
|
float calTempC = 25.0f;
|
||||||
float cachedTempC = 25.0f;
|
float cachedTempC = 25.0f;
|
||||||
@@ -128,14 +111,10 @@ float cachedTempC = 25.0f;
|
|||||||
uint32_t loopStalls = 0; // loop iterations where dt > 20ms (behind schedule)
|
uint32_t loopStalls = 0; // loop iterations where dt > 20ms (behind schedule)
|
||||||
bool pendingCal = false;
|
bool pendingCal = false;
|
||||||
bool pendingReset = false;
|
bool pendingReset = false;
|
||||||
|
#ifdef FEATURE_OTA
|
||||||
|
bool pendingOTA = false;
|
||||||
|
#endif
|
||||||
|
|
||||||
// ── Jerk-based shock detection — freeze cursor during tap impacts ────────────
|
|
||||||
// Jerk = da/dt (rate of change of acceleration). Normal mouse rotation produces
|
|
||||||
// smooth accel changes (low jerk); a tap is a sharp impulse (very high jerk).
|
|
||||||
// This cleanly separates taps from any intentional motion regardless of speed.
|
|
||||||
unsigned long shockFreezeUntil = 0;
|
|
||||||
float prevAx = 0, prevAy = 0, prevAz = 0; // previous frame's accel for Δa
|
|
||||||
const unsigned long SHOCK_FREEZE_MS = 80; // hold freeze after last spike
|
|
||||||
|
|
||||||
ChargeStatus lastChargeStatus = CHGSTAT_DISCHARGING;
|
ChargeStatus lastChargeStatus = CHGSTAT_DISCHARGING;
|
||||||
|
|
||||||
@@ -158,7 +137,7 @@ unsigned long bootStartMs = 0;
|
|||||||
bool safeMode = false;
|
bool safeMode = false;
|
||||||
bool bootCountCleared = false;
|
bool bootCountCleared = false;
|
||||||
|
|
||||||
// ─── Advertising ─────────────────────────────────────────────────────────────
|
// Advertising
|
||||||
static void startAdvertising() {
|
static void startAdvertising() {
|
||||||
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
|
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
|
||||||
Bluefruit.Advertising.addTxPower();
|
Bluefruit.Advertising.addTxPower();
|
||||||
@@ -174,7 +153,7 @@ static void startAdvertising() {
|
|||||||
Bluefruit.Advertising.start(0);
|
Bluefruit.Advertising.start(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Setup ────────────────────────────────────────────────────────────────────
|
// Setup
|
||||||
void setup() {
|
void setup() {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
unsigned long serialWait = millis();
|
unsigned long serialWait = millis();
|
||||||
@@ -185,14 +164,14 @@ void setup() {
|
|||||||
pinMode(LED_GREEN, OUTPUT); digitalWrite(LED_GREEN, HIGH);
|
pinMode(LED_GREEN, OUTPUT); digitalWrite(LED_GREEN, HIGH);
|
||||||
pinMode(LED_BLUE, OUTPUT); digitalWrite(LED_BLUE, HIGH);
|
pinMode(LED_BLUE, OUTPUT); digitalWrite(LED_BLUE, HIGH);
|
||||||
|
|
||||||
// ── Boot-loop detection ───────────────────────────────────────────────────
|
// Boot-loop detection
|
||||||
#ifdef FEATURE_BOOT_LOOP_DETECT
|
#ifdef FEATURE_BOOT_LOOP_DETECT
|
||||||
if (bootMagic != 0xCAFEBABE) { bootMagic = 0xCAFEBABE; bootCount = 0; }
|
if (bootMagic != 0xCAFEBABE) { bootMagic = 0xCAFEBABE; bootCount = 0; }
|
||||||
bootCount++;
|
bootCount++;
|
||||||
Serial.print("[BOOT] count="); Serial.println(bootCount);
|
Serial.print("[BOOT] count="); Serial.println(bootCount);
|
||||||
if (bootCount >= 3) {
|
if (bootCount >= 3) {
|
||||||
bootCount = 0; safeMode = true;
|
bootCount = 0; safeMode = true;
|
||||||
Serial.println("[BOOT] Boot loop — safe mode (no config service)");
|
Serial.println("[BOOT] Boot loop - safe mode (no config service)");
|
||||||
InternalFS.begin(); InternalFS.remove(CONFIG_FILENAME);
|
InternalFS.begin(); InternalFS.remove(CONFIG_FILENAME);
|
||||||
for (int i=0; i<3; i++) { digitalWrite(LED_RED,LOW); delay(150); digitalWrite(LED_RED,HIGH); delay(150); } // fault: red
|
for (int i=0; i<3; i++) { digitalWrite(LED_RED,LOW); delay(150); digitalWrite(LED_RED,HIGH); delay(150); } // fault: red
|
||||||
}
|
}
|
||||||
@@ -211,7 +190,7 @@ void setup() {
|
|||||||
Bluefruit.begin(1, 0);
|
Bluefruit.begin(1, 0);
|
||||||
Bluefruit.setTxPower(4);
|
Bluefruit.setTxPower(4);
|
||||||
Bluefruit.setName(safeMode ? "IMU Mouse (safe)" : "IMU Mouse");
|
Bluefruit.setName(safeMode ? "IMU Mouse (safe)" : "IMU Mouse");
|
||||||
Bluefruit.Periph.setConnInterval(16, 32); // 20-40ms — wider interval reduces SoftDevice TX stalls
|
Bluefruit.Periph.setConnInterval(16, 32); // 20-40ms - wider interval reduces SoftDevice TX stalls
|
||||||
|
|
||||||
Wire1.begin(); // LSM6DS3 is on internal I2C bus (Wire1), must init before imu.begin()
|
Wire1.begin(); // LSM6DS3 is on internal I2C bus (Wire1), must init before imu.begin()
|
||||||
if (imu.begin() != 0) {
|
if (imu.begin() != 0) {
|
||||||
@@ -221,7 +200,11 @@ void setup() {
|
|||||||
Serial.println("[OK] IMU ready");
|
Serial.println("[OK] IMU ready");
|
||||||
|
|
||||||
#ifdef FEATURE_TAP_DETECTION
|
#ifdef FEATURE_TAP_DETECTION
|
||||||
setupTapDetection();
|
if (cfg.featureFlags & FLAG_TAP_ENABLED) setupTapDetection();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef FEATURE_PHYSICAL_BUTTONS
|
||||||
|
setupPhysicalButtons();
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
cachedTempC = readIMUTemp();
|
cachedTempC = readIMUTemp();
|
||||||
@@ -232,8 +215,8 @@ void setup() {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
calibrateGyroBias();
|
calibrateGyroBias();
|
||||||
// Seed previous-accel for jerk detection so first frame doesn't spike
|
|
||||||
prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ();
|
sleepManagerInit();
|
||||||
|
|
||||||
bledis.setManufacturer("Seeed Studio");
|
bledis.setManufacturer("Seeed Studio");
|
||||||
bledis.setModel("XIAO nRF52840 Sense");
|
bledis.setModel("XIAO nRF52840 Sense");
|
||||||
@@ -255,7 +238,7 @@ void setup() {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
startAdvertising();
|
startAdvertising();
|
||||||
Serial.print("[OK] Advertising — features:");
|
Serial.print("[OK] Advertising - features:");
|
||||||
#ifdef FEATURE_CONFIG_SERVICE
|
#ifdef FEATURE_CONFIG_SERVICE
|
||||||
Serial.print(" CFG");
|
Serial.print(" CFG");
|
||||||
#endif
|
#endif
|
||||||
@@ -280,13 +263,17 @@ void setup() {
|
|||||||
#ifdef FEATURE_BOOT_LOOP_DETECT
|
#ifdef FEATURE_BOOT_LOOP_DETECT
|
||||||
Serial.print(" BOOTDET");
|
Serial.print(" BOOTDET");
|
||||||
#endif
|
#endif
|
||||||
|
#ifdef FEATURE_PHYSICAL_BUTTONS
|
||||||
|
Serial.print(" PHYSBTN");
|
||||||
|
#endif
|
||||||
|
Serial.print(" SLEEP");
|
||||||
Serial.println();
|
Serial.println();
|
||||||
|
|
||||||
bootStartMs = millis();
|
bootStartMs = millis();
|
||||||
lastTime = lastBattTime = lastHeartbeat = lastTelemetry = millis();
|
lastTime = lastBattTime = lastHeartbeat = lastTelemetry = millis();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Loop ─────────────────────────────────────────────────────────────────────
|
// Loop
|
||||||
void loop() {
|
void loop() {
|
||||||
unsigned long now = millis();
|
unsigned long now = millis();
|
||||||
|
|
||||||
@@ -294,19 +281,39 @@ void loop() {
|
|||||||
#ifdef FEATURE_BOOT_LOOP_DETECT
|
#ifdef FEATURE_BOOT_LOOP_DETECT
|
||||||
if (!bootCountCleared && (now - bootStartMs >= BOOT_SAFE_MS)) {
|
if (!bootCountCleared && (now - bootStartMs >= BOOT_SAFE_MS)) {
|
||||||
bootCount = 0; bootCountCleared = true;
|
bootCount = 0; bootCountCleared = true;
|
||||||
Serial.println("[BOOT] Stable — counter cleared");
|
Serial.println("[BOOT] Stable - counter cleared");
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Serial commands: 'c' = calibrate, 'r' = factory reset
|
// Serial commands: 'c' = calibrate, 'r' = factory reset, 'd' = axis diagnostic
|
||||||
|
static unsigned long diagUntil = 0;
|
||||||
while (Serial.available()) {
|
while (Serial.available()) {
|
||||||
char cmd = Serial.read();
|
char cmd = Serial.read();
|
||||||
if (cmd == 'c') { Serial.println("[SERIAL] Calibrate"); pendingCal = true; }
|
if (cmd == 'c') { Serial.println("[SERIAL] Calibrate"); pendingCal = true; }
|
||||||
if (cmd == 'r') { Serial.println("[SERIAL] Reset"); pendingReset = true; }
|
if (cmd == 'r') { Serial.println("[SERIAL] Reset"); pendingReset = true; }
|
||||||
|
if (cmd == 'd') { Serial.println("[DIAG] Printing raw gyro for 10s — pan, nod, roll one at a time"); diagUntil = now + 10000; }
|
||||||
|
#ifdef FEATURE_OTA
|
||||||
|
if (cmd == 'o') { Serial.println("[SERIAL] OTA DFU"); pendingOTA = true; }
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pendingCal) { pendingCal = false; calibrateGyroBias(); prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ(); }
|
if (pendingCal) { pendingCal = false; calibrateGyroBias(); }
|
||||||
if (pendingReset) { pendingReset = false; factoryReset(); }
|
if (pendingReset) { pendingReset = false; factoryReset(); }
|
||||||
|
#ifdef FEATURE_OTA
|
||||||
|
if (pendingOTA) {
|
||||||
|
pendingOTA = false;
|
||||||
|
Serial.println("[OTA] Disconnecting BLE and entering bootloader DFU mode...");
|
||||||
|
Serial.flush();
|
||||||
|
// Gracefully close the BLE connection first so the host can detect the
|
||||||
|
// disconnect and be ready to see DfuTarg advertise after the reboot.
|
||||||
|
if (Bluefruit.connected()) {
|
||||||
|
Bluefruit.disconnect(0);
|
||||||
|
delay(300);
|
||||||
|
}
|
||||||
|
delay(200);
|
||||||
|
enterOTADfu(); // Adafruit nRF52 core: sets GPREGRET correctly and resets into bootloader OTA mode
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
// Heartbeat LED
|
// Heartbeat LED
|
||||||
if (now - lastHeartbeat >= HEARTBEAT_MS) {
|
if (now - lastHeartbeat >= HEARTBEAT_MS) {
|
||||||
@@ -320,9 +327,18 @@ void loop() {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifdef FEATURE_TAP_DETECTION
|
#ifdef FEATURE_TAP_DETECTION
|
||||||
processTaps(now);
|
if (cfg.featureFlags & FLAG_TAP_ENABLED) processTaps(now);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifdef FEATURE_PHYSICAL_BUTTONS
|
||||||
|
processPhysicalButtons();
|
||||||
|
#endif
|
||||||
|
{
|
||||||
|
bool idle_for_sleep = (sleepStage == SLEEP_IMU_LP) ? true
|
||||||
|
: (idleFrames >= IDLE_FRAMES);
|
||||||
|
if (sleepManagerUpdate(now, idle_for_sleep, Bluefruit.connected())) return;
|
||||||
|
}
|
||||||
|
|
||||||
if (now - lastTime < (unsigned long)LOOP_RATE_MS) return;
|
if (now - lastTime < (unsigned long)LOOP_RATE_MS) return;
|
||||||
float dt = (now - lastTime) / 1000.0f;
|
float dt = (now - lastTime) / 1000.0f;
|
||||||
lastTime = now;
|
lastTime = now;
|
||||||
@@ -339,83 +355,38 @@ void loop() {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Gyro reads with optional temperature compensation
|
// Gyro reads with optional temperature compensation.
|
||||||
float gx, gy, gz;
|
float correction = 0.0f;
|
||||||
#ifdef FEATURE_TEMP_COMPENSATION
|
#ifdef FEATURE_TEMP_COMPENSATION
|
||||||
float correction = TEMP_COMP_COEFF_DPS_C * (cachedTempC - calTempC);
|
if (cfg.featureFlags & FLAG_TEMP_COMP_ENABLED)
|
||||||
gx = (imu.readFloatGyroX() - biasGX - correction) * (PI/180.0f);
|
correction = TEMP_COMP_COEFF_DPS_C * (cachedTempC - calTempC);
|
||||||
gy = (imu.readFloatGyroY() - biasGY - correction) * (PI/180.0f);
|
|
||||||
gz = (imu.readFloatGyroZ() - biasGZ - correction) * (PI/180.0f);
|
|
||||||
#else
|
|
||||||
gx = (imu.readFloatGyroX() - biasGX) * (PI/180.0f);
|
|
||||||
gy = (imu.readFloatGyroY() - biasGY) * (PI/180.0f);
|
|
||||||
gz = (imu.readFloatGyroZ() - biasGZ) * (PI/180.0f);
|
|
||||||
#endif
|
#endif
|
||||||
|
float gx = (imu.readFloatGyroX() - biasGX) * (PI/180.0f); // roll (unused for cursor)
|
||||||
|
float gy = (imu.readFloatGyroY() - biasGY - correction) * (PI/180.0f); // pitch → cursor Y
|
||||||
|
float gz = (imu.readFloatGyroZ() - biasGZ - correction) * (PI/180.0f); // yaw → cursor X
|
||||||
|
|
||||||
float ax = imu.readFloatAccelX();
|
// Axis diagnostic — send 'd' over serial to enable
|
||||||
float ay = imu.readFloatAccelY();
|
if (diagUntil && now < diagUntil) {
|
||||||
float az = imu.readFloatAccelZ();
|
static unsigned long lastDiagPrint = 0;
|
||||||
|
if (now - lastDiagPrint >= 100) { lastDiagPrint = now;
|
||||||
// ── Jerk-based shock detection — freeze cursor during tap impacts ────────
|
Serial.print("[DIAG] gx="); Serial.print(gx,3);
|
||||||
// Jerk = da/dt. Normal rotation = smooth accel changes (low jerk);
|
Serial.print(" gy="); Serial.print(gy,3);
|
||||||
// a tap is a sharp impulse (very high jerk).
|
Serial.print(" gz="); Serial.println(gz,3);
|
||||||
float jx = (ax - prevAx) / dt, jy = (ay - prevAy) / dt, jz = (az - prevAz) / dt;
|
|
||||||
float jerkSq = jx*jx + jy*jy + jz*jz;
|
|
||||||
prevAx = ax; prevAy = ay; prevAz = az;
|
|
||||||
bool shocked = (jerkSq > cfg.jerkThreshold) || (now < shockFreezeUntil);
|
|
||||||
if (jerkSq > cfg.jerkThreshold) shockFreezeUntil = now + SHOCK_FREEZE_MS;
|
|
||||||
|
|
||||||
// Complementary filter — gx=pitch axis, gz=yaw axis on this board layout
|
|
||||||
// During shock: gyro-only integration to avoid accel spike corrupting angles
|
|
||||||
if (shocked) {
|
|
||||||
angleX += gx * dt;
|
|
||||||
angleY += gz * dt;
|
|
||||||
} else {
|
|
||||||
angleX = ALPHA*(angleX + gx*dt) + (1.0f - ALPHA)*atan2f(ax, sqrtf(ay*ay + az*az));
|
|
||||||
angleY = ALPHA*(angleY + gz*dt) + (1.0f - ALPHA)*atan2f(ay, sqrtf(ax*ax + az*az));
|
|
||||||
}
|
}
|
||||||
|
} else if (diagUntil) { diagUntil = 0; Serial.println("[DIAG] Done"); }
|
||||||
|
|
||||||
// ── Gravity-based axis decomposition ──────────────────────────────────────
|
// Direct axis mapping (empirically verified via diagnostic)
|
||||||
// Low-pass filter accel to get a stable gravity estimate in device frame.
|
float yawRate = gz; // gyroZ = pan left/right → cursor X
|
||||||
// This lets us project angular velocity onto world-aligned axes regardless
|
float pitchRate = gy; // gyroY = nod up/down → cursor Y
|
||||||
// of how the device is rolled. Device forward (pointing) axis = X.
|
|
||||||
// Confirmed by diagnostics: GX=roll, GY=nod, GZ=pan in user's hold.
|
|
||||||
// Skip update during shock to protect the gravity estimate from tap spikes.
|
|
||||||
const float GRAV_LP = 0.05f;
|
|
||||||
if (!shocked) {
|
|
||||||
gravX += GRAV_LP * (ax - gravX);
|
|
||||||
gravY += GRAV_LP * (ay - gravY);
|
|
||||||
gravZ += GRAV_LP * (az - gravZ);
|
|
||||||
}
|
|
||||||
|
|
||||||
float gN = sqrtf(gravX*gravX + gravY*gravY + gravZ*gravZ);
|
// Dead zone (equal for both axes)
|
||||||
if (gN < 0.3f) gN = 1.0f;
|
|
||||||
float gnx = gravX/gN, gny = gravY/gN, gnz = gravZ/gN;
|
|
||||||
|
|
||||||
// Screen-right = cross(forward, up) = cross([1,0,0], [gnx,gny,gnz])
|
|
||||||
// = [0, -gnz, gny]
|
|
||||||
float ry = -gnz, rz = gny;
|
|
||||||
float rN = sqrtf(ry*ry + rz*rz);
|
|
||||||
if (rN < 0.01f) { ry = -1.0f; rz = 0.0f; rN = 1.0f; }
|
|
||||||
ry /= rN; rz /= rN;
|
|
||||||
|
|
||||||
// Yaw (cursor X) = angular velocity component around gravity (vertical)
|
|
||||||
// Pitch (cursor Y) = angular velocity component around screen-right
|
|
||||||
float yawRate = gx*gnx + gy*gny + gz*gnz;
|
|
||||||
float pitchRate = -(gy*ry + gz*rz);
|
|
||||||
|
|
||||||
// Projected rates amplify residual gyro bias (especially GY drift on pitch axis).
|
|
||||||
// Use a wider dead zone for pitch to prevent constant cursor drift at rest.
|
|
||||||
float fYaw = (fabsf(yawRate) > cfg.deadZone) ? yawRate : 0.0f;
|
float fYaw = (fabsf(yawRate) > cfg.deadZone) ? yawRate : 0.0f;
|
||||||
float fPitch = (fabsf(pitchRate) > cfg.deadZone * 3.0f) ? pitchRate : 0.0f;
|
float fPitch = (fabsf(pitchRate) > cfg.deadZone) ? pitchRate : 0.0f;
|
||||||
|
|
||||||
// DIAG: print every 500ms to debug gravity projection — remove when confirmed
|
|
||||||
#ifdef DEBUG
|
#ifdef DEBUG
|
||||||
{ static unsigned long lastDiag = 0;
|
{ static unsigned long lastDiag = 0;
|
||||||
if (now - lastDiag >= 500) { lastDiag = now;
|
if (now - lastDiag >= 500) { lastDiag = now;
|
||||||
Serial.print("[PROJ] grav="); Serial.print(gnx,2); Serial.print(","); Serial.print(gny,2); Serial.print(","); Serial.print(gnz,2);
|
Serial.print("[IMU] gyro="); Serial.print(gx,2); Serial.print(","); Serial.print(gy,2); Serial.print(","); Serial.print(gz,2);
|
||||||
Serial.print(" R="); Serial.print(ry,2); Serial.print(","); Serial.print(rz,2);
|
|
||||||
Serial.print(" gyro="); Serial.print(gx,2); Serial.print(","); Serial.print(gy,2); Serial.print(","); Serial.print(gz,2);
|
|
||||||
Serial.print(" yaw="); Serial.print(yawRate,3); Serial.print(" pitch="); Serial.println(pitchRate,3);
|
Serial.print(" yaw="); Serial.print(yawRate,3); Serial.print(" pitch="); Serial.println(pitchRate,3);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -427,20 +398,19 @@ void loop() {
|
|||||||
bool idle = (idleFrames >= IDLE_FRAMES);
|
bool idle = (idleFrames >= IDLE_FRAMES);
|
||||||
|
|
||||||
#ifdef FEATURE_AUTO_RECAL
|
#ifdef FEATURE_AUTO_RECAL
|
||||||
if (idle && idleStartMs != 0 && (now - idleStartMs >= AUTO_RECAL_MS)) {
|
if ((cfg.featureFlags & FLAG_AUTO_RECAL_ENABLED) && idle && idleStartMs != 0 && (now - idleStartMs >= AUTO_RECAL_MS)) {
|
||||||
Serial.println("[AUTO-CAL] Long idle — recalibrating...");
|
Serial.println("[AUTO-CAL] Long idle - recalibrating...");
|
||||||
idleStartMs = 0; calibrateGyroBias(); prevAx = imu.readFloatAccelX(); prevAy = imu.readFloatAccelY(); prevAz = imu.readFloatAccelZ(); return;
|
idleStartMs = 0; calibrateGyroBias(); return;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
int8_t moveX = 0, moveY = 0;
|
int8_t moveX = 0, moveY = 0;
|
||||||
uint8_t flags = 0;
|
uint8_t flags = 0;
|
||||||
|
|
||||||
if (shocked) {
|
static float smoothX = 0.0f, smoothY = 0.0f;
|
||||||
// Shock freeze — discard accumulated sub-pixel motion and suppress output
|
|
||||||
accumX = accumY = 0.0f;
|
if (idle) {
|
||||||
flags |= 0x08; // bit3 = shock freeze active
|
smoothX = smoothY = 0.0f;
|
||||||
} else if (idle) {
|
|
||||||
accumX = accumY = 0.0f;
|
accumX = accumY = 0.0f;
|
||||||
flags |= 0x01;
|
flags |= 0x01;
|
||||||
} else {
|
} else {
|
||||||
@@ -448,7 +418,10 @@ void loop() {
|
|||||||
float rawY = applyAcceleration(applyCurve(-fPitch * cfg.sensitivity * dt));
|
float rawY = applyAcceleration(applyCurve(-fPitch * cfg.sensitivity * dt));
|
||||||
if (cfg.axisFlip & 0x01) rawX = -rawX;
|
if (cfg.axisFlip & 0x01) rawX = -rawX;
|
||||||
if (cfg.axisFlip & 0x02) rawY = -rawY;
|
if (cfg.axisFlip & 0x02) rawY = -rawY;
|
||||||
accumX += rawX; accumY += rawY;
|
// Single-pole low-pass smoothing
|
||||||
|
smoothX = smoothX * (1.0f - SMOOTH_ALPHA) + rawX * SMOOTH_ALPHA;
|
||||||
|
smoothY = smoothY * (1.0f - SMOOTH_ALPHA) + rawY * SMOOTH_ALPHA;
|
||||||
|
accumX += smoothX; accumY += smoothY;
|
||||||
moveX = (int8_t)constrain((int)accumX, -127, 127);
|
moveX = (int8_t)constrain((int)accumX, -127, 127);
|
||||||
moveY = (int8_t)constrain((int)accumY, -127, 127);
|
moveY = (int8_t)constrain((int)accumY, -127, 127);
|
||||||
accumX -= moveX; accumY -= moveY;
|
accumX -= moveX; accumY -= moveY;
|
||||||
@@ -461,8 +434,9 @@ void loop() {
|
|||||||
lastImuStream = now;
|
lastImuStream = now;
|
||||||
|
|
||||||
if (now < streamBackoffUntil) {
|
if (now < streamBackoffUntil) {
|
||||||
// Backing off — host TX buffer congested, skip to avoid 100ms block
|
// Backing off - host TX buffer congested, skip to avoid 100ms block
|
||||||
} else {
|
} else {
|
||||||
|
float ax = imu.readFloatAccelX(), ay = imu.readFloatAccelY(), az = imu.readFloatAccelZ();
|
||||||
ImuPacket pkt;
|
ImuPacket pkt;
|
||||||
pkt.gyroX_mDPS = (int16_t)constrain(gx*(180.f/PI)*1000.f, -32000, 32000);
|
pkt.gyroX_mDPS = (int16_t)constrain(gx*(180.f/PI)*1000.f, -32000, 32000);
|
||||||
pkt.gyroZ_mDPS = (int16_t)constrain(gz*(180.f/PI)*1000.f, -32000, 32000);
|
pkt.gyroZ_mDPS = (int16_t)constrain(gz*(180.f/PI)*1000.f, -32000, 32000);
|
||||||
@@ -482,7 +456,7 @@ void loop() {
|
|||||||
if (streamConsecFails >= STREAM_BACKOFF_THRESH) {
|
if (streamConsecFails >= STREAM_BACKOFF_THRESH) {
|
||||||
streamBackoffUntil = now + STREAM_BACKOFF_MS;
|
streamBackoffUntil = now + STREAM_BACKOFF_MS;
|
||||||
streamConsecFails = 0;
|
streamConsecFails = 0;
|
||||||
Serial.print("[STREAM] TX congested — backing off ");
|
Serial.print("[STREAM] TX congested - backing off ");
|
||||||
Serial.print(STREAM_BACKOFF_MS); Serial.println("ms");
|
Serial.print(STREAM_BACKOFF_MS); Serial.println("ms");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,364 @@
|
|||||||
|
#include "sleep.h"
|
||||||
|
#include "imu.h" // config.h REG_* macros
|
||||||
|
#include <bluefruit.h> // sd_app_evt_wait()
|
||||||
|
#include "Wire.h"
|
||||||
|
|
||||||
|
// Registers not in config.h
|
||||||
|
#define SLP_CTRL2_G 0x11
|
||||||
|
#define SLP_CTRL6_C 0x15
|
||||||
|
#define SLP_CTRL7_G 0x16
|
||||||
|
#define SLP_WAKE_UP_DUR 0x5C
|
||||||
|
#define SLP_WAKE_UP_SRC 0x1B
|
||||||
|
|
||||||
|
#define LSM_ADDR 0x6A
|
||||||
|
|
||||||
|
#define XL_ODR_26HZ 0x20
|
||||||
|
#define XL_ODR_416HZ 0x60
|
||||||
|
#define G_ODR_416HZ 0x60
|
||||||
|
|
||||||
|
// Module state
|
||||||
|
volatile SleepStage sleepStage = SLEEP_AWAKE;
|
||||||
|
volatile bool imuWakeFlag = false;
|
||||||
|
|
||||||
|
static unsigned long idleEnteredMs = 0; // when motion pipeline first went idle
|
||||||
|
static unsigned long wakeSettleMs = 0; // when sleepManagerWakeIMU() was called
|
||||||
|
static unsigned long lpEnteredMs = 0; // when IMU LP was entered (for recal decision)
|
||||||
|
|
||||||
|
static bool wasIdle = false;
|
||||||
|
static uint8_t savedCtrl1XL = XL_ODR_416HZ;
|
||||||
|
static uint8_t savedCtrl2G = G_ODR_416HZ;
|
||||||
|
static volatile bool pendingWakeSettle = false; // always set on wake - 120ms blackout
|
||||||
|
static volatile bool pendingWakeRecal = false; // set only when recal is also needed
|
||||||
|
|
||||||
|
// Only force recalibration after waking from deep sleep, or after the gyro
|
||||||
|
// has been off long enough for thermal drift to matter (~5 minutes).
|
||||||
|
static constexpr unsigned long RECAL_AFTER_LP_MS = 5UL * 60UL * 1000UL;
|
||||||
|
|
||||||
|
// Post-wake stillness gate: don't calibrate while the device is moving.
|
||||||
|
// Each axis of the gyro must stay below RECAL_STILL_DPS for RECAL_STILL_FRAMES
|
||||||
|
// consecutive loop ticks before calibration fires. If the device keeps moving
|
||||||
|
// past RECAL_WAIT_MAX_MS, recal is skipped and the pre-sleep bias is kept.
|
||||||
|
static constexpr float RECAL_STILL_DPS = 10.0f; // deg/s per axis
|
||||||
|
static constexpr uint8_t RECAL_STILL_FRAMES = 10; // ~100 ms at 10 ms/frame
|
||||||
|
static constexpr unsigned long RECAL_WAIT_MAX_MS = 3000; // give up after 3 s
|
||||||
|
|
||||||
|
static uint8_t recalStillFrames = 0;
|
||||||
|
static unsigned long recalLastWarnMs = 0;
|
||||||
|
|
||||||
|
// I2C helpers - Wire1 at 0x6A (SA0 LOW on XIAO nRF52840 Sense)
|
||||||
|
static uint8_t lsmRead(uint8_t reg) {
|
||||||
|
Wire1.beginTransmission(LSM_ADDR);
|
||||||
|
Wire1.write(reg);
|
||||||
|
Wire1.endTransmission(false);
|
||||||
|
Wire1.requestFrom(LSM_ADDR, (uint8_t)1);
|
||||||
|
return Wire1.available() ? Wire1.read() : 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void lsmWrite(uint8_t reg, uint8_t val) {
|
||||||
|
Wire1.beginTransmission(LSM_ADDR);
|
||||||
|
Wire1.write(reg);
|
||||||
|
Wire1.write(val);
|
||||||
|
Wire1.endTransmission();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ISR
|
||||||
|
static void imuInt1ISR() {
|
||||||
|
imuWakeFlag = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static volatile bool btnWakeFlag = false;
|
||||||
|
static void btnWakeISR() {
|
||||||
|
btnWakeFlag = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Arm wakeup interrupt
|
||||||
|
static void armWakeupInterrupt() {
|
||||||
|
lsmWrite(SLP_WAKE_UP_DUR, (uint8_t)((SLEEP_WAKEUP_DUR & 0x03) << 4));
|
||||||
|
|
||||||
|
// Preserve bit7 (tap single/double enable)
|
||||||
|
uint8_t wuth = lsmRead(REG_WAKE_UP_THS);
|
||||||
|
wuth = (wuth & 0xC0) | (SLEEP_WAKEUP_THS & 0x3F);
|
||||||
|
lsmWrite(REG_WAKE_UP_THS, wuth);
|
||||||
|
|
||||||
|
// INTERRUPTS_ENABLE=1, SLOPE_FDS=0 (HP filter is gated in LP - must be 0)
|
||||||
|
uint8_t tcfg = lsmRead(REG_TAP_CFG);
|
||||||
|
tcfg |= (1 << 7);
|
||||||
|
tcfg &= ~(1 << 4);
|
||||||
|
lsmWrite(REG_TAP_CFG, tcfg);
|
||||||
|
|
||||||
|
uint8_t md1 = lsmRead(REG_MD1_CFG);
|
||||||
|
md1 |= (1 << 5);
|
||||||
|
lsmWrite(REG_MD1_CFG, md1);
|
||||||
|
|
||||||
|
// Clear any stale latch BEFORE re-arming the edge interrupt.
|
||||||
|
(void)lsmRead(SLP_WAKE_UP_SRC);
|
||||||
|
delay(2);
|
||||||
|
|
||||||
|
// Re-attach with RISING - guaranteed clean edge now that latch is cleared
|
||||||
|
detachInterrupt(digitalPinToInterrupt(IMU_INT1_PIN));
|
||||||
|
attachInterrupt(digitalPinToInterrupt(IMU_INT1_PIN), imuInt1ISR, RISING);
|
||||||
|
imuWakeFlag = false;
|
||||||
|
|
||||||
|
#ifdef DEBUG
|
||||||
|
Serial.print("[SLEEP] armWakeup - TAP_CFG=0x"); Serial.print(lsmRead(REG_TAP_CFG), HEX);
|
||||||
|
Serial.print(" MD1_CFG=0x"); Serial.print(lsmRead(REG_MD1_CFG), HEX);
|
||||||
|
Serial.print(" WAKE_UP_THS=0x"); Serial.println(lsmRead(REG_WAKE_UP_THS), HEX);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
static void disarmWakeupInterrupt() {
|
||||||
|
// Restore SLOPE_FDS=1 for tap detection HP filter path
|
||||||
|
uint8_t tcfg = lsmRead(REG_TAP_CFG);
|
||||||
|
tcfg |= (1 << 4);
|
||||||
|
lsmWrite(REG_TAP_CFG, tcfg);
|
||||||
|
|
||||||
|
// Clear INT1_WU to stop wakeup engine driving INT1 at full rate
|
||||||
|
uint8_t md1 = lsmRead(REG_MD1_CFG);
|
||||||
|
md1 &= ~(1 << 5);
|
||||||
|
lsmWrite(REG_MD1_CFG, md1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enter IMU LP
|
||||||
|
static void enterImuLP() {
|
||||||
|
if (sleepStage >= SLEEP_IMU_LP) return;
|
||||||
|
|
||||||
|
savedCtrl1XL = lsmRead(REG_CTRL1_XL);
|
||||||
|
savedCtrl2G = lsmRead(SLP_CTRL2_G);
|
||||||
|
|
||||||
|
lsmWrite(SLP_CTRL2_G, savedCtrl2G & 0x0F); // gyro off
|
||||||
|
lsmWrite(REG_CTRL1_XL, (savedCtrl1XL & 0x0F) | XL_ODR_26HZ); // accel 26 Hz
|
||||||
|
lsmWrite(SLP_CTRL6_C, lsmRead(SLP_CTRL6_C) | (1 << 4)); // XL_HM_MODE=1
|
||||||
|
lsmWrite(SLP_CTRL7_G, lsmRead(SLP_CTRL7_G) | (1 << 7)); // G_HM_MODE=1
|
||||||
|
|
||||||
|
armWakeupInterrupt();
|
||||||
|
|
||||||
|
// Arm button wake interrupt
|
||||||
|
#if BTN_LEFT_PIN != BTN_PIN_NONE
|
||||||
|
btnWakeFlag = false;
|
||||||
|
attachInterrupt(digitalPinToInterrupt(BTN_LEFT_PIN), btnWakeISR, FALLING);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Turn off all LEDs for sleep
|
||||||
|
digitalWrite(LED_RED, HIGH); digitalWrite(LED_GREEN, HIGH); digitalWrite(LED_BLUE, HIGH);
|
||||||
|
|
||||||
|
lpEnteredMs = millis();
|
||||||
|
sleepStage = SLEEP_IMU_LP;
|
||||||
|
Serial.print("[SLEEP] IMU LP entered - idle for ");
|
||||||
|
Serial.print((millis() - idleEnteredMs) / 1000); Serial.println("s");
|
||||||
|
|
||||||
|
#ifdef DEBUG
|
||||||
|
Serial.print("[SLEEP] CTRL1_XL=0x"); Serial.print(lsmRead(REG_CTRL1_XL), HEX);
|
||||||
|
Serial.print(" CTRL2_G=0x"); Serial.print(lsmRead(SLP_CTRL2_G), HEX);
|
||||||
|
Serial.print(" CTRL6_C=0x"); Serial.print(lsmRead(SLP_CTRL6_C), HEX);
|
||||||
|
Serial.print(" CTRL7_G=0x"); Serial.println(lsmRead(SLP_CTRL7_G), HEX);
|
||||||
|
Serial.print("[SLEEP] TAP_CFG=0x"); Serial.print(lsmRead(REG_TAP_CFG), HEX);
|
||||||
|
Serial.print(" MD1_CFG=0x"); Serial.print(lsmRead(REG_MD1_CFG), HEX);
|
||||||
|
Serial.print(" WAKE_UP_THS=0x"); Serial.print(lsmRead(REG_WAKE_UP_THS), HEX);
|
||||||
|
Serial.print(" WAKE_UP_DUR=0x"); Serial.println(lsmRead(SLP_WAKE_UP_DUR), HEX);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enter deep sleep
|
||||||
|
static void enterDeepSleep() {
|
||||||
|
if (sleepStage >= SLEEP_DEEP) return;
|
||||||
|
if (sleepStage < SLEEP_IMU_LP) enterImuLP();
|
||||||
|
|
||||||
|
sleepStage = SLEEP_DEEP;
|
||||||
|
Serial.println("[SLEEP] Deep sleep - WFE on INT1");
|
||||||
|
Serial.flush();
|
||||||
|
|
||||||
|
digitalWrite(LED_RED, HIGH); digitalWrite(LED_GREEN, HIGH); digitalWrite(LED_BLUE, HIGH);
|
||||||
|
|
||||||
|
while (!imuWakeFlag && !btnWakeFlag) {
|
||||||
|
(void)lsmRead(SLP_WAKE_UP_SRC);
|
||||||
|
sd_app_evt_wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public: wake
|
||||||
|
void sleepManagerWakeIMU() {
|
||||||
|
(void)lsmRead(SLP_WAKE_UP_SRC);
|
||||||
|
|
||||||
|
lsmWrite(SLP_CTRL6_C, lsmRead(SLP_CTRL6_C) & ~(1 << 4));
|
||||||
|
lsmWrite(SLP_CTRL7_G, lsmRead(SLP_CTRL7_G) & ~(1 << 7));
|
||||||
|
lsmWrite(REG_CTRL1_XL, savedCtrl1XL);
|
||||||
|
lsmWrite(SLP_CTRL2_G, savedCtrl2G);
|
||||||
|
|
||||||
|
disarmWakeupInterrupt();
|
||||||
|
|
||||||
|
// Detach button wake interrupt — normal polling takes over
|
||||||
|
#if BTN_LEFT_PIN != BTN_PIN_NONE
|
||||||
|
detachInterrupt(digitalPinToInterrupt(BTN_LEFT_PIN));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Only recalibrate if gyro was off long enough for thermal drift to accumulate,
|
||||||
|
// or if waking from full deep sleep. Short LP naps reuse the existing bias.
|
||||||
|
unsigned long lpDuration = millis() - lpEnteredMs;
|
||||||
|
bool needsRecal = (sleepStage == SLEEP_DEEP) || (lpDuration >= RECAL_AFTER_LP_MS);
|
||||||
|
|
||||||
|
wakeSettleMs = millis();
|
||||||
|
pendingWakeSettle = true; // always block output for 120ms
|
||||||
|
pendingWakeRecal = needsRecal; // additionally recalibrate if needed
|
||||||
|
|
||||||
|
wasIdle = false;
|
||||||
|
idleEnteredMs = 0;
|
||||||
|
lpEnteredMs = 0;
|
||||||
|
|
||||||
|
// Reset motion filter state to prevent a cursor jump on the first frame.
|
||||||
|
extern float accumX, accumY;
|
||||||
|
extern unsigned long lastTime;
|
||||||
|
accumX = accumY = 0.0f;
|
||||||
|
lastTime = millis();
|
||||||
|
|
||||||
|
sleepStage = SLEEP_AWAKE;
|
||||||
|
if (needsRecal)
|
||||||
|
Serial.println("[SLEEP] Awake - gyro settling, recal needed");
|
||||||
|
else
|
||||||
|
Serial.println("[SLEEP] Awake - short LP, reusing existing bias");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public: init
|
||||||
|
void sleepManagerInit() {
|
||||||
|
pinMode(IMU_INT1_PIN, INPUT);
|
||||||
|
attachInterrupt(digitalPinToInterrupt(IMU_INT1_PIN), imuInt1ISR, RISING);
|
||||||
|
|
||||||
|
// Sanity check: WHO_AM_I should return 0x6A for LSM6DS3
|
||||||
|
uint8_t whoami = imuReadReg(0x0F);
|
||||||
|
Serial.print("[SLEEP] WHO_AM_I=0x"); Serial.print(whoami, HEX);
|
||||||
|
if (whoami == 0x6A) Serial.println(" (OK)");
|
||||||
|
else Serial.println(" (WRONG - I2C not working, sleep disabled)");
|
||||||
|
|
||||||
|
if (whoami != 0x6A) return; // don't arm anything if we can't talk to the IMU
|
||||||
|
|
||||||
|
Serial.print("[SLEEP] Init - INT1 pin="); Serial.print(IMU_INT1_PIN);
|
||||||
|
Serial.print(", WU_THS="); Serial.print(SLEEP_WAKEUP_THS);
|
||||||
|
Serial.print(" (~"); Serial.print(SLEEP_WAKEUP_THS * 7.8f, 0); Serial.print(" mg)");
|
||||||
|
Serial.print(", IMU_LP after "); Serial.print(SLEEP_IMU_IDLE_MS / 1000); Serial.print("s");
|
||||||
|
Serial.print(", deep after "); Serial.print(SLEEP_DEEP_IDLE_MS / 1000); Serial.println("s");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public: per-loop update
|
||||||
|
// Must be called AFTER idleFrames/idle is updated by the motion pipeline.
|
||||||
|
// Returns true → caller must skip IMU reads this iteration.
|
||||||
|
bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected) {
|
||||||
|
|
||||||
|
// ISR wakeup (IMU motion or button press)
|
||||||
|
bool woke = false;
|
||||||
|
if (imuWakeFlag) {
|
||||||
|
imuWakeFlag = false;
|
||||||
|
Serial.print("[SLEEP] INT1 fired - stage="); Serial.println((int)sleepStage);
|
||||||
|
woke = true;
|
||||||
|
}
|
||||||
|
if (btnWakeFlag) {
|
||||||
|
btnWakeFlag = false;
|
||||||
|
Serial.print("[SLEEP] Button fired - stage="); Serial.println((int)sleepStage);
|
||||||
|
woke = true;
|
||||||
|
}
|
||||||
|
if (woke) {
|
||||||
|
if (sleepStage == SLEEP_DEEP || sleepStage == SLEEP_IMU_LP) {
|
||||||
|
sleepManagerWakeIMU();
|
||||||
|
} else {
|
||||||
|
(void)lsmRead(SLP_WAKE_UP_SRC);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Post-wake recalibration — gated on device being still
|
||||||
|
if (pendingWakeRecal) {
|
||||||
|
if (nowMs - wakeSettleMs < 120) return true; // initial hardware settle
|
||||||
|
|
||||||
|
// Sample gyro magnitude; each axis must be below threshold
|
||||||
|
float gx = fabsf(imu.readFloatGyroX());
|
||||||
|
float gy = fabsf(imu.readFloatGyroY());
|
||||||
|
float gz = fabsf(imu.readFloatGyroZ());
|
||||||
|
bool still = (gx < RECAL_STILL_DPS && gy < RECAL_STILL_DPS && gz < RECAL_STILL_DPS);
|
||||||
|
|
||||||
|
if (!still) {
|
||||||
|
recalStillFrames = 0;
|
||||||
|
// Rate-limited log so we don't flood serial while waiting
|
||||||
|
if (nowMs - recalLastWarnMs >= 500) {
|
||||||
|
recalLastWarnMs = nowMs;
|
||||||
|
Serial.print("[SLEEP] Waiting for still: gx="); Serial.print(gx, 1);
|
||||||
|
Serial.print(" gy="); Serial.print(gy, 1);
|
||||||
|
Serial.print(" gz="); Serial.println(gz, 1);
|
||||||
|
}
|
||||||
|
if (nowMs - wakeSettleMs >= RECAL_WAIT_MAX_MS) {
|
||||||
|
// Device never settled — keep pre-sleep bias rather than corrupt it
|
||||||
|
pendingWakeRecal = false;
|
||||||
|
recalStillFrames = 0;
|
||||||
|
recalLastWarnMs = 0;
|
||||||
|
Serial.println("[SLEEP] Recal skipped — device still moving after timeout");
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Device is still — accumulate consecutive still frames
|
||||||
|
if (++recalStillFrames < RECAL_STILL_FRAMES) return true;
|
||||||
|
|
||||||
|
pendingWakeRecal = false;
|
||||||
|
recalStillFrames = 0;
|
||||||
|
recalLastWarnMs = 0;
|
||||||
|
calibrateGyroBias();
|
||||||
|
Serial.println("[SLEEP] Post-wake recal done");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// IMU_LP path
|
||||||
|
// main.cpp returns early when we return true, so idleFrames never increments
|
||||||
|
// and the motion pipeline's `idle` flag is stale. Use our own idleEnteredMs
|
||||||
|
// (captured before LP entry) to drive the deep-sleep countdown independently.
|
||||||
|
if (sleepStage == SLEEP_IMU_LP) {
|
||||||
|
// Periodic log: confirms loop is running, shows live INT1 pin level and
|
||||||
|
// WAKE_UP_SRC register. If INT1_pin never goes high after movement, the
|
||||||
|
// wakeup engine is not generating an interrupt - check register values.
|
||||||
|
static unsigned long lastLpLog = 0;
|
||||||
|
if (nowMs - lastLpLog >= 5000) {
|
||||||
|
lastLpLog = nowMs;
|
||||||
|
unsigned long lpSecs = idleEnteredMs ? (nowMs - idleEnteredMs) / 1000 : 0;
|
||||||
|
Serial.print("[SLEEP] LP tick - idle="); Serial.print(lpSecs);
|
||||||
|
Serial.print("s INT1="); Serial.print(digitalRead(IMU_INT1_PIN));
|
||||||
|
Serial.print(" WAKE_UP_SRC=0x"); Serial.println(lsmRead(SLP_WAKE_UP_SRC), HEX);
|
||||||
|
}
|
||||||
|
if (!bleConnected && idleEnteredMs != 0
|
||||||
|
&& (nowMs - idleEnteredMs >= SLEEP_DEEP_IDLE_MS))
|
||||||
|
{
|
||||||
|
Serial.println("[SLEEP] Deep sleep threshold reached");
|
||||||
|
enterDeepSleep();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// AWAKE path
|
||||||
|
if (!idle) {
|
||||||
|
if (wasIdle) {
|
||||||
|
Serial.println("[SLEEP] Motion - idle timer reset");
|
||||||
|
}
|
||||||
|
wasIdle = false;
|
||||||
|
idleEnteredMs = 0;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!wasIdle) {
|
||||||
|
wasIdle = true;
|
||||||
|
idleEnteredMs = nowMs;
|
||||||
|
Serial.println("[SLEEP] Idle started");
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned long idleElapsed = nowMs - idleEnteredMs;
|
||||||
|
|
||||||
|
// Progress report every 5 s while waiting for LP threshold
|
||||||
|
#ifdef DEBUG
|
||||||
|
{ static unsigned long lastReport = 0;
|
||||||
|
if (nowMs - lastReport >= 5000) { lastReport = nowMs;
|
||||||
|
Serial.print("[SLEEP] idle="); Serial.print(idleElapsed/1000);
|
||||||
|
Serial.print("s / LP@"); Serial.print(SLEEP_IMU_IDLE_MS/1000); Serial.println("s");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if (idleElapsed >= SLEEP_IMU_IDLE_MS) {
|
||||||
|
enterImuLP();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
// Tuning
|
||||||
|
#ifndef SLEEP_IMU_IDLE_MS
|
||||||
|
#define SLEEP_IMU_IDLE_MS (10UL * 1000UL) // 10 s → gyro off, accel LP
|
||||||
|
#endif
|
||||||
|
#ifndef SLEEP_DEEP_IDLE_MS
|
||||||
|
#define SLEEP_DEEP_IDLE_MS (60UL * 1000UL) // 60 s → system deep sleep (no-BLE only)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// LSM6DS3 wakeup threshold: 1 LSB = 7.8 mg at ±2 g FS (±2g range).
|
||||||
|
#ifndef SLEEP_WAKEUP_THS
|
||||||
|
#define SLEEP_WAKEUP_THS 6 // 0–63
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Number of consecutive 26 Hz samples that must exceed the threshold.
|
||||||
|
#ifndef SLEEP_WAKEUP_DUR
|
||||||
|
#define SLEEP_WAKEUP_DUR 1 // 0–3
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// GPIO pin connected to LSM6DS3 INT1.
|
||||||
|
#ifndef IMU_INT1_PIN
|
||||||
|
#define IMU_INT1_PIN PIN_LSM6DS3TR_C_INT1
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Public state (read-only from main.cpp)
|
||||||
|
enum SleepStage : uint8_t {
|
||||||
|
SLEEP_AWAKE = 0, // normal full-rate operation
|
||||||
|
SLEEP_IMU_LP = 1, // gyro off, accel LP - nRF awake
|
||||||
|
SLEEP_DEEP = 2, // system WFE - BLE disconnected only
|
||||||
|
};
|
||||||
|
|
||||||
|
extern volatile SleepStage sleepStage;
|
||||||
|
extern volatile bool imuWakeFlag;
|
||||||
|
|
||||||
|
void sleepManagerInit();
|
||||||
|
bool sleepManagerUpdate(unsigned long nowMs, bool idle, bool bleConnected);
|
||||||
|
void sleepManagerWakeIMU();
|
||||||
+4
-15
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
extern BLEHidAdafruit blehid;
|
extern BLEHidAdafruit blehid;
|
||||||
|
|
||||||
// ─── Tap detection setup ──────────────────────────────────────────────────────
|
// Tap detection setup
|
||||||
// REG_TAP_THS_6D bits[4:0] = tapThreshold (1–31); 1 LSB = FS/32 = 62.5 mg at ±2g.
|
// REG_TAP_THS_6D bits[4:0] = tapThreshold (1–31); 1 LSB = FS/32 = 62.5 mg at ±2g.
|
||||||
// REG_INT_DUR2 at ODR=416 Hz:
|
// REG_INT_DUR2 at ODR=416 Hz:
|
||||||
// SHOCK[7:6] = 2 → 38 ms max tap duration
|
// SHOCK[7:6] = 2 → 38 ms max tap duration
|
||||||
@@ -30,18 +30,7 @@ void setupTapDetection() {
|
|||||||
Serial.print(" (~"); Serial.print(cfg.tapThreshold * 62.5f, 0); Serial.println(" mg)");
|
Serial.print(" (~"); Serial.print(cfg.tapThreshold * 62.5f, 0); Serial.println(" mg)");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Tap processing ───────────────────────────────────────────────────────────
|
// Tap processing
|
||||||
// Only double-tap is mapped to an action. Single-tap is ignored (it always fires
|
|
||||||
// before the double is confirmed and cannot be reliably disambiguated on this
|
|
||||||
// hardware without an unacceptable latency penalty).
|
|
||||||
//
|
|
||||||
// The LSM6DS3 sets SINGLE_TAP immediately on first contact — we wait until
|
|
||||||
// DOUBLE_TAP is set (within the hardware DUR window of 115 ms) before acting.
|
|
||||||
// An additional TAP_CONFIRM_MS guard ensures the TAP_SRC register has settled.
|
|
||||||
//
|
|
||||||
// IMPORTANT: call mouseButtonPress(bitmask) — single arg only. The two-arg
|
|
||||||
// overload takes (conn_hdl, buttons) and sends the wrong button value.
|
|
||||||
|
|
||||||
static enum { TAP_IDLE, TAP_PENDING, TAP_EXECUTING } tapState = TAP_IDLE;
|
static enum { TAP_IDLE, TAP_PENDING, TAP_EXECUTING } tapState = TAP_IDLE;
|
||||||
static unsigned long tapPendingMs = 0;
|
static unsigned long tapPendingMs = 0;
|
||||||
static uint8_t pendingButton = 0; // 0 = key action pending
|
static uint8_t pendingButton = 0; // 0 = key action pending
|
||||||
@@ -83,7 +72,7 @@ static void fireTapAction(unsigned long now) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void processTaps(unsigned long now) {
|
void processTaps(unsigned long now) {
|
||||||
// ── Release ───────────────────────────────────────────────────────────────
|
// Release
|
||||||
if (tapState == TAP_EXECUTING) {
|
if (tapState == TAP_EXECUTING) {
|
||||||
if (now - clickDownMs >= CLICK_HOLD_MS) {
|
if (now - clickDownMs >= CLICK_HOLD_MS) {
|
||||||
if (pendingButton) {
|
if (pendingButton) {
|
||||||
@@ -99,7 +88,7 @@ void processTaps(unsigned long now) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Poll TAP_SRC ──────────────────────────────────────────────────────────
|
// Poll TAP_SRC
|
||||||
uint8_t tapSrc = imuReadReg(REG_TAP_SRC);
|
uint8_t tapSrc = imuReadReg(REG_TAP_SRC);
|
||||||
bool tapIA = !!(tapSrc & 0x40);
|
bool tapIA = !!(tapSrc & 0x40);
|
||||||
bool doubleTap = !!(tapSrc & 0x10);
|
bool doubleTap = !!(tapSrc & 0x10);
|
||||||
|
|||||||
+161
-65
@@ -1,4 +1,4 @@
|
|||||||
// ── UUIDs ────────────────────────────────────────────────────────────────────
|
// UUIDs
|
||||||
// v3.3: 4 characteristics instead of 10
|
// v3.3: 4 characteristics instead of 10
|
||||||
const SVC_UUID = '00001234-0000-1000-8000-00805f9b34fb';
|
const SVC_UUID = '00001234-0000-1000-8000-00805f9b34fb';
|
||||||
const CHR = {
|
const CHR = {
|
||||||
@@ -9,18 +9,26 @@ const CHR = {
|
|||||||
gitHash: '00001239-0000-1000-8000-00805f9b34fb', // GitHash R 8 bytes
|
gitHash: '00001239-0000-1000-8000-00805f9b34fb', // GitHash R 8 bytes
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Runtime feature-override flag bitmask constants (mirror firmware FLAG_* defines)
|
||||||
|
const FLAG_TAP_ENABLED = 0x01;
|
||||||
|
const FLAG_TEMP_COMP_ENABLED = 0x02;
|
||||||
|
const FLAG_AUTO_RECAL_ENABLED = 0x04;
|
||||||
|
const FLAG_ALL_DEFAULT = FLAG_TAP_ENABLED | FLAG_TEMP_COMP_ENABLED | FLAG_AUTO_RECAL_ENABLED;
|
||||||
|
|
||||||
// Local shadow of the current config (kept in sync with device)
|
// Local shadow of the current config (kept in sync with device)
|
||||||
const config = { sensitivity:600, deadZone:0.06, accelStrength:0.08, curve:0, axisFlip:0, chargeMode:1,
|
const config = { sensitivity:600, deadZone:0.06, accelStrength:0.08, curve:0, axisFlip:0, chargeMode:0,
|
||||||
tapThreshold:12, tapAction:0, tapKey:0, tapMod:0, jerkThreshold:2000 };
|
tapThreshold:12, tapAction:0, tapKey:0, tapMod:0, tapFreezeEnabled:1, jerkThreshold:2000,
|
||||||
|
featureFlags:FLAG_ALL_DEFAULT,
|
||||||
|
};
|
||||||
|
|
||||||
let device=null, server=null, chars={}, userDisconnected=false;
|
let device=null, server=null, chars={}, userDisconnected=false;
|
||||||
let currentChargeStatus=0, currentBattPct=null, currentBattVoltage=null;
|
let currentChargeStatus=0, currentBattPct=null, currentBattVoltage=null;
|
||||||
let advancedMode = localStorage.getItem('advanced') === 'true';
|
let advancedMode = localStorage.getItem('advanced') === 'true';
|
||||||
|
|
||||||
// ── GATT write queue (prevents "operation already in progress") ───────────────
|
// GATT write queue (prevents "operation already in progress")
|
||||||
// Serialises all GATT writes. Features:
|
// Serialises all GATT writes. Features:
|
||||||
// • Per-operation 3s timeout — hangs don't block the queue forever
|
// • Per-operation 3s timeout - hangs don't block the queue forever
|
||||||
// • Max depth of 2 pending ops — drops excess writes when device goes silent
|
// • Max depth of 2 pending ops - drops excess writes when device goes silent
|
||||||
// • gattQueueReset() flushes on disconnect so a reconnect starts clean
|
// • gattQueueReset() flushes on disconnect so a reconnect starts clean
|
||||||
const GATT_TIMEOUT_MS = 3000;
|
const GATT_TIMEOUT_MS = 3000;
|
||||||
const GATT_MAX_DEPTH = 2;
|
const GATT_MAX_DEPTH = 2;
|
||||||
@@ -29,7 +37,10 @@ let _gattDepth = 0;
|
|||||||
|
|
||||||
function _withTimeout(promise, ms) {
|
function _withTimeout(promise, ms) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const t = setTimeout(() => reject(new Error(`GATT timeout (${ms}ms)`)), ms);
|
const t = setTimeout(() => {
|
||||||
|
console.warn(`[GATT] operation timed out after ${ms}ms`);
|
||||||
|
reject(new Error(`GATT timeout (${ms}ms)`));
|
||||||
|
}, ms);
|
||||||
promise.then(v => { clearTimeout(t); resolve(v); },
|
promise.then(v => { clearTimeout(t); resolve(v); },
|
||||||
e => { clearTimeout(t); reject(e); });
|
e => { clearTimeout(t); reject(e); });
|
||||||
});
|
});
|
||||||
@@ -37,7 +48,8 @@ function _withTimeout(promise, ms) {
|
|||||||
|
|
||||||
function _enqueue(fn) {
|
function _enqueue(fn) {
|
||||||
if (_gattDepth >= GATT_MAX_DEPTH) {
|
if (_gattDepth >= GATT_MAX_DEPTH) {
|
||||||
return Promise.reject(new Error('GATT queue full — device unreachable?'));
|
console.warn(`[GATT] write dropped - queue depth ${_gattDepth} >= max ${GATT_MAX_DEPTH}`);
|
||||||
|
return Promise.reject(new Error('GATT queue full - device unreachable?'));
|
||||||
}
|
}
|
||||||
_gattDepth++;
|
_gattDepth++;
|
||||||
const p = _gattQueue.then(() => _withTimeout(fn(), GATT_TIMEOUT_MS));
|
const p = _gattQueue.then(() => _withTimeout(fn(), GATT_TIMEOUT_MS));
|
||||||
@@ -49,12 +61,13 @@ function gattWrite(char, value) { return _enqueue(() => char.writeValueWithRespo
|
|||||||
function gattCmd (char, value) { return _enqueue(() => char.writeValueWithoutResponse(value)); }
|
function gattCmd (char, value) { return _enqueue(() => char.writeValueWithoutResponse(value)); }
|
||||||
|
|
||||||
function gattQueueReset() {
|
function gattQueueReset() {
|
||||||
|
console.log('[GATT] queue reset');
|
||||||
// Drain the chain so a reconnect starts with a fresh resolved promise
|
// Drain the chain so a reconnect starts with a fresh resolved promise
|
||||||
_gattQueue = Promise.resolve();
|
_gattQueue = Promise.resolve();
|
||||||
_gattDepth = 0;
|
_gattDepth = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Logging ──────────────────────────────────────────────────────────────────
|
// Logging
|
||||||
(function() {
|
(function() {
|
||||||
const _methods = { log: '', warn: 'warn', error: 'err' };
|
const _methods = { log: '', warn: 'warn', error: 'err' };
|
||||||
for (const [method, type] of Object.entries(_methods)) {
|
for (const [method, type] of Object.entries(_methods)) {
|
||||||
@@ -77,7 +90,7 @@ function log(msg, type='') {
|
|||||||
const p2=n=>String(n).padStart(2,'0'), p3=n=>String(n).padStart(3,'0');
|
const p2=n=>String(n).padStart(2,'0'), p3=n=>String(n).padStart(3,'0');
|
||||||
function cssVar(n) { return getComputedStyle(document.documentElement).getPropertyValue(n).trim(); }
|
function cssVar(n) { return getComputedStyle(document.documentElement).getPropertyValue(n).trim(); }
|
||||||
|
|
||||||
// ── Connection ───────────────────────────────────────────────────────────────
|
// Connection
|
||||||
async function doConnect() {
|
async function doConnect() {
|
||||||
if (!navigator.bluetooth) { log('Web Bluetooth not supported.','err'); return; }
|
if (!navigator.bluetooth) { log('Web Bluetooth not supported.','err'); return; }
|
||||||
userDisconnected = false;
|
userDisconnected = false;
|
||||||
@@ -123,27 +136,26 @@ async function discoverServices() {
|
|||||||
// Read firmware git hash and check against web build hash
|
// Read firmware git hash and check against web build hash
|
||||||
await checkHashMatch();
|
await checkHashMatch();
|
||||||
|
|
||||||
// Telemetry notify (1 Hz) — also carries chargeStatus
|
// Telemetry notify (1 Hz) - also carries chargeStatus
|
||||||
chars.telemetry.addEventListener('characteristicvaluechanged', e => parseTelemetry(e.target.value));
|
chars.telemetry.addEventListener('characteristicvaluechanged', e => {
|
||||||
|
const val = e.target.value; // capture immediately — Chrome reuses the DataView buffer on next notify
|
||||||
|
parseTelemetry(val);
|
||||||
|
});
|
||||||
await chars.telemetry.startNotifications();
|
await chars.telemetry.startNotifications();
|
||||||
// Initial read so values show immediately. Also force updateChargeUI() here
|
|
||||||
// because parseTelemetry() only calls it on a *change*, and currentChargeStatus
|
|
||||||
// starts at 0 (discharging) — so a discharging device would never trigger the
|
|
||||||
// update and ciStatus would stay at '--'.
|
|
||||||
parseTelemetry(await chars.telemetry.readValue());
|
parseTelemetry(await chars.telemetry.readValue());
|
||||||
updateChargeUI();
|
updateChargeUI();
|
||||||
|
|
||||||
// IMU stream — subscribed on demand via play button
|
// IMU stream - subscribed on demand via play button
|
||||||
chars.imuStream.addEventListener('characteristicvaluechanged', e => parseImuStream(e.target.value));
|
chars.imuStream.addEventListener('characteristicvaluechanged', e => parseImuStream(e.target.value));
|
||||||
|
|
||||||
log('Config service ready (4 chars)','ok');
|
log('Config service ready (4 chars)','ok');
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
log(`Service discovery failed: ${e.message}`,'err');
|
log(`Service discovery failed: ${e.message}`,'err');
|
||||||
// Safe mode device might not have config service
|
// Safe mode device might not have config service
|
||||||
if (e.message.includes('not found')) log('Device may be in safe mode — basic mouse only','warn');
|
if (e.message.includes('not found')) log('Device may be in safe mode - basic mouse only','warn');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Battery service (standard — always present)
|
// Battery service (standard - always present)
|
||||||
try {
|
try {
|
||||||
const bsvc = await server.getPrimaryService('battery_service');
|
const bsvc = await server.getPrimaryService('battery_service');
|
||||||
const bch = await bsvc.getCharacteristic('battery_level');
|
const bch = await bsvc.getCharacteristic('battery_level');
|
||||||
@@ -159,7 +171,7 @@ async function discoverServices() {
|
|||||||
} catch(e) { log('Battery service unavailable','warn'); }
|
} catch(e) { log('Battery service unavailable','warn'); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Firmware / web hash mismatch banner ──────────────────────────────────────
|
// Firmware / web hash mismatch banner
|
||||||
async function checkHashMatch() {
|
async function checkHashMatch() {
|
||||||
const banner = document.getElementById('hashMismatchBanner');
|
const banner = document.getElementById('hashMismatchBanner');
|
||||||
if (!chars.gitHash) return;
|
if (!chars.gitHash) return;
|
||||||
@@ -191,19 +203,20 @@ async function checkHashMatch() {
|
|||||||
].join(';');
|
].join(';');
|
||||||
banner.innerHTML =
|
banner.innerHTML =
|
||||||
`<span style="font-size:14px">⚠</span>` +
|
`<span style="font-size:14px">⚠</span>` +
|
||||||
`<span>FIRMWARE / WEB MISMATCH — ` +
|
`<span>FIRMWARE / WEB MISMATCH - ` +
|
||||||
`firmware <b>${fwHash}</b> · web <b>${webHash}</b> — ` +
|
`firmware <b>${fwHash}</b> · web <b>${webHash}</b> - ` +
|
||||||
`flash firmware or reload the page after a <code>pio run</code></span>` +
|
`flash firmware or reload the page after a <code>pio run</code></span>` +
|
||||||
`<button onclick="document.getElementById('hashMismatchBanner').style.display='none'" ` +
|
`<button onclick="document.getElementById('hashMismatchBanner').style.display='none'" ` +
|
||||||
`style="margin-left:8px;background:none;border:1px solid #c04040;color:#ffd0d0;` +
|
`style="margin-left:8px;background:none;border:1px solid #c04040;color:#ffd0d0;` +
|
||||||
`cursor:pointer;padding:2px 8px;font-family:var(--mono);font-size:10px">✕</button>`;
|
`cursor:pointer;padding:2px 8px;font-family:var(--mono);font-size:10px">✕</button>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── ConfigBlob read / write ──────────────────────────────────────────────────
|
// ConfigBlob read / write
|
||||||
// ConfigBlob layout (20 bytes LE):
|
// ConfigBlob layout (25 bytes LE):
|
||||||
// float sensitivity [0], float deadZone [4], float accelStrength [8]
|
// float sensitivity [0], float deadZone [4], float accelStrength [8]
|
||||||
// uint8 curve [12], uint8 axisFlip [13], uint8 chargeMode [14]
|
// uint8 curve [12], uint8 axisFlip [13], uint8 chargeMode [14] (0=SLOW 1=FAST)
|
||||||
// uint8 tapThreshold [15], uint8 tapAction [16], uint8 tapKey [17], uint8 tapMod [18], uint8 pad [19]
|
// uint8 tapThreshold [15], uint8 tapAction [16], uint8 tapKey [17], uint8 tapMod [18], uint8 tapFreezeEnabled [19]
|
||||||
|
// float jerkThreshold [20], uint8 featureFlags [24]
|
||||||
|
|
||||||
async function readConfigBlob() {
|
async function readConfigBlob() {
|
||||||
if (!chars.configBlob) return;
|
if (!chars.configBlob) return;
|
||||||
@@ -221,12 +234,18 @@ async function readConfigBlob() {
|
|||||||
config.tapAction = view.getUint8(16);
|
config.tapAction = view.getUint8(16);
|
||||||
config.tapKey = view.getUint8(17);
|
config.tapKey = view.getUint8(17);
|
||||||
config.tapMod = view.getUint8(18);
|
config.tapMod = view.getUint8(18);
|
||||||
|
config.tapFreezeEnabled = view.getUint8(19);
|
||||||
}
|
}
|
||||||
if (view.byteLength >= 24) {
|
if (view.byteLength >= 24) {
|
||||||
config.jerkThreshold = view.getFloat32(20, true);
|
config.jerkThreshold = view.getFloat32(20, true);
|
||||||
}
|
}
|
||||||
|
if (view.byteLength >= 25) {
|
||||||
|
config.featureFlags = view.getUint8(24);
|
||||||
|
} else {
|
||||||
|
config.featureFlags = FLAG_ALL_DEFAULT; // old firmware - assume all on
|
||||||
|
}
|
||||||
applyConfigToUI();
|
applyConfigToUI();
|
||||||
log(`Config loaded — sens=${config.sensitivity.toFixed(0)} dz=${config.deadZone.toFixed(3)} tapThr=${config.tapThreshold}`,'ok');
|
log(`Config loaded - sens=${config.sensitivity.toFixed(0)} dz=${config.deadZone.toFixed(3)} tapThr=${config.tapThreshold}`,'ok');
|
||||||
} catch(e) { log(`Config read error: ${e.message}`,'err'); }
|
} catch(e) { log(`Config read error: ${e.message}`,'err'); }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,8 +260,10 @@ function applyConfigToUI() {
|
|||||||
document.getElementById('flipX').checked = !!(config.axisFlip & 1);
|
document.getElementById('flipX').checked = !!(config.axisFlip & 1);
|
||||||
document.getElementById('flipY').checked = !!(config.axisFlip & 2);
|
document.getElementById('flipY').checked = !!(config.axisFlip & 2);
|
||||||
setChargeModeUI(config.chargeMode);
|
setChargeModeUI(config.chargeMode);
|
||||||
|
document.getElementById('tapFreezeEnabled').checked = !!config.tapFreezeEnabled;
|
||||||
document.getElementById('slJerkThreshold').value = config.jerkThreshold;
|
document.getElementById('slJerkThreshold').value = config.jerkThreshold;
|
||||||
updateDisplay('jerkThreshold', config.jerkThreshold);
|
updateDisplay('jerkThreshold', config.jerkThreshold);
|
||||||
|
updateTapFreezeUI(!!config.tapFreezeEnabled);
|
||||||
document.getElementById('slTapThreshold').value = config.tapThreshold;
|
document.getElementById('slTapThreshold').value = config.tapThreshold;
|
||||||
updateDisplay('tapThreshold', config.tapThreshold);
|
updateDisplay('tapThreshold', config.tapThreshold);
|
||||||
setTapActionUI(config.tapAction);
|
setTapActionUI(config.tapAction);
|
||||||
@@ -251,8 +272,12 @@ function applyConfigToUI() {
|
|||||||
document.getElementById('tapModShift').checked = !!(config.tapMod & 0x02);
|
document.getElementById('tapModShift').checked = !!(config.tapMod & 0x02);
|
||||||
document.getElementById('tapModAlt').checked = !!(config.tapMod & 0x04);
|
document.getElementById('tapModAlt').checked = !!(config.tapMod & 0x04);
|
||||||
document.getElementById('tapModGui').checked = !!(config.tapMod & 0x08);
|
document.getElementById('tapModGui').checked = !!(config.tapMod & 0x08);
|
||||||
|
document.getElementById('capTapEnabled').checked = !!(config.featureFlags & FLAG_TAP_ENABLED);
|
||||||
|
document.getElementById('capTempComp').checked = !!(config.featureFlags & FLAG_TEMP_COMP_ENABLED);
|
||||||
|
document.getElementById('capAutoRecal').checked = !!(config.featureFlags & FLAG_AUTO_RECAL_ENABLED);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
let _writeConfigTimer = null;
|
let _writeConfigTimer = null;
|
||||||
function writeConfigBlob() {
|
function writeConfigBlob() {
|
||||||
clearTimeout(_writeConfigTimer);
|
clearTimeout(_writeConfigTimer);
|
||||||
@@ -272,10 +297,14 @@ async function _doWriteConfigBlob() {
|
|||||||
| (document.getElementById('tapModShift').checked ? 0x02 : 0)
|
| (document.getElementById('tapModShift').checked ? 0x02 : 0)
|
||||||
| (document.getElementById('tapModAlt').checked ? 0x04 : 0)
|
| (document.getElementById('tapModAlt').checked ? 0x04 : 0)
|
||||||
| (document.getElementById('tapModGui').checked ? 0x08 : 0);
|
| (document.getElementById('tapModGui').checked ? 0x08 : 0);
|
||||||
|
config.tapFreezeEnabled = document.getElementById('tapFreezeEnabled').checked ? 1 : 0;
|
||||||
config.jerkThreshold = +document.getElementById('slJerkThreshold').value;
|
config.jerkThreshold = +document.getElementById('slJerkThreshold').value;
|
||||||
|
config.featureFlags = (document.getElementById('capTapEnabled').checked ? FLAG_TAP_ENABLED : 0)
|
||||||
|
| (document.getElementById('capTempComp').checked ? FLAG_TEMP_COMP_ENABLED : 0)
|
||||||
|
| (document.getElementById('capAutoRecal').checked ? FLAG_AUTO_RECAL_ENABLED : 0);
|
||||||
// config.curve, config.chargeMode, config.tapAction, config.tapKey updated directly
|
// config.curve, config.chargeMode, config.tapAction, config.tapKey updated directly
|
||||||
|
|
||||||
const buf = new ArrayBuffer(24);
|
const buf = new ArrayBuffer(25);
|
||||||
const view = new DataView(buf);
|
const view = new DataView(buf);
|
||||||
view.setFloat32(0, config.sensitivity, true);
|
view.setFloat32(0, config.sensitivity, true);
|
||||||
view.setFloat32(4, config.deadZone, true);
|
view.setFloat32(4, config.deadZone, true);
|
||||||
@@ -287,16 +316,17 @@ async function _doWriteConfigBlob() {
|
|||||||
view.setUint8(16, config.tapAction);
|
view.setUint8(16, config.tapAction);
|
||||||
view.setUint8(17, config.tapKey);
|
view.setUint8(17, config.tapKey);
|
||||||
view.setUint8(18, config.tapMod);
|
view.setUint8(18, config.tapMod);
|
||||||
view.setUint8(19, 0);
|
view.setUint8(19, config.tapFreezeEnabled);
|
||||||
view.setFloat32(20, config.jerkThreshold, true);
|
view.setFloat32(20, config.jerkThreshold, true);
|
||||||
|
view.setUint8(24, config.featureFlags);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await gattWrite(chars.configBlob, buf);
|
await gattWrite(chars.configBlob, buf);
|
||||||
log(`Config written — sens=${config.sensitivity.toFixed(0)} tapThr=${config.tapThreshold} tapAction=${config.tapAction}`,'ok');
|
log(`Config written - sens=${config.sensitivity.toFixed(0)} tapThr=${config.tapThreshold} tapAction=${config.tapAction}`,'ok');
|
||||||
} catch(e) { log(`Config write failed: ${e.message}`,'err'); }
|
} catch(e) { log(`Config write failed: ${e.message}`,'err'); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Individual control handlers ───────────────────────────────────────────────
|
// Individual control handlers
|
||||||
// These update the local config shadow then write the full blob
|
// These update the local config shadow then write the full blob
|
||||||
|
|
||||||
function setCurve(val) {
|
function setCurve(val) {
|
||||||
@@ -314,15 +344,31 @@ function setChargeMode(val) {
|
|||||||
config.chargeMode = val;
|
config.chargeMode = val;
|
||||||
setChargeModeUI(val);
|
setChargeModeUI(val);
|
||||||
writeConfigBlob();
|
writeConfigBlob();
|
||||||
log(`Charge → ${['OFF','SLOW 50mA','FAST 100mA'][val]}`,'warn');
|
log(`Charge → ${['SLOW 50mA','FAST 100mA'][val]}`,'warn');
|
||||||
}
|
}
|
||||||
function setChargeModeUI(val) {
|
function setChargeModeUI(val) {
|
||||||
[['chgOff','off'],['chgSlow','slow'],['chgFast','fast']].forEach(([id,cls],i) => {
|
[['chgSlow','slow'],['chgFast','fast']].forEach(([id,cls],i) => {
|
||||||
const b = document.getElementById(id);
|
const b = document.getElementById(id);
|
||||||
b.classList.remove('active','off','slow','fast');
|
b.classList.remove('active','slow','fast');
|
||||||
if (i===val) b.classList.add('active', cls);
|
if (i===val) b.classList.add('active', cls);
|
||||||
});
|
});
|
||||||
document.getElementById('ciMode').textContent = ['Off (0mA)','50 mA','100 mA'][val] ?? '--';
|
document.getElementById('ciMode').textContent = ['50 mA','100 mA'][val] ?? '--';
|
||||||
|
}
|
||||||
|
|
||||||
|
function onCapTapChange(enabled) {
|
||||||
|
writeConfigBlob();
|
||||||
|
log('Tap detection ' + (enabled ? 'enabled' : 'disabled') + ' - restart device to apply', 'warn');
|
||||||
|
}
|
||||||
|
|
||||||
|
function onTapFreezeChange(enabled) {
|
||||||
|
config.tapFreezeEnabled = enabled ? 1 : 0;
|
||||||
|
updateTapFreezeUI(enabled);
|
||||||
|
writeConfigBlob();
|
||||||
|
}
|
||||||
|
function updateTapFreezeUI(enabled) {
|
||||||
|
const slider = document.getElementById('slJerkThreshold');
|
||||||
|
// Only grey out when connected (on disconnect, setStatus handles all inputs)
|
||||||
|
if (device) slider.disabled = !enabled;
|
||||||
}
|
}
|
||||||
|
|
||||||
function setTapAction(val) {
|
function setTapAction(val) {
|
||||||
@@ -344,7 +390,7 @@ function onTapKeyInput() {
|
|||||||
|
|
||||||
async function sendCalibrate() {
|
async function sendCalibrate() {
|
||||||
if (!chars.command) return;
|
if (!chars.command) return;
|
||||||
try { await gattCmd(chars.command, new Uint8Array([0x01])); log('Calibration sent — hold still!','warn'); }
|
try { await gattCmd(chars.command, new Uint8Array([0x01])); log('Calibration sent - hold still!','warn'); }
|
||||||
catch(e) { log(`Calibrate failed: ${e.message}`,'err'); }
|
catch(e) { log(`Calibrate failed: ${e.message}`,'err'); }
|
||||||
}
|
}
|
||||||
function confirmReset() { document.getElementById('overlay').classList.add('show'); }
|
function confirmReset() { document.getElementById('overlay').classList.add('show'); }
|
||||||
@@ -358,8 +404,8 @@ async function doReset() {
|
|||||||
} catch(e) { log(`Reset failed: ${e.message}`,'err'); }
|
} catch(e) { log(`Reset failed: ${e.message}`,'err'); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Telemetry ────────────────────────────────────────────────────────────────
|
// Telemetry
|
||||||
// TelemetryPacket (28 bytes LE — backwards compatible with 24-byte v3.3):
|
// TelemetryPacket (28 bytes LE - backwards compatible with 24-byte v3.3):
|
||||||
// uint32 uptime [0], uint32 leftClicks [4], uint32 rightClicks [8]
|
// uint32 uptime [0], uint32 leftClicks [4], uint32 rightClicks [8]
|
||||||
// float temp [12], float biasRms [16]
|
// float temp [12], float biasRms [16]
|
||||||
// uint16 recalCount [20], uint8 chargeStatus [22], uint8 pad [23]
|
// uint16 recalCount [20], uint8 chargeStatus [22], uint8 pad [23]
|
||||||
@@ -368,12 +414,12 @@ function parseTelemetry(dv) {
|
|||||||
let view;
|
let view;
|
||||||
try {
|
try {
|
||||||
view = dv instanceof DataView ? new DataView(dv.buffer, dv.byteOffset, dv.byteLength) : new DataView(dv);
|
view = dv instanceof DataView ? new DataView(dv.buffer, dv.byteOffset, dv.byteLength) : new DataView(dv);
|
||||||
} catch(e) { log(`parseTelemetry: DataView wrap failed — ${e.message}`,'err'); return; }
|
} catch(e) { log(`parseTelemetry: DataView wrap failed - ${e.message}`,'err'); return; }
|
||||||
|
|
||||||
if (view.byteLength < 24) {
|
if (view.byteLength < 24) {
|
||||||
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
||||||
const hex = Array.from(bytes).map(b=>b.toString(16).padStart(2,'0')).join(' ');
|
const hex = Array.from(bytes).map(b=>b.toString(16).padStart(2,'0')).join(' ');
|
||||||
log(`TELEM: expected 24-28B, got ${view.byteLength}B — MTU too small? raw: ${hex}`,'err');
|
log(`TELEM: expected 24-28B, got ${view.byteLength}B - MTU too small? raw: ${hex}`,'err');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -387,7 +433,7 @@ function parseTelemetry(dv) {
|
|||||||
recalCount = view.getUint16(20, true);
|
recalCount = view.getUint16(20, true);
|
||||||
chargeStatus= view.getUint8(22);
|
chargeStatus= view.getUint8(22);
|
||||||
if (view.byteLength >= 28) battVoltage = view.getFloat32(24, true);
|
if (view.byteLength >= 28) battVoltage = view.getFloat32(24, true);
|
||||||
} catch(e) { log(`parseTelemetry: parse error at offset — ${e.message}`,'err'); return; }
|
} catch(e) { log(`parseTelemetry: parse error at offset - ${e.message}`,'err'); return; }
|
||||||
|
|
||||||
document.getElementById('telTemp').textContent = temp.toFixed(1)+'°';
|
document.getElementById('telTemp').textContent = temp.toFixed(1)+'°';
|
||||||
document.getElementById('telUptime').textContent = formatUptime(uptime);
|
document.getElementById('telUptime').textContent = formatUptime(uptime);
|
||||||
@@ -398,7 +444,6 @@ function parseTelemetry(dv) {
|
|||||||
const tEl = document.getElementById('telTemp');
|
const tEl = document.getElementById('telTemp');
|
||||||
tEl.className = 'telem-val '+(temp>40?'warn':'accent');
|
tEl.className = 'telem-val '+(temp>40?'warn':'accent');
|
||||||
|
|
||||||
// chargeStatus is now delivered via telemetry (no separate characteristic)
|
|
||||||
if (chargeStatus !== currentChargeStatus) {
|
if (chargeStatus !== currentChargeStatus) {
|
||||||
currentChargeStatus = chargeStatus;
|
currentChargeStatus = chargeStatus;
|
||||||
updateChargeUI();
|
updateChargeUI();
|
||||||
@@ -407,6 +452,8 @@ function parseTelemetry(dv) {
|
|||||||
if (battVoltage !== null) {
|
if (battVoltage !== null) {
|
||||||
currentBattVoltage = battVoltage;
|
currentBattVoltage = battVoltage;
|
||||||
document.getElementById('ciVolt').textContent = battVoltage.toFixed(2) + 'V';
|
document.getElementById('ciVolt').textContent = battVoltage.toFixed(2) + 'V';
|
||||||
|
const pct = Math.round(Math.min(100, Math.max(0, (battVoltage - 3.00) / (4.20 - 3.00) * 100)));
|
||||||
|
if (pct !== currentBattPct) { currentBattPct = pct; updateBatteryBar(pct, currentChargeStatus); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function formatUptime(s) {
|
function formatUptime(s) {
|
||||||
@@ -418,7 +465,7 @@ function clearTelemetry() {
|
|||||||
document.getElementById(id).textContent='--');
|
document.getElementById(id).textContent='--');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Battery & Charge UI ───────────────────────────────────────────────────────
|
// Battery & Charge UI
|
||||||
function updateBatteryBar(pct, status) {
|
function updateBatteryBar(pct, status) {
|
||||||
document.getElementById('battBar').style.display='flex';
|
document.getElementById('battBar').style.display='flex';
|
||||||
document.getElementById('battPct').textContent=pct+'%';
|
document.getElementById('battPct').textContent=pct+'%';
|
||||||
@@ -442,7 +489,7 @@ function updateChargeUI() {
|
|||||||
if (currentBattPct!==null) updateBatteryBar(currentBattPct, currentChargeStatus);
|
if (currentBattPct!==null) updateBatteryBar(currentBattPct, currentChargeStatus);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Advanced toggle ───────────────────────────────────────────────────────
|
// Advanced toggle
|
||||||
function toggleAdvanced(on) {
|
function toggleAdvanced(on) {
|
||||||
advancedMode = on;
|
advancedMode = on;
|
||||||
localStorage.setItem('advanced', on);
|
localStorage.setItem('advanced', on);
|
||||||
@@ -452,7 +499,7 @@ function toggleAdvanced(on) {
|
|||||||
document.getElementById('chargeInfo').style.gridTemplateColumns = on ? '1fr 1fr 1fr 1fr' : '1fr 1fr 1fr';
|
document.getElementById('chargeInfo').style.gridTemplateColumns = on ? '1fr 1fr 1fr 1fr' : '1fr 1fr 1fr';
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── IMU Debug Recorder ────────────────────────────────────────────────────────
|
// IMU Debug Recorder
|
||||||
let debugModalOpen = false;
|
let debugModalOpen = false;
|
||||||
let debugRecording = false;
|
let debugRecording = false;
|
||||||
let debugBuffer = [];
|
let debugBuffer = [];
|
||||||
@@ -461,6 +508,7 @@ let debugLiveRing = [];
|
|||||||
let debugT0 = 0;
|
let debugT0 = 0;
|
||||||
|
|
||||||
function openDebugModal() {
|
function openDebugModal() {
|
||||||
|
console.log('[DEBUG] modal opened (imuSubscribed=' + imuSubscribed + ')');
|
||||||
debugModalOpen = true;
|
debugModalOpen = true;
|
||||||
debugT0 = Date.now();
|
debugT0 = Date.now();
|
||||||
debugLiveRing = [];
|
debugLiveRing = [];
|
||||||
@@ -469,6 +517,7 @@ function openDebugModal() {
|
|||||||
if (!imuSubscribed && chars.imuStream) vizSetPaused(false);
|
if (!imuSubscribed && chars.imuStream) vizSetPaused(false);
|
||||||
}
|
}
|
||||||
function closeDebugModal() {
|
function closeDebugModal() {
|
||||||
|
console.log('[DEBUG] modal closed');
|
||||||
debugModalOpen = false;
|
debugModalOpen = false;
|
||||||
document.getElementById('debugOverlay').classList.remove('show');
|
document.getElementById('debugOverlay').classList.remove('show');
|
||||||
}
|
}
|
||||||
@@ -545,7 +594,7 @@ function clearDebugRec() {
|
|||||||
document.getElementById('debugRecCount').textContent = '0 samples';
|
document.getElementById('debugRecCount').textContent = '0 samples';
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Param display ─────────────────────────────────────────────────────────────
|
// Param display
|
||||||
function updateDisplay(key, val) {
|
function updateDisplay(key, val) {
|
||||||
const map = {
|
const map = {
|
||||||
sensitivity: ['valSensitivity', v=>parseFloat(v).toFixed(0)],
|
sensitivity: ['valSensitivity', v=>parseFloat(v).toFixed(0)],
|
||||||
@@ -558,7 +607,7 @@ function updateDisplay(key, val) {
|
|||||||
document.getElementById(id).textContent = fmt(val);
|
document.getElementById(id).textContent = fmt(val);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Status UI ────────────────────────────────────────────────────────────────
|
// Status UI
|
||||||
function setStatus(state) {
|
function setStatus(state) {
|
||||||
const pill=document.getElementById('statusPill');
|
const pill=document.getElementById('statusPill');
|
||||||
document.getElementById('statusText').textContent={connected:'CONNECTED',connecting:'CONNECTING…',disconnected:'DISCONNECTED'}[state];
|
document.getElementById('statusText').textContent={connected:'CONNECTED',connecting:'CONNECTING…',disconnected:'DISCONNECTED'}[state];
|
||||||
@@ -587,7 +636,7 @@ function onDisconnected() {
|
|||||||
document.getElementById('badgeCharging').classList.remove('show');
|
document.getElementById('badgeCharging').classList.remove('show');
|
||||||
document.getElementById('badgeFull').classList.remove('show');
|
document.getElementById('badgeFull').classList.remove('show');
|
||||||
imuSubscribed = false; vizPaused = true; vizUpdateIndicator(); streamDiagReset();
|
imuSubscribed = false; vizPaused = true; vizUpdateIndicator(); streamDiagReset();
|
||||||
document.getElementById('orientLabel').textContent = '— not streaming —';
|
document.getElementById('orientLabel').textContent = '- not streaming -';
|
||||||
document.getElementById('hashMismatchBanner').style.display = 'none';
|
document.getElementById('hashMismatchBanner').style.display = 'none';
|
||||||
clearTelemetry();
|
clearTelemetry();
|
||||||
if (!userDisconnected && document.getElementById('autoReconnect').checked && savedDevice) {
|
if (!userDisconnected && document.getElementById('autoReconnect').checked && savedDevice) {
|
||||||
@@ -609,7 +658,7 @@ function onDisconnected() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── IMU Stream + Visualiser ──────────────────────────────────────────────────
|
// IMU Stream + Visualiser
|
||||||
// ImuPacket (14 bytes LE):
|
// ImuPacket (14 bytes LE):
|
||||||
// int16 gyroX_mDPS [0], int16 gyroZ_mDPS [2]
|
// int16 gyroX_mDPS [0], int16 gyroZ_mDPS [2]
|
||||||
// int16 accelX_mg [4], int16 accelY_mg [6], int16 accelZ_mg [8]
|
// int16 accelX_mg [4], int16 accelY_mg [6], int16 accelZ_mg [8]
|
||||||
@@ -620,8 +669,9 @@ const TRAIL_LEN = 120;
|
|||||||
let cursorX = canvas.width/2, cursorY = canvas.height/2, trail = [];
|
let cursorX = canvas.width/2, cursorY = canvas.height/2, trail = [];
|
||||||
let vizPaused = true;
|
let vizPaused = true;
|
||||||
let imuSubscribed = false;
|
let imuSubscribed = false;
|
||||||
|
let _prevIdle = false;
|
||||||
|
|
||||||
// ── Stream diagnostics ────────────────────────────────────────────────────────
|
// Stream diagnostics
|
||||||
let streamPktCount = 0; // packets received this second
|
let streamPktCount = 0; // packets received this second
|
||||||
let streamPktTotal = 0; // lifetime packet count
|
let streamPktTotal = 0; // lifetime packet count
|
||||||
let streamLastPktT = 0; // timestamp of last packet (for gap detection)
|
let streamLastPktT = 0; // timestamp of last packet (for gap detection)
|
||||||
@@ -629,14 +679,16 @@ let streamLastRateT = 0; // timestamp of last rate log
|
|||||||
let streamFreezeTimer = null; // fires if no packet for >1s while subscribed
|
let streamFreezeTimer = null; // fires if no packet for >1s while subscribed
|
||||||
|
|
||||||
function streamDiagReset() {
|
function streamDiagReset() {
|
||||||
|
console.log('[STREAM] diagnostics reset');
|
||||||
streamPktCount = streamPktTotal = streamLastPktT = streamLastRateT = 0;
|
streamPktCount = streamPktTotal = streamLastPktT = streamLastRateT = 0;
|
||||||
|
_prevIdle = false;
|
||||||
if (streamFreezeTimer) { clearTimeout(streamFreezeTimer); streamFreezeTimer = null; }
|
if (streamFreezeTimer) { clearTimeout(streamFreezeTimer); streamFreezeTimer = null; }
|
||||||
}
|
}
|
||||||
|
|
||||||
function streamDiagPkt() {
|
function streamDiagPkt() {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
// Gap detection — warn if >300ms since last packet while streaming
|
// Gap detection - warn if >300ms since last packet while streaming
|
||||||
if (streamLastPktT) {
|
if (streamLastPktT) {
|
||||||
const gap = now - streamLastPktT;
|
const gap = now - streamLastPktT;
|
||||||
if (gap > 300) log(`[STREAM] gap ${gap}ms (pkt #${streamPktTotal})`, 'warn');
|
if (gap > 300) log(`[STREAM] gap ${gap}ms (pkt #${streamPktTotal})`, 'warn');
|
||||||
@@ -645,10 +697,10 @@ function streamDiagPkt() {
|
|||||||
streamPktCount++;
|
streamPktCount++;
|
||||||
streamPktTotal++;
|
streamPktTotal++;
|
||||||
|
|
||||||
// Reset freeze watchdog — 1.5s without a packet = freeze
|
// Reset freeze watchdog - 1.5s without a packet = freeze
|
||||||
if (streamFreezeTimer) clearTimeout(streamFreezeTimer);
|
if (streamFreezeTimer) clearTimeout(streamFreezeTimer);
|
||||||
streamFreezeTimer = setTimeout(() => {
|
streamFreezeTimer = setTimeout(() => {
|
||||||
log(`[STREAM] FROZEN — no packet for 1.5s (total rx: ${streamPktTotal})`, 'err');
|
log(`[STREAM] FROZEN - no packet for 1.5s (total rx: ${streamPktTotal})`, 'err');
|
||||||
streamFreezeTimer = null;
|
streamFreezeTimer = null;
|
||||||
}, 1500);
|
}, 1500);
|
||||||
|
|
||||||
@@ -664,7 +716,7 @@ function streamDiagPkt() {
|
|||||||
|
|
||||||
// Roll compensation is done entirely in firmware (calibrateGyroBias computes
|
// Roll compensation is done entirely in firmware (calibrateGyroBias computes
|
||||||
// rollSin/rollCos from boot-pose accel and applies the rotation before moveX/moveY).
|
// rollSin/rollCos from boot-pose accel and applies the rotation before moveX/moveY).
|
||||||
// The web visualiser just uses moveX/moveY directly — no re-rotation needed here.
|
// The web visualiser just uses moveX/moveY directly - no re-rotation needed here.
|
||||||
function resetOrient() {} // kept for call-site compatibility
|
function resetOrient() {} // kept for call-site compatibility
|
||||||
|
|
||||||
function vizUpdateIndicator() {
|
function vizUpdateIndicator() {
|
||||||
@@ -685,6 +737,7 @@ function vizUpdateIndicator() {
|
|||||||
async function vizSetPaused(paused) {
|
async function vizSetPaused(paused) {
|
||||||
vizPaused = paused;
|
vizPaused = paused;
|
||||||
if (!paused && chars.imuStream && !imuSubscribed) {
|
if (!paused && chars.imuStream && !imuSubscribed) {
|
||||||
|
console.log('[STREAM] requesting subscribe');
|
||||||
try {
|
try {
|
||||||
await chars.imuStream.startNotifications();
|
await chars.imuStream.startNotifications();
|
||||||
imuSubscribed = true;
|
imuSubscribed = true;
|
||||||
@@ -692,12 +745,15 @@ async function vizSetPaused(paused) {
|
|||||||
log('IMU stream subscribed','ok');
|
log('IMU stream subscribed','ok');
|
||||||
} catch(e) { log(`IMU stream start failed: ${e.message}`,'err'); vizPaused = true; }
|
} catch(e) { log(`IMU stream start failed: ${e.message}`,'err'); vizPaused = true; }
|
||||||
} else if (paused && imuSubscribed) {
|
} else if (paused && imuSubscribed) {
|
||||||
|
console.log(`[STREAM] requesting unsubscribe (total rx: ${streamPktTotal})`);
|
||||||
try {
|
try {
|
||||||
await chars.imuStream.stopNotifications();
|
await chars.imuStream.stopNotifications();
|
||||||
imuSubscribed = false;
|
imuSubscribed = false;
|
||||||
streamDiagReset();
|
streamDiagReset();
|
||||||
document.getElementById('orientLabel').textContent = '— not streaming —';
|
document.getElementById('orientLabel').textContent = '- not streaming -';
|
||||||
} catch(e) { log(`IMU stream stop failed: ${e.message}`,'err'); }
|
} catch(e) { log(`IMU stream stop failed: ${e.message}`,'err'); }
|
||||||
|
} else {
|
||||||
|
console.log(`[STREAM] vizSetPaused(${paused}) - no action (imuSubscribed=${imuSubscribed})`);
|
||||||
}
|
}
|
||||||
vizUpdateIndicator();
|
vizUpdateIndicator();
|
||||||
}
|
}
|
||||||
@@ -706,7 +762,7 @@ function parseImuStream(dv) {
|
|||||||
let view;
|
let view;
|
||||||
try {
|
try {
|
||||||
view = dv instanceof DataView ? new DataView(dv.buffer, dv.byteOffset, dv.byteLength) : new DataView(dv);
|
view = dv instanceof DataView ? new DataView(dv.buffer, dv.byteOffset, dv.byteLength) : new DataView(dv);
|
||||||
} catch(e) { log(`parseImuStream: DataView wrap failed — ${e.message}`,'err'); return; }
|
} catch(e) { log(`parseImuStream: DataView wrap failed - ${e.message}`,'err'); return; }
|
||||||
|
|
||||||
if (view.byteLength < 14) {
|
if (view.byteLength < 14) {
|
||||||
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
||||||
@@ -725,12 +781,13 @@ function parseImuStream(dv) {
|
|||||||
moveX = view.getInt8(10);
|
moveX = view.getInt8(10);
|
||||||
moveY = view.getInt8(11);
|
moveY = view.getInt8(11);
|
||||||
flags = view.getUint8(12);
|
flags = view.getUint8(12);
|
||||||
} catch(e) { log(`parseImuStream: parse error — ${e.message}`,'err'); return; }
|
} catch(e) { log(`parseImuStream: parse error - ${e.message}`,'err'); return; }
|
||||||
|
|
||||||
// Feed debug recorder (even when viz is paused)
|
// Feed debug recorder (even when viz is paused)
|
||||||
feedDebugRow(gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags);
|
feedDebugRow(gyroX, gyroZ, accelX, accelY, accelZ, moveX, moveY, flags);
|
||||||
|
|
||||||
if (vizPaused) return;
|
if (vizPaused) return;
|
||||||
|
|
||||||
const idle = !!(flags & 0x01);
|
const idle = !!(flags & 0x01);
|
||||||
const single = !!(flags & 0x02);
|
const single = !!(flags & 0x02);
|
||||||
const dbl = !!(flags & 0x04);
|
const dbl = !!(flags & 0x04);
|
||||||
@@ -740,7 +797,7 @@ function parseImuStream(dv) {
|
|||||||
updateAxisBar('gz', -gyroX, 30000);
|
updateAxisBar('gz', -gyroX, 30000);
|
||||||
|
|
||||||
if (!idle) {
|
if (!idle) {
|
||||||
// moveX/moveY are already roll-corrected by firmware — use them directly
|
// moveX/moveY are already roll-corrected by firmware - use them directly
|
||||||
cursorX = Math.max(4, Math.min(canvas.width - 4, cursorX + moveX * 1.5));
|
cursorX = Math.max(4, Math.min(canvas.width - 4, cursorX + moveX * 1.5));
|
||||||
cursorY = Math.max(4, Math.min(canvas.height - 4, cursorY + moveY * 1.5));
|
cursorY = Math.max(4, Math.min(canvas.height - 4, cursorY + moveY * 1.5));
|
||||||
}
|
}
|
||||||
@@ -749,6 +806,13 @@ function parseImuStream(dv) {
|
|||||||
|
|
||||||
streamDiagPkt();
|
streamDiagPkt();
|
||||||
|
|
||||||
|
if (idle !== _prevIdle) {
|
||||||
|
console.log(`[STREAM] idle → ${idle ? 'idle' : 'active'} (pkt #${streamPktTotal})`);
|
||||||
|
_prevIdle = idle;
|
||||||
|
}
|
||||||
|
if (single) console.log(`[STREAM] single tap (pkt #${streamPktTotal})`);
|
||||||
|
if (dbl) console.log(`[STREAM] double tap (pkt #${streamPktTotal})`);
|
||||||
|
|
||||||
if (single) flashTap('Left');
|
if (single) flashTap('Left');
|
||||||
if (dbl) flashTap('Right');
|
if (dbl) flashTap('Right');
|
||||||
drawViz(idle);
|
drawViz(idle);
|
||||||
@@ -808,7 +872,7 @@ function drawInitState() {
|
|||||||
ctx.fillStyle=cssVar('--canvas-idle-text');ctx.font='10px Share Tech Mono,monospace';
|
ctx.fillStyle=cssVar('--canvas-idle-text');ctx.font='10px Share Tech Mono,monospace';
|
||||||
ctx.textAlign='center';ctx.fillText('connect to activate stream',W/2,H/2+4);ctx.textAlign='left';
|
ctx.textAlign='center';ctx.fillText('connect to activate stream',W/2,H/2+4);ctx.textAlign='left';
|
||||||
}
|
}
|
||||||
// ── 3D Orientation Viewer ─────────────────────────────────────────────────────
|
// 3D Orientation Viewer
|
||||||
// Device box: L=115mm (X), W=36mm (Y), H=20mm (Z)
|
// Device box: L=115mm (X), W=36mm (Y), H=20mm (Z)
|
||||||
// Complementary filter mirrors firmware: α=0.96, dt from packet rate (~50ms)
|
// Complementary filter mirrors firmware: α=0.96, dt from packet rate (~50ms)
|
||||||
const ORIENT_ALPHA = 0.96;
|
const ORIENT_ALPHA = 0.96;
|
||||||
@@ -820,12 +884,12 @@ let orientLastT = 0;
|
|||||||
|
|
||||||
function initOrientViewer() {
|
function initOrientViewer() {
|
||||||
const el = document.getElementById('orientCanvas');
|
const el = document.getElementById('orientCanvas');
|
||||||
const W = el.clientWidth || 340, H = 160;
|
const W = el.clientWidth || 340, H = el.clientHeight || W;
|
||||||
el.width = W; el.height = H;
|
el.width = W; el.height = H;
|
||||||
|
|
||||||
orientScene = new THREE.Scene();
|
orientScene = new THREE.Scene();
|
||||||
orientCamera = new THREE.PerspectiveCamera(40, W / H, 0.01, 10);
|
orientCamera = new THREE.PerspectiveCamera(55, W / H, 0.01, 10);
|
||||||
orientCamera.position.set(0.6, 0.5, 0.9);
|
orientCamera.position.set(0.75, 0.60, 1.10);
|
||||||
orientCamera.lookAt(0, 0, 0);
|
orientCamera.lookAt(0, 0, 0);
|
||||||
|
|
||||||
orientRenderer = new THREE.WebGLRenderer({ canvas: el, antialias: true, alpha: true });
|
orientRenderer = new THREE.WebGLRenderer({ canvas: el, antialias: true, alpha: true });
|
||||||
@@ -846,7 +910,7 @@ function initOrientViewer() {
|
|||||||
orientEdges = new THREE.LineSegments(new THREE.EdgesGeometry(geo), edgeMat);
|
orientEdges = new THREE.LineSegments(new THREE.EdgesGeometry(geo), edgeMat);
|
||||||
orientMesh.add(orientEdges);
|
orientMesh.add(orientEdges);
|
||||||
|
|
||||||
// "Front" face marker — small arrow along +X (length axis)
|
// "Front" face marker - small arrow along +X (length axis)
|
||||||
const arrowGeo = new THREE.ConeGeometry(0.02, 0.07, 6);
|
const arrowGeo = new THREE.ConeGeometry(0.02, 0.07, 6);
|
||||||
arrowGeo.rotateZ(-Math.PI / 2);
|
arrowGeo.rotateZ(-Math.PI / 2);
|
||||||
arrowGeo.translate(DEVICE_L / 2 + 0.04, 0, 0);
|
arrowGeo.translate(DEVICE_L / 2 + 0.04, 0, 0);
|
||||||
@@ -896,7 +960,7 @@ function orientFeedIMU(ax, ay, az, gyX_mDPS, gyZ_mDPS) {
|
|||||||
qAccel.copy(orientQ);
|
qAccel.copy(orientQ);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gyro integration — firmware sends gyroX (pitch) and gyroZ (yaw), mDPS
|
// Gyro integration - firmware sends gyroX (pitch) and gyroZ (yaw), mDPS
|
||||||
// Map to Three.js axes: gyroZ→world Y, gyroX→world X
|
// Map to Three.js axes: gyroZ→world Y, gyroX→world X
|
||||||
const gyRad = gyX_mDPS * (Math.PI / 180) / 1000;
|
const gyRad = gyX_mDPS * (Math.PI / 180) / 1000;
|
||||||
const gzRad = gyZ_mDPS * (Math.PI / 180) / 1000;
|
const gzRad = gyZ_mDPS * (Math.PI / 180) / 1000;
|
||||||
@@ -915,7 +979,7 @@ function orientFeedIMU(ax, ay, az, gyX_mDPS, gyZ_mDPS) {
|
|||||||
orientRenderer.render(orientScene, orientCamera);
|
orientRenderer.render(orientScene, orientCamera);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Theme ─────────────────────────────────────────────────────────────────────
|
// Theme
|
||||||
const THEMES = ['auto','dark','light'];
|
const THEMES = ['auto','dark','light'];
|
||||||
const THEME_LABELS = {auto:'AUTO',dark:'DARK',light:'LIGHT'};
|
const THEME_LABELS = {auto:'AUTO',dark:'DARK',light:'LIGHT'};
|
||||||
let themeIdx = 0;
|
let themeIdx = 0;
|
||||||
@@ -948,3 +1012,35 @@ if (!navigator.bluetooth) {
|
|||||||
} else {
|
} else {
|
||||||
log('Web Bluetooth ready. Click CONNECT to pair your IMU Mouse.','info');
|
log('Web Bluetooth ready. Click CONNECT to pair your IMU Mouse.','info');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
// OTA firmware update
|
||||||
|
//
|
||||||
|
// The OTAFIX bootloader uses Nordic Legacy DFU (service 00001530-...) which is
|
||||||
|
// blocklisted in Chrome's Web Bluetooth implementation. Browser-side upload is
|
||||||
|
// therefore not possible without special flags or a native app wrapper.
|
||||||
|
//
|
||||||
|
// What the UI does instead:
|
||||||
|
// • "Enter DFU Mode" sends command 0x02 via BLE → device reboots as XIAO_DFU
|
||||||
|
// • User then uploads firmware_dfu.zip via nRF Connect (mobile or desktop)
|
||||||
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function otaLog(msg, type = 'info') {
|
||||||
|
log('[OTA] ' + msg, type);
|
||||||
|
const el = document.getElementById('otaStatus');
|
||||||
|
if (el) { el.textContent = msg; el.className = 'ota-status' + (type !== 'info' ? ' ota-' + type : ''); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send command 0x02 → firmware reboots into XIAO_DFU bootloader mode.
|
||||||
|
// User then uploads firmware_dfu.zip via nRF Connect.
|
||||||
|
async function sendOTATrigger() {
|
||||||
|
if (!chars.command) { otaLog('Not connected', 'err'); return; }
|
||||||
|
document.getElementById('btnOTA').disabled = true;
|
||||||
|
try {
|
||||||
|
await chars.command.writeValueWithResponse(new Uint8Array([0x02]));
|
||||||
|
otaLog('Device rebooting into DFU mode — connect to XIAO_DFU in nRF Connect', 'ok');
|
||||||
|
} catch (e) {
|
||||||
|
otaLog('Failed: ' + e.message, 'err');
|
||||||
|
document.getElementById('btnOTA').disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+79
-25
@@ -32,10 +32,14 @@
|
|||||||
<button class="btn btn-disconnect" id="disconnectBtn" onclick="doDisconnect()" style="display:none"><span>Disconnect</span></button>
|
<button class="btn btn-disconnect" id="disconnectBtn" onclick="doDisconnect()" style="display:none"><span>Disconnect</span></button>
|
||||||
<label class="toggle" title="Auto-Reconnect" style="margin-left:6px;flex-shrink:0"><input type="checkbox" id="autoReconnect"><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
<label class="toggle" title="Auto-Reconnect" style="margin-left:6px;flex-shrink:0"><input type="checkbox" id="autoReconnect"><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
||||||
<span style="font-family:var(--mono);font-size:9px;color:var(--label);white-space:nowrap">AUTO-RECONNECT</span>
|
<span style="font-family:var(--mono);font-size:9px;color:var(--label);white-space:nowrap">AUTO-RECONNECT</span>
|
||||||
|
<label class="toggle" style="margin-left:10px;flex-shrink:0" title="Advanced"><input type="checkbox" id="advancedToggle" onchange="toggleAdvanced(this.checked)"><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
||||||
|
<span style="font-family:var(--mono);font-size:9px;color:var(--label);white-space:nowrap">ADVANCED</span>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main id="mainContent">
|
<main id="mainContent">
|
||||||
|
|
||||||
|
<!-- col-left: cursor motion -->
|
||||||
<div class="col-left">
|
<div class="col-left">
|
||||||
|
|
||||||
<div class="section-label">Motion Parameters</div>
|
<div class="section-label">Motion Parameters</div>
|
||||||
@@ -47,7 +51,7 @@
|
|||||||
<div class="param-value" id="valSensitivity">600</div>
|
<div class="param-value" id="valSensitivity">600</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="param">
|
<div class="param">
|
||||||
<div><div class="param-label">Dead Zone</div><div class="param-desc">Noise floor (rad/s) — raise to reduce drift</div></div>
|
<div><div class="param-label">Dead Zone</div><div class="param-desc">Noise floor (rad/s) - raise to reduce drift</div></div>
|
||||||
<input type="range" id="slDeadZone" min="0.005" max="0.2" step="0.005" value="0.06"
|
<input type="range" id="slDeadZone" min="0.005" max="0.2" step="0.005" value="0.06"
|
||||||
oninput="updateDisplay('deadZone',this.value)" onchange="writeConfigBlob()">
|
oninput="updateDisplay('deadZone',this.value)" onchange="writeConfigBlob()">
|
||||||
<div class="param-value" id="valDeadZone">0.060</div>
|
<div class="param-value" id="valDeadZone">0.060</div>
|
||||||
@@ -82,9 +86,8 @@
|
|||||||
<div class="param" style="border-bottom:none;padding:0">
|
<div class="param" style="border-bottom:none;padding:0">
|
||||||
<div><div class="param-label">Charge Mode</div><div class="param-desc">BQ25100 ISET via P0.13 (HICHG)</div></div>
|
<div><div class="param-label">Charge Mode</div><div class="param-desc">BQ25100 ISET via P0.13 (HICHG)</div></div>
|
||||||
<div class="segmented charge-seg" style="grid-column:2/4">
|
<div class="segmented charge-seg" style="grid-column:2/4">
|
||||||
<button class="seg-btn off" id="chgOff" onclick="setChargeMode(0)" disabled>OFF</button>
|
<button class="seg-btn slow" id="chgSlow" onclick="setChargeMode(0)" disabled>SLOW · 50mA</button>
|
||||||
<button class="seg-btn slow" id="chgSlow" onclick="setChargeMode(1)" disabled>SLOW · 50mA</button>
|
<button class="seg-btn fast" id="chgFast" onclick="setChargeMode(1)" disabled>FAST · 100mA</button>
|
||||||
<button class="seg-btn fast" id="chgFast" onclick="setChargeMode(2)" disabled>FAST · 100mA</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="charge-info" id="chargeInfo">
|
<div class="charge-info" id="chargeInfo">
|
||||||
@@ -93,16 +96,56 @@
|
|||||||
<div class="ci-item"><div class="ci-val" id="ciPct">--%</div><div class="ci-lbl">Level</div></div>
|
<div class="ci-item"><div class="ci-val" id="ciPct">--%</div><div class="ci-lbl">Level</div></div>
|
||||||
<div class="ci-item ci-advanced" id="ciVoltItem" style="display:none"><div class="ci-val accent" id="ciVolt">--</div><div class="ci-lbl">Voltage</div></div>
|
<div class="ci-item ci-advanced" id="ciVoltItem" style="display:none"><div class="ci-val accent" id="ciVolt">--</div><div class="ci-lbl">Voltage</div></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="advanced-row">
|
</div>
|
||||||
<label class="toggle"><input type="checkbox" id="advancedToggle" onchange="toggleAdvanced(this.checked)"><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
|
||||||
<span class="advanced-label">ADVANCED</span>
|
<div class="section-label">Axis Configuration</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="flip-row">
|
||||||
|
<div class="flip-label">Flip X Axis</div>
|
||||||
|
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Invert left / right</div>
|
||||||
|
<label class="toggle"><input type="checkbox" id="flipX" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
||||||
|
</div>
|
||||||
|
<div class="flip-row" style="border-bottom:none">
|
||||||
|
<div class="flip-label">Flip Y Axis</div>
|
||||||
|
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Invert up / down</div>
|
||||||
|
<label class="toggle"><input type="checkbox" id="flipY" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="section-label">Device Capabilities</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="flip-row">
|
||||||
|
<div class="flip-label">Tap Detection</div>
|
||||||
|
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Double-tap click action <span class="restart-note">· restart to apply</span></div>
|
||||||
|
<label class="toggle"><input type="checkbox" id="capTapEnabled" onchange="onCapTapChange(this.checked)" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
||||||
|
</div>
|
||||||
|
<div class="flip-row">
|
||||||
|
<div class="flip-label">Temp Compensation</div>
|
||||||
|
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Gyro drift correction by temperature</div>
|
||||||
|
<label class="toggle"><input type="checkbox" id="capTempComp" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
||||||
|
</div>
|
||||||
|
<div class="flip-row" style="border-bottom:none">
|
||||||
|
<div class="flip-label">Auto Recalibration</div>
|
||||||
|
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Recalibrate gyro after long idle period</div>
|
||||||
|
<label class="toggle"><input type="checkbox" id="capAutoRecal" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div><!-- /col-left -->
|
||||||
|
|
||||||
|
<!-- col-mid: button configuration -->
|
||||||
|
<div class="col-mid">
|
||||||
|
|
||||||
<div class="section-label">Tap Configuration</div>
|
<div class="section-label">Tap Configuration</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="param">
|
<div class="param">
|
||||||
<div><div class="param-label">Tap Freeze Sensitivity</div><div class="param-desc">Jerk² threshold — lower = more aggressive cursor freeze during taps</div></div>
|
<div><div class="param-label">Tap Freeze</div><div class="param-desc">Freeze cursor during tap impacts (jerk detection)</div></div>
|
||||||
|
<div style="grid-column:2/4;display:flex;justify-content:flex-end;align-items:center">
|
||||||
|
<label class="toggle"><input type="checkbox" id="tapFreezeEnabled" onchange="onTapFreezeChange(this.checked)" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="param">
|
||||||
|
<div><div class="param-label">Tap Freeze Sensitivity</div><div class="param-desc">Jerk² threshold - lower = more aggressive cursor freeze during taps</div></div>
|
||||||
<input type="range" id="slJerkThreshold" min="500" max="10000" step="100" value="2000"
|
<input type="range" id="slJerkThreshold" min="500" max="10000" step="100" value="2000"
|
||||||
oninput="updateDisplay('jerkThreshold',this.value)" onchange="writeConfigBlob()">
|
oninput="updateDisplay('jerkThreshold',this.value)" onchange="writeConfigBlob()">
|
||||||
<div class="param-value" id="valJerkThreshold">2000</div>
|
<div class="param-value" id="valJerkThreshold">2000</div>
|
||||||
@@ -137,25 +180,11 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="section-label">Axis Configuration</div>
|
|
||||||
<div class="card">
|
|
||||||
<div class="flip-row">
|
|
||||||
<div class="flip-label">Flip X Axis</div>
|
|
||||||
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Invert left / right</div>
|
|
||||||
<label class="toggle"><input type="checkbox" id="flipX" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
|
||||||
</div>
|
|
||||||
<div class="flip-row" style="border-bottom:none">
|
|
||||||
<div class="flip-label">Flip Y Axis</div>
|
|
||||||
<div class="param-desc" style="flex:1;font-size:9px;color:var(--label)">Invert up / down</div>
|
|
||||||
<label class="toggle"><input type="checkbox" id="flipY" onchange="writeConfigBlob()" disabled><div class="toggle-track"></div><div class="toggle-thumb"></div></label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="section-label">Device Commands</div>
|
<div class="section-label">Device Commands</div>
|
||||||
<div class="cmd-grid">
|
<div class="cmd-grid">
|
||||||
<button class="cmd-btn calibrate" id="btnCal" onclick="sendCalibrate()" disabled>
|
<button class="cmd-btn calibrate" id="btnCal" onclick="sendCalibrate()" disabled>
|
||||||
<span class="cmd-icon">⊕</span><span>Calibrate Gyro</span>
|
<span class="cmd-icon">⊕</span><span>Calibrate Gyro</span>
|
||||||
<span class="cmd-desc">Hold device still — recalculates bias + records cal temperature.</span>
|
<span class="cmd-desc">Hold device still - recalculates bias + records cal temperature.</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="cmd-btn reset" id="btnReset" onclick="confirmReset()" disabled>
|
<button class="cmd-btn reset" id="btnReset" onclick="confirmReset()" disabled>
|
||||||
<span class="cmd-icon">⚠</span><span>Factory Reset</span>
|
<span class="cmd-icon">⚠</span><span>Factory Reset</span>
|
||||||
@@ -163,11 +192,35 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="section-label" style="margin-top:8px">Firmware Update (OTA)</div>
|
||||||
|
<div class="card ota-card" id="otaCard">
|
||||||
|
<div class="ota-notice">
|
||||||
|
<div class="ota-notice-icon">⚠</div>
|
||||||
|
<div>
|
||||||
|
<div class="ota-notice-title">Browser OTA not available</div>
|
||||||
|
<div class="ota-notice-body">Chrome blocks the Nordic Legacy DFU service UUID used by this bootloader. Use <strong>nRF Connect</strong> (mobile or desktop) to upload firmware instead.</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ol class="ota-steps">
|
||||||
|
<li>Build firmware: <code>pio run</code> → produces <code>firmware_dfu.zip</code></li>
|
||||||
|
<li>Click <strong>Enter DFU Mode</strong> below — device reboots as <em>XIAO_DFU</em></li>
|
||||||
|
<li>Open nRF Connect → connect to <em>XIAO_DFU</em> → DFU → select <code>firmware_dfu.zip</code></li>
|
||||||
|
</ol>
|
||||||
|
<div class="ota-btn-row" style="grid-template-columns:1fr">
|
||||||
|
<button class="cmd-btn ota-trigger" id="btnOTA" onclick="sendOTATrigger()" disabled>
|
||||||
|
<span class="cmd-icon">⟳</span><span>Enter DFU Mode</span>
|
||||||
|
<span class="cmd-desc">Reboots device into XIAO_DFU so nRF Connect can upload firmware.</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="ota-status-row"><div class="ota-status" id="otaStatus"></div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="section-label" style="margin-top:8px">Event Log</div>
|
<div class="section-label" style="margin-top:8px">Event Log</div>
|
||||||
<div class="console" id="console"></div>
|
<div class="console" id="console"></div>
|
||||||
|
|
||||||
</div>
|
</div><!-- /col-mid -->
|
||||||
|
|
||||||
|
<!-- col-right: live monitoring -->
|
||||||
<div class="col-right">
|
<div class="col-right">
|
||||||
|
|
||||||
<div class="section-label">Live Cursor Visualiser</div>
|
<div class="section-label">Live Cursor Visualiser</div>
|
||||||
@@ -203,7 +256,7 @@
|
|||||||
<div class="section-label">Device Orientation</div>
|
<div class="section-label">Device Orientation</div>
|
||||||
<div class="card orient-card">
|
<div class="card orient-card">
|
||||||
<canvas id="orientCanvas"></canvas>
|
<canvas id="orientCanvas"></canvas>
|
||||||
<div style="font-size:9px;color:var(--label);text-align:center;margin-top:6px" id="orientLabel">— not streaming —</div>
|
<div style="font-size:9px;color:var(--label);text-align:center;margin-top:6px" id="orientLabel">- not streaming -</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="section-label">Live Telemetry</div>
|
<div class="section-label">Live Telemetry</div>
|
||||||
@@ -219,6 +272,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
|
||||||
<div class="overlay" id="overlay">
|
<div class="overlay" id="overlay">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<h3>⚠ Factory Reset</h3>
|
<h3>⚠ Factory Reset</h3>
|
||||||
|
|||||||
+44
-11
@@ -34,7 +34,7 @@
|
|||||||
--tap-right: rgba(255,61,113,0.35);
|
--tap-right: rgba(255,61,113,0.35);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Light theme (explicit) ──────────────────────────────────────────────── */
|
/* Light theme (explicit) */
|
||||||
:root.theme-light {
|
:root.theme-light {
|
||||||
--bg: #f0f2f5;
|
--bg: #f0f2f5;
|
||||||
--panel: #ffffff;
|
--panel: #ffffff;
|
||||||
@@ -66,7 +66,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* ── Auto light (OS hint; explicit class overrides) ──────────────────────── */
|
/* Auto light (OS hint; explicit class overrides) */
|
||||||
@media (prefers-color-scheme: light) {
|
@media (prefers-color-scheme: light) {
|
||||||
:root:not(.theme-dark) {
|
:root:not(.theme-dark) {
|
||||||
--bg: #f0f2f5;
|
--bg: #f0f2f5;
|
||||||
@@ -110,7 +110,7 @@
|
|||||||
.logo-sub { font-size:10px; color:var(--label); letter-spacing:0.25em; text-transform:uppercase; margin-top:3px; }
|
.logo-sub { font-size:10px; color:var(--label); letter-spacing:0.25em; text-transform:uppercase; margin-top:3px; }
|
||||||
.header-right { margin-left:auto; display:flex; align-items:center; gap:10px; flex-wrap:wrap; justify-content:flex-end; }
|
.header-right { margin-left:auto; display:flex; align-items:center; gap:10px; flex-wrap:wrap; justify-content:flex-end; }
|
||||||
|
|
||||||
.status-pill { display:flex; align-items:center; gap:8px; padding:6px 12px; border:1px solid var(--border); font-size:11px; letter-spacing:0.15em; text-transform:uppercase; color:var(--label); transition:all 0.3s; white-space:nowrap; }
|
.status-pill { display:flex; align-items:center; gap:8px; height:34px; padding:0 14px; border:1px solid var(--border); font-size:11px; letter-spacing:0.15em; text-transform:uppercase; color:var(--label); transition:all 0.3s; white-space:nowrap; }
|
||||||
.status-pill.connected { border-color:var(--ok); color:var(--ok); }
|
.status-pill.connected { border-color:var(--ok); color:var(--ok); }
|
||||||
.status-pill.connecting { border-color:var(--warn); color:var(--warn); }
|
.status-pill.connecting { border-color:var(--warn); color:var(--warn); }
|
||||||
.dot { width:7px; height:7px; border-radius:50%; background:var(--dim); flex-shrink:0; }
|
.dot { width:7px; height:7px; border-radius:50%; background:var(--dim); flex-shrink:0; }
|
||||||
@@ -131,7 +131,7 @@
|
|||||||
.btn:disabled { border-color:var(--dim); color:var(--dim); cursor:not-allowed; }
|
.btn:disabled { border-color:var(--dim); color:var(--dim); cursor:not-allowed; }
|
||||||
.btn:disabled::before { display:none; }
|
.btn:disabled::before { display:none; }
|
||||||
.btn:disabled:hover { color:var(--dim); }
|
.btn:disabled:hover { color:var(--dim); }
|
||||||
.btn-debug { border:1px solid var(--dim); color:var(--label); min-width:52px; text-align:center; font-size:10px; padding:6px 10px; }
|
.btn-debug { border:1px solid var(--dim); color:var(--label); min-width:52px; text-align:center; font-size:10px; height:34px; padding:0 10px; }
|
||||||
.btn-debug::before { background:var(--accent); }
|
.btn-debug::before { background:var(--accent); }
|
||||||
.btn-theme { border:1px solid var(--dim); color:var(--label); min-width:72px; text-align:center; }
|
.btn-theme { border:1px solid var(--dim); color:var(--label); min-width:72px; text-align:center; }
|
||||||
.btn-theme::before { background:var(--text); }
|
.btn-theme::before { background:var(--text); }
|
||||||
@@ -148,10 +148,25 @@
|
|||||||
.chg-badge.full { border-color:var(--ok); color:var(--ok); }
|
.chg-badge.full { border-color:var(--ok); color:var(--ok); }
|
||||||
.chg-badge.show { display:flex; }
|
.chg-badge.show { display:flex; }
|
||||||
|
|
||||||
main { max-width:1100px; margin:0 auto; padding:32px 20px 80px; display:grid; grid-template-columns:1fr 380px; gap:16px; align-items:start; }
|
main { max-width:1440px; margin:0 auto; padding:32px 20px 80px; display:grid; grid-template-columns:1fr 1fr 380px; gap:16px; align-items:start; }
|
||||||
.col-left { display:grid; gap:12px; }
|
.col-left { display:grid; gap:12px; }
|
||||||
|
.col-mid { display:grid; gap:12px; }
|
||||||
.col-right { display:grid; gap:12px; position:sticky; top:80px; }
|
.col-right { display:grid; gap:12px; position:sticky; top:80px; }
|
||||||
|
|
||||||
|
|
||||||
|
/* Responsive */
|
||||||
|
@media (max-width:1100px) {
|
||||||
|
main { grid-template-columns:1fr 380px; grid-template-rows:auto auto; }
|
||||||
|
.col-left { grid-column:1; grid-row:1; }
|
||||||
|
.col-mid { grid-column:1; grid-row:2; }
|
||||||
|
.col-right { grid-column:2; grid-row:1/3; }
|
||||||
|
}
|
||||||
|
@media (max-width:700px) {
|
||||||
|
main { grid-template-columns:1fr; }
|
||||||
|
.col-left, .col-mid, .col-right { grid-column:1; grid-row:auto; }
|
||||||
|
.col-right { position:static; }
|
||||||
|
}
|
||||||
|
|
||||||
.section-label { font-family:var(--sans); font-size:11px; font-weight:600; letter-spacing:0.3em; text-transform:uppercase; color:var(--label); padding:4px 0; border-bottom:1px solid var(--border); margin-bottom:4px; display:flex; align-items:center; gap:8px; }
|
.section-label { font-family:var(--sans); font-size:11px; font-weight:600; letter-spacing:0.3em; text-transform:uppercase; color:var(--label); padding:4px 0; border-bottom:1px solid var(--border); margin-bottom:4px; display:flex; align-items:center; gap:8px; }
|
||||||
.section-label::before { content:'//'; color:var(--accent); font-family:var(--mono); font-size:10px; }
|
.section-label::before { content:'//'; color:var(--accent); font-family:var(--mono); font-size:10px; }
|
||||||
|
|
||||||
@@ -177,7 +192,6 @@
|
|||||||
.seg-btn:last-child { border-right:none; }
|
.seg-btn:last-child { border-right:none; }
|
||||||
.seg-btn.active { background:var(--accent); color:var(--bg); font-weight:bold; }
|
.seg-btn.active { background:var(--accent); color:var(--bg); font-weight:bold; }
|
||||||
.seg-btn:disabled { cursor:not-allowed; opacity:0.35; }
|
.seg-btn:disabled { cursor:not-allowed; opacity:0.35; }
|
||||||
.charge-seg .seg-btn.active.off { background:var(--dim); color:#fff; }
|
|
||||||
.charge-seg .seg-btn.active.slow { background:var(--warn); color:var(--bg); }
|
.charge-seg .seg-btn.active.slow { background:var(--warn); color:var(--bg); }
|
||||||
.charge-seg .seg-btn.active.fast { background:var(--accent2);color:#fff; }
|
.charge-seg .seg-btn.active.fast { background:var(--accent2);color:#fff; }
|
||||||
|
|
||||||
@@ -225,7 +239,7 @@
|
|||||||
.viz-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; }
|
.viz-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; }
|
||||||
.viz-title { font-family:var(--sans); font-size:11px; font-weight:600; letter-spacing:0.25em; text-transform:uppercase; color:var(--label); }
|
.viz-title { font-family:var(--sans); font-size:11px; font-weight:600; letter-spacing:0.25em; text-transform:uppercase; color:var(--label); }
|
||||||
.orient-card { padding:12px; display:flex; flex-direction:column; align-items:center; }
|
.orient-card { padding:12px; display:flex; flex-direction:column; align-items:center; }
|
||||||
#orientCanvas { display:block; width:100%; height:160px; }
|
#orientCanvas { display:block; width:100%; aspect-ratio:1; }
|
||||||
.viz-ctrl-btn { background:none; border:1px solid var(--border); color:var(--label); font-size:11px; line-height:1; padding:3px 8px; cursor:pointer; letter-spacing:0.05em; }
|
.viz-ctrl-btn { background:none; border:1px solid var(--border); color:var(--label); font-size:11px; line-height:1; padding:3px 8px; cursor:pointer; letter-spacing:0.05em; }
|
||||||
.viz-ctrl-btn:hover { border-color:var(--accent); color:var(--accent); }
|
.viz-ctrl-btn:hover { border-color:var(--accent); color:var(--accent); }
|
||||||
.viz-live { font-size:9px; letter-spacing:0.2em; display:block; }
|
.viz-live { font-size:9px; letter-spacing:0.2em; display:block; }
|
||||||
@@ -254,9 +268,6 @@
|
|||||||
.ci-val { font-family:var(--sans); font-size:16px; font-weight:700; }
|
.ci-val { font-family:var(--sans); font-size:16px; font-weight:700; }
|
||||||
.ci-lbl { font-size:9px; letter-spacing:0.2em; text-transform:uppercase; color:var(--label); margin-top:3px; }
|
.ci-lbl { font-size:9px; letter-spacing:0.2em; text-transform:uppercase; color:var(--label); margin-top:3px; }
|
||||||
|
|
||||||
.advanced-row { display:flex; align-items:center; gap:8px; margin-top:10px; justify-content:flex-end; }
|
|
||||||
.advanced-label { font-family:var(--mono); font-size:9px; color:var(--label); letter-spacing:0.15em; }
|
|
||||||
|
|
||||||
.overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,0.88); z-index:500; align-items:center; justify-content:center; }
|
.overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,0.88); z-index:500; align-items:center; justify-content:center; }
|
||||||
.overlay.show { display:flex; }
|
.overlay.show { display:flex; }
|
||||||
.modal { background:var(--panel); border:1px solid var(--accent2); padding:28px; max-width:360px; width:100%; }
|
.modal { background:var(--panel); border:1px solid var(--accent2); padding:28px; max-width:360px; width:100%; }
|
||||||
@@ -269,7 +280,7 @@
|
|||||||
.btn-confirm { border-color:var(--accent2); color:var(--accent2); }
|
.btn-confirm { border-color:var(--accent2); color:var(--accent2); }
|
||||||
.btn-confirm:hover { background:var(--accent2); color:var(--bg); }
|
.btn-confirm:hover { background:var(--accent2); color:var(--bg); }
|
||||||
|
|
||||||
/* ── Debug modal ────────────────────────────────────────────────────────── */
|
/* Debug modal */
|
||||||
.debug-modal { max-width:720px; padding:20px; border-color:var(--accent); }
|
.debug-modal { max-width:720px; padding:20px; border-color:var(--accent); }
|
||||||
.debug-modal h3 { color:var(--accent); margin-bottom:0; }
|
.debug-modal h3 { color:var(--accent); margin-bottom:0; }
|
||||||
.debug-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; }
|
.debug-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; }
|
||||||
@@ -297,6 +308,7 @@
|
|||||||
.no-ble p { font-size:13px; color:var(--label); line-height:1.8; }
|
.no-ble p { font-size:13px; color:var(--label); line-height:1.8; }
|
||||||
|
|
||||||
body.disconnected .card { opacity:0.45; pointer-events:none; transition:opacity 0.3s; }
|
body.disconnected .card { opacity:0.45; pointer-events:none; transition:opacity 0.3s; }
|
||||||
|
body.disconnected .card.ota-card { opacity:1; pointer-events:auto; } /* OTA works when disconnected too */
|
||||||
body.disconnected .cmd-grid { opacity:0.45; pointer-events:none; transition:opacity 0.3s; }
|
body.disconnected .cmd-grid { opacity:0.45; pointer-events:none; transition:opacity 0.3s; }
|
||||||
|
|
||||||
.tap-key-row { display:flex; align-items:center; gap:10px; padding-top:12px; flex-wrap:wrap; }
|
.tap-key-row { display:flex; align-items:center; gap:10px; padding-top:12px; flex-wrap:wrap; }
|
||||||
@@ -306,8 +318,29 @@
|
|||||||
.mod-btn input:checked + span { background:var(--accent); color:var(--bg); border-color:var(--accent); font-weight:bold; }
|
.mod-btn input:checked + span { background:var(--accent); color:var(--bg); border-color:var(--accent); font-weight:bold; }
|
||||||
.mod-btn input:disabled + span { opacity:0.35; cursor:not-allowed; }
|
.mod-btn input:disabled + span { opacity:0.35; cursor:not-allowed; }
|
||||||
|
|
||||||
|
.restart-note { color:var(--warn); font-family:var(--mono); font-size:9px; }
|
||||||
|
|
||||||
|
|
||||||
.tap-flash { position:absolute; inset:0; pointer-events:none; opacity:0; transition:opacity 0.25s; }
|
.tap-flash { position:absolute; inset:0; pointer-events:none; opacity:0; transition:opacity 0.25s; }
|
||||||
.tap-flash.left { background:radial-gradient(circle at center, var(--tap-left) 0%, transparent 70%); }
|
.tap-flash.left { background:radial-gradient(circle at center, var(--tap-left) 0%, transparent 70%); }
|
||||||
.tap-flash.right { background:radial-gradient(circle at center, var(--tap-right) 0%, transparent 70%); }
|
.tap-flash.right { background:radial-gradient(circle at center, var(--tap-right) 0%, transparent 70%); }
|
||||||
.tap-flash.show { opacity:1; }
|
.tap-flash.show { opacity:1; }
|
||||||
.viz-wrap { position:relative; }
|
.viz-wrap { position:relative; }
|
||||||
|
|
||||||
|
/* ── OTA Firmware Update ── */
|
||||||
|
.ota-card { display:flex; flex-direction:column; gap:14px; }
|
||||||
|
.ota-notice { display:flex; gap:12px; align-items:flex-start; padding:10px 12px; background:color-mix(in srgb, var(--warn) 8%, var(--bg)); border-left:3px solid var(--warn); }
|
||||||
|
.ota-notice-icon { font-size:16px; color:var(--warn); flex-shrink:0; line-height:1.4; }
|
||||||
|
.ota-notice-title { font-family:var(--sans); font-size:11px; font-weight:700; color:var(--warn); letter-spacing:0.08em; text-transform:uppercase; margin-bottom:4px; }
|
||||||
|
.ota-notice-body { font-family:var(--mono); font-size:10px; color:var(--label); line-height:1.6; }
|
||||||
|
.ota-steps { font-family:var(--mono); font-size:10px; color:var(--label); line-height:1.9; margin:0; padding-left:18px; }
|
||||||
|
.ota-steps code { color:var(--text); }
|
||||||
|
.ota-steps strong { color:var(--text); }
|
||||||
|
.ota-steps em { color:var(--accent); font-style:normal; }
|
||||||
|
.ota-btn-row { display:grid; gap:8px; }
|
||||||
|
.ota-status-row { min-height:14px; }
|
||||||
|
.ota-status { font-family:var(--mono); font-size:10px; color:var(--label); }
|
||||||
|
.ota-status.ota-ok { color:var(--ok); }
|
||||||
|
.ota-status.ota-err { color:var(--accent2); }
|
||||||
|
.cmd-btn.ota-trigger::before { background:var(--accent); }
|
||||||
|
.cmd-btn.ota-trigger:hover { border-color:var(--accent); }
|
||||||
|
|||||||
Reference in New Issue
Block a user