titimoby/StackChan-pilotpublic Fork
⑂ 6c77733
Commits
⬇ Clone ▾
git clone https://git.rickub.com/titimoby/StackChan-pilot.git
git clone ssh://git@rickub.com/titimoby/StackChan-pilot.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

switch to english

Thierry Chantier committed 2026-11-27T16:29:28+01:00 Browse files
6c77733 parent: 9b32110
modified CLAUDE.md +29 -29
@@ -1,49 +1,49 @@
1-# StackChan — firmware et pilotage par Claude
1+# StackChan — firmware and control from Claude
22
3-Projet perso : firmware et outils pour le robot de bureau **M5Stack StackChan (K151)** — CoreS3 (ESP32-S3) + corps motorisé (2 servos Feetech SCS0009, 12 LED, tactile tête, NFC, IR). Langue de travail : français.
3+Personal project: firmware and tooling for the **M5Stack StackChan (K151)** desktop robot — CoreS3 (ESP32-S3) + motorized body (2 Feetech SCS0009 servos, 12 LEDs, head touch, NFC, IR). Repository docs and code are in English; talk to the user in French.
44
55 ## Architecture
66
77 ```
8-sessions Claude ──MCP HTTP 127.0.0.1:8765/mcp──> mcp/ (Python, serveur partagé stackchan-mcp) ──USB série, JSON-lines──> firmware/ (Arduino, CoreS3)
8+Claude sessions ──MCP HTTP 127.0.0.1:8765/mcp──> mcp/ (Python, shared stackchan-mcp server) ──USB serial, JSON-lines──> firmware/ (Arduino, CoreS3)
99 ```
1010
11-- `firmware/` — PlatformIO, framework Arduino. `src/main.cpp` : protocole + gestes ; `src/face.{h,cpp}` : visage dessiné dans un sprite PSRAM.
12-- `mcp/` — serveur MCP (SDK `mcp` **2.x** : `MCPServer` dans `mcp.server.mcpserver`, pas `FastMCP`). `robot.py` : lien série ; `sessions.py` : prise de main et curseurs d'événements par session ; `server.py` : outils.
13-- Serveur enregistré en portée **utilisateur** (`claude mcp add --transport http --scope user stackchan http://127.0.0.1:8765/mcp`), donc visible de toutes les sessions ; démarrage **manuel** avec `tools/stackchan-server.sh start|stop|status|logs`.
14-- `tools/serial_cmd.py`, `tools/serial_read.py` — accès série brut pour déboguer sans MCP.
15-- `docs/hardware-reference.md` (matériel, brochage), `docs/protocol.md` (**contrat firmware ↔ serveur**, à tenir à jour à chaque nouvelle commande).
11+- `firmware/` — PlatformIO, Arduino framework. `src/main.cpp`: protocol + gestures; `src/face.{h,cpp}`: face drawn into a PSRAM sprite.
12+- `mcp/` — MCP server (`mcp` SDK **2.x**: `MCPServer` in `mcp.server.mcpserver`, not `FastMCP`). `robot.py`: serial link; `sessions.py`: control lease and per-session event cursors; `server.py`: tools.
13+- The server is registered at **user** scope (`claude mcp add --transport http --scope user stackchan http://127.0.0.1:8765/mcp`), so every session sees it; it is started **manually** with `tools/stackchan-server.sh start|stop|status|logs`.
14+- `tools/serial_cmd.py`, `tools/serial_read.py` — raw serial access for debugging without MCP.
15+- `docs/hardware-reference.md` (hardware, pinout), `docs/protocol.md` (**firmware ↔ server contract**, keep it up to date with every new command).
1616
17-## Commandes
17+## Commands
1818
1919 ```bash
20-cd firmware && pio run # compiler
21-cd firmware && pio run -t upload --upload-port /dev/cu.usbmodem101 # flasher
22-cd mcp && uv sync # dépendances serveur MCP
23-tools/stackchan-server.sh start # serveur MCP partagé (logs : ~/Library/Logs/stackchan-mcp.log)
20+cd firmware && pio run # build
21+cd firmware && pio run -t upload --upload-port /dev/cu.usbmodem101 # flash
22+cd mcp && uv sync # MCP server dependencies
23+tools/stackchan-server.sh start # shared MCP server (logs: ~/Library/Logs/stackchan-mcp.log)
2424 ~/.local/share/uv/tools/platformio/bin/python -I tools/serial_cmd.py /dev/cu.usbmodem101 3 '{"id":1,"cmd":"status"}'
2525 ```
2626
27-- `pio` est installé via `uv tool` (`~/.local/bin/pio`). Plateforme **pioarduino 55.03.313** (core Arduino 3.3.13) : la plateforme espressif32 officielle est trop ancienne pour la lib `M5StackChan`. Ne pas passer au core 4.x sans valider M5Unified/M5GFX.
28-- Port USB : `/dev/cu.usbmodem101` (VID Espressif `303A`). Flash sans mode download manuel.
27+- `pio` is installed with `uv tool` (`~/.local/bin/pio`). Platform **pioarduino 55.03.313** (Arduino core 3.3.13): the official espressif32 platform is too old for the `M5StackChan` lib. Do not move to core 4.x without validating M5Unified/M5GFX.
28+- USB port: `/dev/cu.usbmodem101` (Espressif VID `303A`). Flashing works without manual download mode.
2929
30-## Règles importantes
30+## Important rules
3131
32-- **Un seul process sur le port USB à la fois.** Le serveur partagé le garde ouvert. Pour flasher : outil `flash_firmware` ; pour `pio run -t upload` à la main ou `tools/serial_cmd.py` : `tools/stackchan-server.sh stop` d'abord.
33-- **Prise de main entre sessions** : une commande au robot donne la main pour 10 s (prolongée à chaque commande) ; les autres sessions sont refusées. `get_status`, `stop` et le toucher restent libres. Un refus « robot utilisé par une autre session » est normal : attendre ou demander à l'utilisateur.
34-- Si le robot ne répond plus du tout (même à `esptool`) alors que le port USB est visible : demander à l'utilisateur de débrancher/rebrancher l'USB.
35-- **Ouvrir le port redémarre le robot** (macOS / USB-Serial-JTAG), même avec DTR/RTS bas : attendre l'événement `{"event":"boot"}` avant d'envoyer des commandes. Visage et LED reviennent à l'état initial.
36-- **Limites servos** (unités BSP = 1/10°) : yaw −90…+90°, pitch **5…85°** (au-delà : risque de calage et de casse, recommandation M5Stack). Le bornage est fait dans le firmware (`kYawMin/Max`, `kPitchMin/Max`) — ne pas l'assouplir.
37-- **Sens vérifié** : yaw positif = la tête tourne vers **la gauche du robot** ; pitch plus grand = regarde vers le haut ; (0, 0) = position calibrée, écran perpendiculaire à la base.
38-- La calibration du zéro est en NVS (namespace `servo`, clés `zero_pos_1/2`) et doit être refaite après un firmware tiers. Elle nécessite que l'utilisateur place la tête à la main (couple coupé) — ne jamais appeler `set_home` sans lui.
39-- Ne pas forcer la tête à la main quand les moteurs sont alimentés.
40-- Bus servo : UART1 1 Mbaud, TX=G6 / RX=G7. I2C corps (G11/G12) : INA226 0x41, NFC 0x50, Si12T 0x68, IO expander PY32L020 0x6F (alimentation servos + LED).
41-- Le drapeau `moving` du servo peut rester vrai à l'arrêt : juger la fin d'un mouvement sur la stabilité de la position (voir `_wait_still` dans `server.py`).
32+- **Only one process on the USB port at a time.** The shared server keeps it open. To flash: `flash_firmware` tool; for a manual `pio run -t upload` or `tools/serial_cmd.py`: run `tools/stackchan-server.sh stop` first.
33+- **Control lease between sessions**: a robot command grants control for 10 s (extended by each command); other sessions are refused. `get_status`, `stop` and touch stay free. A "robot in use by another session" refusal is expected: wait, or ask the user.
34+- If the robot stops answering entirely (even to `esptool`) while the USB port is listed: ask the user to unplug/replug the USB cable.
35+- **Opening the port reboots the robot** (macOS / USB-Serial-JTAG), even with DTR/RTS low: wait for the `{"event":"boot"}` event before sending commands. Face and LEDs go back to their initial state.
36+- **Servo limits** (BSP units = 1/10°): yaw −90…+90°, pitch **5…85°** (beyond: risk of stalling and breakage, M5Stack recommendation). Clamping is done in the firmware (`kYawMin/Max`, `kPitchMin/Max`) — do not loosen it.
37+- **Verified directions**: positive yaw = head turns towards **the robot's left**; larger pitch = looks up; (0, 0) = calibrated position, screen perpendicular to the base.
38+- Zero calibration lives in NVS (namespace `servo`, keys `zero_pos_1/2`) and must be redone after a third-party firmware. It requires the user to position the head by hand (torque off) — never call `set_home` without them.
39+- Do not force the head by hand while the motors are powered.
40+- Servo bus: UART1 1 Mbaud, TX=G6 / RX=G7. Body I2C (G11/G12): INA226 0x41, NFC 0x50, Si12T 0x68, PY32L020 IO expander 0x6F (servo power + LEDs).
41+- The servo `moving` flag can stay true at rest: judge the end of a move on position stability (see `_wait_still` in `server.py`).
4242
4343 ## Validation
4444
45-Pas de tests automatisés. Après toute modification : compiler, flasher, puis exercer les commandes touchées via `tools/serial_cmd.py` ou un client MCP (serveur à redémarrer après modification de `mcp/` : `tools/stackchan-server.sh restart`), et demander à l'utilisateur ce qu'il voit (écran, LED, mouvements) — je ne peux pas l'observer.
45+No automated tests. After any change: build, flash, then exercise the affected commands via `tools/serial_cmd.py` or an MCP client (restart the server after changing `mcp/`: `tools/stackchan-server.sh restart`), and ask the user what they see (screen, LEDs, movements) — I cannot observe it.
4646
47-## Versions validées
47+## Validated versions
4848
49-M5StackChan 1.1.1, M5Unified 0.3.0, M5GFX 0.3.0, ArduinoJson 7.x, mcp 2.3, firmware maison 0.1.0. Le firmware d'origine M5Stack (XiaoZhi) a été écrasé ; il se restaure avec M5Burner.
49+M5StackChan 1.1.1, M5Unified 0.3.0, M5GFX 0.3.0, ArduinoJson 7.x, mcp 2.3, custom firmware 0.1.0. The original M5Stack firmware (XiaoZhi) has been overwritten; it can be restored with M5Burner.
@@ -1,49 +1,49 @@
1-# StackChan — firmware et pilotage par Claude1+# StackChan — firmware and control from Claude
2 2
3-Projet perso : firmware et outils pour le robot de bureau **M5Stack StackChan (K151)** — CoreS3 (ESP32-S3) + corps motorisé (2 servos Feetech SCS0009, 12 LED, tactile tête, NFC, IR). Langue de travail : français.3+Personal project: firmware and tooling for the **M5Stack StackChan (K151)** desktop robot — CoreS3 (ESP32-S3) + motorized body (2 Feetech SCS0009 servos, 12 LEDs, head touch, NFC, IR). Repository docs and code are in English; talk to the user in French.
4 4
5 ## Architecture5 ## Architecture
6 6
7 ```7 ```
8-sessions Claude ──MCP HTTP 127.0.0.1:8765/mcp──> mcp/ (Python, serveur partagé stackchan-mcp) ──USB série, JSON-lines──> firmware/ (Arduino, CoreS3)8+Claude sessions ──MCP HTTP 127.0.0.1:8765/mcp──> mcp/ (Python, shared stackchan-mcp server) ──USB serial, JSON-lines──> firmware/ (Arduino, CoreS3)
9 ```9 ```
10 10
11-- `firmware/` — PlatformIO, framework Arduino. `src/main.cpp` : protocole + gestes ; `src/face.{h,cpp}` : visage dessiné dans un sprite PSRAM.11+- `firmware/` — PlatformIO, Arduino framework. `src/main.cpp`: protocol + gestures; `src/face.{h,cpp}`: face drawn into a PSRAM sprite.
12-- `mcp/` — serveur MCP (SDK `mcp` **2.x** : `MCPServer` dans `mcp.server.mcpserver`, pas `FastMCP`). `robot.py` : lien série ; `sessions.py` : prise de main et curseurs d'événements par session ; `server.py` : outils.12+- `mcp/` — MCP server (`mcp` SDK **2.x**: `MCPServer` in `mcp.server.mcpserver`, not `FastMCP`). `robot.py`: serial link; `sessions.py`: control lease and per-session event cursors; `server.py`: tools.
13-- Serveur enregistré en portée **utilisateur** (`claude mcp add --transport http --scope user stackchan http://127.0.0.1:8765/mcp`), donc visible de toutes les sessions ; démarrage **manuel** avec `tools/stackchan-server.sh start|stop|status|logs`.13+- The server is registered at **user** scope (`claude mcp add --transport http --scope user stackchan http://127.0.0.1:8765/mcp`), so every session sees it; it is started **manually** with `tools/stackchan-server.sh start|stop|status|logs`.
14-- `tools/serial_cmd.py`, `tools/serial_read.py` — accès série brut pour déboguer sans MCP.14+- `tools/serial_cmd.py`, `tools/serial_read.py` — raw serial access for debugging without MCP.
15-- `docs/hardware-reference.md` (matériel, brochage), `docs/protocol.md` (**contrat firmware ↔ serveur**, à tenir à jour à chaque nouvelle commande).15+- `docs/hardware-reference.md` (hardware, pinout), `docs/protocol.md` (**firmware ↔ server contract**, keep it up to date with every new command).
16 16
17-## Commandes17+## Commands
18 18
19 ```bash19 ```bash
20-cd firmware && pio run # compiler20+cd firmware && pio run # build
21-cd firmware && pio run -t upload --upload-port /dev/cu.usbmodem101 # flasher21+cd firmware && pio run -t upload --upload-port /dev/cu.usbmodem101 # flash
22-cd mcp && uv sync # dépendances serveur MCP22+cd mcp && uv sync # MCP server dependencies
23-tools/stackchan-server.sh start # serveur MCP partagé (logs : ~/Library/Logs/stackchan-mcp.log)23+tools/stackchan-server.sh start # shared MCP server (logs: ~/Library/Logs/stackchan-mcp.log)
24 ~/.local/share/uv/tools/platformio/bin/python -I tools/serial_cmd.py /dev/cu.usbmodem101 3 '{"id":1,"cmd":"status"}'24 ~/.local/share/uv/tools/platformio/bin/python -I tools/serial_cmd.py /dev/cu.usbmodem101 3 '{"id":1,"cmd":"status"}'
25 ```25 ```
26 26
27-- `pio` est installé via `uv tool` (`~/.local/bin/pio`). Plateforme **pioarduino 55.03.313** (core Arduino 3.3.13) : la plateforme espressif32 officielle est trop ancienne pour la lib `M5StackChan`. Ne pas passer au core 4.x sans valider M5Unified/M5GFX.27+- `pio` is installed with `uv tool` (`~/.local/bin/pio`). Platform **pioarduino 55.03.313** (Arduino core 3.3.13): the official espressif32 platform is too old for the `M5StackChan` lib. Do not move to core 4.x without validating M5Unified/M5GFX.
28-- Port USB : `/dev/cu.usbmodem101` (VID Espressif `303A`). Flash sans mode download manuel.28+- USB port: `/dev/cu.usbmodem101` (Espressif VID `303A`). Flashing works without manual download mode.
29 29
30-## Règles importantes30+## Important rules
31 31
32-- **Un seul process sur le port USB à la fois.** Le serveur partagé le garde ouvert. Pour flasher : outil `flash_firmware` ; pour `pio run -t upload` à la main ou `tools/serial_cmd.py` : `tools/stackchan-server.sh stop` d'abord.32+- **Only one process on the USB port at a time.** The shared server keeps it open. To flash: `flash_firmware` tool; for a manual `pio run -t upload` or `tools/serial_cmd.py`: run `tools/stackchan-server.sh stop` first.
33-- **Prise de main entre sessions** : une commande au robot donne la main pour 10 s (prolongée à chaque commande) ; les autres sessions sont refusées. `get_status`, `stop` et le toucher restent libres. Un refus « robot utilisé par une autre session » est normal : attendre ou demander à l'utilisateur.33+- **Control lease between sessions**: a robot command grants control for 10 s (extended by each command); other sessions are refused. `get_status`, `stop` and touch stay free. A "robot in use by another session" refusal is expected: wait, or ask the user.
34-- Si le robot ne répond plus du tout (même à `esptool`) alors que le port USB est visible : demander à l'utilisateur de débrancher/rebrancher l'USB.34+- If the robot stops answering entirely (even to `esptool`) while the USB port is listed: ask the user to unplug/replug the USB cable.
35-- **Ouvrir le port redémarre le robot** (macOS / USB-Serial-JTAG), même avec DTR/RTS bas : attendre l'événement `{"event":"boot"}` avant d'envoyer des commandes. Visage et LED reviennent à l'état initial.35+- **Opening the port reboots the robot** (macOS / USB-Serial-JTAG), even with DTR/RTS low: wait for the `{"event":"boot"}` event before sending commands. Face and LEDs go back to their initial state.
36-- **Limites servos** (unités BSP = 1/10°) : yaw −90…+90°, pitch **5…85°** (au-delà : risque de calage et de casse, recommandation M5Stack). Le bornage est fait dans le firmware (`kYawMin/Max`, `kPitchMin/Max`) — ne pas l'assouplir.36+- **Servo limits** (BSP units = 1/10°): yaw −90…+90°, pitch **5…85°** (beyond: risk of stalling and breakage, M5Stack recommendation). Clamping is done in the firmware (`kYawMin/Max`, `kPitchMin/Max`) — do not loosen it.
37-- **Sens vérifié** : yaw positif = la tête tourne vers **la gauche du robot** ; pitch plus grand = regarde vers le haut ; (0, 0) = position calibrée, écran perpendiculaire à la base.37+- **Verified directions**: positive yaw = head turns towards **the robot's left**; larger pitch = looks up; (0, 0) = calibrated position, screen perpendicular to the base.
38-- La calibration du zéro est en NVS (namespace `servo`, clés `zero_pos_1/2`) et doit être refaite après un firmware tiers. Elle nécessite que l'utilisateur place la tête à la main (couple coupé) — ne jamais appeler `set_home` sans lui.38+- Zero calibration lives in NVS (namespace `servo`, keys `zero_pos_1/2`) and must be redone after a third-party firmware. It requires the user to position the head by hand (torque off) — never call `set_home` without them.
39-- Ne pas forcer la tête à la main quand les moteurs sont alimentés.39+- Do not force the head by hand while the motors are powered.
40-- Bus servo : UART1 1 Mbaud, TX=G6 / RX=G7. I2C corps (G11/G12) : INA226 0x41, NFC 0x50, Si12T 0x68, IO expander PY32L020 0x6F (alimentation servos + LED).40+- Servo bus: UART1 1 Mbaud, TX=G6 / RX=G7. Body I2C (G11/G12): INA226 0x41, NFC 0x50, Si12T 0x68, PY32L020 IO expander 0x6F (servo power + LEDs).
41-- Le drapeau `moving` du servo peut rester vrai à l'arrêt : juger la fin d'un mouvement sur la stabilité de la position (voir `_wait_still` dans `server.py`).41+- The servo `moving` flag can stay true at rest: judge the end of a move on position stability (see `_wait_still` in `server.py`).
42 42
43 ## Validation43 ## Validation
44 44
45-Pas de tests automatisés. Après toute modification : compiler, flasher, puis exercer les commandes touchées via `tools/serial_cmd.py` ou un client MCP (serveur à redémarrer après modification de `mcp/` : `tools/stackchan-server.sh restart`), et demander à l'utilisateur ce qu'il voit (écran, LED, mouvements) — je ne peux pas l'observer.45+No automated tests. After any change: build, flash, then exercise the affected commands via `tools/serial_cmd.py` or an MCP client (restart the server after changing `mcp/`: `tools/stackchan-server.sh restart`), and ask the user what they see (screen, LEDs, movements) — I cannot observe it.
46 46
47-## Versions validées47+## Validated versions
48 48
49-M5StackChan 1.1.1, M5Unified 0.3.0, M5GFX 0.3.0, ArduinoJson 7.x, mcp 2.3, firmware maison 0.1.0. Le firmware d'origine M5Stack (XiaoZhi) a été écrasé ; il se restaure avec M5Burner.49+M5StackChan 1.1.1, M5Unified 0.3.0, M5GFX 0.3.0, ArduinoJson 7.x, mcp 2.3, custom firmware 0.1.0. The original M5Stack firmware (XiaoZhi) has been overwritten; it can be restored with M5Burner.
modified docs/hardware-reference.md +94 -94
@@ -1,98 +1,98 @@
1-# M5Stack StackChan — fiche technique
1+# M5Stack StackChan — hardware reference
22
3-Collecté le 2026-11-27. Sources en bas de page. Les points marqués **⚠** sont ambigus ou contradictoires entre les sources.
3+Collected on 2026-11-27. Sources at the bottom of the page. Items marked **⚠** are ambiguous or contradictory across sources.
44
55 ## 1. Identification
66
77 | | |
88 |---|---|
9-| Produit | M5Stack **StackChan** « Kawaii co-created open-source AI desktop robot » |
10-| SKU | **K151** (robot seul) · **K151-R** (robot + télécommande) |
11-| Contrôleur | **M5Stack CoreS3** (amovible, fixé sur le corps) |
9+| Product | M5Stack **StackChan** "Kawaii co-created open-source AI desktop robot" |
10+| SKU | **K151** (robot only) · **K151-R** (robot + remote control) |
11+| Controller | **M5Stack CoreS3** (removable, mounted on the body) |
1212 | Dimensions | 54.0 × 70.5 × 61.5 mm |
13-| Poids | 187.2 g (robot) · 37.6 g (télécommande) |
13+| Weight | 187.2 g (robot) · 37.6 g (remote) |
1414
15-Il existe deux mondes distincts :
16-- **Produit officiel M5Stack** (K151, 2026) : corps motorisé avec électronique dédiée + CoreS3, firmware usine ESP-IDF.
17-- **Projet communautaire Stack-chan** (Shinya Ishikawa / `stack-chan` org, Apache 2.0) : l'origine du concept, firmware Moddable JS/TS, qui supporte désormais aussi le K151 (« M5StackChan CoreS3 »).
15+There are two distinct worlds:
16+- **Official M5Stack product** (K151, 2026): motorized body with dedicated electronics + CoreS3, ESP-IDF factory firmware.
17+- **Community Stack-chan project** (Shinya Ishikawa / `stack-chan` org, Apache 2.0): where the concept originated, Moddable JS/TS firmware, which now also supports the K151 ("M5StackChan CoreS3").
1818
19-## 2. Contrôleur CoreS3
19+## 2. CoreS3 controller
2020
21-| Élément | Composant |
21+| Item | Component |
2222 |---|---|
2323 | SoC | ESP32-S3, Xtensa LX7 dual-core 240 MHz |
24-| Mémoire | 16 MB Flash, 8 MB PSRAM (Quad) |
25-| Radio | Wi-Fi 2.4 GHz 802.11 b/g/n, Bluetooth 5 LE (ESP-NOW utilisé pour la télécommande) |
26-| Écran | IPS 2.0", 320×240, ILI9342C → **ILI9342E depuis 2026-08-07** (⚠ M5GFX ≥ 0.2.27 requis) |
27-| Tactile écran | Capacitif multi-touch, FT6336U |
28-| Caméra | GC0308, 0.3 MP (640×480) |
29-| Audio entrée | 2 micros, codec ES7210 |
30-| Audio sortie | HP 1 W, ampli I2S AW88298 16 bits |
31-| Capteurs | Proximité/lumière LTR-553ALS-WA · IMU 9 axes BMI270 + BMM150 |
32-| Alim / RTC | PMIC AXP2101 · RTC BM8563 |
33-| Divers | microSD, USB-C (CDC + OTG full-speed), boutons power/reset |
34-
35-Pinmap complet du CoreS3 : https://docs.m5stack.com/en/core/CoreS3#pinmap
36-
37-## 3. Corps du robot (base)
38-
39-| Élément | Composant | Notes |
24+| Memory | 16 MB Flash, 8 MB PSRAM (Quad) |
25+| Radio | Wi-Fi 2.4 GHz 802.11 b/g/n, Bluetooth 5 LE (ESP-NOW used for the remote) |
26+| Display | IPS 2.0", 320×240, ILI9342C → **ILI9342E since 2026-08-07** (⚠ requires M5GFX ≥ 0.2.27) |
27+| Screen touch | Capacitive multi-touch, FT6336U |
28+| Camera | GC0308, 0.3 MP (640×480) |
29+| Audio in | 2 microphones, ES7210 codec |
30+| Audio out | 1 W speaker, AW88298 16-bit I2S amplifier |
31+| Sensors | Proximity/light LTR-553ALS-WA · 9-axis IMU BMI270 + BMM150 |
32+| Power / RTC | AXP2101 PMIC · BM8563 RTC |
33+| Misc | microSD, USB-C (CDC + full-speed OTG), power/reset buttons |
34+
35+Full CoreS3 pin map: https://docs.m5stack.com/en/core/CoreS3#pinmap
36+
37+## 3. Robot body (base)
38+
39+| Item | Component | Notes |
4040 |---|---|---|
41-| Servo pan (X / yaw) | Feetech **SCS0009** (série TTL, avec retour position) | ID **1**, rotation 360° |
42-| Servo tilt (Y / pitch) | Feetech **SCS0009** | ID **2**, course 90°, **rester entre 5° et 85°** (risque de calage / casse) |
43-| LED | 12 × WS2812C | idx 0-5 gauche, 6-11 droite ; pilotées **via l'IO expander** |
44-| Tactile tête | 3 zones, Si12T (compatible TSM12) | clic, swipe avant/arrière |
45-| NFC | ST25R3916 | lecture + émulation |
46-| IR | Récepteur IRM56384 + émetteur | protocole NEC dans les exemples |
47-| Batterie | 550 mAh (⚠ 700 mAh annoncé par un revendeur) | mesure via INA226 (shunt 10 mΩ) |
48-| IO expander | PY32L020 | IO1 = VM_EN (alim servos), IO14 = data LED RGB |
49-| Extension | 3 × Grove, trous compatibles LEGO | |
50-
51-### Brochage (ESP32-S3)
52-
53-| GPIO | Fonction |
41+| Pan servo (X / yaw) | Feetech **SCS0009** (TTL serial, with position feedback) | ID **1**, 360° rotation |
42+| Tilt servo (Y / pitch) | Feetech **SCS0009** | ID **2**, 90° travel, **stay between 5° and 85°** (risk of stalling / breakage) |
43+| LEDs | 12 × WS2812C | idx 0-5 left, 6-11 right; driven **through the IO expander** |
44+| Head touch | 3 zones, Si12T (TSM12 compatible) | click, forward/backward swipe |
45+| NFC | ST25R3916 | read + emulation |
46+| IR | IRM56384 receiver + emitter | NEC protocol in the examples |
47+| Battery | 550 mAh (⚠ 700 mAh stated by one reseller) | measured via INA226 (10 mΩ shunt) |
48+| IO expander | PY32L020 | IO1 = VM_EN (servo power), IO14 = RGB LED data |
49+| Expansion | 3 × Grove, LEGO-compatible holes | |
50+
51+### Pinout (ESP32-S3)
52+
53+| GPIO | Function |
5454 |---|---|
5555 | G6 | Servo bus TX (UART1) |
5656 | G7 | Servo bus RX (UART1) |
57-| G5 | IR émission |
58-| G10 | IR réception |
59-| G11 | I2C SCL (corps) |
60-| G12 | I2C SDA (corps) |
57+| G5 | IR transmit |
58+| G10 | IR receive |
59+| G11 | I2C SCL (body) |
60+| G12 | I2C SDA (body) |
6161 | G2 / G1 | Port A (Grove) |
6262 | G9 / G8 | Port B (Grove) |
6363 | G17 / G18 | Port C (Grove) |
6464
65-### Bus I2C du corps
65+### Body I2C bus
6666
67-| Adresse | Composant |
67+| Address | Component |
6868 |---|---|
69-| 0x41 | INA226 (batterie : tension / courant / puissance) |
69+| 0x41 | INA226 (battery: voltage / current / power) |
7070 | 0x50 | ST25R3916 (NFC) |
71-| 0x68 | Si12T (tactile tête) |
72-| 0x6F (0x71 si ADD_SEL haut) | PY32L020 (IO expander) |
71+| 0x68 | Si12T (head touch) |
72+| 0x6F (0x71 if ADD_SEL high) | PY32L020 (IO expander) |
7373
74-### Servos — détails confirmés dans le code BSP
74+### Servos — details confirmed in the BSP code
7575
76-- Bus série half-duplex Feetech **SCS**, **UART1 à 1 000 000 baud**, TX=6 / RX=7 (`_scs_bus.begin(UART_NUM_1, 1000000, 6, 7)`).
77-- L'alimentation servos doit être activée via l'IO expander (IO VM_EN) avant usage.
78-- Unités logicielles : **1/10 de degré**.
79- - Yaw (ID 1) : limites −1280…+1280, zéro brut par défaut 460, mode PWM/rotation continue possible (`rotate(-1000…1000)`).
80- - Pitch (ID 2) : limites 0…900, zéro brut par défaut 620.
81- - Position brute servo : 0…1000.
82-- Calibration du zéro stockée en NVS : namespace `servo`, clés `zero_pos_1` / `zero_pos_2`. À refaire après flash d'un nouveau firmware.
83-- Sécurité : ne pas forcer les axes à la main quand les moteurs peuvent être alimentés.
76+- Feetech **SCS** half-duplex serial bus, **UART1 at 1,000,000 baud**, TX=6 / RX=7 (`_scs_bus.begin(UART_NUM_1, 1000000, 6, 7)`).
77+- Servo power must be enabled through the IO expander (VM_EN pin) before use.
78+- Software units: **1/10 of a degree**.
79+ - Yaw (ID 1): limits −1280…+1280, default raw zero 460, PWM/continuous rotation mode available (`rotate(-1000…1000)`).
80+ - Pitch (ID 2): limits 0…900, default raw zero 620.
81+ - Raw servo position: 0…1000.
82+- Zero calibration stored in NVS: namespace `servo`, keys `zero_pos_1` / `zero_pos_2`. Must be redone after flashing a new firmware.
83+- Safety: do not force the axes by hand when the motors may be powered.
8484
85-## 4. Firmwares et environnements
85+## 4. Firmwares and environments
8686
87-| Option | Langage / framework | Statut |
87+| Option | Language / framework | Status |
8888 |---|---|---|
89-| **Firmware usine M5Stack** — [m5stack/StackChan](https://github.com/m5stack/StackChan) `firmware/` | C/C++ **ESP-IDF v6.1** | Agent IA XiaoZhi (wake word « Hi, StackChan »), avatar, caméra, danse, App Center, OTA, ESP-NOW. App mobile « StackChan World ». Le dépôt contient aussi `app/`, `remote/`, `server/`. |
90-| **Arduino / PlatformIO** — lib [M5StackChan](https://github.com/m5stack/StackChan-BSP) v1.1.1 (MIT) | C++ | Carte « M5CoreS3 », board pkg ≥ 3.2.2 (≥ 3.3.7 pour tactile), M5Unified ≥ 0.2.11, M5GFX ≥ 0.2.18 (≥ 0.2.27 pour ILI9342E). Dépendances : IRremoteESP8266, M5Unit-NFC. Exemples : Servo, RGB, TouchSensor, NFC, IR, INA226. |
91-| **UiFlow2 / MicroPython** | Python | `from hardware.stackchan import StackChan` ; API servo, RGB, touch, batterie, NFC, caméra + détection de visage. |
92-| **Stack-chan communautaire** — [stack-chan/stack-chan](https://github.com/stack-chan/stack-chan) (Apache 2.0) | JS/TS sur **Moddable SDK** | Architecture host + « MODs » rechargeables sans reflasher le host. Cible de référence : « M5StackChan CoreS3 ». TTS (VOICEVOX, ElevenLabs, OpenAI…), conversation WebRTC, éditeur de visage, simulateur Wasm, Blockly. Installeur web. |
93-| ESPHome / Home Assistant | YAML | Fonctions de base seulement (voix, écran, touch, servos). ⚠ page doc HA en 404 au moment de la collecte. |
89+| **M5Stack factory firmware** — [m5stack/StackChan](https://github.com/m5stack/StackChan) `firmware/` | C/C++ **ESP-IDF v6.1** | XiaoZhi AI agent (wake word "Hi, StackChan"), avatar, camera, dance, App Center, OTA, ESP-NOW. "StackChan World" mobile app. The repo also contains `app/`, `remote/`, `server/`. |
90+| **Arduino / PlatformIO** — [M5StackChan](https://github.com/m5stack/StackChan-BSP) lib v1.1.1 (MIT) | C++ | "M5CoreS3" board, board package ≥ 3.2.2 (≥ 3.3.7 for touch), M5Unified ≥ 0.2.11, M5GFX ≥ 0.2.18 (≥ 0.2.27 for ILI9342E). Dependencies: IRremoteESP8266, M5Unit-NFC. Examples: Servo, RGB, TouchSensor, NFC, IR, INA226. |
91+| **UiFlow2 / MicroPython** | Python | `from hardware.stackchan import StackChan`; API for servos, RGB, touch, battery, NFC, camera + face detection. |
92+| **Community Stack-chan** — [stack-chan/stack-chan](https://github.com/stack-chan/stack-chan) (Apache 2.0) | JS/TS on **Moddable SDK** | Host + "MODs" architecture, MODs reloadable without reflashing the host. Reference target: "M5StackChan CoreS3". TTS (VOICEVOX, ElevenLabs, OpenAI…), WebRTC conversation, face editor, Wasm simulator, Blockly. Web installer. |
93+| ESPHome / Home Assistant | YAML | Basic features only (voice, display, touch, servos). ⚠ HA doc page returned 404 at collection time. |
9494
95-### API Arduino (résumé)
95+### Arduino API (summary)
9696
9797 ```cpp
9898 #include <M5Unified.h>
@@ -100,47 +100,47 @@ Pinmap complet du CoreS3 : https://docs.m5stack.com/en/core/CoreS3#pinmap
100100
101101 void setup() { M5StackChan.begin(); } // M5.begin + touch + IO expander + servos + INA226
102102 void loop() {
103- M5StackChan.update(); // obligatoire à chaque boucle
104- M5StackChan.Motion.move(x, y); // ou moveX(angle, speed), moveY(...), rotateX(vel), goHome()
103+ M5StackChan.update(); // required on every loop
104+ M5StackChan.Motion.move(x, y); // or moveX(angle, speed), moveY(...), rotateX(vel), goHome()
105105 M5StackChan.setRgbColor(i, r, g, b); M5StackChan.refreshRgb();
106106 if (M5StackChan.TouchSensor.wasClicked()) { /* ... */ }
107107 float v = M5StackChan.getBatteryVoltage();
108- M5.Speaker.tone(1000, 100); // audio, écran, IMU... via M5Unified
108+ M5.Speaker.tone(1000, 100); // audio, display, IMU... via M5Unified
109109 }
110110 ```
111111
112-### Flash / restauration
112+### Flashing / restoring
113113
114-- Mode download : maintenir RST ~3 s jusqu'à la LED verte, puis relâcher (⚠ formulation incohérente dans la doc).
115-- Restaurer le firmware usine : **M5Burner**, filtre « Only Official ».
116-- Flasher Stack-chan communautaire ou un firmware maison **écrase** le firmware usine.
114+- Download mode: hold RST ~3 s until the green LED, then release (⚠ wording inconsistent in the docs).
115+- Restore the factory firmware: **M5Burner**, "Only Official" filter.
116+- Flashing community Stack-chan or a custom firmware **overwrites** the factory firmware.
117117
118-## 5. Contenu des kits
118+## 5. Kit contents
119119
120-K151 : robot (CoreS3 pré-monté), câble USB-C, rallonge 1.25-4P 100 mm, clés Allen 1.5 mm (M2) et 2.5 mm (M3), stickers expressions, manuel.
121-K151-R : idem + **télécommande** (StickC-Plus + Hat Mini JoyC, ESP-NOW ; ID cible 0 = broadcast).
120+K151: robot (CoreS3 pre-mounted), USB-C cable, 1.25-4P 100 mm extension cable, 1.5 mm (M2) and 2.5 mm (M3) hex keys, expression stickers, manual.
121+K151-R: same + **remote control** (StickC-Plus + Hat Mini JoyC, ESP-NOW; target ID 0 = broadcast).
122122
123-## 6. Ressources
123+## 6. Resources
124124
125-- Doc produit : https://docs.m5stack.com/en/StackChan
126-- Doc Arduino par périphérique : `https://docs.m5stack.com/en/arduino/stackchan/<servo|rgb|touchsensor|speaker|display|mic|camera|imu|nfc|ir_nec|battery|...>`
127-- MicroPython : https://uiflow-micropython.readthedocs.io/en/latest/controllers/stackchan.html
128-- Schémas : [CoreS3](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/490/Sch_M5_CoreS3_v1.0.pdf) · [Adapter](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Adapter.pdf) · [Power](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Power.pdf) · [Ring](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Ring.pdf) · [Touch](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Touch.pdf)
129-- Datasheet servo : https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCS0009.pdf
130-- Mécanique (STL) : https://github.com/m5stack/M5_Hardware/tree/master/Products/K151_StackChan/Structures
125+- Product docs: https://docs.m5stack.com/en/StackChan
126+- Arduino docs per peripheral: `https://docs.m5stack.com/en/arduino/stackchan/<servo|rgb|touchsensor|speaker|display|mic|camera|imu|nfc|ir_nec|battery|...>`
127+- MicroPython: https://uiflow-micropython.readthedocs.io/en/latest/controllers/stackchan.html
128+- Schematics: [CoreS3](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/490/Sch_M5_CoreS3_v1.0.pdf) · [Adapter](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Adapter.pdf) · [Power](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Power.pdf) · [Ring](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Ring.pdf) · [Touch](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Touch.pdf)
129+- Servo datasheet: https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCS0009.pdf
130+- Mechanical (STL): https://github.com/m5stack/M5_Hardware/tree/master/Products/K151_StackChan/Structures
131131
132-## 7. Validé sur notre unité (2026-11-27)
132+## 7. Validated on our unit (2026-11-27)
133133
134-Avec PlatformIO + pioarduino 55.03.313 (core Arduino 3.3.13), M5StackChan 1.1.1, M5Unified/M5GFX 0.3.0 :
134+With PlatformIO + pioarduino 55.03.313 (Arduino core 3.3.13), M5StackChan 1.1.1, M5Unified/M5GFX 0.3.0:
135135
136-- Écran, LED RGB, tactile tête, haut-parleur, INA226 (≈3.65 V lus) : OK.
137-- Bus servo SCS (UART1 1 Mbaud) : lecture position, calibration du zéro via `setCurrentPostionAsHome()`, mouvements X ±45° et Y jusqu'à 45° : OK.
138-- Port USB : `/dev/cu.usbmodem101` (USB-Serial-JTAG natif, VID:PID 303A:1001), flash sans mode download manuel.
139-- ⚠ L'ouverture du port série depuis macOS **resette la puce** même avec DTR/RTS bas : attendre la ligne `[boot]` avant d'envoyer des commandes (géré par `tools/serial_cmd.py`).
136+- Display, RGB LEDs, head touch, speaker, INA226 (≈3.65 V read): OK.
137+- SCS servo bus (UART1 1 Mbaud): position readback, zero calibration via `setCurrentPostionAsHome()`, X moves ±45° and Y up to 45°: OK.
138+- USB port: `/dev/cu.usbmodem101` (native USB-Serial-JTAG, VID:PID 303A:1001), flashing without manual download mode.
139+- ⚠ Opening the serial port from macOS **resets the chip** even with DTR/RTS low: wait for the boot line before sending commands (handled by `tools/serial_cmd.py`).
140140
141-## 8. Points ouverts
141+## 8. Open questions
142142
143-- Circuit de charge batterie du corps (IC, courant, quel port USB-C) non documenté — voir schéma Power.
144-- Le corps a-t-il un firmware propre en dehors du PY32L020 ? (l'IO expander en est un, MCU PY32).
145-- Broches d'interruption NFC / tactile, fréquence porteuse IR.
146-- Licence exacte du firmware usine (`firmware/LICENSE` non lu).
143+- Body battery charging circuit (IC, current, which USB-C port) undocumented — see the Power schematic.
144+- Does the body run firmware of its own besides the PY32L020? (the IO expander is one, a PY32 MCU).
145+- NFC / touch interrupt pins, IR carrier frequency.
146+- Exact license of the factory firmware (`firmware/LICENSE` not read).
@@ -1,98 +1,98 @@
1-# M5Stack StackChan — fiche technique1+# M5Stack StackChan — hardware reference
2 2
3-Collecté le 2026-11-27. Sources en bas de page. Les points marqués **⚠** sont ambigus ou contradictoires entre les sources.3+Collected on 2026-11-27. Sources at the bottom of the page. Items marked **⚠** are ambiguous or contradictory across sources.
4 4
5 ## 1. Identification5 ## 1. Identification
6 6
7 | | |7 | | |
8 |---|---|8 |---|---|
9-| Produit | M5Stack **StackChan** « Kawaii co-created open-source AI desktop robot » |9+| Product | M5Stack **StackChan** "Kawaii co-created open-source AI desktop robot" |
10-| SKU | **K151** (robot seul) · **K151-R** (robot + télécommande) |10+| SKU | **K151** (robot only) · **K151-R** (robot + remote control) |
11-| Contrôleur | **M5Stack CoreS3** (amovible, fixé sur le corps) |11+| Controller | **M5Stack CoreS3** (removable, mounted on the body) |
12 | Dimensions | 54.0 × 70.5 × 61.5 mm |12 | Dimensions | 54.0 × 70.5 × 61.5 mm |
13-| Poids | 187.2 g (robot) · 37.6 g (télécommande) |13+| Weight | 187.2 g (robot) · 37.6 g (remote) |
14 14
15-Il existe deux mondes distincts :15+There are two distinct worlds:
16-- **Produit officiel M5Stack** (K151, 2026) : corps motorisé avec électronique dédiée + CoreS3, firmware usine ESP-IDF.16+- **Official M5Stack product** (K151, 2026): motorized body with dedicated electronics + CoreS3, ESP-IDF factory firmware.
17-- **Projet communautaire Stack-chan** (Shinya Ishikawa / `stack-chan` org, Apache 2.0) : l'origine du concept, firmware Moddable JS/TS, qui supporte désormais aussi le K151 (« M5StackChan CoreS3 »).17+- **Community Stack-chan project** (Shinya Ishikawa / `stack-chan` org, Apache 2.0): where the concept originated, Moddable JS/TS firmware, which now also supports the K151 ("M5StackChan CoreS3").
18 18
19-## 2. Contrôleur CoreS319+## 2. CoreS3 controller
20 20
21-| Élément | Composant |21+| Item | Component |
22 |---|---|22 |---|---|
23 | SoC | ESP32-S3, Xtensa LX7 dual-core 240 MHz |23 | SoC | ESP32-S3, Xtensa LX7 dual-core 240 MHz |
24-| Mémoire | 16 MB Flash, 8 MB PSRAM (Quad) |24+| Memory | 16 MB Flash, 8 MB PSRAM (Quad) |
25-| Radio | Wi-Fi 2.4 GHz 802.11 b/g/n, Bluetooth 5 LE (ESP-NOW utilisé pour la télécommande) |25+| Radio | Wi-Fi 2.4 GHz 802.11 b/g/n, Bluetooth 5 LE (ESP-NOW used for the remote) |
26-| Écran | IPS 2.0", 320×240, ILI9342C → **ILI9342E depuis 2026-08-07** (⚠ M5GFX ≥ 0.2.27 requis) |26+| Display | IPS 2.0", 320×240, ILI9342C → **ILI9342E since 2026-08-07** (⚠ requires M5GFX ≥ 0.2.27) |
27-| Tactile écran | Capacitif multi-touch, FT6336U |27+| Screen touch | Capacitive multi-touch, FT6336U |
28-| Caméra | GC0308, 0.3 MP (640×480) |28+| Camera | GC0308, 0.3 MP (640×480) |
29-| Audio entrée | 2 micros, codec ES7210 |29+| Audio in | 2 microphones, ES7210 codec |
30-| Audio sortie | HP 1 W, ampli I2S AW88298 16 bits |30+| Audio out | 1 W speaker, AW88298 16-bit I2S amplifier |
31-| Capteurs | Proximité/lumière LTR-553ALS-WA · IMU 9 axes BMI270 + BMM150 |31+| Sensors | Proximity/light LTR-553ALS-WA · 9-axis IMU BMI270 + BMM150 |
32-| Alim / RTC | PMIC AXP2101 · RTC BM8563 |32+| Power / RTC | AXP2101 PMIC · BM8563 RTC |
33-| Divers | microSD, USB-C (CDC + OTG full-speed), boutons power/reset |33+| Misc | microSD, USB-C (CDC + full-speed OTG), power/reset buttons |
34-34+
35-Pinmap complet du CoreS3 : https://docs.m5stack.com/en/core/CoreS3#pinmap35+Full CoreS3 pin map: https://docs.m5stack.com/en/core/CoreS3#pinmap
36-36+
37-## 3. Corps du robot (base)37+## 3. Robot body (base)
38-38+
39-| Élément | Composant | Notes |39+| Item | Component | Notes |
40 |---|---|---|40 |---|---|---|
41-| Servo pan (X / yaw) | Feetech **SCS0009** (série TTL, avec retour position) | ID **1**, rotation 360° |41+| Pan servo (X / yaw) | Feetech **SCS0009** (TTL serial, with position feedback) | ID **1**, 360° rotation |
42-| Servo tilt (Y / pitch) | Feetech **SCS0009** | ID **2**, course 90°, **rester entre 5° et 85°** (risque de calage / casse) |42+| Tilt servo (Y / pitch) | Feetech **SCS0009** | ID **2**, 90° travel, **stay between 5° and 85°** (risk of stalling / breakage) |
43-| LED | 12 × WS2812C | idx 0-5 gauche, 6-11 droite ; pilotées **via l'IO expander** |43+| LEDs | 12 × WS2812C | idx 0-5 left, 6-11 right; driven **through the IO expander** |
44-| Tactile tête | 3 zones, Si12T (compatible TSM12) | clic, swipe avant/arrière |44+| Head touch | 3 zones, Si12T (TSM12 compatible) | click, forward/backward swipe |
45-| NFC | ST25R3916 | lecture + émulation |45+| NFC | ST25R3916 | read + emulation |
46-| IR | Récepteur IRM56384 + émetteur | protocole NEC dans les exemples |46+| IR | IRM56384 receiver + emitter | NEC protocol in the examples |
47-| Batterie | 550 mAh (⚠ 700 mAh annoncé par un revendeur) | mesure via INA226 (shunt 10 mΩ) |47+| Battery | 550 mAh (⚠ 700 mAh stated by one reseller) | measured via INA226 (10 mΩ shunt) |
48-| IO expander | PY32L020 | IO1 = VM_EN (alim servos), IO14 = data LED RGB |48+| IO expander | PY32L020 | IO1 = VM_EN (servo power), IO14 = RGB LED data |
49-| Extension | 3 × Grove, trous compatibles LEGO | |49+| Expansion | 3 × Grove, LEGO-compatible holes | |
50-50+
51-### Brochage (ESP32-S3)51+### Pinout (ESP32-S3)
52-52+
53-| GPIO | Fonction |53+| GPIO | Function |
54 |---|---|54 |---|---|
55 | G6 | Servo bus TX (UART1) |55 | G6 | Servo bus TX (UART1) |
56 | G7 | Servo bus RX (UART1) |56 | G7 | Servo bus RX (UART1) |
57-| G5 | IR émission |57+| G5 | IR transmit |
58-| G10 | IR réception |58+| G10 | IR receive |
59-| G11 | I2C SCL (corps) |59+| G11 | I2C SCL (body) |
60-| G12 | I2C SDA (corps) |60+| G12 | I2C SDA (body) |
61 | G2 / G1 | Port A (Grove) |61 | G2 / G1 | Port A (Grove) |
62 | G9 / G8 | Port B (Grove) |62 | G9 / G8 | Port B (Grove) |
63 | G17 / G18 | Port C (Grove) |63 | G17 / G18 | Port C (Grove) |
64 64
65-### Bus I2C du corps65+### Body I2C bus
66 66
67-| Adresse | Composant |67+| Address | Component |
68 |---|---|68 |---|---|
69-| 0x41 | INA226 (batterie : tension / courant / puissance) |69+| 0x41 | INA226 (battery: voltage / current / power) |
70 | 0x50 | ST25R3916 (NFC) |70 | 0x50 | ST25R3916 (NFC) |
71-| 0x68 | Si12T (tactile tête) |71+| 0x68 | Si12T (head touch) |
72-| 0x6F (0x71 si ADD_SEL haut) | PY32L020 (IO expander) |72+| 0x6F (0x71 if ADD_SEL high) | PY32L020 (IO expander) |
73 73
74-### Servos — détails confirmés dans le code BSP74+### Servos — details confirmed in the BSP code
75 75
76-- Bus série half-duplex Feetech **SCS**, **UART1 à 1 000 000 baud**, TX=6 / RX=7 (`_scs_bus.begin(UART_NUM_1, 1000000, 6, 7)`).76+- Feetech **SCS** half-duplex serial bus, **UART1 at 1,000,000 baud**, TX=6 / RX=7 (`_scs_bus.begin(UART_NUM_1, 1000000, 6, 7)`).
77-- L'alimentation servos doit être activée via l'IO expander (IO VM_EN) avant usage.77+- Servo power must be enabled through the IO expander (VM_EN pin) before use.
78-- Unités logicielles : **1/10 de degré**.78+- Software units: **1/10 of a degree**.
79- - Yaw (ID 1) : limites −1280…+1280, zéro brut par défaut 460, mode PWM/rotation continue possible (`rotate(-1000…1000)`).79+ - Yaw (ID 1): limits −1280…+1280, default raw zero 460, PWM/continuous rotation mode available (`rotate(-1000…1000)`).
80- - Pitch (ID 2) : limites 0…900, zéro brut par défaut 620.80+ - Pitch (ID 2): limits 0…900, default raw zero 620.
81- - Position brute servo : 0…1000.81+ - Raw servo position: 0…1000.
82-- Calibration du zéro stockée en NVS : namespace `servo`, clés `zero_pos_1` / `zero_pos_2`. À refaire après flash d'un nouveau firmware.82+- Zero calibration stored in NVS: namespace `servo`, keys `zero_pos_1` / `zero_pos_2`. Must be redone after flashing a new firmware.
83-- Sécurité : ne pas forcer les axes à la main quand les moteurs peuvent être alimentés.83+- Safety: do not force the axes by hand when the motors may be powered.
84 84
85-## 4. Firmwares et environnements85+## 4. Firmwares and environments
86 86
87-| Option | Langage / framework | Statut |87+| Option | Language / framework | Status |
88 |---|---|---|88 |---|---|---|
89-| **Firmware usine M5Stack** — [m5stack/StackChan](https://github.com/m5stack/StackChan) `firmware/` | C/C++ **ESP-IDF v6.1** | Agent IA XiaoZhi (wake word « Hi, StackChan »), avatar, caméra, danse, App Center, OTA, ESP-NOW. App mobile « StackChan World ». Le dépôt contient aussi `app/`, `remote/`, `server/`. |89+| **M5Stack factory firmware** — [m5stack/StackChan](https://github.com/m5stack/StackChan) `firmware/` | C/C++ **ESP-IDF v6.1** | XiaoZhi AI agent (wake word "Hi, StackChan"), avatar, camera, dance, App Center, OTA, ESP-NOW. "StackChan World" mobile app. The repo also contains `app/`, `remote/`, `server/`. |
90-| **Arduino / PlatformIO** — lib [M5StackChan](https://github.com/m5stack/StackChan-BSP) v1.1.1 (MIT) | C++ | Carte « M5CoreS3 », board pkg ≥ 3.2.2 (≥ 3.3.7 pour tactile), M5Unified ≥ 0.2.11, M5GFX ≥ 0.2.18 (≥ 0.2.27 pour ILI9342E). Dépendances : IRremoteESP8266, M5Unit-NFC. Exemples : Servo, RGB, TouchSensor, NFC, IR, INA226. |90+| **Arduino / PlatformIO** — [M5StackChan](https://github.com/m5stack/StackChan-BSP) lib v1.1.1 (MIT) | C++ | "M5CoreS3" board, board package ≥ 3.2.2 (≥ 3.3.7 for touch), M5Unified ≥ 0.2.11, M5GFX ≥ 0.2.18 (≥ 0.2.27 for ILI9342E). Dependencies: IRremoteESP8266, M5Unit-NFC. Examples: Servo, RGB, TouchSensor, NFC, IR, INA226. |
91-| **UiFlow2 / MicroPython** | Python | `from hardware.stackchan import StackChan` ; API servo, RGB, touch, batterie, NFC, caméra + détection de visage. |91+| **UiFlow2 / MicroPython** | Python | `from hardware.stackchan import StackChan`; API for servos, RGB, touch, battery, NFC, camera + face detection. |
92-| **Stack-chan communautaire** — [stack-chan/stack-chan](https://github.com/stack-chan/stack-chan) (Apache 2.0) | JS/TS sur **Moddable SDK** | Architecture host + « MODs » rechargeables sans reflasher le host. Cible de référence : « M5StackChan CoreS3 ». TTS (VOICEVOX, ElevenLabs, OpenAI…), conversation WebRTC, éditeur de visage, simulateur Wasm, Blockly. Installeur web. |92+| **Community Stack-chan** — [stack-chan/stack-chan](https://github.com/stack-chan/stack-chan) (Apache 2.0) | JS/TS on **Moddable SDK** | Host + "MODs" architecture, MODs reloadable without reflashing the host. Reference target: "M5StackChan CoreS3". TTS (VOICEVOX, ElevenLabs, OpenAI…), WebRTC conversation, face editor, Wasm simulator, Blockly. Web installer. |
93-| ESPHome / Home Assistant | YAML | Fonctions de base seulement (voix, écran, touch, servos). ⚠ page doc HA en 404 au moment de la collecte. |93+| ESPHome / Home Assistant | YAML | Basic features only (voice, display, touch, servos). ⚠ HA doc page returned 404 at collection time. |
94 94
95-### API Arduino (résumé)95+### Arduino API (summary)
96 96
97 ```cpp97 ```cpp
98 #include <M5Unified.h>98 #include <M5Unified.h>
@@ -100,47 +100,47 @@ Pinmap complet du CoreS3 : https://docs.m5stack.com/en/core/CoreS3#pinmap
100 100
101 void setup() { M5StackChan.begin(); } // M5.begin + touch + IO expander + servos + INA226101 void setup() { M5StackChan.begin(); } // M5.begin + touch + IO expander + servos + INA226
102 void loop() {102 void loop() {
103- M5StackChan.update(); // obligatoire à chaque boucle103+ M5StackChan.update(); // required on every loop
104- M5StackChan.Motion.move(x, y); // ou moveX(angle, speed), moveY(...), rotateX(vel), goHome()104+ M5StackChan.Motion.move(x, y); // or moveX(angle, speed), moveY(...), rotateX(vel), goHome()
105 M5StackChan.setRgbColor(i, r, g, b); M5StackChan.refreshRgb();105 M5StackChan.setRgbColor(i, r, g, b); M5StackChan.refreshRgb();
106 if (M5StackChan.TouchSensor.wasClicked()) { /* ... */ }106 if (M5StackChan.TouchSensor.wasClicked()) { /* ... */ }
107 float v = M5StackChan.getBatteryVoltage();107 float v = M5StackChan.getBatteryVoltage();
108- M5.Speaker.tone(1000, 100); // audio, écran, IMU... via M5Unified108+ M5.Speaker.tone(1000, 100); // audio, display, IMU... via M5Unified
109 }109 }
110 ```110 ```
111 111
112-### Flash / restauration112+### Flashing / restoring
113 113
114-- Mode download : maintenir RST ~3 s jusqu'à la LED verte, puis relâcher (⚠ formulation incohérente dans la doc).114+- Download mode: hold RST ~3 s until the green LED, then release (⚠ wording inconsistent in the docs).
115-- Restaurer le firmware usine : **M5Burner**, filtre « Only Official ».115+- Restore the factory firmware: **M5Burner**, "Only Official" filter.
116-- Flasher Stack-chan communautaire ou un firmware maison **écrase** le firmware usine.116+- Flashing community Stack-chan or a custom firmware **overwrites** the factory firmware.
117 117
118-## 5. Contenu des kits118+## 5. Kit contents
119 119
120-K151 : robot (CoreS3 pré-monté), câble USB-C, rallonge 1.25-4P 100 mm, clés Allen 1.5 mm (M2) et 2.5 mm (M3), stickers expressions, manuel.120+K151: robot (CoreS3 pre-mounted), USB-C cable, 1.25-4P 100 mm extension cable, 1.5 mm (M2) and 2.5 mm (M3) hex keys, expression stickers, manual.
121-K151-R : idem + **télécommande** (StickC-Plus + Hat Mini JoyC, ESP-NOW ; ID cible 0 = broadcast).121+K151-R: same + **remote control** (StickC-Plus + Hat Mini JoyC, ESP-NOW; target ID 0 = broadcast).
122 122
123-## 6. Ressources123+## 6. Resources
124 124
125-- Doc produit : https://docs.m5stack.com/en/StackChan125+- Product docs: https://docs.m5stack.com/en/StackChan
126-- Doc Arduino par périphérique : `https://docs.m5stack.com/en/arduino/stackchan/<servo|rgb|touchsensor|speaker|display|mic|camera|imu|nfc|ir_nec|battery|...>`126+- Arduino docs per peripheral: `https://docs.m5stack.com/en/arduino/stackchan/<servo|rgb|touchsensor|speaker|display|mic|camera|imu|nfc|ir_nec|battery|...>`
127-- MicroPython : https://uiflow-micropython.readthedocs.io/en/latest/controllers/stackchan.html127+- MicroPython: https://uiflow-micropython.readthedocs.io/en/latest/controllers/stackchan.html
128-- Schémas : [CoreS3](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/490/Sch_M5_CoreS3_v1.0.pdf) · [Adapter](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Adapter.pdf) · [Power](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Power.pdf) · [Ring](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Ring.pdf) · [Touch](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Touch.pdf)128+- Schematics: [CoreS3](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/490/Sch_M5_CoreS3_v1.0.pdf) · [Adapter](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Adapter.pdf) · [Power](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Power.pdf) · [Ring](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Ring.pdf) · [Touch](https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCH_Touch.pdf)
129-- Datasheet servo : https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCS0009.pdf129+- Servo datasheet: https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/1205/SCS0009.pdf
130-- Mécanique (STL) : https://github.com/m5stack/M5_Hardware/tree/master/Products/K151_StackChan/Structures130+- Mechanical (STL): https://github.com/m5stack/M5_Hardware/tree/master/Products/K151_StackChan/Structures
131 131
132-## 7. Validé sur notre unité (2026-11-27)132+## 7. Validated on our unit (2026-11-27)
133 133
134-Avec PlatformIO + pioarduino 55.03.313 (core Arduino 3.3.13), M5StackChan 1.1.1, M5Unified/M5GFX 0.3.0 :134+With PlatformIO + pioarduino 55.03.313 (Arduino core 3.3.13), M5StackChan 1.1.1, M5Unified/M5GFX 0.3.0:
135 135
136-- Écran, LED RGB, tactile tête, haut-parleur, INA226 (≈3.65 V lus) : OK.136+- Display, RGB LEDs, head touch, speaker, INA226 (≈3.65 V read): OK.
137-- Bus servo SCS (UART1 1 Mbaud) : lecture position, calibration du zéro via `setCurrentPostionAsHome()`, mouvements X ±45° et Y jusqu'à 45° : OK.137+- SCS servo bus (UART1 1 Mbaud): position readback, zero calibration via `setCurrentPostionAsHome()`, X moves ±45° and Y up to 45°: OK.
138-- Port USB : `/dev/cu.usbmodem101` (USB-Serial-JTAG natif, VID:PID 303A:1001), flash sans mode download manuel.138+- USB port: `/dev/cu.usbmodem101` (native USB-Serial-JTAG, VID:PID 303A:1001), flashing without manual download mode.
139-- ⚠ L'ouverture du port série depuis macOS **resette la puce** même avec DTR/RTS bas : attendre la ligne `[boot]` avant d'envoyer des commandes (géré par `tools/serial_cmd.py`).139+- ⚠ Opening the serial port from macOS **resets the chip** even with DTR/RTS low: wait for the boot line before sending commands (handled by `tools/serial_cmd.py`).
140 140
141-## 8. Points ouverts141+## 8. Open questions
142 142
143-- Circuit de charge batterie du corps (IC, courant, quel port USB-C) non documenté — voir schéma Power.143+- Body battery charging circuit (IC, current, which USB-C port) undocumented — see the Power schematic.
144-- Le corps a-t-il un firmware propre en dehors du PY32L020 ? (l'IO expander en est un, MCU PY32).144+- Does the body run firmware of its own besides the PY32L020? (the IO expander is one, a PY32 MCU).
145-- Broches d'interruption NFC / tactile, fréquence porteuse IR.145+- NFC / touch interrupt pins, IR carrier frequency.
146-- Licence exacte du firmware usine (`firmware/LICENSE` non lu).146+- Exact license of the factory firmware (`firmware/LICENSE` not read).
modified docs/protocol.md +22 -22
@@ -1,24 +1,24 @@
1-# Protocole de pilotage StackChan (v1)
1+# StackChan control protocol (v1)
22
3-Transport : USB série (USB-Serial-JTAG natif, 115200), **une ligne JSON par message**, terminée par `\n`.
3+Transport: USB serial (native USB-Serial-JTAG, 115200), **one JSON object per line**, terminated by `\n`.
44
5-## Requêtes (Mac → robot)
5+## Requests (host → robot)
66
77 ```json
88 {"id": 12, "cmd": "move", "yaw": 20, "pitch": 30, "speed": 400}
99 ```
1010
11-- `id` (entier, optionnel) : renvoyé tel quel dans la réponse.
12-- `cmd` : nom de la commande, paramètres au même niveau.
11+- `id` (integer, optional): echoed back unchanged in the response.
12+- `cmd`: command name; parameters sit at the same level.
1313
14-## Réponses (robot → Mac)
14+## Responses (robot → host)
1515
1616 ```json
17-{"id": 12, "ok": true, ...données}
17+{"id": 12, "ok": true, ...data}
1818 {"id": 12, "ok": false, "error": "message"}
1919 ```
2020
21-## Événements spontanés (robot → Mac)
21+## Unsolicited events (robot → host)
2222
2323 ```json
2424 {"event": "boot", "fw": "0.1.0"}
@@ -26,25 +26,25 @@ Transport : USB série (USB-Serial-JTAG natif, 115200), **une ligne JSON par mes
2626 {"event": "gesture_done", "name": "nod"}
2727 ```
2828
29-## Unités et bornes
29+## Units and bounds
3030
31-- Angles en **degrés** (flottants acceptés). Yaw (X, rotation) : **−90…+90**, **positif = vers la gauche du robot** (vérifié sur l'unité le 2026-11-27). Pitch (Y, inclinaison) : **5…85**. Les valeurs hors bornes sont ramenées dans l'intervalle et la réponse contient `"clamped": true`.
32-- Vitesse : 0…1000 (défaut 300).
33-- Le zéro (yaw 0, pitch 0) est la position calibrée : écran face à l'avant, perpendiculaire à la base.
31+- Angles in **degrees** (floats accepted). Yaw (X, rotation): **−90…+90**, **positive = towards the robot's left** (verified on the unit on 2026-11-27). Pitch (Y, tilt): **5…85**. Out-of-range values are clamped and the response contains `"clamped": true`.
32+- Speed: 0…1000 (default 300).
33+- Zero (yaw 0, pitch 0) is the calibrated position: screen facing forward, perpendicular to the base.
3434
35-## Commandes
35+## Commands
3636
37-| cmd | Paramètres | Réponse |
37+| cmd | Parameters | Response |
3838 |---|---|---|
3939 | `ping` | — | `fw`, `uptime_ms` |
4040 | `status` | — | `yaw`, `pitch`, `moving`, `torque`, `battery_v`, `battery_a`, `face`, `gesture` |
41-| `move` | `yaw`, `pitch`, `speed?` | `yaw`, `pitch` (cibles après bornage), `clamped` |
42-| `rest` | `speed?` | position de repos (0, 5) |
43-| `stop` | — | arrête mouvement et geste en cours |
41+| `move` | `yaw`, `pitch`, `speed?` | `yaw`, `pitch` (targets after clamping), `clamped` |
42+| `rest` | `speed?` | rest position (0, 5) |
43+| `stop` | — | stops the current move and gesture |
4444 | `torque` | `on` (bool) | — |
45-| `set_home` | — | la position actuelle devient le zéro (NVS) |
46-| `gesture` | `name` : `nod`, `shake`, `look_around`, `wiggle`, `look_up` | non bloquant, puis événement `gesture_done` |
47-| `leds` | `color` `[r,g,b]` **ou** `colors` (12 × `[r,g,b]`), `brightness?` 0…1 | — |
48-| `face` | `expression` : `neutral`, `happy`, `sad`, `surprised`, `sleepy`, `angry`, `thinking` | — |
49-| `say` | `text` (≤ 120 car.), `duration_ms?` (0 = permanent) | affiche une bulle de texte sous le visage |
45+| `set_home` | — | the current position becomes zero (NVS) |
46+| `gesture` | `name`: `nod`, `shake`, `look_around`, `wiggle`, `look_up` | non-blocking, then a `gesture_done` event |
47+| `leds` | `color` `[r,g,b]` **or** `colors` (12 × `[r,g,b]`), `brightness?` 0…1 | — |
48+| `face` | `expression`: `neutral`, `happy`, `sad`, `surprised`, `sleepy`, `angry`, `thinking` | — |
49+| `say` | `text` (≤ 120 chars), `duration_ms?` (0 = permanent) | shows a speech bubble under the face |
5050 | `tone` | `freq` (Hz, 50…10000), `ms` (≤ 2000) | — |
@@ -1,24 +1,24 @@
1-# Protocole de pilotage StackChan (v1)1+# StackChan control protocol (v1)
2 2
3-Transport : USB série (USB-Serial-JTAG natif, 115200), **une ligne JSON par message**, terminée par `\n`.3+Transport: USB serial (native USB-Serial-JTAG, 115200), **one JSON object per line**, terminated by `\n`.
4 4
5-## Requêtes (Mac → robot)5+## Requests (host → robot)
6 6
7 ```json7 ```json
8 {"id": 12, "cmd": "move", "yaw": 20, "pitch": 30, "speed": 400}8 {"id": 12, "cmd": "move", "yaw": 20, "pitch": 30, "speed": 400}
9 ```9 ```
10 10
11-- `id` (entier, optionnel) : renvoyé tel quel dans la réponse.11+- `id` (integer, optional): echoed back unchanged in the response.
12-- `cmd` : nom de la commande, paramètres au même niveau.12+- `cmd`: command name; parameters sit at the same level.
13 13
14-## Réponses (robot → Mac)14+## Responses (robot → host)
15 15
16 ```json16 ```json
17-{"id": 12, "ok": true, ...données}17+{"id": 12, "ok": true, ...data}
18 {"id": 12, "ok": false, "error": "message"}18 {"id": 12, "ok": false, "error": "message"}
19 ```19 ```
20 20
21-## Événements spontanés (robot → Mac)21+## Unsolicited events (robot → host)
22 22
23 ```json23 ```json
24 {"event": "boot", "fw": "0.1.0"}24 {"event": "boot", "fw": "0.1.0"}
@@ -26,25 +26,25 @@ Transport : USB série (USB-Serial-JTAG natif, 115200), **une ligne JSON par mes
26 {"event": "gesture_done", "name": "nod"}26 {"event": "gesture_done", "name": "nod"}
27 ```27 ```
28 28
29-## Unités et bornes29+## Units and bounds
30 30
31-- Angles en **degrés** (flottants acceptés). Yaw (X, rotation) : **−90…+90**, **positif = vers la gauche du robot** (vérifié sur l'unité le 2026-11-27). Pitch (Y, inclinaison) : **5…85**. Les valeurs hors bornes sont ramenées dans l'intervalle et la réponse contient `"clamped": true`.31+- Angles in **degrees** (floats accepted). Yaw (X, rotation): **−90…+90**, **positive = towards the robot's left** (verified on the unit on 2026-11-27). Pitch (Y, tilt): **5…85**. Out-of-range values are clamped and the response contains `"clamped": true`.
32-- Vitesse : 0…1000 (défaut 300).32+- Speed: 0…1000 (default 300).
33-- Le zéro (yaw 0, pitch 0) est la position calibrée : écran face à l'avant, perpendiculaire à la base.33+- Zero (yaw 0, pitch 0) is the calibrated position: screen facing forward, perpendicular to the base.
34 34
35-## Commandes35+## Commands
36 36
37-| cmd | Paramètres | Réponse |37+| cmd | Parameters | Response |
38 |---|---|---|38 |---|---|---|
39 | `ping` | — | `fw`, `uptime_ms` |39 | `ping` | — | `fw`, `uptime_ms` |
40 | `status` | — | `yaw`, `pitch`, `moving`, `torque`, `battery_v`, `battery_a`, `face`, `gesture` |40 | `status` | — | `yaw`, `pitch`, `moving`, `torque`, `battery_v`, `battery_a`, `face`, `gesture` |
41-| `move` | `yaw`, `pitch`, `speed?` | `yaw`, `pitch` (cibles après bornage), `clamped` |41+| `move` | `yaw`, `pitch`, `speed?` | `yaw`, `pitch` (targets after clamping), `clamped` |
42-| `rest` | `speed?` | position de repos (0, 5) |42+| `rest` | `speed?` | rest position (0, 5) |
43-| `stop` | — | arrête mouvement et geste en cours |43+| `stop` | — | stops the current move and gesture |
44 | `torque` | `on` (bool) | — |44 | `torque` | `on` (bool) | — |
45-| `set_home` | — | la position actuelle devient le zéro (NVS) |45+| `set_home` | — | the current position becomes zero (NVS) |
46-| `gesture` | `name` : `nod`, `shake`, `look_around`, `wiggle`, `look_up` | non bloquant, puis événement `gesture_done` |46+| `gesture` | `name`: `nod`, `shake`, `look_around`, `wiggle`, `look_up` | non-blocking, then a `gesture_done` event |
47-| `leds` | `color` `[r,g,b]` **ou** `colors` (12 × `[r,g,b]`), `brightness?` 0…1 | — |47+| `leds` | `color` `[r,g,b]` **or** `colors` (12 × `[r,g,b]`), `brightness?` 0…1 | — |
48-| `face` | `expression` : `neutral`, `happy`, `sad`, `surprised`, `sleepy`, `angry`, `thinking` | — |48+| `face` | `expression`: `neutral`, `happy`, `sad`, `surprised`, `sleepy`, `angry`, `thinking` | — |
49-| `say` | `text` (≤ 120 car.), `duration_ms?` (0 = permanent) | affiche une bulle de texte sous le visage |49+| `say` | `text` (≤ 120 chars), `duration_ms?` (0 = permanent) | shows a speech bubble under the face |
50 | `tone` | `freq` (Hz, 50…10000), `ms` (≤ 2000) | — |50 | `tone` | `freq` (Hz, 50…10000), `ms` (≤ 2000) | — |
modified firmware/platformio.ini +2 -2
@@ -1,5 +1,5 @@
1-; StackChan (M5Stack K151) — CoreS3 + corps motorisé
2-; Plateforme pioarduino : core Arduino 3.3.13 (ESP-IDF 5.5.6), requis par la lib M5StackChan (>= 3.2.2)
1+; StackChan (M5Stack K151) — CoreS3 + motorized body
2+; pioarduino platform: Arduino core 3.3.13 (ESP-IDF 5.5.6), required by the M5StackChan lib (>= 3.2.2)
33
44 [env:stackchan]
55 platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.313/platform-espressif32.zip
@@ -1,5 +1,5 @@
1-; StackChan (M5Stack K151) — CoreS3 + corps motorisé1+; StackChan (M5Stack K151) — CoreS3 + motorized body
2-; Plateforme pioarduino : core Arduino 3.3.13 (ESP-IDF 5.5.6), requis par la lib M5StackChan (>= 3.2.2)2+; pioarduino platform: Arduino core 3.3.13 (ESP-IDF 5.5.6), required by the M5StackChan lib (>= 3.2.2)
3 3
4 [env:stackchan]4 [env:stackchan]
5 platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.313/platform-espressif32.zip5 platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.313/platform-espressif32.zip
modified firmware/src/face.cpp +3 -3
@@ -68,7 +68,7 @@ void Face::update()
6868
6969 if (_text.length() && _text_until && now > _text_until) clearSay();
7070
71- // Clignement : uniquement pour les yeux « ronds ».
71+ // Blinking: only for "round" eyes.
7272 const bool can_blink = _expr != Expression::Happy && _expr != Expression::Sleepy;
7373 if (can_blink && _blink_end == 0 && now > _next_blink) {
7474 _blink_end = now + 130;
@@ -117,7 +117,7 @@ void Face::drawEyes(bool closed)
117117 break;
118118 }
119119 }
120- // Sourcils
120+ // Eyebrows
121121 if (_expr == Expression::Angry) {
122122 int x0 = left ? ex - 18 : ex + 18, x1 = left ? ex + 12 : ex - 12;
123123 _canvas.drawWideLine(x0, kEyeY - 30, x1, kEyeY - 18, 3.0f, kFg);
@@ -163,7 +163,7 @@ void Face::drawBubble()
163163 const int bx = margin, bw = _canvas.width() - 2 * margin;
164164 const int max_w = bw - 2 * pad;
165165
166- // Retour à la ligne simple, mot par mot.
166+ // Simple word-by-word line wrapping.
167167 String lines[max_lines];
168168 int n = 0;
169169 String cur, word;
@@ -68,7 +68,7 @@ void Face::update()
68 68
69 if (_text.length() && _text_until && now > _text_until) clearSay();69 if (_text.length() && _text_until && now > _text_until) clearSay();
70 70
71- // Clignement : uniquement pour les yeux « ronds ».71+ // Blinking: only for "round" eyes.
72 const bool can_blink = _expr != Expression::Happy && _expr != Expression::Sleepy;72 const bool can_blink = _expr != Expression::Happy && _expr != Expression::Sleepy;
73 if (can_blink && _blink_end == 0 && now > _next_blink) {73 if (can_blink && _blink_end == 0 && now > _next_blink) {
74 _blink_end = now + 130;74 _blink_end = now + 130;
@@ -117,7 +117,7 @@ void Face::drawEyes(bool closed)
117 break;117 break;
118 }118 }
119 }119 }
120- // Sourcils120+ // Eyebrows
121 if (_expr == Expression::Angry) {121 if (_expr == Expression::Angry) {
122 int x0 = left ? ex - 18 : ex + 18, x1 = left ? ex + 12 : ex - 12;122 int x0 = left ? ex - 18 : ex + 18, x1 = left ? ex + 12 : ex - 12;
123 _canvas.drawWideLine(x0, kEyeY - 30, x1, kEyeY - 18, 3.0f, kFg);123 _canvas.drawWideLine(x0, kEyeY - 30, x1, kEyeY - 18, 3.0f, kFg);
@@ -163,7 +163,7 @@ void Face::drawBubble()
163 const int bx = margin, bw = _canvas.width() - 2 * margin;163 const int bx = margin, bw = _canvas.width() - 2 * margin;
164 const int max_w = bw - 2 * pad;164 const int max_w = bw - 2 * pad;
165 165
166- // Retour à la ligne simple, mot par mot.166+ // Simple word-by-word line wrapping.
167 String lines[max_lines];167 String lines[max_lines];
168 int n = 0;168 int n = 0;
169 String cur, word;169 String cur, word;
modified firmware/src/face.h +2 -2
@@ -1,13 +1,13 @@
11 #pragma once
22 #include <M5Unified.h>
33
4-// Visage simple dessiné dans un sprite plein écran (PSRAM), redessiné seulement si nécessaire.
4+// Simple face drawn in a full-screen sprite (PSRAM), redrawn only when needed.
55 class Face {
66 public:
77 enum class Expression { Neutral, Happy, Sad, Surprised, Sleepy, Angry, Thinking };
88
99 void begin(M5GFX& display);
10- void update(); // à appeler dans loop() : clignement, expiration de la bulle
10+ void update(); // call from loop(): blinking, speech bubble expiry
1111
1212 bool setExpression(const char* name);
1313 const char* expressionName() const;
@@ -1,13 +1,13 @@
1 #pragma once1 #pragma once
2 #include <M5Unified.h>2 #include <M5Unified.h>
3 3
4-// Visage simple dessiné dans un sprite plein écran (PSRAM), redessiné seulement si nécessaire.4+// Simple face drawn in a full-screen sprite (PSRAM), redrawn only when needed.
5 class Face {5 class Face {
6 public:6 public:
7 enum class Expression { Neutral, Happy, Sad, Surprised, Sleepy, Angry, Thinking };7 enum class Expression { Neutral, Happy, Sad, Surprised, Sleepy, Angry, Thinking };
8 8
9 void begin(M5GFX& display);9 void begin(M5GFX& display);
10- void update(); // à appeler dans loop() : clignement, expiration de la bulle10+ void update(); // call from loop(): blinking, speech bubble expiry
11 11
12 bool setExpression(const char* name);12 bool setExpression(const char* name);
13 const char* expressionName() const;13 const char* expressionName() const;
modified firmware/src/main.cpp +18 -18
@@ -1,4 +1,4 @@
1-// Firmware de pilotage StackChan : protocole JSON-lines sur USB série (voir docs/protocol.md).
1+// StackChan control firmware: JSON-lines protocol over USB serial (see docs/protocol.md).
22 #include <M5Unified.h>
33 #include <M5StackChan.h>
44 #include <ArduinoJson.h>
@@ -9,7 +9,7 @@
99
1010 namespace {
1111
12-// Bornes en 1/10 de degré (unité du BSP). Pitch : 5°..85° recommandé par M5Stack.
12+// Limits in 1/10 degree (BSP unit). Pitch: 5°..85° as recommended by M5Stack.
1313 constexpr int kYawMin = -900, kYawMax = 900;
1414 constexpr int kPitchMin = 50, kPitchMax = 850;
1515 constexpr int kRestPitch = 50;
@@ -21,7 +21,7 @@ String rx_line;
2121
2222 auto& motion() { return M5StackChan.Motion; }
2323
24-// ---------------------------------------------------------------- sortie JSON
24+// ---------------------------------------------------------------- JSON output
2525
2626 void send(JsonDocument& doc)
2727 {
@@ -37,7 +37,7 @@ void sendEvent(const char* name, const char* key = nullptr, const char* value =
3737 send(doc);
3838 }
3939
40-// ---------------------------------------------------------------- mouvement
40+// ---------------------------------------------------------------- motion
4141
4242 int toTenths(float deg) { return (int)lroundf(deg * 10.0f); }
4343
@@ -55,10 +55,10 @@ bool clampedMove(int yaw, int pitch, int speed, int* out_yaw = nullptr, int* out
5555 return cy != yaw || cp != pitch;
5656 }
5757
58-// ---------------------------------------------------------------- gestes (non bloquants)
58+// ---------------------------------------------------------------- gestures (non-blocking)
5959
6060 struct Step {
61- int16_t dyaw, dpitch; // relatifs à la position de départ, 1/10°
61+ int16_t dyaw, dpitch; // relative to the start position, 1/10°
6262 int16_t speed;
6363 uint16_t hold_ms;
6464 };
@@ -89,7 +89,7 @@ int g_base_yaw = 0, g_base_pitch = kRestPitch;
8989 void startStep()
9090 {
9191 const Step& s = g_current->steps[g_index];
92- // Près d'une butée, on inverse le sens du geste pour qu'il reste visible.
92+ // Near a limit, reverse the gesture direction so it stays visible.
9393 int yaw = g_base_yaw + s.dyaw;
9494 if (yaw > kYawMax || yaw < kYawMin) yaw = g_base_yaw - s.dyaw;
9595 int pitch = g_base_pitch + s.dpitch;
@@ -137,7 +137,7 @@ bool readRgb(JsonVariantConst v, float k, uint8_t rgb[3])
137137 return true;
138138 }
139139
140-// ---------------------------------------------------------------- commandes
140+// ---------------------------------------------------------------- commands
141141
142142 void handle(JsonDocument& req)
143143 {
@@ -162,7 +162,7 @@ void handle(JsonDocument& req)
162162
163163 } else if (!strcmp(cmd, "move")) {
164164 if (req["yaw"].isNull() || req["pitch"].isNull()) {
165- err = "yaw et pitch requis";
165+ err = "yaw and pitch required";
166166 } else {
167167 stopGesture();
168168 int y, p;
@@ -183,7 +183,7 @@ void handle(JsonDocument& req)
183183
184184 } else if (!strcmp(cmd, "torque")) {
185185 if (req["on"].isNull()) {
186- err = "on requis";
186+ err = "on required";
187187 } else {
188188 stopGesture();
189189 torque_on = req["on"].as<bool>();
@@ -195,7 +195,7 @@ void handle(JsonDocument& req)
195195 motion().setCurrentPostionAsHome();
196196
197197 } else if (!strcmp(cmd, "gesture")) {
198- if (!startGesture(req["name"] | "")) err = "geste inconnu";
198+ if (!startGesture(req["name"] | "")) err = "unknown gesture";
199199
200200 } else if (!strcmp(cmd, "leds")) {
201201 float k = constrain(req["brightness"] | 1.0f, 0.0f, 1.0f);
@@ -203,22 +203,22 @@ void handle(JsonDocument& req)
203203 if (req["colors"].is<JsonArrayConst>()) {
204204 JsonArrayConst arr = req["colors"];
205205 if (arr.size() != 12) {
206- err = "colors doit contenir 12 couleurs";
206+ err = "colors must have 12 entries";
207207 } else {
208208 for (int i = 0; i < 12 && !err; i++) {
209- if (!readRgb(arr[i], k, rgb)) err = "couleur invalide";
209+ if (!readRgb(arr[i], k, rgb)) err = "invalid color";
210210 else M5StackChan.setRgbColor(i, rgb[0], rgb[1], rgb[2]);
211211 }
212212 }
213213 } else if (readRgb(req["color"], k, rgb)) {
214214 for (int i = 0; i < 12; i++) M5StackChan.setRgbColor(i, rgb[0], rgb[1], rgb[2]);
215215 } else {
216- err = "color [r,g,b] ou colors requis";
216+ err = "color [r,g,b] or colors required";
217217 }
218218 if (!err) M5StackChan.refreshRgb();
219219
220220 } else if (!strcmp(cmd, "face")) {
221- if (!face.setExpression(req["expression"] | "")) err = "expression inconnue";
221+ if (!face.setExpression(req["expression"] | "")) err = "unknown expression";
222222
223223 } else if (!strcmp(cmd, "say")) {
224224 String text = req["text"] | "";
@@ -232,7 +232,7 @@ void handle(JsonDocument& req)
232232 M5.Speaker.tone(freq, ms);
233233
234234 } else {
235- err = "commande inconnue";
235+ err = "unknown command";
236236 }
237237
238238 res["ok"] = err == nullptr;
@@ -252,7 +252,7 @@ void pollSerial()
252252 if (e) {
253253 JsonDocument res;
254254 res["ok"] = false;
255- res["error"] = String("JSON invalide: ") + e.c_str();
255+ res["error"] = String("invalid JSON: ") + e.c_str();
256256 send(res);
257257 } else {
258258 handle(req);
@@ -275,7 +275,7 @@ void pollTouch()
275275
276276 void setup()
277277 {
278- Serial.setRxBufferSize(4096); // le rendu du visage peut bloquer la boucle quelques dizaines de ms
278+ Serial.setRxBufferSize(4096); // face rendering can block the loop for a few tens of ms
279279 Serial.begin(115200);
280280 M5StackChan.begin();
281281 M5.Speaker.setVolume(128);
@@ -1,4 +1,4 @@
1-// Firmware de pilotage StackChan : protocole JSON-lines sur USB série (voir docs/protocol.md).1+// StackChan control firmware: JSON-lines protocol over USB serial (see docs/protocol.md).
2 #include <M5Unified.h>2 #include <M5Unified.h>
3 #include <M5StackChan.h>3 #include <M5StackChan.h>
4 #include <ArduinoJson.h>4 #include <ArduinoJson.h>
@@ -9,7 +9,7 @@
9 9
10 namespace {10 namespace {
11 11
12-// Bornes en 1/10 de degré (unité du BSP). Pitch : 5°..85° recommandé par M5Stack.12+// Limits in 1/10 degree (BSP unit). Pitch: 5°..85° as recommended by M5Stack.
13 constexpr int kYawMin = -900, kYawMax = 900;13 constexpr int kYawMin = -900, kYawMax = 900;
14 constexpr int kPitchMin = 50, kPitchMax = 850;14 constexpr int kPitchMin = 50, kPitchMax = 850;
15 constexpr int kRestPitch = 50;15 constexpr int kRestPitch = 50;
@@ -21,7 +21,7 @@ String rx_line;
21 21
22 auto& motion() { return M5StackChan.Motion; }22 auto& motion() { return M5StackChan.Motion; }
23 23
24-// ---------------------------------------------------------------- sortie JSON24+// ---------------------------------------------------------------- JSON output
25 25
26 void send(JsonDocument& doc)26 void send(JsonDocument& doc)
27 {27 {
@@ -37,7 +37,7 @@ void sendEvent(const char* name, const char* key = nullptr, const char* value =
37 send(doc);37 send(doc);
38 }38 }
39 39
40-// ---------------------------------------------------------------- mouvement40+// ---------------------------------------------------------------- motion
41 41
42 int toTenths(float deg) { return (int)lroundf(deg * 10.0f); }42 int toTenths(float deg) { return (int)lroundf(deg * 10.0f); }
43 43
@@ -55,10 +55,10 @@ bool clampedMove(int yaw, int pitch, int speed, int* out_yaw = nullptr, int* out
55 return cy != yaw || cp != pitch;55 return cy != yaw || cp != pitch;
56 }56 }
57 57
58-// ---------------------------------------------------------------- gestes (non bloquants)58+// ---------------------------------------------------------------- gestures (non-blocking)
59 59
60 struct Step {60 struct Step {
61- int16_t dyaw, dpitch; // relatifs à la position de départ, 1/10°61+ int16_t dyaw, dpitch; // relative to the start position, 1/10°
62 int16_t speed;62 int16_t speed;
63 uint16_t hold_ms;63 uint16_t hold_ms;
64 };64 };
@@ -89,7 +89,7 @@ int g_base_yaw = 0, g_base_pitch = kRestPitch;
89 void startStep()89 void startStep()
90 {90 {
91 const Step& s = g_current->steps[g_index];91 const Step& s = g_current->steps[g_index];
92- // Près d'une butée, on inverse le sens du geste pour qu'il reste visible.92+ // Near a limit, reverse the gesture direction so it stays visible.
93 int yaw = g_base_yaw + s.dyaw;93 int yaw = g_base_yaw + s.dyaw;
94 if (yaw > kYawMax || yaw < kYawMin) yaw = g_base_yaw - s.dyaw;94 if (yaw > kYawMax || yaw < kYawMin) yaw = g_base_yaw - s.dyaw;
95 int pitch = g_base_pitch + s.dpitch;95 int pitch = g_base_pitch + s.dpitch;
@@ -137,7 +137,7 @@ bool readRgb(JsonVariantConst v, float k, uint8_t rgb[3])
137 return true;137 return true;
138 }138 }
139 139
140-// ---------------------------------------------------------------- commandes140+// ---------------------------------------------------------------- commands
141 141
142 void handle(JsonDocument& req)142 void handle(JsonDocument& req)
143 {143 {
@@ -162,7 +162,7 @@ void handle(JsonDocument& req)
162 162
163 } else if (!strcmp(cmd, "move")) {163 } else if (!strcmp(cmd, "move")) {
164 if (req["yaw"].isNull() || req["pitch"].isNull()) {164 if (req["yaw"].isNull() || req["pitch"].isNull()) {
165- err = "yaw et pitch requis";165+ err = "yaw and pitch required";
166 } else {166 } else {
167 stopGesture();167 stopGesture();
168 int y, p;168 int y, p;
@@ -183,7 +183,7 @@ void handle(JsonDocument& req)
183 183
184 } else if (!strcmp(cmd, "torque")) {184 } else if (!strcmp(cmd, "torque")) {
185 if (req["on"].isNull()) {185 if (req["on"].isNull()) {
186- err = "on requis";186+ err = "on required";
187 } else {187 } else {
188 stopGesture();188 stopGesture();
189 torque_on = req["on"].as<bool>();189 torque_on = req["on"].as<bool>();
@@ -195,7 +195,7 @@ void handle(JsonDocument& req)
195 motion().setCurrentPostionAsHome();195 motion().setCurrentPostionAsHome();
196 196
197 } else if (!strcmp(cmd, "gesture")) {197 } else if (!strcmp(cmd, "gesture")) {
198- if (!startGesture(req["name"] | "")) err = "geste inconnu";198+ if (!startGesture(req["name"] | "")) err = "unknown gesture";
199 199
200 } else if (!strcmp(cmd, "leds")) {200 } else if (!strcmp(cmd, "leds")) {
201 float k = constrain(req["brightness"] | 1.0f, 0.0f, 1.0f);201 float k = constrain(req["brightness"] | 1.0f, 0.0f, 1.0f);
@@ -203,22 +203,22 @@ void handle(JsonDocument& req)
203 if (req["colors"].is<JsonArrayConst>()) {203 if (req["colors"].is<JsonArrayConst>()) {
204 JsonArrayConst arr = req["colors"];204 JsonArrayConst arr = req["colors"];
205 if (arr.size() != 12) {205 if (arr.size() != 12) {
206- err = "colors doit contenir 12 couleurs";206+ err = "colors must have 12 entries";
207 } else {207 } else {
208 for (int i = 0; i < 12 && !err; i++) {208 for (int i = 0; i < 12 && !err; i++) {
209- if (!readRgb(arr[i], k, rgb)) err = "couleur invalide";209+ if (!readRgb(arr[i], k, rgb)) err = "invalid color";
210 else M5StackChan.setRgbColor(i, rgb[0], rgb[1], rgb[2]);210 else M5StackChan.setRgbColor(i, rgb[0], rgb[1], rgb[2]);
211 }211 }
212 }212 }
213 } else if (readRgb(req["color"], k, rgb)) {213 } else if (readRgb(req["color"], k, rgb)) {
214 for (int i = 0; i < 12; i++) M5StackChan.setRgbColor(i, rgb[0], rgb[1], rgb[2]);214 for (int i = 0; i < 12; i++) M5StackChan.setRgbColor(i, rgb[0], rgb[1], rgb[2]);
215 } else {215 } else {
216- err = "color [r,g,b] ou colors requis";216+ err = "color [r,g,b] or colors required";
217 }217 }
218 if (!err) M5StackChan.refreshRgb();218 if (!err) M5StackChan.refreshRgb();
219 219
220 } else if (!strcmp(cmd, "face")) {220 } else if (!strcmp(cmd, "face")) {
221- if (!face.setExpression(req["expression"] | "")) err = "expression inconnue";221+ if (!face.setExpression(req["expression"] | "")) err = "unknown expression";
222 222
223 } else if (!strcmp(cmd, "say")) {223 } else if (!strcmp(cmd, "say")) {
224 String text = req["text"] | "";224 String text = req["text"] | "";
@@ -232,7 +232,7 @@ void handle(JsonDocument& req)
232 M5.Speaker.tone(freq, ms);232 M5.Speaker.tone(freq, ms);
233 233
234 } else {234 } else {
235- err = "commande inconnue";235+ err = "unknown command";
236 }236 }
237 237
238 res["ok"] = err == nullptr;238 res["ok"] = err == nullptr;
@@ -252,7 +252,7 @@ void pollSerial()
252 if (e) {252 if (e) {
253 JsonDocument res;253 JsonDocument res;
254 res["ok"] = false;254 res["ok"] = false;
255- res["error"] = String("JSON invalide: ") + e.c_str();255+ res["error"] = String("invalid JSON: ") + e.c_str();
256 send(res);256 send(res);
257 } else {257 } else {
258 handle(req);258 handle(req);
@@ -275,7 +275,7 @@ void pollTouch()
275 275
276 void setup()276 void setup()
277 {277 {
278- Serial.setRxBufferSize(4096); // le rendu du visage peut bloquer la boucle quelques dizaines de ms278+ Serial.setRxBufferSize(4096); // face rendering can block the loop for a few tens of ms
279 Serial.begin(115200);279 Serial.begin(115200);
280 M5StackChan.begin();280 M5StackChan.begin();
281 M5.Speaker.setVolume(128);281 M5.Speaker.setVolume(128);
modified mcp/README.md +38 -38
@@ -1,62 +1,62 @@
11 # stackchan-mcp
22
3-Serveur MCP **partagé** qui pilote le StackChan via USB série, en parlant le protocole décrit dans [../docs/protocol.md](../docs/protocol.md). Un seul process tient le port USB ; toutes les sessions Claude s'y connectent en HTTP local.
3+**Shared** MCP server that drives the StackChan over USB serial, speaking the protocol described in [../docs/protocol.md](../docs/protocol.md). A single process owns the USB port; every Claude session connects to it over local HTTP.
44
55 ```
6-session Claude 1 ─┐
7-session Claude 2 ─┼─ HTTP 127.0.0.1:8765/mcp ──> stackchan-mcp ──USB série──> robot
8-session Claude N ─┘
6+Claude session 1 ─┐
7+Claude session 2 ─┼─ HTTP 127.0.0.1:8765/mcp ──> stackchan-mcp ──USB serial──> robot
8+Claude session N ─┘
99 ```
1010
11-## Lancement (manuel)
11+## Running (manual start)
1212
1313 ```bash
14-tools/stackchan-server.sh start # démarre en arrière-plan (fait aussi uv sync)
14+tools/stackchan-server.sh start # starts in the background (also runs uv sync)
1515 tools/stackchan-server.sh status
1616 tools/stackchan-server.sh logs -f # ~/Library/Logs/stackchan-mcp.log
1717 tools/stackchan-server.sh stop
1818 ```
1919
20-Enregistrement dans Claude Code, une fois, pour **toutes** les sessions (portée utilisateur) :
20+Register it once in Claude Code, for **all** sessions (user scope):
2121
2222 ```bash
2323 claude mcp add --transport http --scope user stackchan http://127.0.0.1:8765/mcp
2424 ```
2525
26-Options : `--port` (ou `STACKCHAN_MCP_PORT`, défaut 8765), `--host` (boucle locale uniquement, toute autre adresse est refusée), `--stdio` (ancien mode, un seul client). Variables : `STACKCHAN_PORT` (port série, sinon détection par VID Espressif `303A`), `STACKCHAN_LEASE_S` (durée de la prise de main, défaut 10), `STACKCHAN_FIRMWARE_DIR`.
26+Options: `--port` (or `STACKCHAN_MCP_PORT`, default 8765), `--host` (loopback only, any other address is refused), `--stdio` (legacy mode, single client). Environment variables: `STACKCHAN_PORT` (serial port, otherwise detected by the Espressif VID `303A`), `STACKCHAN_LEASE_S` (control lease duration, default 10), `STACKCHAN_FIRMWARE_DIR`.
2727
28-Le port USB est ouvert au premier appel d'outil, pas au démarrage. Robot débranché : les outils renvoient une erreur explicite, et le serveur se reconnecte au branchement suivant.
28+The USB port is opened on the first tool call, not at startup. With the robot unplugged, tools return an explicit error, and the server reconnects as soon as it is plugged back in (including after an unplug mid-connection).
2929
30-## Partage entre sessions
30+## Sharing between sessions
3131
32-- **Prise de main** : la session qui envoie une commande au robot (tête, visage, bulle, LED, son, calibration, flash) le garde tant qu'elle envoie au moins une commande toutes les 10 s. Les autres sessions sont **refusées immédiatement** (« robot utilisé par une autre session : réessayer dans N s »).
33-- **Libres pour tous** : `get_status` (indique `controlled_by`), `stop` (arrêt d'urgence), `get_touch_events`, `wait_for_touch`.
34-- **Toucher** : chaque session reçoit tous les événements ; `get_touch_events` renvoie ce qui est arrivé depuis le dernier appel de *cette* session (5 min max, et rien d'antérieur à son premier appel).
32+- **Control lease**: the session that sends a command to the robot (head, face, bubble, LEDs, sound, calibration, flash) keeps control as long as it sends at least one command every 10 s. Other sessions are **refused immediately** (`robot in use by another session: retry in N s`).
33+- **Free for everyone**: `get_status` (reports `controlled_by`), `stop` (emergency stop), `get_touch_events`, `wait_for_touch`.
34+- **Touch**: every session receives every event; `get_touch_events` returns what happened since *this* session's previous call (5 min max, and nothing older than its first call).
3535
36-## Outils
36+## Tools
3737
38-| Outil | Prise de main | Rôle |
38+| Tool | Needs lease | Purpose |
3939 |---|---|---|
40-| `get_status` | non | position (°), mouvement, couple, batterie, expression, geste, session qui a la main |
41-| `stop` | non | arrêt immédiat du mouvement et du geste |
42-| `get_touch_events`, `wait_for_touch` | non | tactile sur la tête |
43-| `move_head(yaw, pitch, speed, wait)` | oui | yaw −90…90, pitch 5…85, bornage automatique |
44-| `rest` | oui | position de repos |
45-| `gesture(name)` | oui | `nod`, `shake`, `look_around`, `wiggle`, `look_up` |
46-| `set_face(expression)` | oui | `neutral`, `happy`, `sad`, `surprised`, `sleepy`, `angry`, `thinking` |
47-| `say(text, duration_ms)` | oui | bulle de texte à l'écran (pas de voix) |
48-| `set_leds(color \| colors, brightness)` | oui | 12 LED RGB |
49-| `play_tone(freq, ms)` | oui | bip |
50-| `set_torque`, `set_home` | oui | calibration |
51-| `flash_firmware` | oui | compile et flashe `firmware/` (libère le port, `pio run -t upload`, se reconnecte) |
52-
53-## À savoir
54-
55-- Pour flasher : outil `flash_firmware`, ou `tools/stackchan-server.sh stop` avant un `pio run -t upload` manuel.
56-- Sur macOS, ouvrir le port **redémarre le robot** : visage, LED et bulle reviennent à l'état initial à chaque (re)connexion.
57-- Si le robot ne répond plus du tout (même à `esptool`) alors que le port reste visible, débrancher/rebrancher l'USB.
58-
59-## Études futures
60-
61-- Jeton d'authentification sur l'API HTTP (aujourd'hui protégée seulement par l'écoute sur 127.0.0.1).
62-- Transport Wi-Fi entre le serveur et le robot.
40+| `get_status` | no | position (°), moving, torque, battery, expression, gesture, session in control |
41+| `stop` | no | immediately stops the current move and gesture |
42+| `get_touch_events`, `wait_for_touch` | no | head touch sensor |
43+| `move_head(yaw, pitch, speed, wait)` | yes | yaw −90…90, pitch 5…85, automatic clamping |
44+| `rest` | yes | rest position |
45+| `gesture(name)` | yes | `nod`, `shake`, `look_around`, `wiggle`, `look_up` |
46+| `set_face(expression)` | yes | `neutral`, `happy`, `sad`, `surprised`, `sleepy`, `angry`, `thinking` |
47+| `say(text, duration_ms)` | yes | on-screen speech bubble (no voice) |
48+| `set_leds(color \| colors, brightness)` | yes | 12 RGB LEDs |
49+| `play_tone(freq, ms)` | yes | beep |
50+| `set_torque`, `set_home` | yes | calibration |
51+| `flash_firmware` | yes | builds and flashes `firmware/` (releases the port, runs `pio run -t upload`, reconnects) |
52+
53+## Good to know
54+
55+- To flash: use the `flash_firmware` tool, or `tools/stackchan-server.sh stop` before a manual `pio run -t upload`.
56+- On macOS, opening the port **reboots the robot**: face, LEDs and bubble go back to their initial state on every (re)connection.
57+- If the robot stops answering entirely (even to `esptool`) while the port is still listed, unplug and replug the USB cable.
58+
59+## Future work
60+
61+- Authentication token on the HTTP API (currently protected only by listening on 127.0.0.1).
62+- Wi-Fi transport between the server and the robot.
@@ -1,62 +1,62 @@
1 # stackchan-mcp1 # stackchan-mcp
2 2
3-Serveur MCP **partagé** qui pilote le StackChan via USB série, en parlant le protocole décrit dans [../docs/protocol.md](../docs/protocol.md). Un seul process tient le port USB ; toutes les sessions Claude s'y connectent en HTTP local.3+**Shared** MCP server that drives the StackChan over USB serial, speaking the protocol described in [../docs/protocol.md](../docs/protocol.md). A single process owns the USB port; every Claude session connects to it over local HTTP.
4 4
5 ```5 ```
6-session Claude 1 ─┐6+Claude session 1 ─┐
7-session Claude 2 ─┼─ HTTP 127.0.0.1:8765/mcp ──> stackchan-mcp ──USB série──> robot7+Claude session 2 ─┼─ HTTP 127.0.0.1:8765/mcp ──> stackchan-mcp ──USB serial──> robot
8-session Claude N ─┘8+Claude session N ─┘
9 ```9 ```
10 10
11-## Lancement (manuel)11+## Running (manual start)
12 12
13 ```bash13 ```bash
14-tools/stackchan-server.sh start # démarre en arrière-plan (fait aussi uv sync)14+tools/stackchan-server.sh start # starts in the background (also runs uv sync)
15 tools/stackchan-server.sh status15 tools/stackchan-server.sh status
16 tools/stackchan-server.sh logs -f # ~/Library/Logs/stackchan-mcp.log16 tools/stackchan-server.sh logs -f # ~/Library/Logs/stackchan-mcp.log
17 tools/stackchan-server.sh stop17 tools/stackchan-server.sh stop
18 ```18 ```
19 19
20-Enregistrement dans Claude Code, une fois, pour **toutes** les sessions (portée utilisateur) :20+Register it once in Claude Code, for **all** sessions (user scope):
21 21
22 ```bash22 ```bash
23 claude mcp add --transport http --scope user stackchan http://127.0.0.1:8765/mcp23 claude mcp add --transport http --scope user stackchan http://127.0.0.1:8765/mcp
24 ```24 ```
25 25
26-Options : `--port` (ou `STACKCHAN_MCP_PORT`, défaut 8765), `--host` (boucle locale uniquement, toute autre adresse est refusée), `--stdio` (ancien mode, un seul client). Variables : `STACKCHAN_PORT` (port série, sinon détection par VID Espressif `303A`), `STACKCHAN_LEASE_S` (durée de la prise de main, défaut 10), `STACKCHAN_FIRMWARE_DIR`.26+Options: `--port` (or `STACKCHAN_MCP_PORT`, default 8765), `--host` (loopback only, any other address is refused), `--stdio` (legacy mode, single client). Environment variables: `STACKCHAN_PORT` (serial port, otherwise detected by the Espressif VID `303A`), `STACKCHAN_LEASE_S` (control lease duration, default 10), `STACKCHAN_FIRMWARE_DIR`.
27 27
28-Le port USB est ouvert au premier appel d'outil, pas au démarrage. Robot débranché : les outils renvoient une erreur explicite, et le serveur se reconnecte au branchement suivant.28+The USB port is opened on the first tool call, not at startup. With the robot unplugged, tools return an explicit error, and the server reconnects as soon as it is plugged back in (including after an unplug mid-connection).
29 29
30-## Partage entre sessions30+## Sharing between sessions
31 31
32-- **Prise de main** : la session qui envoie une commande au robot (tête, visage, bulle, LED, son, calibration, flash) le garde tant qu'elle envoie au moins une commande toutes les 10 s. Les autres sessions sont **refusées immédiatement** (« robot utilisé par une autre session : réessayer dans N s »).32+- **Control lease**: the session that sends a command to the robot (head, face, bubble, LEDs, sound, calibration, flash) keeps control as long as it sends at least one command every 10 s. Other sessions are **refused immediately** (`robot in use by another session: retry in N s`).
33-- **Libres pour tous** : `get_status` (indique `controlled_by`), `stop` (arrêt d'urgence), `get_touch_events`, `wait_for_touch`.33+- **Free for everyone**: `get_status` (reports `controlled_by`), `stop` (emergency stop), `get_touch_events`, `wait_for_touch`.
34-- **Toucher** : chaque session reçoit tous les événements ; `get_touch_events` renvoie ce qui est arrivé depuis le dernier appel de *cette* session (5 min max, et rien d'antérieur à son premier appel).34+- **Touch**: every session receives every event; `get_touch_events` returns what happened since *this* session's previous call (5 min max, and nothing older than its first call).
35 35
36-## Outils36+## Tools
37 37
38-| Outil | Prise de main | Rôle |38+| Tool | Needs lease | Purpose |
39 |---|---|---|39 |---|---|---|
40-| `get_status` | non | position (°), mouvement, couple, batterie, expression, geste, session qui a la main |40+| `get_status` | no | position (°), moving, torque, battery, expression, gesture, session in control |
41-| `stop` | non | arrêt immédiat du mouvement et du geste |41+| `stop` | no | immediately stops the current move and gesture |
42-| `get_touch_events`, `wait_for_touch` | non | tactile sur la tête |42+| `get_touch_events`, `wait_for_touch` | no | head touch sensor |
43-| `move_head(yaw, pitch, speed, wait)` | oui | yaw −90…90, pitch 5…85, bornage automatique |43+| `move_head(yaw, pitch, speed, wait)` | yes | yaw −90…90, pitch 5…85, automatic clamping |
44-| `rest` | oui | position de repos |44+| `rest` | yes | rest position |
45-| `gesture(name)` | oui | `nod`, `shake`, `look_around`, `wiggle`, `look_up` |45+| `gesture(name)` | yes | `nod`, `shake`, `look_around`, `wiggle`, `look_up` |
46-| `set_face(expression)` | oui | `neutral`, `happy`, `sad`, `surprised`, `sleepy`, `angry`, `thinking` |46+| `set_face(expression)` | yes | `neutral`, `happy`, `sad`, `surprised`, `sleepy`, `angry`, `thinking` |
47-| `say(text, duration_ms)` | oui | bulle de texte à l'écran (pas de voix) |47+| `say(text, duration_ms)` | yes | on-screen speech bubble (no voice) |
48-| `set_leds(color \| colors, brightness)` | oui | 12 LED RGB |48+| `set_leds(color \| colors, brightness)` | yes | 12 RGB LEDs |
49-| `play_tone(freq, ms)` | oui | bip |49+| `play_tone(freq, ms)` | yes | beep |
50-| `set_torque`, `set_home` | oui | calibration |50+| `set_torque`, `set_home` | yes | calibration |
51-| `flash_firmware` | oui | compile et flashe `firmware/` (libère le port, `pio run -t upload`, se reconnecte) |51+| `flash_firmware` | yes | builds and flashes `firmware/` (releases the port, runs `pio run -t upload`, reconnects) |
52-52+
53-## À savoir53+## Good to know
54-54+
55-- Pour flasher : outil `flash_firmware`, ou `tools/stackchan-server.sh stop` avant un `pio run -t upload` manuel.55+- To flash: use the `flash_firmware` tool, or `tools/stackchan-server.sh stop` before a manual `pio run -t upload`.
56-- Sur macOS, ouvrir le port **redémarre le robot** : visage, LED et bulle reviennent à l'état initial à chaque (re)connexion.56+- On macOS, opening the port **reboots the robot**: face, LEDs and bubble go back to their initial state on every (re)connection.
57-- Si le robot ne répond plus du tout (même à `esptool`) alors que le port reste visible, débrancher/rebrancher l'USB.57+- If the robot stops answering entirely (even to `esptool`) while the port is still listed, unplug and replug the USB cable.
58-58+
59-## Études futures59+## Future work
60-60+
61-- Jeton d'authentification sur l'API HTTP (aujourd'hui protégée seulement par l'écoute sur 127.0.0.1).61+- Authentication token on the HTTP API (currently protected only by listening on 127.0.0.1).
62-- Transport Wi-Fi entre le serveur et le robot.62+- Wi-Fi transport between the server and the robot.
modified mcp/pyproject.toml +1 -1
@@ -1,7 +1,7 @@
11 [project]
22 name = "stackchan-mcp"
33 version = "0.1.0"
4-description = "Serveur MCP pour piloter le robot M5Stack StackChan via USB série"
4+description = "MCP server to drive the M5Stack StackChan robot over USB serial"
55 requires-python = ">=3.11"
66 dependencies = [
77 "mcp>=2.3,<3",
@@ -1,7 +1,7 @@
1 [project]1 [project]
2 name = "stackchan-mcp"2 name = "stackchan-mcp"
3 version = "0.1.0"3 version = "0.1.0"
4-description = "Serveur MCP pour piloter le robot M5Stack StackChan via USB série"4+description = "MCP server to drive the M5Stack StackChan robot over USB serial"
5 requires-python = ">=3.11"5 requires-python = ">=3.11"
6 dependencies = [6 dependencies = [
7 "mcp>=2.3,<3",7 "mcp>=2.3,<3",
modified mcp/src/stackchan_mcp/robot.py +25 -25
@@ -1,4 +1,4 @@
1-"""Lien série vers le firmware StackChan (protocole JSON-lines, voir docs/protocol.md)."""
1+"""Serial link to the StackChan firmware (JSON-lines protocol, see docs/protocol.md)."""
22
33 from __future__ import annotations
44
@@ -15,15 +15,15 @@ from mcp.server.mcpserver.exceptions import ToolError
1515 from serial.tools import list_ports
1616
1717 ESPRESSIF_VID = 0x303A
18-EVENT_RETENTION_S = 300 # événements conservés 5 min pour les sessions qui les lisent tard
18+EVENT_RETENTION_S = 300 # events kept for 5 min for sessions that read them late
1919
2020
2121 class RobotError(ToolError):
22- """Erreur attendue (robot absent, commande refusée…) : son message est transmis tel quel au client MCP."""
22+ """Expected error (robot missing, command refused…): its message is passed as-is to the MCP client."""
2323
2424
2525 def log(msg: str) -> None:
26- # stdout est réservé au protocole MCP : tout le reste va sur stderr.
26+ # stdout is reserved for the MCP protocol: everything else goes to stderr.
2727 print(f"[stackchan] {msg}", file=sys.stderr, flush=True)
2828
2929
@@ -34,14 +34,14 @@ def find_port() -> str:
3434 for p in list_ports.comports():
3535 if p.vid == ESPRESSIF_VID:
3636 return p.device
37- raise RobotError("StackChan introuvable : aucun port USB Espressif (VID 303A). Le robot est-il branché ?")
37+ raise RobotError("StackChan not found: no Espressif USB port (VID 303A). Is the robot plugged in?")
3838
3939
4040 class Robot:
4141 def __init__(self) -> None:
4242 self._ser: serial.Serial | None = None
4343 self._reader: threading.Thread | None = None
44- self._lock = threading.Lock() # protège l'ouverture/fermeture et l'écriture
44+ self._lock = threading.Lock() # guards open/close and writes
4545 self._ids = itertools.count(1)
4646 self._pending: dict[int, tuple[threading.Event, list]] = {}
4747 self._events: collections.deque[dict] = collections.deque(maxlen=200)
@@ -49,10 +49,10 @@ class Robot:
4949 self._boot = threading.Event()
5050 self.firmware: str | None = None
5151 self.port: str | None = None
52- # Raison de l'indisponibilité volontaire du port (ex. flash en cours), sinon None.
52+ # Reason the port is deliberately unavailable (e.g. flash in progress), otherwise None.
5353 self.maintenance: str | None = None
5454
55- # ------------------------------------------------------------ connexion
55+ # ------------------------------------------------------------ connection
5656
5757 @property
5858 def connected(self) -> bool:
@@ -63,7 +63,7 @@ class Robot:
6363 if self.connected:
6464 return
6565 if self.maintenance:
66- raise RobotError(f"robot indisponible : {self.maintenance}")
66+ raise RobotError(f"robot unavailable: {self.maintenance}")
6767 port = find_port()
6868 self.port = port
6969 s = serial.Serial()
@@ -74,18 +74,18 @@ class Robot:
7474 s.open()
7575 except serial.SerialException as e:
7676 raise RobotError(
77- f"Impossible d'ouvrir {port} ({e}). Un autre programme (pio upload, moniteur série) l'utilise peut-être."
77+ f"Cannot open {port} ({e}). Another program (pio upload, serial monitor) may be using it."
7878 ) from e
7979 self._ser = s
8080 self._boot.clear()
8181 self._reader = threading.Thread(target=self._read_loop, name="stackchan-reader", daemon=True)
8282 self._reader.start()
83- log(f"port {port} ouvert")
83+ log(f"port {port} opened")
8484
85- # Sur macOS l'ouverture du port resette souvent l'ESP32-S3 : on attend l'événement boot,
86- # sinon on vérifie par un ping que le firmware répond déjà.
85+ # On macOS opening the port often resets the ESP32-S3: wait for the boot event,
86+ # otherwise check with a ping that the firmware is already responding.
8787 if not self._boot.wait(6.0):
88- log("pas d'événement boot reçu, vérification par ping")
88+ log("no boot event received, checking with ping")
8989 info = self.request("ping", timeout=3.0)
9090 self.firmware = info.get("fw")
9191
@@ -97,7 +97,7 @@ class Robot:
9797 except Exception:
9898 pass
9999 self._ser = None
100- self._fail_pending("port série fermé")
100+ self._fail_pending("serial port closed")
101101
102102 def _fail_pending(self, reason: str) -> None:
103103 for ev, box in list(self._pending.values()):
@@ -105,7 +105,7 @@ class Robot:
105105 ev.set()
106106 self._pending.clear()
107107
108- # ------------------------------------------------------------ lecture
108+ # ------------------------------------------------------------ reading
109109
110110 def _read_loop(self) -> None:
111111 ser = self._ser
@@ -114,7 +114,7 @@ class Robot:
114114 try:
115115 chunk = ser.read(256)
116116 except (serial.SerialException, OSError, TypeError) as e:
117- log(f"lecture interrompue : {e}")
117+ log(f"read interrupted: {e}")
118118 break
119119 if not chunk:
120120 continue
@@ -124,15 +124,15 @@ class Robot:
124124 self._dispatch(line.decode(errors="replace").strip())
125125 if self._ser is ser:
126126 self._ser = None
127- self._fail_pending("connexion perdue avec le robot")
127+ self._fail_pending("connection to the robot lost")
128128
129129 def _dispatch(self, line: str) -> None:
130130 if not line.startswith("{"):
131- return # traces ROM/boot de l'ESP32
131+ return # ESP32 ROM/boot output
132132 try:
133133 msg = json.loads(line)
134134 except json.JSONDecodeError:
135- log(f"ligne ignorée : {line[:120]}")
135+ log(f"ignored line: {line[:120]}")
136136 return
137137
138138 if "event" in msg:
@@ -154,7 +154,7 @@ class Robot:
154154 box.append(msg)
155155 ev.set()
156156
157- # ------------------------------------------------------------ requêtes
157+ # ------------------------------------------------------------ requests
158158
159159 def request(self, cmd: str, timeout: float = 3.0, **params) -> dict:
160160 if not self.connected:
@@ -166,20 +166,20 @@ class Robot:
166166 with self._lock:
167167 if self._ser is None:
168168 self._pending.pop(rid, None)
169- raise RobotError("robot déconnecté")
169+ raise RobotError("robot disconnected")
170170 self._ser.write(payload.encode("utf-8"))
171171 self._ser.flush()
172172 if not ev.wait(timeout):
173173 self._pending.pop(rid, None)
174- raise RobotError(f"pas de réponse du robot à '{cmd}' en {timeout:.0f} s")
174+ raise RobotError(f"no response from the robot to '{cmd}' within {timeout:.0f} s")
175175 res = box[0]
176176 if not res.get("ok"):
177- raise RobotError(res.get("error", "erreur inconnue"))
177+ raise RobotError(res.get("error", "unknown error"))
178178 res.pop("ok", None)
179179 res.pop("id", None)
180180 return res
181181
182- # ------------------------------------------------------------ événements
182+ # ------------------------------------------------------------ events
183183
184184 def events_since(self, t0: float, kind: str | None = None) -> list[dict]:
185185 horizon = max(t0, time.time() - EVENT_RETENTION_S)
@@ -1,4 +1,4 @@
1-"""Lien série vers le firmware StackChan (protocole JSON-lines, voir docs/protocol.md)."""1+"""Serial link to the StackChan firmware (JSON-lines protocol, see docs/protocol.md)."""
2 2
3 from __future__ import annotations3 from __future__ import annotations
4 4
@@ -15,15 +15,15 @@ from mcp.server.mcpserver.exceptions import ToolError
15 from serial.tools import list_ports15 from serial.tools import list_ports
16 16
17 ESPRESSIF_VID = 0x303A17 ESPRESSIF_VID = 0x303A
18-EVENT_RETENTION_S = 300 # événements conservés 5 min pour les sessions qui les lisent tard18+EVENT_RETENTION_S = 300 # events kept for 5 min for sessions that read them late
19 19
20 20
21 class RobotError(ToolError):21 class RobotError(ToolError):
22- """Erreur attendue (robot absent, commande refusée…) : son message est transmis tel quel au client MCP."""22+ """Expected error (robot missing, command refused…): its message is passed as-is to the MCP client."""
23 23
24 24
25 def log(msg: str) -> None:25 def log(msg: str) -> None:
26- # stdout est réservé au protocole MCP : tout le reste va sur stderr.26+ # stdout is reserved for the MCP protocol: everything else goes to stderr.
27 print(f"[stackchan] {msg}", file=sys.stderr, flush=True)27 print(f"[stackchan] {msg}", file=sys.stderr, flush=True)
28 28
29 29
@@ -34,14 +34,14 @@ def find_port() -> str:
34 for p in list_ports.comports():34 for p in list_ports.comports():
35 if p.vid == ESPRESSIF_VID:35 if p.vid == ESPRESSIF_VID:
36 return p.device36 return p.device
37- raise RobotError("StackChan introuvable : aucun port USB Espressif (VID 303A). Le robot est-il branché ?")37+ raise RobotError("StackChan not found: no Espressif USB port (VID 303A). Is the robot plugged in?")
38 38
39 39
40 class Robot:40 class Robot:
41 def __init__(self) -> None:41 def __init__(self) -> None:
42 self._ser: serial.Serial | None = None42 self._ser: serial.Serial | None = None
43 self._reader: threading.Thread | None = None43 self._reader: threading.Thread | None = None
44- self._lock = threading.Lock() # protège l'ouverture/fermeture et l'écriture44+ self._lock = threading.Lock() # guards open/close and writes
45 self._ids = itertools.count(1)45 self._ids = itertools.count(1)
46 self._pending: dict[int, tuple[threading.Event, list]] = {}46 self._pending: dict[int, tuple[threading.Event, list]] = {}
47 self._events: collections.deque[dict] = collections.deque(maxlen=200)47 self._events: collections.deque[dict] = collections.deque(maxlen=200)
@@ -49,10 +49,10 @@ class Robot:
49 self._boot = threading.Event()49 self._boot = threading.Event()
50 self.firmware: str | None = None50 self.firmware: str | None = None
51 self.port: str | None = None51 self.port: str | None = None
52- # Raison de l'indisponibilité volontaire du port (ex. flash en cours), sinon None.52+ # Reason the port is deliberately unavailable (e.g. flash in progress), otherwise None.
53 self.maintenance: str | None = None53 self.maintenance: str | None = None
54 54
55- # ------------------------------------------------------------ connexion55+ # ------------------------------------------------------------ connection
56 56
57 @property57 @property
58 def connected(self) -> bool:58 def connected(self) -> bool:
@@ -63,7 +63,7 @@ class Robot:
63 if self.connected:63 if self.connected:
64 return64 return
65 if self.maintenance:65 if self.maintenance:
66- raise RobotError(f"robot indisponible : {self.maintenance}")66+ raise RobotError(f"robot unavailable: {self.maintenance}")
67 port = find_port()67 port = find_port()
68 self.port = port68 self.port = port
69 s = serial.Serial()69 s = serial.Serial()
@@ -74,18 +74,18 @@ class Robot:
74 s.open()74 s.open()
75 except serial.SerialException as e:75 except serial.SerialException as e:
76 raise RobotError(76 raise RobotError(
77- f"Impossible d'ouvrir {port} ({e}). Un autre programme (pio upload, moniteur série) l'utilise peut-être."77+ f"Cannot open {port} ({e}). Another program (pio upload, serial monitor) may be using it."
78 ) from e78 ) from e
79 self._ser = s79 self._ser = s
80 self._boot.clear()80 self._boot.clear()
81 self._reader = threading.Thread(target=self._read_loop, name="stackchan-reader", daemon=True)81 self._reader = threading.Thread(target=self._read_loop, name="stackchan-reader", daemon=True)
82 self._reader.start()82 self._reader.start()
83- log(f"port {port} ouvert")83+ log(f"port {port} opened")
84 84
85- # Sur macOS l'ouverture du port resette souvent l'ESP32-S3 : on attend l'événement boot,85+ # On macOS opening the port often resets the ESP32-S3: wait for the boot event,
86- # sinon on vérifie par un ping que le firmware répond déjà.86+ # otherwise check with a ping that the firmware is already responding.
87 if not self._boot.wait(6.0):87 if not self._boot.wait(6.0):
88- log("pas d'événement boot reçu, vérification par ping")88+ log("no boot event received, checking with ping")
89 info = self.request("ping", timeout=3.0)89 info = self.request("ping", timeout=3.0)
90 self.firmware = info.get("fw")90 self.firmware = info.get("fw")
91 91
@@ -97,7 +97,7 @@ class Robot:
97 except Exception:97 except Exception:
98 pass98 pass
99 self._ser = None99 self._ser = None
100- self._fail_pending("port série fermé")100+ self._fail_pending("serial port closed")
101 101
102 def _fail_pending(self, reason: str) -> None:102 def _fail_pending(self, reason: str) -> None:
103 for ev, box in list(self._pending.values()):103 for ev, box in list(self._pending.values()):
@@ -105,7 +105,7 @@ class Robot:
105 ev.set()105 ev.set()
106 self._pending.clear()106 self._pending.clear()
107 107
108- # ------------------------------------------------------------ lecture108+ # ------------------------------------------------------------ reading
109 109
110 def _read_loop(self) -> None:110 def _read_loop(self) -> None:
111 ser = self._ser111 ser = self._ser
@@ -114,7 +114,7 @@ class Robot:
114 try:114 try:
115 chunk = ser.read(256)115 chunk = ser.read(256)
116 except (serial.SerialException, OSError, TypeError) as e:116 except (serial.SerialException, OSError, TypeError) as e:
117- log(f"lecture interrompue : {e}")117+ log(f"read interrupted: {e}")
118 break118 break
119 if not chunk:119 if not chunk:
120 continue120 continue
@@ -124,15 +124,15 @@ class Robot:
124 self._dispatch(line.decode(errors="replace").strip())124 self._dispatch(line.decode(errors="replace").strip())
125 if self._ser is ser:125 if self._ser is ser:
126 self._ser = None126 self._ser = None
127- self._fail_pending("connexion perdue avec le robot")127+ self._fail_pending("connection to the robot lost")
128 128
129 def _dispatch(self, line: str) -> None:129 def _dispatch(self, line: str) -> None:
130 if not line.startswith("{"):130 if not line.startswith("{"):
131- return # traces ROM/boot de l'ESP32131+ return # ESP32 ROM/boot output
132 try:132 try:
133 msg = json.loads(line)133 msg = json.loads(line)
134 except json.JSONDecodeError:134 except json.JSONDecodeError:
135- log(f"ligne ignorée : {line[:120]}")135+ log(f"ignored line: {line[:120]}")
136 return136 return
137 137
138 if "event" in msg:138 if "event" in msg:
@@ -154,7 +154,7 @@ class Robot:
154 box.append(msg)154 box.append(msg)
155 ev.set()155 ev.set()
156 156
157- # ------------------------------------------------------------ requêtes157+ # ------------------------------------------------------------ requests
158 158
159 def request(self, cmd: str, timeout: float = 3.0, **params) -> dict:159 def request(self, cmd: str, timeout: float = 3.0, **params) -> dict:
160 if not self.connected:160 if not self.connected:
@@ -166,20 +166,20 @@ class Robot:
166 with self._lock:166 with self._lock:
167 if self._ser is None:167 if self._ser is None:
168 self._pending.pop(rid, None)168 self._pending.pop(rid, None)
169- raise RobotError("robot déconnecté")169+ raise RobotError("robot disconnected")
170 self._ser.write(payload.encode("utf-8"))170 self._ser.write(payload.encode("utf-8"))
171 self._ser.flush()171 self._ser.flush()
172 if not ev.wait(timeout):172 if not ev.wait(timeout):
173 self._pending.pop(rid, None)173 self._pending.pop(rid, None)
174- raise RobotError(f"pas de réponse du robot à '{cmd}' en {timeout:.0f} s")174+ raise RobotError(f"no response from the robot to '{cmd}' within {timeout:.0f} s")
175 res = box[0]175 res = box[0]
176 if not res.get("ok"):176 if not res.get("ok"):
177- raise RobotError(res.get("error", "erreur inconnue"))177+ raise RobotError(res.get("error", "unknown error"))
178 res.pop("ok", None)178 res.pop("ok", None)
179 res.pop("id", None)179 res.pop("id", None)
180 return res180 return res
181 181
182- # ------------------------------------------------------------ événements182+ # ------------------------------------------------------------ events
183 183
184 def events_since(self, t0: float, kind: str | None = None) -> list[dict]:184 def events_since(self, t0: float, kind: str | None = None) -> list[dict]:
185 horizon = max(t0, time.time() - EVENT_RETENTION_S)185 horizon = max(t0, time.time() - EVENT_RETENTION_S)
modified mcp/src/stackchan_mcp/server.py +70 -70
@@ -1,4 +1,4 @@
1-"""Serveur MCP StackChan : un seul processus possède le port USB, toutes les sessions s'y connectent en HTTP local."""
1+"""StackChan MCP server: a single process owns the USB port, all sessions connect to it over local HTTP."""
22
33 from __future__ import annotations
44
@@ -24,14 +24,14 @@ FIRMWARE_DIR = Path(os.environ.get("STACKCHAN_FIRMWARE_DIR", Path(__file__).reso
2424 mcp = MCPServer(
2525 "stackchan",
2626 instructions=(
27- "Pilote un petit robot de bureau M5Stack StackChan branché en USB, partagé entre plusieurs sessions. "
28- "La tête a deux axes : yaw (rotation, -90..90°, positif = vers la gauche du robot) "
29- "et pitch (inclinaison, 5..85°, 0 = regard droit devant, plus grand = regarde vers le haut). "
30- "L'écran affiche un visage expressif et une bulle de texte ; 12 LED RGB ; haut-parleur ; "
31- "capteur tactile sur le dessus de la tête. Préférer des mouvements doux (speed 200-500). "
32- "Une session qui envoie une commande prend la main sur le robot pendant 10 s après sa dernière commande ; "
33- "les autres sessions reçoivent alors une erreur indiquant quand réessayer. stop, get_status et la lecture "
34- "du tactile restent toujours disponibles."
27+ "Drives a small M5Stack StackChan desk robot connected over USB, shared between several sessions. "
28+ "The head has two axes: yaw (rotation, -90..90°, positive = toward the robot's left) "
29+ "and pitch (tilt, 5..85°, 0 = looking straight ahead, larger = looking up). "
30+ "The screen shows an expressive face and a text bubble; 12 RGB LEDs; speaker; "
31+ "touch sensor on top of the head. Prefer gentle movements (speed 200-500). "
32+ "A session that sends a command takes control of the robot until 10 s after its last command; "
33+ "other sessions then get an error saying when to retry. stop, get_status and reading "
34+ "touch events are always available."
3535 ),
3636 )
3737
@@ -62,11 +62,11 @@ def _client_label(ctx: Context) -> str | None:
6262
6363
6464 def _take(ctx: Context, extra_s: float = 0.0) -> None:
65- """Prend (ou prolonge) la main sur le robot pour cette session, sinon RobotError."""
65+ """Takes (or extends) the control lease for this session, otherwise RobotError."""
6666 lease.acquire(_session(ctx), _client_label(ctx), extra_s)
6767
6868
69-# ------------------------------------------------------------------ appels robot
69+# ------------------------------------------------------------------ robot calls
7070
7171
7272 def _call(cmd: str, timeout: float = 3.0, **params) -> dict:
@@ -74,14 +74,14 @@ def _call(cmd: str, timeout: float = 3.0, **params) -> dict:
7474 return robot.request(cmd, timeout=timeout, **params)
7575 except RobotError:
7676 raise
77- except Exception as e: # erreurs série inattendues : on repart d'une connexion propre
77+ except Exception as e: # unexpected serial errors: start again from a clean connection
7878 robot.close()
79- raise RobotError(f"erreur de communication : {e}") from e
79+ raise RobotError(f"communication error: {e}") from e
8080
8181
8282 def _wait_still(timeout: float = 6.0) -> dict:
83- """Attend la fin d'un mouvement. Le drapeau `moving` du servo peut rester vrai à l'arrêt
84- (charge sur l'axe), donc on considère aussi la tête immobile si sa position ne bouge plus."""
83+ """Waits for a movement to end. The servo `moving` flag can stay true when stopped
84+ (load on the axis), so the head is also considered still once its position stops changing."""
8585 deadline = time.time() + timeout
8686 time.sleep(0.15)
8787 st = _call("status")
@@ -99,13 +99,13 @@ def _wait_still(timeout: float = 6.0) -> dict:
9999 return st
100100
101101
102-# ------------------------------------------------------------------ outils libres
102+# ------------------------------------------------------------------ tools without lease
103103
104104
105105 @mcp.tool()
106106 def get_status() -> dict:
107- """Position de la tête (degrés), mouvement, couple, batterie, expression, geste en cours,
108- et quelle session a la main sur le robot."""
107+ """Head position (degrees), moving, torque, battery, expression, current gesture,
108+ and which session is in control of the robot."""
109109 st = _call("status")
110110 st["firmware"] = robot.firmware
111111 st["controlled_by"] = lease.holder()
@@ -114,15 +114,15 @@ def get_status() -> dict:
114114
115115 @mcp.tool()
116116 def stop() -> str:
117- """Arrête immédiatement tout mouvement ou geste. Toujours autorisé, même si une autre session a la main."""
117+ """Immediately stops any movement or gesture. Always allowed, even if another session is in control."""
118118 _call("stop")
119- return "arrêté"
119+ return "stopped"
120120
121121
122122 @mcp.tool()
123123 def get_touch_events(ctx: Context) -> list[dict]:
124- """Événements tactiles (click, swipe_forward, swipe_backward) reçus depuis le dernier appel de CETTE session
125- (au plus 5 min en arrière). Chaque session reçoit tous les événements."""
124+ """Touch events (click, swipe_forward, swipe_backward) received since THIS session's last call
125+ (at most 5 min back). Every session receives all events."""
126126 if not robot.connected:
127127 _call("ping")
128128 sid = _session(ctx)
@@ -135,7 +135,7 @@ def get_touch_events(ctx: Context) -> list[dict]:
135135
136136 @mcp.tool()
137137 def wait_for_touch(ctx: Context, timeout_s: Annotated[float, Field(ge=1, le=120)] = 30) -> dict:
138- """Attend qu'on touche le dessus de la tête. Renvoie le type d'appui, ou touched=false si délai dépassé."""
138+ """Waits for a touch on top of the head. Returns the touch type, or touched=false on timeout."""
139139 if not robot.connected:
140140 _call("ping")
141141 t0 = time.time()
@@ -144,18 +144,18 @@ def wait_for_touch(ctx: Context, timeout_s: Annotated[float, Field(ge=1, le=120)
144144 return {"touched": True, "type": ev.get("type")} if ev else {"touched": False}
145145
146146
147-# ------------------------------------------------------------------ outils soumis à la prise de main
147+# ------------------------------------------------------------------ tools requiring the control lease
148148
149149
150150 @mcp.tool()
151151 def move_head(
152152 ctx: Context,
153- yaw: Annotated[float, Field(description="Rotation en degrés, -90..90 (positif = vers la gauche du robot)")],
154- pitch: Annotated[float, Field(description="Inclinaison en degrés, 5..85 (plus grand = vers le haut)")],
155- speed: Annotated[int, Field(ge=0, le=1000, description="Vitesse 0..1000")] = 300,
156- wait: Annotated[bool, Field(description="Attendre la fin du mouvement")] = True,
153+ yaw: Annotated[float, Field(description="Rotation in degrees, -90..90 (positive = toward the robot's left)")],
154+ pitch: Annotated[float, Field(description="Tilt in degrees, 5..85 (larger = up)")],
155+ speed: Annotated[int, Field(ge=0, le=1000, description="Speed 0..1000")] = 300,
156+ wait: Annotated[bool, Field(description="Wait for the movement to end")] = True,
157157 ) -> dict:
158- """Oriente la tête. Les angles hors bornes sont ramenés dans l'intervalle (clamped=true)."""
158+ """Points the head. Out-of-range angles are clamped into range (clamped=true)."""
159159 _take(ctx)
160160 res = _call("move", yaw=yaw, pitch=pitch, speed=speed)
161161 if wait:
@@ -166,62 +166,62 @@ def move_head(
166166
167167 @mcp.tool()
168168 def rest(ctx: Context, speed: Annotated[int, Field(ge=0, le=1000)] = 300) -> str:
169- """Ramène la tête en position de repos (regard droit devant)."""
169+ """Returns the head to its rest position (looking straight ahead)."""
170170 _take(ctx)
171171 _call("rest", speed=speed)
172172 _wait_still()
173- return "au repos"
173+ return "at rest"
174174
175175
176176 @mcp.tool()
177177 def gesture(
178178 ctx: Context,
179- name: Annotated[GestureName, Field(description="nod=oui, shake=non, look_around, wiggle=trémousser, look_up")],
179+ name: Annotated[GestureName, Field(description="nod=yes, shake=no, look_around, wiggle, look_up")],
180180 wait: bool = True,
181181 ) -> str:
182- """Joue un geste prédéfini de la tête, relatif à sa position actuelle."""
182+ """Plays a predefined head gesture, relative to its current position."""
183183 _take(ctx)
184184 t0 = time.time()
185185 _call("gesture", name=name)
186186 if not wait:
187- return f"geste {name} lancé"
187+ return f"gesture {name} started"
188188 ev = robot.wait_event("gesture_done", t0, timeout=10.0, match=lambda e: e.get("name") == name)
189- return f"geste {name} terminé" if ev else f"geste {name} lancé (fin non confirmée)"
189+ return f"gesture {name} done" if ev else f"gesture {name} started (end not confirmed)"
190190
191191
192192 @mcp.tool()
193193 def set_face(ctx: Context, expression: Expression) -> str:
194- """Change l'expression du visage affiché à l'écran."""
194+ """Changes the expression of the face shown on screen."""
195195 _take(ctx)
196196 _call("face", expression=expression)
197- return f"expression : {expression}"
197+ return f"expression: {expression}"
198198
199199
200200 @mcp.tool()
201201 def say(
202202 ctx: Context,
203- text: Annotated[str, Field(max_length=120, description="Texte à afficher dans une bulle (vide = effacer)")],
204- duration_ms: Annotated[int, Field(ge=0, description="Durée d'affichage, 0 = jusqu'au prochain say")] = 0,
203+ text: Annotated[str, Field(max_length=120, description="Text to show in a bubble (empty = clear)")],
204+ duration_ms: Annotated[int, Field(ge=0, description="Display duration in ms, 0 = until the next say")] = 0,
205205 ) -> str:
206- """Affiche une bulle de texte sous le visage (pas de synthèse vocale)."""
206+ """Shows a text bubble below the face (no speech synthesis)."""
207207 _take(ctx)
208208 _call("say", text=text, duration_ms=duration_ms)
209- return "bulle effacée" if not text else "affiché"
209+ return "bubble cleared" if not text else "shown"
210210
211211
212212 @mcp.tool()
213213 def set_leds(
214214 ctx: Context,
215- color: Annotated[RGB | None, Field(description="Une couleur [r,g,b] pour les 12 LED")] = None,
215+ color: Annotated[RGB | None, Field(description="One [r,g,b] color for all 12 LEDs")] = None,
216216 colors: Annotated[
217217 list[RGB] | None,
218- Field(min_length=12, max_length=12, description="12 couleurs : index 0-5 côté gauche, 6-11 côté droit"),
218+ Field(min_length=12, max_length=12, description="12 colors: index 0-5 left side, 6-11 right side"),
219219 ] = None,
220220 brightness: Annotated[float, Field(ge=0, le=1)] = 0.3,
221221 ) -> str:
222- """Allume les LED RGB du corps. [0,0,0] pour éteindre. Luminosité par défaut modérée (0.3)."""
222+ """Sets the body RGB LEDs. [0,0,0] to turn off. Moderate default brightness (0.3)."""
223223 if (color is None) == (colors is None):
224- raise RobotError("donner soit color, soit colors")
224+ raise RobotError("give either color or colors")
225225 _take(ctx)
226226 params = {"brightness": brightness}
227227 if color is not None:
@@ -229,53 +229,53 @@ def set_leds(
229229 else:
230230 params["colors"] = colors
231231 _call("leds", **params)
232- return "LED mises à jour"
232+ return "LEDs updated"
233233
234234
235235 @mcp.tool()
236236 def play_tone(
237237 ctx: Context,
238- freq: Annotated[int, Field(ge=50, le=10000, description="Fréquence en Hz")] = 1000,
239- ms: Annotated[int, Field(ge=1, le=2000, description="Durée en ms")] = 150,
238+ freq: Annotated[int, Field(ge=50, le=10000, description="Frequency in Hz")] = 1000,
239+ ms: Annotated[int, Field(ge=1, le=2000, description="Duration in ms")] = 150,
240240 ) -> str:
241- """Joue un bip sur le haut-parleur."""
241+ """Plays a beep on the speaker."""
242242 _take(ctx)
243243 _call("tone", freq=freq, ms=ms)
244- return "bip"
244+ return "beep"
245245
246246
247247 @mcp.tool()
248248 def set_torque(ctx: Context, on: bool) -> str:
249- """Active/désactive le maintien des moteurs. Off = la tête peut être bougée à la main (calibration)."""
249+ """Enables/disables motor holding torque. Off = the head can be moved by hand (calibration)."""
250250 _take(ctx)
251251 _call("torque", on=on)
252- return f"couple {'activé' if on else 'coupé'}"
252+ return f"torque {'on' if on else 'off'}"
253253
254254
255255 @mcp.tool()
256256 def set_home(ctx: Context) -> str:
257- """Calibration : enregistre la position ACTUELLE de la tête comme zéro (yaw 0, pitch 0).
258- À n'utiliser que si l'utilisateur vient de placer la tête droite devant, couple coupé."""
257+ """Calibration: saves the CURRENT head position as zero (yaw 0, pitch 0).
258+ Only use when the user has just placed the head facing straight ahead, with torque off."""
259259 _take(ctx)
260260 _call("set_home")
261- return "zéro enregistré"
261+ return "zero saved"
262262
263263
264264 @mcp.tool()
265265 def flash_firmware(ctx: Context) -> dict:
266- """Compile firmware/ (PlatformIO) et le flashe sur le robot : libère le port USB, lance
267- `pio run -t upload`, puis se reconnecte. Peut prendre plusieurs minutes. Le robot redémarre."""
266+ """Builds firmware/ (PlatformIO) and flashes it to the robot: releases the USB port, runs
267+ `pio run -t upload`, then reconnects. Can take several minutes. The robot reboots."""
268268 pio = shutil.which("pio") or str(Path.home() / ".local/bin/pio")
269269 if not Path(pio).exists():
270- raise RobotError("pio introuvable (attendu dans ~/.local/bin)")
270+ raise RobotError("pio not found (expected in ~/.local/bin)")
271271 if not (FIRMWARE_DIR / "platformio.ini").exists():
272- raise RobotError(f"projet firmware introuvable : {FIRMWARE_DIR}")
272+ raise RobotError(f"firmware project not found: {FIRMWARE_DIR}")
273273
274- _take(ctx, extra_s=900) # garde la main pendant toute l'opération
274+ _take(ctx, extra_s=900) # keep control for the whole operation
275275 port = robot.port or find_port()
276- robot.maintenance = "flash du firmware en cours"
276+ robot.maintenance = "firmware flash in progress"
277277 robot.close()
278- log(f"flash : {pio} run -t upload --upload-port {port} (dans {FIRMWARE_DIR})")
278+ log(f"flash: {pio} run -t upload --upload-port {port} (in {FIRMWARE_DIR})")
279279 t0 = time.time()
280280 try:
281281 proc = subprocess.run(
@@ -286,10 +286,10 @@ def flash_firmware(ctx: Context) -> dict:
286286 timeout=900,
287287 )
288288 except subprocess.TimeoutExpired:
289- raise RobotError("flash interrompu : délai de 15 min dépassé")
289+ raise RobotError("flash aborted: 15 min timeout exceeded")
290290 finally:
291291 robot.maintenance = None
292- _take(ctx) # retour à la temporisation normale, même en cas d'échec
292+ _take(ctx) # back to the normal lease duration, even on failure
293293
294294 out = (proc.stdout + proc.stderr).strip().splitlines()
295295 tail = [l for l in out if l.strip() and not l.startswith("Writing at")][-15:]
@@ -304,12 +304,12 @@ def flash_firmware(ctx: Context) -> dict:
304304 return result
305305
306306
307-# ------------------------------------------------------------------ lancement
307+# ------------------------------------------------------------------ startup
308308
309309
310310 def main() -> None:
311- p = argparse.ArgumentParser(description="Serveur MCP StackChan")
312- p.add_argument("--stdio", action="store_true", help="mode stdio (un seul client, pour déboguer)")
311+ p = argparse.ArgumentParser(description="StackChan MCP server")
312+ p.add_argument("--stdio", action="store_true", help="stdio mode (single client, for debugging)")
313313 p.add_argument("--host", default="127.0.0.1")
314314 p.add_argument("--port", type=int, default=int(os.environ.get("STACKCHAN_MCP_PORT", DEFAULT_PORT)))
315315 args = p.parse_args()
@@ -318,10 +318,10 @@ def main() -> None:
318318 mcp.run()
319319 return
320320
321- # Pas d'authentification pour l'instant : écoute locale obligatoire.
321+ # No authentication for now: local listening only.
322322 if not ipaddress.ip_address(args.host).is_loopback:
323- sys.exit("refus : sans jeton d'accès, le serveur n'écoute que sur une adresse locale (127.0.0.1 / ::1)")
324- log(f"écoute sur http://{args.host}:{args.port}/mcp (firmware : {FIRMWARE_DIR})")
323+ sys.exit("refused: without an access token, the server only listens on a loopback address (127.0.0.1 / ::1)")
324+ log(f"listening on http://{args.host}:{args.port}/mcp (firmware: {FIRMWARE_DIR})")
325325 mcp.run("streamable-http", host=args.host, port=args.port)
326326
327327
@@ -1,4 +1,4 @@
1-"""Serveur MCP StackChan : un seul processus possède le port USB, toutes les sessions s'y connectent en HTTP local."""1+"""StackChan MCP server: a single process owns the USB port, all sessions connect to it over local HTTP."""
2 2
3 from __future__ import annotations3 from __future__ import annotations
4 4
@@ -24,14 +24,14 @@ FIRMWARE_DIR = Path(os.environ.get("STACKCHAN_FIRMWARE_DIR", Path(__file__).reso
24 mcp = MCPServer(24 mcp = MCPServer(
25 "stackchan",25 "stackchan",
26 instructions=(26 instructions=(
27- "Pilote un petit robot de bureau M5Stack StackChan branché en USB, partagé entre plusieurs sessions. "27+ "Drives a small M5Stack StackChan desk robot connected over USB, shared between several sessions. "
28- "La tête a deux axes : yaw (rotation, -90..90°, positif = vers la gauche du robot) "28+ "The head has two axes: yaw (rotation, -90..90°, positive = toward the robot's left) "
29- "et pitch (inclinaison, 5..85°, 0 = regard droit devant, plus grand = regarde vers le haut). "29+ "and pitch (tilt, 5..85°, 0 = looking straight ahead, larger = looking up). "
30- "L'écran affiche un visage expressif et une bulle de texte ; 12 LED RGB ; haut-parleur ; "30+ "The screen shows an expressive face and a text bubble; 12 RGB LEDs; speaker; "
31- "capteur tactile sur le dessus de la tête. Préférer des mouvements doux (speed 200-500). "31+ "touch sensor on top of the head. Prefer gentle movements (speed 200-500). "
32- "Une session qui envoie une commande prend la main sur le robot pendant 10 s après sa dernière commande ; "32+ "A session that sends a command takes control of the robot until 10 s after its last command; "
33- "les autres sessions reçoivent alors une erreur indiquant quand réessayer. stop, get_status et la lecture "33+ "other sessions then get an error saying when to retry. stop, get_status and reading "
34- "du tactile restent toujours disponibles."34+ "touch events are always available."
35 ),35 ),
36 )36 )
37 37
@@ -62,11 +62,11 @@ def _client_label(ctx: Context) -> str | None:
62 62
63 63
64 def _take(ctx: Context, extra_s: float = 0.0) -> None:64 def _take(ctx: Context, extra_s: float = 0.0) -> None:
65- """Prend (ou prolonge) la main sur le robot pour cette session, sinon RobotError."""65+ """Takes (or extends) the control lease for this session, otherwise RobotError."""
66 lease.acquire(_session(ctx), _client_label(ctx), extra_s)66 lease.acquire(_session(ctx), _client_label(ctx), extra_s)
67 67
68 68
69-# ------------------------------------------------------------------ appels robot69+# ------------------------------------------------------------------ robot calls
70 70
71 71
72 def _call(cmd: str, timeout: float = 3.0, **params) -> dict:72 def _call(cmd: str, timeout: float = 3.0, **params) -> dict:
@@ -74,14 +74,14 @@ def _call(cmd: str, timeout: float = 3.0, **params) -> dict:
74 return robot.request(cmd, timeout=timeout, **params)74 return robot.request(cmd, timeout=timeout, **params)
75 except RobotError:75 except RobotError:
76 raise76 raise
77- except Exception as e: # erreurs série inattendues : on repart d'une connexion propre77+ except Exception as e: # unexpected serial errors: start again from a clean connection
78 robot.close()78 robot.close()
79- raise RobotError(f"erreur de communication : {e}") from e79+ raise RobotError(f"communication error: {e}") from e
80 80
81 81
82 def _wait_still(timeout: float = 6.0) -> dict:82 def _wait_still(timeout: float = 6.0) -> dict:
83- """Attend la fin d'un mouvement. Le drapeau `moving` du servo peut rester vrai à l'arrêt83+ """Waits for a movement to end. The servo `moving` flag can stay true when stopped
84- (charge sur l'axe), donc on considère aussi la tête immobile si sa position ne bouge plus."""84+ (load on the axis), so the head is also considered still once its position stops changing."""
85 deadline = time.time() + timeout85 deadline = time.time() + timeout
86 time.sleep(0.15)86 time.sleep(0.15)
87 st = _call("status")87 st = _call("status")
@@ -99,13 +99,13 @@ def _wait_still(timeout: float = 6.0) -> dict:
99 return st99 return st
100 100
101 101
102-# ------------------------------------------------------------------ outils libres102+# ------------------------------------------------------------------ tools without lease
103 103
104 104
105 @mcp.tool()105 @mcp.tool()
106 def get_status() -> dict:106 def get_status() -> dict:
107- """Position de la tête (degrés), mouvement, couple, batterie, expression, geste en cours,107+ """Head position (degrees), moving, torque, battery, expression, current gesture,
108- et quelle session a la main sur le robot."""108+ and which session is in control of the robot."""
109 st = _call("status")109 st = _call("status")
110 st["firmware"] = robot.firmware110 st["firmware"] = robot.firmware
111 st["controlled_by"] = lease.holder()111 st["controlled_by"] = lease.holder()
@@ -114,15 +114,15 @@ def get_status() -> dict:
114 114
115 @mcp.tool()115 @mcp.tool()
116 def stop() -> str:116 def stop() -> str:
117- """Arrête immédiatement tout mouvement ou geste. Toujours autorisé, même si une autre session a la main."""117+ """Immediately stops any movement or gesture. Always allowed, even if another session is in control."""
118 _call("stop")118 _call("stop")
119- return "arrêté"119+ return "stopped"
120 120
121 121
122 @mcp.tool()122 @mcp.tool()
123 def get_touch_events(ctx: Context) -> list[dict]:123 def get_touch_events(ctx: Context) -> list[dict]:
124- """Événements tactiles (click, swipe_forward, swipe_backward) reçus depuis le dernier appel de CETTE session124+ """Touch events (click, swipe_forward, swipe_backward) received since THIS session's last call
125- (au plus 5 min en arrière). Chaque session reçoit tous les événements."""125+ (at most 5 min back). Every session receives all events."""
126 if not robot.connected:126 if not robot.connected:
127 _call("ping")127 _call("ping")
128 sid = _session(ctx)128 sid = _session(ctx)
@@ -135,7 +135,7 @@ def get_touch_events(ctx: Context) -> list[dict]:
135 135
136 @mcp.tool()136 @mcp.tool()
137 def wait_for_touch(ctx: Context, timeout_s: Annotated[float, Field(ge=1, le=120)] = 30) -> dict:137 def wait_for_touch(ctx: Context, timeout_s: Annotated[float, Field(ge=1, le=120)] = 30) -> dict:
138- """Attend qu'on touche le dessus de la tête. Renvoie le type d'appui, ou touched=false si délai dépassé."""138+ """Waits for a touch on top of the head. Returns the touch type, or touched=false on timeout."""
139 if not robot.connected:139 if not robot.connected:
140 _call("ping")140 _call("ping")
141 t0 = time.time()141 t0 = time.time()
@@ -144,18 +144,18 @@ def wait_for_touch(ctx: Context, timeout_s: Annotated[float, Field(ge=1, le=120)
144 return {"touched": True, "type": ev.get("type")} if ev else {"touched": False}144 return {"touched": True, "type": ev.get("type")} if ev else {"touched": False}
145 145
146 146
147-# ------------------------------------------------------------------ outils soumis à la prise de main147+# ------------------------------------------------------------------ tools requiring the control lease
148 148
149 149
150 @mcp.tool()150 @mcp.tool()
151 def move_head(151 def move_head(
152 ctx: Context,152 ctx: Context,
153- yaw: Annotated[float, Field(description="Rotation en degrés, -90..90 (positif = vers la gauche du robot)")],153+ yaw: Annotated[float, Field(description="Rotation in degrees, -90..90 (positive = toward the robot's left)")],
154- pitch: Annotated[float, Field(description="Inclinaison en degrés, 5..85 (plus grand = vers le haut)")],154+ pitch: Annotated[float, Field(description="Tilt in degrees, 5..85 (larger = up)")],
155- speed: Annotated[int, Field(ge=0, le=1000, description="Vitesse 0..1000")] = 300,155+ speed: Annotated[int, Field(ge=0, le=1000, description="Speed 0..1000")] = 300,
156- wait: Annotated[bool, Field(description="Attendre la fin du mouvement")] = True,156+ wait: Annotated[bool, Field(description="Wait for the movement to end")] = True,
157 ) -> dict:157 ) -> dict:
158- """Oriente la tête. Les angles hors bornes sont ramenés dans l'intervalle (clamped=true)."""158+ """Points the head. Out-of-range angles are clamped into range (clamped=true)."""
159 _take(ctx)159 _take(ctx)
160 res = _call("move", yaw=yaw, pitch=pitch, speed=speed)160 res = _call("move", yaw=yaw, pitch=pitch, speed=speed)
161 if wait:161 if wait:
@@ -166,62 +166,62 @@ def move_head(
166 166
167 @mcp.tool()167 @mcp.tool()
168 def rest(ctx: Context, speed: Annotated[int, Field(ge=0, le=1000)] = 300) -> str:168 def rest(ctx: Context, speed: Annotated[int, Field(ge=0, le=1000)] = 300) -> str:
169- """Ramène la tête en position de repos (regard droit devant)."""169+ """Returns the head to its rest position (looking straight ahead)."""
170 _take(ctx)170 _take(ctx)
171 _call("rest", speed=speed)171 _call("rest", speed=speed)
172 _wait_still()172 _wait_still()
173- return "au repos"173+ return "at rest"
174 174
175 175
176 @mcp.tool()176 @mcp.tool()
177 def gesture(177 def gesture(
178 ctx: Context,178 ctx: Context,
179- name: Annotated[GestureName, Field(description="nod=oui, shake=non, look_around, wiggle=trémousser, look_up")],179+ name: Annotated[GestureName, Field(description="nod=yes, shake=no, look_around, wiggle, look_up")],
180 wait: bool = True,180 wait: bool = True,
181 ) -> str:181 ) -> str:
182- """Joue un geste prédéfini de la tête, relatif à sa position actuelle."""182+ """Plays a predefined head gesture, relative to its current position."""
183 _take(ctx)183 _take(ctx)
184 t0 = time.time()184 t0 = time.time()
185 _call("gesture", name=name)185 _call("gesture", name=name)
186 if not wait:186 if not wait:
187- return f"geste {name} lancé"187+ return f"gesture {name} started"
188 ev = robot.wait_event("gesture_done", t0, timeout=10.0, match=lambda e: e.get("name") == name)188 ev = robot.wait_event("gesture_done", t0, timeout=10.0, match=lambda e: e.get("name") == name)
189- return f"geste {name} terminé" if ev else f"geste {name} lancé (fin non confirmée)"189+ return f"gesture {name} done" if ev else f"gesture {name} started (end not confirmed)"
190 190
191 191
192 @mcp.tool()192 @mcp.tool()
193 def set_face(ctx: Context, expression: Expression) -> str:193 def set_face(ctx: Context, expression: Expression) -> str:
194- """Change l'expression du visage affiché à l'écran."""194+ """Changes the expression of the face shown on screen."""
195 _take(ctx)195 _take(ctx)
196 _call("face", expression=expression)196 _call("face", expression=expression)
197- return f"expression : {expression}"197+ return f"expression: {expression}"
198 198
199 199
200 @mcp.tool()200 @mcp.tool()
201 def say(201 def say(
202 ctx: Context,202 ctx: Context,
203- text: Annotated[str, Field(max_length=120, description="Texte à afficher dans une bulle (vide = effacer)")],203+ text: Annotated[str, Field(max_length=120, description="Text to show in a bubble (empty = clear)")],
204- duration_ms: Annotated[int, Field(ge=0, description="Durée d'affichage, 0 = jusqu'au prochain say")] = 0,204+ duration_ms: Annotated[int, Field(ge=0, description="Display duration in ms, 0 = until the next say")] = 0,
205 ) -> str:205 ) -> str:
206- """Affiche une bulle de texte sous le visage (pas de synthèse vocale)."""206+ """Shows a text bubble below the face (no speech synthesis)."""
207 _take(ctx)207 _take(ctx)
208 _call("say", text=text, duration_ms=duration_ms)208 _call("say", text=text, duration_ms=duration_ms)
209- return "bulle effacée" if not text else "affiché"209+ return "bubble cleared" if not text else "shown"
210 210
211 211
212 @mcp.tool()212 @mcp.tool()
213 def set_leds(213 def set_leds(
214 ctx: Context,214 ctx: Context,
215- color: Annotated[RGB | None, Field(description="Une couleur [r,g,b] pour les 12 LED")] = None,215+ color: Annotated[RGB | None, Field(description="One [r,g,b] color for all 12 LEDs")] = None,
216 colors: Annotated[216 colors: Annotated[
217 list[RGB] | None,217 list[RGB] | None,
218- Field(min_length=12, max_length=12, description="12 couleurs : index 0-5 côté gauche, 6-11 côté droit"),218+ Field(min_length=12, max_length=12, description="12 colors: index 0-5 left side, 6-11 right side"),
219 ] = None,219 ] = None,
220 brightness: Annotated[float, Field(ge=0, le=1)] = 0.3,220 brightness: Annotated[float, Field(ge=0, le=1)] = 0.3,
221 ) -> str:221 ) -> str:
222- """Allume les LED RGB du corps. [0,0,0] pour éteindre. Luminosité par défaut modérée (0.3)."""222+ """Sets the body RGB LEDs. [0,0,0] to turn off. Moderate default brightness (0.3)."""
223 if (color is None) == (colors is None):223 if (color is None) == (colors is None):
224- raise RobotError("donner soit color, soit colors")224+ raise RobotError("give either color or colors")
225 _take(ctx)225 _take(ctx)
226 params = {"brightness": brightness}226 params = {"brightness": brightness}
227 if color is not None:227 if color is not None:
@@ -229,53 +229,53 @@ def set_leds(
229 else:229 else:
230 params["colors"] = colors230 params["colors"] = colors
231 _call("leds", **params)231 _call("leds", **params)
232- return "LED mises à jour"232+ return "LEDs updated"
233 233
234 234
235 @mcp.tool()235 @mcp.tool()
236 def play_tone(236 def play_tone(
237 ctx: Context,237 ctx: Context,
238- freq: Annotated[int, Field(ge=50, le=10000, description="Fréquence en Hz")] = 1000,238+ freq: Annotated[int, Field(ge=50, le=10000, description="Frequency in Hz")] = 1000,
239- ms: Annotated[int, Field(ge=1, le=2000, description="Durée en ms")] = 150,239+ ms: Annotated[int, Field(ge=1, le=2000, description="Duration in ms")] = 150,
240 ) -> str:240 ) -> str:
241- """Joue un bip sur le haut-parleur."""241+ """Plays a beep on the speaker."""
242 _take(ctx)242 _take(ctx)
243 _call("tone", freq=freq, ms=ms)243 _call("tone", freq=freq, ms=ms)
244- return "bip"244+ return "beep"
245 245
246 246
247 @mcp.tool()247 @mcp.tool()
248 def set_torque(ctx: Context, on: bool) -> str:248 def set_torque(ctx: Context, on: bool) -> str:
249- """Active/désactive le maintien des moteurs. Off = la tête peut être bougée à la main (calibration)."""249+ """Enables/disables motor holding torque. Off = the head can be moved by hand (calibration)."""
250 _take(ctx)250 _take(ctx)
251 _call("torque", on=on)251 _call("torque", on=on)
252- return f"couple {'activé' if on else 'coupé'}"252+ return f"torque {'on' if on else 'off'}"
253 253
254 254
255 @mcp.tool()255 @mcp.tool()
256 def set_home(ctx: Context) -> str:256 def set_home(ctx: Context) -> str:
257- """Calibration : enregistre la position ACTUELLE de la tête comme zéro (yaw 0, pitch 0).257+ """Calibration: saves the CURRENT head position as zero (yaw 0, pitch 0).
258- À n'utiliser que si l'utilisateur vient de placer la tête droite devant, couple coupé."""258+ Only use when the user has just placed the head facing straight ahead, with torque off."""
259 _take(ctx)259 _take(ctx)
260 _call("set_home")260 _call("set_home")
261- return "zéro enregistré"261+ return "zero saved"
262 262
263 263
264 @mcp.tool()264 @mcp.tool()
265 def flash_firmware(ctx: Context) -> dict:265 def flash_firmware(ctx: Context) -> dict:
266- """Compile firmware/ (PlatformIO) et le flashe sur le robot : libère le port USB, lance266+ """Builds firmware/ (PlatformIO) and flashes it to the robot: releases the USB port, runs
267- `pio run -t upload`, puis se reconnecte. Peut prendre plusieurs minutes. Le robot redémarre."""267+ `pio run -t upload`, then reconnects. Can take several minutes. The robot reboots."""
268 pio = shutil.which("pio") or str(Path.home() / ".local/bin/pio")268 pio = shutil.which("pio") or str(Path.home() / ".local/bin/pio")
269 if not Path(pio).exists():269 if not Path(pio).exists():
270- raise RobotError("pio introuvable (attendu dans ~/.local/bin)")270+ raise RobotError("pio not found (expected in ~/.local/bin)")
271 if not (FIRMWARE_DIR / "platformio.ini").exists():271 if not (FIRMWARE_DIR / "platformio.ini").exists():
272- raise RobotError(f"projet firmware introuvable : {FIRMWARE_DIR}")272+ raise RobotError(f"firmware project not found: {FIRMWARE_DIR}")
273 273
274- _take(ctx, extra_s=900) # garde la main pendant toute l'opération274+ _take(ctx, extra_s=900) # keep control for the whole operation
275 port = robot.port or find_port()275 port = robot.port or find_port()
276- robot.maintenance = "flash du firmware en cours"276+ robot.maintenance = "firmware flash in progress"
277 robot.close()277 robot.close()
278- log(f"flash : {pio} run -t upload --upload-port {port} (dans {FIRMWARE_DIR})")278+ log(f"flash: {pio} run -t upload --upload-port {port} (in {FIRMWARE_DIR})")
279 t0 = time.time()279 t0 = time.time()
280 try:280 try:
281 proc = subprocess.run(281 proc = subprocess.run(
@@ -286,10 +286,10 @@ def flash_firmware(ctx: Context) -> dict:
286 timeout=900,286 timeout=900,
287 )287 )
288 except subprocess.TimeoutExpired:288 except subprocess.TimeoutExpired:
289- raise RobotError("flash interrompu : délai de 15 min dépassé")289+ raise RobotError("flash aborted: 15 min timeout exceeded")
290 finally:290 finally:
291 robot.maintenance = None291 robot.maintenance = None
292- _take(ctx) # retour à la temporisation normale, même en cas d'échec292+ _take(ctx) # back to the normal lease duration, even on failure
293 293
294 out = (proc.stdout + proc.stderr).strip().splitlines()294 out = (proc.stdout + proc.stderr).strip().splitlines()
295 tail = [l for l in out if l.strip() and not l.startswith("Writing at")][-15:]295 tail = [l for l in out if l.strip() and not l.startswith("Writing at")][-15:]
@@ -304,12 +304,12 @@ def flash_firmware(ctx: Context) -> dict:
304 return result304 return result
305 305
306 306
307-# ------------------------------------------------------------------ lancement307+# ------------------------------------------------------------------ startup
308 308
309 309
310 def main() -> None:310 def main() -> None:
311- p = argparse.ArgumentParser(description="Serveur MCP StackChan")311+ p = argparse.ArgumentParser(description="StackChan MCP server")
312- p.add_argument("--stdio", action="store_true", help="mode stdio (un seul client, pour déboguer)")312+ p.add_argument("--stdio", action="store_true", help="stdio mode (single client, for debugging)")
313 p.add_argument("--host", default="127.0.0.1")313 p.add_argument("--host", default="127.0.0.1")
314 p.add_argument("--port", type=int, default=int(os.environ.get("STACKCHAN_MCP_PORT", DEFAULT_PORT)))314 p.add_argument("--port", type=int, default=int(os.environ.get("STACKCHAN_MCP_PORT", DEFAULT_PORT)))
315 args = p.parse_args()315 args = p.parse_args()
@@ -318,10 +318,10 @@ def main() -> None:
318 mcp.run()318 mcp.run()
319 return319 return
320 320
321- # Pas d'authentification pour l'instant : écoute locale obligatoire.321+ # No authentication for now: local listening only.
322 if not ipaddress.ip_address(args.host).is_loopback:322 if not ipaddress.ip_address(args.host).is_loopback:
323- sys.exit("refus : sans jeton d'accès, le serveur n'écoute que sur une adresse locale (127.0.0.1 / ::1)")323+ sys.exit("refused: without an access token, the server only listens on a loopback address (127.0.0.1 / ::1)")
324- log(f"écoute sur http://{args.host}:{args.port}/mcp (firmware : {FIRMWARE_DIR})")324+ log(f"listening on http://{args.host}:{args.port}/mcp (firmware: {FIRMWARE_DIR})")
325 mcp.run("streamable-http", host=args.host, port=args.port)325 mcp.run("streamable-http", host=args.host, port=args.port)
326 326
327 327
modified mcp/src/stackchan_mcp/sessions.py +9 -9
@@ -1,4 +1,4 @@
1-"""Partage du robot entre plusieurs sessions MCP : prise de main temporisée et curseurs d'événements."""
1+"""Sharing the robot between several MCP sessions: timed control lease and event cursors."""
22
33 from __future__ import annotations
44
@@ -7,14 +7,14 @@ import time
77
88 from .robot import RobotError
99
10-CURSOR_TTL_S = 3600 # un curseur inutilisé depuis 1 h est oublié
10+CURSOR_TTL_S = 3600 # a cursor unused for 1 h is forgotten
1111
1212
1313 class Lease:
14- """Une seule session à la fois pilote le robot.
14+ """Only one session at a time controls the robot.
1515
16- La session qui envoie une commande prend la main ; elle la garde tant qu'elle envoie
17- au moins une commande toutes les `hold_s` secondes. Les autres sont refusées immédiatement.
16+ The session that sends a command takes control; it keeps it as long as it sends
17+ at least one command every `hold_s` seconds. Other sessions are refused immediately.
1818 """
1919
2020 def __init__(self, hold_s: float = 10.0) -> None:
@@ -31,7 +31,7 @@ class Lease:
3131 wait = self._expires - now
3232 who = f" ({self._owner_label})" if self._owner_label else ""
3333 raise RobotError(
34- f"robot utilisé par une autre session{who} : réessayer dans {wait:.0f} s"
34+ f"robot in use by another session{who}: retry in {wait:.0f} s"
3535 )
3636 self._owner, self._owner_label = session, label
3737 self._expires = now + self.hold_s + extra_s
@@ -45,10 +45,10 @@ class Lease:
4545
4646
4747 class Cursors:
48- """Position de lecture des événements, propre à chaque session."""
48+ """Per-session read position in the event stream."""
4949
5050 def __init__(self) -> None:
51- self._last: dict[str, tuple[float, float]] = {} # session -> (dernière lecture, dernier accès)
51+ self._last: dict[str, tuple[float, float]] = {} # session -> (last read, last access)
5252 self._lock = threading.Lock()
5353
5454 def get(self, session: str) -> float:
@@ -56,7 +56,7 @@ class Cursors:
5656 with self._lock:
5757 for k in [k for k, (_, seen) in self._last.items() if now - seen > CURSOR_TTL_S]:
5858 del self._last[k]
59- # Première lecture d'une session : elle ne reçoit que ce qui arrive après sa connexion.
59+ # First read by a session: it only gets what arrives after it connected.
6060 last, _ = self._last.get(session, (now, now))
6161 self._last[session] = (last, now)
6262 return last
@@ -1,4 +1,4 @@
1-"""Partage du robot entre plusieurs sessions MCP : prise de main temporisée et curseurs d'événements."""1+"""Sharing the robot between several MCP sessions: timed control lease and event cursors."""
2 2
3 from __future__ import annotations3 from __future__ import annotations
4 4
@@ -7,14 +7,14 @@ import time
7 7
8 from .robot import RobotError8 from .robot import RobotError
9 9
10-CURSOR_TTL_S = 3600 # un curseur inutilisé depuis 1 h est oublié10+CURSOR_TTL_S = 3600 # a cursor unused for 1 h is forgotten
11 11
12 12
13 class Lease:13 class Lease:
14- """Une seule session à la fois pilote le robot.14+ """Only one session at a time controls the robot.
15 15
16- La session qui envoie une commande prend la main ; elle la garde tant qu'elle envoie16+ The session that sends a command takes control; it keeps it as long as it sends
17- au moins une commande toutes les `hold_s` secondes. Les autres sont refusées immédiatement.17+ at least one command every `hold_s` seconds. Other sessions are refused immediately.
18 """18 """
19 19
20 def __init__(self, hold_s: float = 10.0) -> None:20 def __init__(self, hold_s: float = 10.0) -> None:
@@ -31,7 +31,7 @@ class Lease:
31 wait = self._expires - now31 wait = self._expires - now
32 who = f" ({self._owner_label})" if self._owner_label else ""32 who = f" ({self._owner_label})" if self._owner_label else ""
33 raise RobotError(33 raise RobotError(
34- f"robot utilisé par une autre session{who} : réessayer dans {wait:.0f} s"34+ f"robot in use by another session{who}: retry in {wait:.0f} s"
35 )35 )
36 self._owner, self._owner_label = session, label36 self._owner, self._owner_label = session, label
37 self._expires = now + self.hold_s + extra_s37 self._expires = now + self.hold_s + extra_s
@@ -45,10 +45,10 @@ class Lease:
45 45
46 46
47 class Cursors:47 class Cursors:
48- """Position de lecture des événements, propre à chaque session."""48+ """Per-session read position in the event stream."""
49 49
50 def __init__(self) -> None:50 def __init__(self) -> None:
51- self._last: dict[str, tuple[float, float]] = {} # session -> (dernière lecture, dernier accès)51+ self._last: dict[str, tuple[float, float]] = {} # session -> (last read, last access)
52 self._lock = threading.Lock()52 self._lock = threading.Lock()
53 53
54 def get(self, session: str) -> float:54 def get(self, session: str) -> float:
@@ -56,7 +56,7 @@ class Cursors:
56 with self._lock:56 with self._lock:
57 for k in [k for k, (_, seen) in self._last.items() if now - seen > CURSOR_TTL_S]:57 for k in [k for k, (_, seen) in self._last.items() if now - seen > CURSOR_TTL_S]:
58 del self._last[k]58 del self._last[k]
59- # Première lecture d'une session : elle ne reçoit que ce qui arrive après sa connexion.59+ # First read by a session: it only gets what arrives after it connected.
60 last, _ = self._last.get(session, (now, now))60 last, _ = self._last.get(session, (now, now))
61 self._last[session] = (last, now)61 self._last[session] = (last, now)
62 return last62 return last
modified tools/serial_cmd.py +5 -5
@@ -1,7 +1,7 @@
1-"""Envoie des commandes ligne par ligne au StackChan et affiche la réponse.
1+"""Sends commands line by line to the StackChan and prints the response.
22
3-Usage : python serial_cmd.py <port> <durée_lecture_s> [commande ...]
4-Sans commande : lecture seule. DTR/RTS restent bas pour ne pas resetter l'ESP32-S3.
3+Usage: python serial_cmd.py <port> <read_duration_s> [command ...]
4+Without a command: read only. DTR/RTS stay low so as not to reset the ESP32-S3.
55 """
66 import sys
77 import time
@@ -16,8 +16,8 @@ s.dtr = False
1616 s.rts = False
1717 s.open()
1818
19-# Sur macOS, l'ouverture du port USB-Serial-JTAG peut quand même resetter la puce :
20-# on attend la ligne "[boot]" (ou 1.5 s de silence) avant d'envoyer quoi que ce soit.
19+# On macOS, opening the USB-Serial-JTAG port can still reset the chip:
20+# wait for the "[boot]" line (or 1.5 s of silence) before sending anything.
2121 deadline, last_rx = time.time() + 6, time.time()
2222 while time.time() < deadline:
2323 line = s.readline()
@@ -1,7 +1,7 @@
1-"""Envoie des commandes ligne par ligne au StackChan et affiche la réponse.1+"""Sends commands line by line to the StackChan and prints the response.
2 2
3-Usage : python serial_cmd.py <port> <durée_lecture_s> [commande ...]3+Usage: python serial_cmd.py <port> <read_duration_s> [command ...]
4-Sans commande : lecture seule. DTR/RTS restent bas pour ne pas resetter l'ESP32-S3.4+Without a command: read only. DTR/RTS stay low so as not to reset the ESP32-S3.
5 """5 """
6 import sys6 import sys
7 import time7 import time
@@ -16,8 +16,8 @@ s.dtr = False
16 s.rts = False16 s.rts = False
17 s.open()17 s.open()
18 18
19-# Sur macOS, l'ouverture du port USB-Serial-JTAG peut quand même resetter la puce :19+# On macOS, opening the USB-Serial-JTAG port can still reset the chip:
20-# on attend la ligne "[boot]" (ou 1.5 s de silence) avant d'envoyer quoi que ce soit.20+# wait for the "[boot]" line (or 1.5 s of silence) before sending anything.
21 deadline, last_rx = time.time() + 6, time.time()21 deadline, last_rx = time.time() + 6, time.time()
22 while time.time() < deadline:22 while time.time() < deadline:
23 line = s.readline()23 line = s.readline()
modified tools/serial_read.py +1 -1
@@ -5,7 +5,7 @@ s = None
55 while time.time() < end and s is None:
66 try: s = serial.Serial(port, 115200, timeout=0.5)
77 except Exception: time.sleep(0.3)
8-if s is None: sys.exit("port indisponible")
8+if s is None: sys.exit("port unavailable")
99 while time.time() < end:
1010 d = s.readline()
1111 if d: print(d.decode(errors="replace").rstrip(), flush=True)
@@ -5,7 +5,7 @@ s = None
5 while time.time() < end and s is None:5 while time.time() < end and s is None:
6 try: s = serial.Serial(port, 115200, timeout=0.5)6 try: s = serial.Serial(port, 115200, timeout=0.5)
7 except Exception: time.sleep(0.3)7 except Exception: time.sleep(0.3)
8-if s is None: sys.exit("port indisponible")8+if s is None: sys.exit("port unavailable")
9 while time.time() < end:9 while time.time() < end:
10 d = s.readline()10 d = s.readline()
11 if d: print(d.decode(errors="replace").rstrip(), flush=True)11 if d: print(d.decode(errors="replace").rstrip(), flush=True)
modified tools/stackchan-server.sh +12 -12
@@ -1,6 +1,6 @@
11 #!/usr/bin/env bash
2-# Démarre / arrête le serveur MCP StackChan partagé (HTTP local).
3-# Usage : tools/stackchan-server.sh start|stop|restart|status|logs [-f]
2+# Starts / stops the shared StackChan MCP server (local HTTP).
3+# Usage: tools/stackchan-server.sh start|stop|restart|status|logs [-f]
44 set -euo pipefail
55
66 ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -25,15 +25,15 @@ listening() {
2525
2626 start() {
2727 if pid="$(running_pid)"; then
28- echo "déjà démarré (pid ${pid}) sur http://127.0.0.1:${PORT}/mcp"
28+ echo "already running (pid ${pid}) on http://127.0.0.1:${PORT}/mcp"
2929 return 0
3030 fi
3131 if listening; then
32- echo "le port ${PORT} est déjà utilisé par un autre programme" >&2
32+ echo "port ${PORT} is already in use by another program" >&2
3333 exit 1
3434 fi
3535 uv sync --quiet --project "${ROOT}/mcp"
36- # Le serveur appelle pio pour flash_firmware : on garantit ~/.local/bin dans le PATH.
36+ # The server calls pio for flash_firmware: make sure ~/.local/bin is in PATH.
3737 PATH="${HOME}/.local/bin:${PATH}" nohup "${BIN}" --port "${PORT}" >>"${LOG_FILE}" 2>&1 &
3838 echo $! >"${PID_FILE}"
3939 for _ in $(seq 1 50); do
@@ -41,9 +41,9 @@ start() {
4141 sleep 0.2
4242 done
4343 if listening; then
44- echo "démarré (pid $(cat "${PID_FILE}")) sur http://127.0.0.1:${PORT}/mcp — logs : ${LOG_FILE}"
44+ echo "started (pid $(cat "${PID_FILE}")) on http://127.0.0.1:${PORT}/mcp — logs: ${LOG_FILE}"
4545 else
46- echo "échec du démarrage, voir ${LOG_FILE}" >&2
46+ echo "failed to start, see ${LOG_FILE}" >&2
4747 tail -n 20 "${LOG_FILE}" >&2
4848 exit 1
4949 fi
@@ -58,18 +58,18 @@ stop() {
5858 done
5959 kill -0 "${pid}" 2>/dev/null && kill -9 "${pid}"
6060 rm -f "${PID_FILE}"
61- echo "arrêté"
61+ echo "stopped"
6262 else
6363 rm -f "${PID_FILE}"
64- echo "pas démarré"
64+ echo "not running"
6565 fi
6666 }
6767
6868 status() {
6969 if pid="$(running_pid)"; then
70- echo "en marche (pid ${pid}) sur http://127.0.0.1:${PORT}/mcp"
70+ echo "running (pid ${pid}) on http://127.0.0.1:${PORT}/mcp"
7171 else
72- echo "arrêté"
72+ echo "stopped"
7373 return 3
7474 fi
7575 }
@@ -80,5 +80,5 @@ case "${1:-}" in
8080 restart) stop; start ;;
8181 status) status ;;
8282 logs) if [[ "${2:-}" == "-f" ]]; then tail -f "${LOG_FILE}"; else tail -n 50 "${LOG_FILE}"; fi ;;
83- *) echo "usage : $0 start|stop|restart|status|logs [-f]" >&2; exit 2 ;;
83+ *) echo "usage: $0 start|stop|restart|status|logs [-f]" >&2; exit 2 ;;
8484 esac
@@ -1,6 +1,6 @@
1 #!/usr/bin/env bash1 #!/usr/bin/env bash
2-# Démarre / arrête le serveur MCP StackChan partagé (HTTP local).2+# Starts / stops the shared StackChan MCP server (local HTTP).
3-# Usage : tools/stackchan-server.sh start|stop|restart|status|logs [-f]3+# Usage: tools/stackchan-server.sh start|stop|restart|status|logs [-f]
4 set -euo pipefail4 set -euo pipefail
5 5
6 ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"6 ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -25,15 +25,15 @@ listening() {
25 25
26 start() {26 start() {
27 if pid="$(running_pid)"; then27 if pid="$(running_pid)"; then
28- echo "déjà démarré (pid ${pid}) sur http://127.0.0.1:${PORT}/mcp"28+ echo "already running (pid ${pid}) on http://127.0.0.1:${PORT}/mcp"
29 return 029 return 0
30 fi30 fi
31 if listening; then31 if listening; then
32- echo "le port ${PORT} est déjà utilisé par un autre programme" >&232+ echo "port ${PORT} is already in use by another program" >&2
33 exit 133 exit 1
34 fi34 fi
35 uv sync --quiet --project "${ROOT}/mcp"35 uv sync --quiet --project "${ROOT}/mcp"
36- # Le serveur appelle pio pour flash_firmware : on garantit ~/.local/bin dans le PATH.36+ # The server calls pio for flash_firmware: make sure ~/.local/bin is in PATH.
37 PATH="${HOME}/.local/bin:${PATH}" nohup "${BIN}" --port "${PORT}" >>"${LOG_FILE}" 2>&1 &37 PATH="${HOME}/.local/bin:${PATH}" nohup "${BIN}" --port "${PORT}" >>"${LOG_FILE}" 2>&1 &
38 echo $! >"${PID_FILE}"38 echo $! >"${PID_FILE}"
39 for _ in $(seq 1 50); do39 for _ in $(seq 1 50); do
@@ -41,9 +41,9 @@ start() {
41 sleep 0.241 sleep 0.2
42 done42 done
43 if listening; then43 if listening; then
44- echo "démarré (pid $(cat "${PID_FILE}")) sur http://127.0.0.1:${PORT}/mcp — logs : ${LOG_FILE}"44+ echo "started (pid $(cat "${PID_FILE}")) on http://127.0.0.1:${PORT}/mcp — logs: ${LOG_FILE}"
45 else45 else
46- echo "échec du démarrage, voir ${LOG_FILE}" >&246+ echo "failed to start, see ${LOG_FILE}" >&2
47 tail -n 20 "${LOG_FILE}" >&247 tail -n 20 "${LOG_FILE}" >&2
48 exit 148 exit 1
49 fi49 fi
@@ -58,18 +58,18 @@ stop() {
58 done58 done
59 kill -0 "${pid}" 2>/dev/null && kill -9 "${pid}"59 kill -0 "${pid}" 2>/dev/null && kill -9 "${pid}"
60 rm -f "${PID_FILE}"60 rm -f "${PID_FILE}"
61- echo "arrêté"61+ echo "stopped"
62 else62 else
63 rm -f "${PID_FILE}"63 rm -f "${PID_FILE}"
64- echo "pas démarré"64+ echo "not running"
65 fi65 fi
66 }66 }
67 67
68 status() {68 status() {
69 if pid="$(running_pid)"; then69 if pid="$(running_pid)"; then
70- echo "en marche (pid ${pid}) sur http://127.0.0.1:${PORT}/mcp"70+ echo "running (pid ${pid}) on http://127.0.0.1:${PORT}/mcp"
71 else71 else
72- echo "arrêté"72+ echo "stopped"
73 return 373 return 3
74 fi74 fi
75 }75 }
@@ -80,5 +80,5 @@ case "${1:-}" in
80 restart) stop; start ;;80 restart) stop; start ;;
81 status) status ;;81 status) status ;;
82 logs) if [[ "${2:-}" == "-f" ]]; then tail -f "${LOG_FILE}"; else tail -n 50 "${LOG_FILE}"; fi ;;82 logs) if [[ "${2:-}" == "-f" ]]; then tail -f "${LOG_FILE}"; else tail -n 50 "${LOG_FILE}"; fi ;;
83- *) echo "usage : $0 start|stop|restart|status|logs [-f]" >&2; exit 2 ;;83+ *) echo "usage: $0 start|stop|restart|status|logs [-f]" >&2; exit 2 ;;
84 esac84 esac