Files
car_stm32f103vet6/docs/upper_computer_ai_guide.md
wangbeihong 48a443c6c1 Update FreeRTOS configuration and enhance upper computer AI documentation
- Increased total heap size in FreeRTOSConfig.h from 10000 to 18000.
- Modified stack sizes for various tasks in freertos.c to improve performance:
  - initTask: 128 to 256
  - CarCtrlTask: 256 to 1024
  - timerTask: 512 to 1024
  - sr04Task: 128 to 512
  - rc522Task: 128 to 512
- Added comprehensive upper computer AI guide for TCP client implementation, detailing protocol contracts, command sets, telemetry, architecture requirements, and error handling strategies.
- Introduced a Python web upper computer AI guide with a recommended tech stack and project structure.
- Created a Chinese version of the upper computer AI guide for local developers.
- Updated STM32 project configuration to reflect new task stack sizes and heap settings.
- Adjusted configuration files for various tools to ensure compatibility with the new project structure.
2026-04-17 22:15:54 +08:00

332 lines
9.2 KiB
Markdown

# Logistics Car Upper Computer AI Guide
## 1. Purpose
This document is written for an AI agent that will implement the upper computer application.
Goal: build a stable TCP client for the logistics car, with both auto mode and manual mecanum mode, based on the embedded protocol implemented in this repository.
Target users:
- AI coding agents (Copilot-like, AutoGen-like, etc.)
- Human developers who review AI-generated upper computer code
Out of scope:
- Modifying embedded firmware behavior
- Replacing transport protocol
---
## 2. Must-Follow Protocol Contract
### 2.1 Frame format
All commands and telemetry use ASCII text:
LOGI:<PAYLOAD>:<CS>#
Fields:
- LOGI: fixed header
- <PAYLOAD>: command or telemetry body
- <CS>: 2-digit uppercase hex checksum
- #: fixed frame tail
### 2.2 Checksum algorithm
Checksum is the low 8 bits of ASCII sum of all bytes from L in LOGI to the byte before the final colon before CS.
Pseudo:
1. base = "LOGI:" + payload
2. cs = sum(base bytes as ASCII) & 0xFF
3. frame = base + ":" + toHex2Upper(cs) + "#"
Python reference:
```python
def build_frame(payload: str) -> str:
base = f"LOGI:{payload}"
cs = sum(base.encode("ascii")) & 0xFF
return f"{base}:{cs:02X}#"
```
C# reference:
```csharp
static string BuildFrame(string payload)
{
string baseStr = $"LOGI:{payload}";
int sum = 0;
foreach (byte b in System.Text.Encoding.ASCII.GetBytes(baseStr))
sum = (sum + b) & 0xFF;
return $"{baseStr}:{sum:X2}#";
}
```
Important:
- Must use uppercase hex (for consistency)
- Do not append CRLF unless your socket tool requires it
- One frame can be sent as raw ASCII bytes directly
---
## 3. Command Set (PC -> Car)
### 3.1 Common control
- SP:xxx set speed 000..100
- ST:RUN start auto run
- ST:STOP stop run
- GS:xxx set target station (current firmware supports 001, 002)
### 3.2 Mode switch (new)
- MD:MAN switch to manual mecanum mode
- MD:AUTO switch to auto tracking mode
### 3.3 Manual movement (new, only valid in MAN mode)
- MV:FWD forward
- MV:BWD backward
- MV:LEFT strafe left
- MV:RIGHT strafe right
- MV:LF forward-left diagonal
- MV:RF forward-right diagonal
- MV:LB backward-left diagonal
- MV:RB backward-right diagonal
- MV:CW rotate clockwise
- MV:CCW rotate counterclockwise
- MV:STOP stop motion
If current mode is AUTO and you send MV:*:
- car returns FB:MV:0 (rejected)
- upper computer must first send MD:MAN
---
## 4. Telemetry and Feedback (Car -> PC)
### 4.1 Periodic status (every ~500ms)
Payload format:
STAT:SP:xxx,STA:xxx,RUN:x,MODE:mode,MAN:dir,DIS:d,TRK:b4b3b2b1,DEV:n,OBS:x,RPM:m1:m2:m3:m4
Fields:
- SP: speed percent
- STA: target station
- RUN: 1 running, 0 stopped
- MODE: AUTO or MAN
- MAN: STOP/FWD/BWD/LEFT/RIGHT/LF/RF/LB/RB/CW/CCW
- DIS: ultrasonic distance in cm
- TRK: 4-channel line mask, order H4 H3 H2 H1
- DEV: track deviation (auto mode meaningful)
- OBS: obstacle lock (1 blocked, 0 clear)
- RPM: 4 motor RPM, order M1:M2:M3:M4 (LR:LF:RF:RR)
### 4.2 Command feedback (immediate)
Payload format:
FB:<CMD>:<0|1>
Examples:
- FB:SP:1 speed accepted
- FB:GS:0 station invalid or parse fail
- FB:MV:0 movement rejected (for example mode mismatch)
Upper computer rule:
- Every button operation should wait for feedback timeout window
- If no feedback in timeout, mark command uncertain and retry policy applies
---
## 5. Upper Computer Architecture Requirements
AI must implement the upper computer with these modules.
### 5.1 Network module
Responsibilities:
- Maintain TCP connection lifecycle
- Auto reconnect with backoff
- Byte stream receive and frame extraction
Required behavior:
- Reconnect delay: 1s, 2s, 3s, then fixed 3s
- On reconnect success, UI state set to Connected
- On disconnect, all movement buttons should be disabled
### 5.2 Protocol module
Responsibilities:
- Build frames from payload
- Parse incoming frames
- Verify checksum before dispatch
Required behavior:
- Drop frame if checksum invalid
- Log invalid frame raw text for diagnostics
- Expose strongly typed events: StatusEvent, FeedbackEvent
### 5.3 Command dispatcher
Responsibilities:
- Serialize outbound commands (single queue)
- Attach request id locally (not in protocol) for UI correlation
- Wait feedback with timeout
Recommended defaults:
- Feedback timeout: 800 ms
- Max retries for idempotent commands (SP, MD, MV:STOP): 2
- No auto-retry for ST:RUN and GS:xxx unless user confirms
### 5.4 UI module
Required controls:
- Connection: IP, port, connect/disconnect
- Mode: AUTO / MAN toggle
- Speed: slider 0..100 with send button
- Auto controls: station selector (001/002), RUN, STOP
- Manual controls: directional keypad + rotation + STOP
- Status panel: parsed telemetry fields
- Logs panel: TX/RX raw frames + parsed result
### 5.5 Safety guard module
Required safety logic:
- If UI in MAN mode and mouse/touch release on direction button, auto send MV:STOP
- If no fresh status for >2s, show stale warning
- Emergency stop hotkey sends MV:STOP first; if in AUTO also send ST:STOP
---
## 6. Exact Button-to-Command Mapping
All below are complete frames with checksum, directly sendable.
### 6.1 Mode
- Switch to manual: LOGI:MD:MAN:0C#
- Switch to auto: LOGI:MD:AUTO:69#
### 6.2 Speed presets
- 30%: LOGI:SP:030:D5#
- 50%: LOGI:SP:050:D7#
- 80%: LOGI:SP:080:DA#
### 6.3 Auto mode
- Station 001: LOGI:GS:001:CA#
- Station 002: LOGI:GS:002:CB#
- Auto run: LOGI:ST:RUN:3B#
- Auto stop: LOGI:ST:STOP:8C#
### 6.4 Manual movement
- Forward: LOGI:MV:FWD:23#
- Backward: LOGI:MV:BWD:1F#
- Left strafe: LOGI:MV:LEFT:6D#
- Right strafe: LOGI:MV:RIGHT:C0#
- Forward-left: LOGI:MV:LF:D4#
- Forward-right: LOGI:MV:RF:DA#
- Backward-left: LOGI:MV:LB:D0#
- Backward-right: LOGI:MV:RB:D6#
- Rotate CW: LOGI:MV:CW:DC#
- Rotate CCW: LOGI:MV:CCW:1F#
- Stop: LOGI:MV:STOP:88#
---
## 7. Recommended Operation Sequences
### 7.1 Manual driving flow
1. Connect TCP
2. Send SP:xxx
3. Send MD:MAN
4. Hold direction button -> send MV:* repeatedly or once per state change
5. Release button -> send MV:STOP
Recommended send style for manual:
- Edge-triggered (on press send once, on release send stop) is preferred
- If network jitter is high, add keepalive send of same MV every 300 ms
### 7.2 Auto transport flow
1. Connect TCP
2. Send SP:xxx
3. Send MD:AUTO
4. Send GS:001 or GS:002
5. Send ST:RUN
6. Observe RUN and feedback/status until arrival
Arrival behavior in firmware:
- Car auto-stops on target RFID
- RUN becomes 0
- Next run requires sending GS again, then ST:RUN
---
## 8. Frame Parsing Strategy (Stream-safe)
TCP is stream-based, not message-based. AI must implement frame extraction correctly.
Required parser behavior:
- Keep a receive buffer string/byte array
- Search for header "LOGI:"
- Search for tail '#'
- Extract candidate frame from first valid header to first following '#'
- Validate checksum
- Dispatch valid frame; remove consumed bytes
- If garbage before header, discard garbage
Do not assume one recv equals one frame.
---
## 9. Error Handling and Recovery
### 9.1 Feedback timeout
If command has no FB within timeout:
- Mark as timeout in UI
- For safe idempotent commands, retry once or twice
- For movement commands, prefer fail-safe by sending STOP
### 9.2 Checksum mismatch in received data
- Drop frame
- Log as warning with raw text
- Keep connection alive (do not disconnect directly)
### 9.3 Mode conflict
If receiving FB:MV:0 after sending MV command:
- UI should hint: "Not in manual mode, switching to MAN"
- Auto-send MD:MAN then retry once
### 9.4 Connection loss during motion
On disconnect event:
- UI enters safe state
- disable movement controls
- after reconnect, require operator to re-confirm mode and speed
---
## 10. AI Implementation Checklist (Definition of Done)
Functional:
- Can connect/disconnect TCP manually
- Can parse status and feedback reliably
- All buttons send correct command frames
- Manual control works in all listed directions
- Auto mode flow works (GS + RUN + STOP)
Robustness:
- Stream parser handles sticky packets and split packets
- Reconnect works automatically
- Command timeout/retry policy implemented
- Logs include TX/RX and parse errors
Usability:
- Telemetry fields visible and updating
- Mode and direction state clearly shown
- Emergency stop is always accessible
Testing:
- Unit test for checksum build/verify
- Unit test for parser with mixed/fragmented frames
- Integration test with mock TCP server replaying status/feedback
---
## 11. Suggested Prompt for Coding AI
Use this prompt when asking another coding AI to generate the upper computer:
"Implement a production-ready TCP upper computer client for an STM32 logistics car protocol. Use ASCII frame format LOGI:<PAYLOAD>:<CS># with checksum as sum(base bytes) & 0xFF where base is LOGI:<PAYLOAD>. Support commands SP, ST, GS, MD, MV. Parse status payload STAT with fields SP, STA, RUN, MODE, MAN, DIS, TRK, DEV, OBS, RPM. Parse feedback payload FB:<CMD>:<0|1>. Build a stream-safe parser for sticky/fragmented TCP packets. Include reconnect, timeout/retry, and a UI with manual mecanum directional controls and auto mode controls."
---
## 12. Notes for Future Extension
If firmware adds fields later:
- Keep parser tolerant: unknown key-value pairs should not crash parser
- Preserve raw payload in logs for forward compatibility
- Version your app-side parser module (for example v1_2)