"""Offline Android sensor verifier for Ch 147: Accelerometer & Gyroscope Sensors."""
import json
import math
import struct
VERSION = (
"CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
"(Android SDK/emulator absent)"
)
def magnitude(x: float, y: float, z: float) -> float:
return math.sqrt(x * x + y * y + z * z)
def run_step_counter(samples: list[tuple[float, float, float]], threshold: float = 1.0, active: bool = True) -> int:
"""Exact port of the chapter's peak-valley accelerometer step counter state machine."""
step = 0
lst_value = 0.0
motive_state = True
for x, y, z in samples:
cur_value = magnitude(x, y, z)
if motive_state:
if cur_value >= lst_value:
lst_value = cur_value
elif abs(cur_value - lst_value) > threshold:
motive_state = False
if not motive_state:
if cur_value <= lst_value:
lst_value = cur_value
elif abs(cur_value - lst_value) > threshold:
if active:
step += 1
motive_state = True
return step
def detect_shakes(samples: list[tuple[float, float, float]], g_threshold: float = 2.0) -> int:
"""Count samples whose normalized g-force exceeds g_threshold (standard shake detector)."""
g = 9.81
return sum(1 for x, y, z in samples if magnitude(x, y, z) / g >= g_threshold)
def float32(v: float) -> float:
return struct.unpack("!f", struct.pack("!f", v))[0]
def main() -> None:
# Case 1: Accelerometer static orientations, peak-valley step counter & shake detection
static_mags = {
"flat_face_up": round(magnitude(0.0, 0.0, 9.81), 2),
"portrait_upright": round(magnitude(0.0, 9.81, 0.0), 2),
"landscape_left": round(magnitude(9.81, 0.0, 0.0), 2),
}
# 3 walking cycles (upward peak ~13.0, downward valley ~7.0, recovery ~10.0)
walk_wave = [
(0.0, 0.0, 9.8), (0.0, 0.0, 12.8), (0.0, 0.0, 11.2), (0.0, 0.0, 7.2), (0.0, 0.0, 9.5),
(0.0, 0.0, 13.1), (0.0, 0.0, 10.9), (0.0, 0.0, 7.0), (0.0, 0.0, 9.8),
(0.0, 0.0, 12.9), (0.0, 0.0, 11.0), (0.0, 0.0, 6.9), (0.0, 0.0, 9.7),
]
steps_active = run_step_counter(walk_wave, threshold=1.0, active=True)
steps_paused = run_step_counter(walk_wave, threshold=1.0, active=False)
shake_samples = [(0.0, 0.0, 9.81), (18.0, 12.0, 10.0), (1.0, 2.0, 9.81), (-21.0, 8.0, 5.0)]
shake_hits = detect_shakes(shake_samples, g_threshold=2.0)
c1_actual = {
"static_orientations_ms2": static_mags,
"steps_when_active": steps_active,
"steps_when_paused": steps_paused,
"shake_events_over_2g": shake_hits,
}
c1_expected = {
"static_orientations_ms2": {
"flat_face_up": 9.81,
"portrait_upright": 9.81,
"landscape_left": 9.81,
},
"steps_when_active": 3,
"steps_when_paused": 0,
"shake_events_over_2g": 2,
}
# Case 2: Gyroscope angular velocity integration (rad/s -> degrees) + long vs float32 timestamp precision bug
ns2s = 1.0 / 1_000_000_000.0
# 5 samples spaced 100ms apart (0.1s), rotating counterclockwise around Z at pi/2 rad/s (90 deg/s)
base_ns = 1_000_000_000_000 # 1000 seconds uptime in nanoseconds
step_ns = 100_000_000 # 100ms
gyro_events = [
(base_ns + i * step_ns, (0.0, 0.0, math.pi / 2.0))
for i in range(6) # 5 intervals = 0.5s => 45 deg
]
angle_long = [0.0, 0.0, 0.0]
prev_ts_long = 0
for ts, omega in gyro_events:
if prev_ts_long != 0:
dt = (ts - prev_ts_long) * ns2s
for idx in range(3):
angle_long[idx] += omega[idx] * dt
prev_ts_long = ts
# Compare against buggy float32 timestamp storage (ULP ~8.39ms at 1-day uptime: 4ms delta collapses to 0!)
large_uptime_ns = 86_400_000_000_000 # 1 day uptime
f32_t0 = float32(float(large_uptime_ns))
f32_t1 = float32(float(large_uptime_ns + 4_000_000)) # +4ms (250Hz sensor)
f32_dt_ms = round((f32_t1 - f32_t0) * ns2s * 1000.0, 3)
c2_actual = {
"integrated_z_deg_long_ts": round(math.degrees(angle_long[2]), 2),
"integrated_xy_deg": [round(math.degrees(angle_long[0]), 2), round(math.degrees(angle_long[1]), 2)],
"float32_timestamp_4ms_collapses_to_zero": f32_dt_ms == 0.0,
}
c2_expected = {
"integrated_z_deg_long_ts": 45.0,
"integrated_xy_deg": [0.0, 0.0],
"float32_timestamp_4ms_collapses_to_zero": True,
}
cases = [
{
"name": "accelerometer_magnitude_step_and_shake",
"summary": "验证三轴加速度模长、波峰波谷简易计步器状态机与 2g 摇一摇阈值检测",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "gyroscope_angle_integration_and_long_timestamp",
"summary": "验证陀螺仪角速度时间积分(0.5s × π/2 rad/s = 45°)并暴露 float 存储纳秒时间戳的精度归零缺陷",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-sensor3-lab/explore-tutorial-sensor3.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-sensor3.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1938.zip