"""Smart Workout Movement Assistant - Etape 8
Historique des series (CSV serie + history.csv) en plus de la derive de regularite, de la simulation et des alertes.
Pas un dispositif medical : aide a la prise de conscience technique uniquement.
"""
from machine import Pin, I2C
from time import sleep_ms, ticks_us, ticks_diff, ticks_ms, ticks_add
from mpu6050 import MPU6050, ComplementaryFilter
import calibration
from display import Display
from reps import RepCounter
from alerts import AlertEngine
from drift import DriftDetector
from history import SessionLog
from feedback import Feedback, GREEN, BLUE, RED, YELLOW, OFF
from profiles import PROFILES
from simulator import SimRig, SCENARIOS, NAMES as SIM_NAMES
# ---------------- Configuration ----------------
PIN_SDA, PIN_SCL = 21, 22
PIN_LED_R, PIN_LED_G, PIN_LED_B = 25, 26, 27
PIN_BUZZER = 14
PIN_VIB = 13
PIN_BTN_EXO, PIN_BTN_CALIB = 32, 33
ADDR_TRUNK, ADDR_PELVIS, ADDR_OLED = 0x68, 0x69, 0x3C
SAMPLE_MS = 20 # 50 Hz : acquisition
OLED_MS = 200 # 5 Hz : rafraichissement ecran (un envoi I2C complet bloque ~25 ms)
PRINT_EVERY = 5 # 1 ligne CSV sur 5 (10 Hz) ; mettre 1 pour tout voir
ALPHA = 0.98
# Convention : angle de pitch positif = flexion vers l'avant.
# Si la flexion apparait negative avec votre montage, mettre -1.
PITCH_SIGN = 1
# Mode simulation : appui LONG (>= 1 s) sur EXO = scenario suivant ; apres le dernier, retour aux capteurs reels.
# SIM_START : nom d'un scenario a lancer des le demarrage (ex. "correct"), ou None.
SIM_START = None
LONG_PRESS_MS = 1000
DRIFT_SHOW_MS = 5000 # duree d'affichage d'un message de derive apres chaque evaluation
# ---------------- Peripheriques ----------------
i2c = I2C(0, sda=Pin(PIN_SDA), scl=Pin(PIN_SCL), freq=400000)
fb = Feedback(PIN_LED_R, PIN_LED_G, PIN_LED_B, PIN_BUZZER, PIN_VIB)
btn_exo = Pin(PIN_BTN_EXO, Pin.IN, Pin.PULL_UP) # actif a 0
btn_calib = Pin(PIN_BTN_CALIB, Pin.IN, Pin.PULL_UP) # actif a 0
oled = None
def show_msg(*lines):
if oled:
oled.message(*lines)
def self_test():
for color in (RED, YELLOW, GREEN):
fb.rgb(color)
sleep_ms(250)
fb.rgb(OFF)
fb.beep(1500, 120)
fb.vib_pulse(200)
def check_i2c():
found = i2c.scan()
print("Peripheriques I2C :", [hex(a) for a in found])
for name, addr in (("MPU tronc", ADDR_TRUNK), ("MPU bassin", ADDR_PELVIS), ("OLED", ADDR_OLED)):
print(" %-10s %s : %s" % (name, hex(addr), "OK" if addr in found else "ABSENT"))
return found
def run_calibration(sensors, current):
"""Lance la calibration. Retourne (calibration, ok)."""
print("# CALIBRATION : restez immobile en position de reference (1 s)...")
show_msg("CALIBRATION", "", "Restez immobile", "pendant 1 s")
fb.reset()
fb.rgb(BLUE) # bleu = calibration en cours
fb.beep(1000, 80)
calib, err = calibration.calibrate(sensors)
if calib is None:
print("# ECHEC calibration :", err)
show_msg("ECHEC CALIB", "", "Restez immobile", "et reessayez")
fb.rgb(RED)
fb.beep(400, 400)
sleep_ms(1200)
fb.reset()
return current, False
for n, c in calib.items():
print("# %s : ref pitch=%.1f roll=%.1f | biais gyro=(%.2f, %.2f, %.2f)"
% (n, c["pitch"], c["roll"], c["gyro"][0], c["gyro"][1], c["gyro"][2]))
saved = calibration.save(calib)
print("# Calibration OK (%s)" % ("sauvegardee" if saved else "non sauvegardee"))
show_msg("CALIBRATION OK", "", "Reference", "enregistree")
fb.reset()
fb.beep(2000, 80)
sleep_ms(60)
fb.beep(2500, 80)
sleep_ms(600)
return calib, True
def new_counter(idx):
p = PROFILES[idx]
return RepCounter(p["start"], p["bottom"])
def set_source(idx):
"""idx = -1 : capteurs reels ; sinon scenario SIM_NAMES[idx]. Remet tout le pipeline a zero."""
global sim_idx, sim_rig, sim_done, sim_stats, drift_until
global sensors, calib, is_calibrated, exercise_idx, counter, last_state
sim_idx = idx
sim_done = False
sim_stats = {}
for f in filters.values():
f.reset()
if idx < 0:
sim_rig = None
sensors = real_sensors
calib = real_calib
is_calibrated = real_is_calibrated
print("# Source : capteurs reels")
show_msg("CAPTEURS REELS")
else:
name = SIM_NAMES[idx]
sim_rig = SimRig(name, ticks_ms)
sensors = sim_rig.sensors
calib = calibration.default_calibration(sensors) # angles synthetiques deja relatifs a la station debout
is_calibrated = False
exercise_idx = 0 # scenarios concus pour le RDL
print("# SIMULATION '%s' : %s" % (name, SCENARIOS[name]["desc"]))
print("# Attendu : %s" % SCENARIOS[name]["expect"])
show_msg("SIMULATION", name, SCENARIOS[name]["desc"])
counter = new_counter(exercise_idx)
drift.reset()
drift_until = 0
alerts.set_profile(PROFILES[exercise_idx])
fb.reset()
last_state = (0, "")
log.start_set(PROFILES[exercise_idx]["name"], SIM_NAMES[idx] if idx >= 0 else "reel")
if oled:
sleep_ms(900)
# ---------------- Programme ----------------
print("=== Smart Workout Movement Assistant - etape 8 ===")
self_test()
found = check_i2c()
if ADDR_OLED in found:
try:
oled = Display(i2c, ADDR_OLED)
except Exception as e: # l'ecran est optionnel : on continue sans
print("# OLED indisponible :", e)
if ADDR_TRUNK not in found or ADDR_PELVIS not in found:
fb.rgb(RED)
show_msg("ERREUR", "MPU6050 absent", "Verifier cablage")
raise SystemExit("MPU6050 introuvable : verifier le cablage (AD0 du bassin a 3V3).")
real_sensors = {"trunk": MPU6050(i2c, ADDR_TRUNK), "pelvis": MPU6050(i2c, ADDR_PELVIS)}
sensors = real_sensors
filters = {n: ComplementaryFilter(ALPHA) for n in sensors}
calib = calibration.load(list(sensors))
is_calibrated = calib is not None
if is_calibrated:
print("# Calibration rechargee depuis", calibration.CALIB_FILE)
else:
calib = calibration.default_calibration(sensors)
print("# Pas de calibration : reference = 0. Appuyer sur CALIB en position debout.")
sleep_ms(800) # laisse lire l'ecran d'accueil
real_calib = calib
real_is_calibrated = is_calibrated
sim_idx = -1 # -1 = capteurs reels, sinon indice dans SIM_NAMES
sim_rig = None
sim_done = False
sim_stats = {} # code d'alerte -> niveau maximal vu pendant le scenario
exercise_idx = 0
counter = new_counter(exercise_idx)
alerts = AlertEngine(PROFILES[exercise_idx])
drift = DriftDetector()
drift_until = 0
log = SessionLog() # etape 8 : historique des series
log.start_set(PROFILES[exercise_idx]["name"], "reel")
print("# Exercice :", PROFILES[exercise_idx]["name"])
fb.reset()
print("t_ms,trunk_pitch,trunk_roll,pelvis_pitch,pelvis_roll,rel_pitch,rel_roll,phase,reps,level")
if SIM_START:
set_source(SIM_NAMES.index(SIM_START))
t_prev = ticks_us()
exo_down_ms = 0
exo_long_done = False
last_calib_btn = 1
last_exo_btn = 1
last_oled_ms = ticks_ms()
last_state = (0, "")
loop_count = 0
while True:
t_now = ticks_us()
dt = ticks_diff(t_now, t_prev) / 1_000_000
t_prev = t_now
now_ms = ticks_ms()
# Angles relatifs a la reference (gyro corrige du biais avant le filtre)
angles = {}
trunk_gyro = (0.0, 0.0, 0.0)
for n, sensor in sensors.items():
ax, ay, az, gx, gy, gz = sensor.read()
c = calib[n]
gx -= c["gyro"][0]
gy -= c["gyro"][1]
gz -= c["gyro"][2]
p, r = filters[n].update(ax, ay, az, gx, gy, gz, dt)
angles[n] = (PITCH_SIGN * (p - c["pitch"]), r - c["roll"])
if n == "trunk":
trunk_gyro = (gx, gy, gz) # yaw inclus : sert a la stabilite
tp, tr = angles["trunk"]
pp, pr = angles["pelvis"]
rel = (tp - pp, tr - pr) # (flexion lombaire vs hanche, ecart lateral tronc/bassin)
# Comptage de repetitions sur la flexion du tronc
rec = counter.update(tp, now_ms, rel[0])
if rec:
print("# [%d ms] REP %d : ecc=%d ms, bas=%d ms, con=%d ms, pic=%.1f deg, rel_max=%.1f deg"
% (now_ms, rec["n"], rec["ecc_ms"], rec["hold_ms"], rec["con_ms"], rec["peak"], rec["rel_max"]))
alerts.on_rep(rec, now_ms) # controle du tempo
# Etape 7 : derive de regularite (duree totale, amplitude, angle relatif max)
total_s = (rec["ecc_ms"] + rec["hold_ms"] + rec["con_ms"]) / 1000
d_lvl, d_score = drift.add_rep(total_s, rec["peak"], rec["rel_max"])
if d_score:
print("# DERIVE rep %d : score=%.2f niveau=%d %s" % (rec["n"], d_score, d_lvl, drift.message()))
drift_until = ticks_add(now_ms, DRIFT_SHOW_MS) if d_lvl else 0
log.add_rep(rec, total_s, d_score, d_lvl, now_ms) # etape 8 : ligne CSV de la repetition
last_oled_ms = 0
# Alertes : confirmees dans le temps, puis LED / buzzer / vibration
level, code, reason = alerts.update(now_ms, tp, tr, rel[0], rel[1], trunk_gyro, tp >= PROFILES[exercise_idx]["bottom"])
# La derive (fatigue possible) ne monte jamais au-dessus d'ATTENTION et ne masque aucune alerte
if level == 0 and drift.level and ticks_diff(drift_until, now_ms) > 0:
level, code, reason = 1, "drift", drift.message()
log.note_alert(level, code) # etape 8 : alertes attribuees a la repetition en cours
if (level, code) != last_state:
print("# [%d ms] ALERTE niveau %d : %s" % (now_ms, level, reason if level else "retour normal"))
last_state = (level, code)
last_oled_ms = 0 # affiche l'alerte tout de suite
fb.set_level(level, now_ms)
fb.tick(now_ms)
if log.tick(now_ms): # serie fermee apres inactivite : on repart a zero
counter.reset()
drift.reset()
drift_until = 0
if sim_rig:
if level and level > sim_stats.get(code, 0):
sim_stats[code] = level
if not sim_done and sim_rig.finished():
sim_done = True
bilan = ", ".join("%s(%d)" % (k, v) for k, v in sim_stats.items()) or "aucune"
print("# BILAN %s : %d reps | alertes : %s" % (sim_rig.name, counter.reps, bilan))
print("# Appui long sur EXO : scenario suivant")
log.end_set() # etape 8 : resume de la serie
loop_count += 1
if loop_count % PRINT_EVERY == 0:
print("%d,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,%s,%d,%d"
% (now_ms, tp, tr, pp, pr, rel[0], rel[1], counter.phase_name, counter.reps, level))
# Rafraichissement OLED a cadence reduite
if oled and ticks_diff(now_ms, last_oled_ms) >= OLED_MS:
last_oled_ms = now_ms
oled.update(PROFILES[exercise_idx]["name"], counter.reps, counter.phase_name, is_calibrated,
angles["trunk"], angles["pelvis"], rel, level, reason, sim_rig.name if sim_rig else None)
# Bouton CALIB (front descendant) : recalibre et remet la serie a zero
b = btn_calib.value()
if b == 0 and last_calib_btn == 1:
if sim_rig:
print("# CALIB inactif en simulation (angles synthetiques deja relatifs a la station debout)")
else:
calib, ok = run_calibration(sensors, calib)
is_calibrated = is_calibrated or ok
real_calib, real_is_calibrated = calib, is_calibrated
for f in filters.values():
f.reset()
counter.reset()
alerts.reset()
drift.reset()
drift_until = 0
log.start_set(PROFILES[exercise_idx]["name"], "reel")
last_state = (0, "")
t_prev = ticks_us()
last_oled_ms = 0
last_calib_btn = b
# Bouton EXO : exercice suivant (profil de comptage et seuils) et remise a zero de la serie
e = btn_exo.value()
if e == 0 and last_exo_btn == 1:
exo_down_ms = now_ms # debut d'appui
exo_long_done = False
elif e == 0 and not exo_long_done and ticks_diff(now_ms, exo_down_ms) >= LONG_PRESS_MS:
exo_long_done = True # appui long : source suivante (reel -> scenarios -> reel)
nxt = sim_idx + 1
set_source(nxt if nxt < len(SIM_NAMES) else -1)
t_prev = ticks_us()
last_oled_ms = 0
elif e == 1 and last_exo_btn == 0 and not exo_long_done:
exercise_idx = (exercise_idx + 1) % len(PROFILES) # appui court, pris en compte au relachement
counter = new_counter(exercise_idx)
alerts.set_profile(PROFILES[exercise_idx])
drift.reset()
drift_until = 0
log.start_set(PROFILES[exercise_idx]["name"], sim_rig.name if sim_rig else "reel")
fb.reset()
last_state = (0, "")
print("# Exercice :", PROFILES[exercise_idx]["name"])
last_oled_ms = 0 # force le rafraichissement immediat
last_exo_btn = e
elapsed_ms = ticks_diff(ticks_us(), t_now) // 1000
sleep_ms(max(1, SAMPLE_MS - elapsed_ms))Loading
esp32-devkit-c-v4
esp32-devkit-c-v4
Loading
ssd1306
ssd1306