# Project export: Vanguard Telematics

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: UC Berkeley AI Hackathon 2026
- Tagline: Fire truck crash? Radio too slow. Rescuers in danger!We build smart tech. Fast sensors feel crash right now. Save the savers fast!
- Devpost: https://devpost.com/software/vanguard-telematics
- GitHub: https://github.com/bencejdanko/VanguardTelematics
- Demo: https://agentverse.ai/agents/details/agent1q05xhz7crc75lwt84v0u78mt2lswwr2a7n0wntp0zpuyedum80m3qwm4rnu/profile
- Video: https://www.youtube.com/embed/6oMx5WiXiPE?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (Best Use of The Agentverse by Fetch AI; Best Use of QNX)
- Team: 4 GitHub contributor(s) — ricsign (30 commits), Angela Xu (18 commits), Bence Danko (17 commits), Claude (2 commits)

## Devpost submission (written by the team)

### Overview

GitHub Link: https://github.com/bencejdanko/VanguardTelematics Public ASI:One Shared Chat Link: https://asi1.ai/invite?channelInviteKey=EUZbyUu8nbYVK2xhekQN3EtGY60i_5mh0dGM9UuKV7I https://asi1.ai/invite?channelInviteKey=5Mb2Ov6_U4rAzxkd5rPNcIdd2zxD5tkx_E99IssFui4 Agentverse Profile: https://agentverse.ai/agents/details/agent1q05xhz7crc75lwt84v0u78mt2lswwr2a7n0wntp0zpuyedum80m3qwm4rnu/profile https://agentverse.ai/agents/details/agent1qgsr563q7gy2y97s4wp8rp3hjw3979xhcdjpnzu3f2vmf4c8pda0jkgsdsv/profile https://agentverse.ai/agents/details/agent1q0sfkv77ye39d8ctsj6rxgzapmulas4lx0ygd8ek2lxuw2ks3p3659kj04g/profile

### Inspiration

82% of U.S. fire departments are all- or mostly-volunteer. Together they protect roughly 30% of the U.S. population — about 100 million people — concentrated in exactly the rural, lower-density areas where cell and radio coverage is weakest. Federal studies have found that communications outages hit within the first 24 hours in more than half of recent major U.S. wildfires. That gap is already being worked on, but not solved. FirstNet is the dominant public-safety connectivity platform and is investing in satellite extension and deployable cell sites — but those are ground-based assets an agency has to request, not something that rides on every truck by default. goTenna Pro/Pro X is real, proven off-grid mesh tech already used by humanitarian responders and law enforcement — it relays a message; it doesn't sense or diagnose anything on its own. We kept circling back to the same question: what happens in the minutes after an incident, before anyone has even picked up a radio? A vehicle that can sense and describe what just happened to it — without needing a human to triage it first — felt like a real, underserved piece of the problem.

### What it does

Our project watches a vehicle's vitals in real time — accelerometer, vibration, temperature, and pressure from an industrial sensor rig, plus a proximity sensor and a camera that feeds live video the moment something gets too close. All of it streams into a live dashboard with a 3D model of the vehicle (we used a model Cybertruck) that visually reacts to the incoming data, so a human can see exactly what the truck is "feeling" at any moment. Underneath that, a custom Fetch.ai multi-agent system watches the same streams and decides, on its own, when something anomalous has actually happened — then generates a free-text, situation-specific description of the event instead of picking from a small, hardcoded list of crash types. The same pipeline is meant to generalize across first-responder vehicle types — an ambulance and a fire engine have very different normal operating signatures, and the system is built to account for that rather than assume one vehicle profile.

### How we built it

On the hardware side: an industrial Nucleo sensor rig feeding accelerometer, vibration, temperature, and pressure data, plus a proximity sensor and camera, all running on a Raspberry Pi 5 under QNX — a real-time OS providing first responders reliability they need. Hence, event detection stays low-latency and deterministic instead of fighting a general-purpose scheduler. Redis sits behind everything as the live telemetry store both the dashboard and the agent pipeline read from. The crash-detection brain is a layered Fetch.ai (uAgents) pipeline. Since we didn't have a pre-built "sentry" crash-detection signal to lean on, the trigger agent had to derive one itself: it keeps a rolling, per-vehicle baseline (mean and standard deviation) for each sensor feature and computes a z-score, $$ z = \frac{x - \mu}{\sigma} $$ flagging an event only when multiple sensors cross threshold together, for several consecutive samples — which filters out single-sensor noise like a pothole or a slammed door while still catching real multi-sensor anomalies. That trigger hands a buffered pre/post-event window to downstream agents, which extract physics features, pull context for the specific vehicle, and feed an LLM-grounded synthesis step that writes an open-ended incident description rather than forcing the event into one of a few fixed categories.

### Challenges we ran into

We originally wanted true off-grid relay — in the spirit of what goTenna does for mesh comms — so the system could report out even with no cell or wifi coverage. We tried wiring a radio link to the Pi 5 and hit a wall on two fronts at once: regulatory limits on unlicensed RF transmission, and practical RF interference that made it unreliable to get clean text through to and from the board. We made the call to descope it for the weekend and treat it as the natural next step rather than a hackathon deliverable. The other real challenge was the crash detector itself. Without an existing crash-detection signal to wrap, we had to build trigger logic from raw sensor physics — and do it in a way that wouldn't quietly bake in assumptions about one specific vehicle or one specific kind of accident. Getting a rolling baseline that adapts per vehicle, instead of a single hardcoded threshold, took more iteration than we expected, especially separating real signal from sensor noise without throwing away genuine events.

### Accomplishments we're proud of

Building a dashboard visualizer that showed us our data is realistic and reliable to actually generate meaningful analytics from. Getting real sensor hardware talking to a real-time OS on actual embedded hardware, end to end, in a weekend. Building an anomaly detector from first principles — rolling baselines and multi-sensor z-scores — instead of a hardcoded if/else crash classifier, paired with a reasoning layer that produces open-ended, vehicle-specific incident descriptions instead of forcing every event into one of three canned labels. And doing the homework before writing code: we went in with real numbers on who this actually affects and a clear-eyed, so we knew what gap we were actually trying to close.

### What we learned

Radio is a much harder problem than "just send a signal" — between licensing and interference, it's a real compliance and RF-engineering problem, not a wiring exercise you can finish in a weekend. We also learned that you can't shortcut crash detection with a single magic threshold number if you actually care about it generalizing across vehicles — you have to understand what a real anomaly looks like across multiple sensors at once, which pushed us toward a statistically grounded approach instead of guessed constants. And splitting the pipeline into agents — deterministic, testable signal processing in one layer, open-ended LLM reasoning in another — made the whole system much easier to debug than one big classifier would have been.

### What's next

Solving off-grid relay properly — likely by pairing with certified mesh hardware like goTenna rather than rolling raw radio from scratch, so we're not fighting licensing and interference ourselves. Real-world impact and drop testing across more vehicle types (ambulance, fire engine) to calibrate the rolling baselines per vehicle class instead of relying on bench simulation. And closing the loop with multi-agent system to gain more meaningful analytics to aide second responders, and inform authorities of the disaster.

## README (from the GitHub repository)

# Vanguard Telematics: UC Berkeley AI Hackathon

### 1st place prize QNX track + honorable mentions @ Fetch AI

*They protect us. Who protects them? This is more than a hackathon idea... Vanguard Telematics is our effort to ensure that those who run toward danger are never left behind in the data silence.*

## Quick Links
- **ASI:One Shared Chat Links:** 
  - [Link 1](https://asi1.ai/invite?channelInviteKey=EUZbyUu8nbYVK2xhekQN3EtGY60i_5mh0dGM9UuKV7I)
  - [Link 2](https://asi1.ai/invite?channelInviteKey=5Mb2Ov6_U4rAzxkd5rPNcIdd2zxD5tkx_E99IssFui4)
- **Agentverse Profiles:** 
  - [Agent 1](https://agentverse.ai/agents/details/agent1q05xhz7crc75lwt84v0u78mt2lswwr2a7n0wntp0zpuyedum80m3qwm4rnu/profile)
  - [Agent 2](https://agentverse.ai/agents/details/agent1qgsr563q7gy2y97s4wp8rp3hjw3979xhcdjpnzu3f2vmf4c8pda0jkgsdsv/profile)
  - [Agent 3](https://agentverse.ai/agents/details/agent1q0sfkv77ye39d8ctsj6rxgzapmulas4lx0ygd8ek2lxuw2ks3p3659kj04g/profile)

## The Blind Spot in Disaster Response (Inspiration)

82% of U.S. fire departments are all- or mostly-volunteer, protecting roughly 100 million people concentrated exactly in the rural, lower-density areas where cell and radio coverage is weakest. Federal studies have found that communications outages hit within the first 24 hours in more than half of recent major U.S. wildfires.

Current solutions fall short:
- **Infrastructure Dependencies:** FirstNet is the dominant public-safety connectivity platform and invests in deployable cell sites—but those are requested ground assets, not native gear riding on every truck by default.
- **Blind Communications Pipes:** Mesh tech like goTenna Pro/Pro X is real, proven off-grid tech used by humanitarian responders. However, it relays messages perfectly but acts solely as a pipe. It doesn't sense or diagnose anomalies on its own.
- **The Operator Dependency:** If an incident occurs and the operator is incapacitated, the best radio network in the world cannot transmit a cry for help.

We kept circling back to the same question: *what happens in the minutes after an incident, before anyone has even picked up a radio?* A vehicle that can sense and describe what just happened to it—without needing a human to triage it first—is a massive, underserved need.

## What It Does: Live 3D Telemetry & Edge Sensing

Our project watches a vehicle's vitals in real time—accelerometer, vibration, temperature, and pressure from an industrial sensor rig, plus a proximity sensor and a camera that feeds live video the moment something gets too close. 

All of it streams into a live dashboard with a 3D model (we used a Cybertruck) that visually reacts to the incoming data. A human supervisor can see exactly what the truck is "feeling" at any exact millisecond, without relying on verbal reports.

Underneath that, a custom Fetch.ai multi-agent system watches the same streams and decides, on its own, when something anomalous has actually happened. It then generates a free-text, situation-specific description of the event instead of picking from a small, hardcoded list of crash types. The pipeline generalizes across first-responder vehicle types, accounting for the very different normal operating signatures of an ambulance versus a fire engine.

## Deterministic Edge Architecture: How We Built It

### Hardware & Real-Time Foundation
- **Raspberry Pi 5 + QNX:** The rig runs under QNX—a real-time OS providing the strict reliability first responders need. Event detection stays low-latency and deterministic instead of fighting a general-purpose scheduler.
- **Industrial Nucleo Rig:** Feeds raw accelerometer, vibration, temperature, and pressure data seamlessly. It processes vehicular physics directly, remaining completely agnostic to specific vehicle CAN buses.
- **Redis Telemetry Store:** Redis sits behind everything as the live, ultra-low latency telemetry store. Both the dashboard visualizer and the downstream agent pipeline read directly from this high-speed memory layer.

### The Crash-Detection Brain
Built as a layered Fetch.ai (uAgents) pipeline. Because we didn't have a pre-built "sentry" crash-detection signal to lean on, the trigger agent had to derive one itself. It maintains a rolling, per-vehicle baseline (mean and standard deviation) for each sensor feature and computes a z-score. It flags an event only when multiple sensors cross the threshold together for several consecutive samples. This filters out single-sensor noise (like a pothole or a slammed door) while catching real multi-sensor anomalies. 

That trigger hands a buffered pre/post-event window to downstream agents, which extract physics features, pull context for the specific vehicle, and feed an LLM-grounded synthesis step that writes an open-ended incident description rather than forcing the event into a few fixed categories.

## Challenges & Technical Realities

- **The Radio Reality:** We originally wanted true off-grid relay—in the spirit of what goTenna does for mesh comms—so the system could report out even with no cell or Wi-Fi coverage. We tried wiring a radio link to the Pi 5 and hit a wall: strict FCC regulatory limits on unlicensed RF and massive practical RF interference made it unreliable to get clean text through to and from the board. We made the call to descope it for the weekend and treat it as a natural next step.
- **Generalized Detection:** Without an existing crash-detection signal to wrap, we had to build trigger logic from raw sensor physics. We wanted to avoid arbitrary thresholds and generalizing events across vehicles. Getting a rolling baseline that adapts per vehicle—separating real multi-sensor signals from noise without missing genuine events—took immense iterations.

## Accomplishments We're Proud Of

- Building a dashboard visualizer that showed our data was realistic and reliable enough to generate meaningful analytics from.
- Getting real sensor hardware talking to a real-time OS on actual embedded hardware, end-to-end, in a single weekend.
- Building an anomaly detector from first principles (rolling baselines and multi-sensor z-scores) instead of a hardcoded if/else crash classifier.
- Pairing deterministic signal processing with a reasoning layer that produces open-ended, vehicle-specific incident descriptions instead of forcing every event into canned labels.
- Doing the homework before writing code: we went in with real numbers on who this actually affects and a clear-eyed view of the gap we were actually trying to close.

## What We Learned

Radio is a much harder problem than "just send a signal"—between licensing and interference, it's a real compliance and RF-engineering problem, not a wiring exercise you can finish in a weekend. We also learned that you can't shortcut crash detection with a single magic threshold number if you actually care about it generalizing across vehicles. You have to understand what a real anomaly looks like across multiple sensors at once, which pushed us toward a statistically grounded approach instead of guessed constants. And splitting the pipeline into agents—deterministic, testable signal processing in one layer, open-ended LLM reasoning in another—made the whole system much easier to debug than one big classifier would have been.

## The Road Ahead

- **Certified Mesh Integration:** Solving off-grid relay properly by pairing our data pipeline with certified mesh hardware like goTenna Pro, rather than fighting licensing constraints and raw RF interference ourselves.
- **Real-World Drop Testing:** Executing physical impact testing across more vehicle types (ambulance, fire engine) to calibrate the rolling baselines per vehicle class instead of relying purely on bench simulation.
- **Analytics Loop:** Closing the loop with the multi-agent system to gain more meaningful macro-analytics to aid second responders, helping inform authorities of shifting disaster zones.

---

## Technical Details

### DataLogFusion Clone
Repurposed from https://www.st.com/en/

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 218 recognized source files, 1359 KB.
- Anthropic (technology) — detected in the code
- C (language) — detected in the code
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Redis (technology) — detected in the code
- TypeScript (language) — detected in the code
- AI coding agent: Claude Code — evidence: config files committed to the repository; commit authorship or trailers
- AI coding agent: Cursor — evidence: config files committed to the repository

## Codebase structure (from repository index)

### Files (120 of 543)

```
.agents/skills/design-taste-frontend/SKILL.md
.agents/skills/frontend-design/SKILL.md
.agents/skills/karpathy-guidelines/examples/EXAMPLES.md
.agents/skills/karpathy-guidelines/SKILL.md
.cursor/rules/karpathy-guidelines.mdc
.gitignore
.mxproject
backend/.gitignore
backend/agent/agent.py
backend/agent/models.py
backend/agent/orchestrator_agent.py
backend/agent/README_ORCHESTRATOR.md
backend/agent/README_SYNTHESIS.md
backend/agent/README.md
backend/agent/register_orchestrator.py
backend/agent/register_synthesis.py
backend/agent/register.py
backend/agent/stripe_horoscope_agent/agent.py
backend/agent/stripe_horoscope_agent/chat_proto.py
backend/agent/stripe_horoscope_agent/client.py
backend/agent/stripe_horoscope_agent/handlers.py
backend/agent/stripe_horoscope_agent/llm.py
backend/agent/stripe_horoscope_agent/payment_proto.py
backend/agent/stripe_horoscope_agent/state.py
backend/agent/stripe_horoscope_agent/stripe_payments.py
backend/agent/synthesis_agent.py
backend/analytics.py
backend/api.py
backend/config.py
backend/load_sample.py
backend/main.py
backend/README.md
backend/requirements.txt
backend/simulator.py
backend/test_detector.py
backend/test_query.py
backend/uagents_core.log
camera-dump-frame-no-screen/.gitignore
camera-dump-frame-no-screen/camera_dump_frame_no_screen.c
camera-dump-frame-no-screen/camera-dump-frame-no-screen.use
camera-dump-frame-no-screen/common.mk
camera-dump-frame-no-screen/LICENSE
camera-dump-frame-no-screen/Makefile
camera-dump-frame-no-screen/nto/aarch64/Makefile
camera-dump-frame-no-screen/nto/aarch64/o.le/Makefile
camera-dump-frame-no-screen/nto/Makefile
camera-dump-frame-no-screen/nto/x86_64/Makefile
camera-dump-frame-no-screen/nto/x86_64/o/Makefile
camera-dump-frame-no-screen/README.md
CLAUDE.md
DataLogFusion.ioc
EWARM/DataLogFusion.ewd
EWARM/DataLogFusion.ewp
EWARM/Project.eww
EWARM/startup_stm32f401xe.s
EWARM/stm32f401xe_flash.icf
EWARM/stm32f401xe_sram.icf
frontend/.eslintrc.cjs
frontend/.gitignore
frontend/index.html
frontend/package.json
frontend/public/cybertruck.glb
frontend/public/sample.csv
frontend/README.md
frontend/src/App.css
frontend/src/App.module.css
frontend/src/App.tsx
frontend/src/components/CybertruckViewer.module.css
frontend/src/components/CybertruckViewer.tsx
frontend/src/components/EmergencyAlert.module.css
frontend/src/components/EmergencyAlert.tsx
frontend/src/components/IncidentPanel.tsx
frontend/src/components/ReportsPage.module.css
frontend/src/components/ReportsPage.tsx
frontend/src/components/TelemetryDashboard.module.css
frontend/src/components/TelemetryDashboard.tsx
frontend/src/components/VehicleList.module.css
frontend/src/components/VehicleList.tsx
frontend/src/config.ts
frontend/src/hooks/useSensorStream.ts
frontend/src/index.css
frontend/src/main.tsx
frontend/src/types.ts
frontend/src/vite-env.d.ts
frontend/tsconfig.json
frontend/tsconfig.node.json
frontend/vite.config.ts
Inc/app_mems.h
Inc/bsp_ip_conf.h
Inc/com.h
Inc/demo_serial.h
Inc/fw_version.h
Inc/iks5a1_conf.h
Inc/iks5a1_mems_control_ex.h
Inc/iks5a1_mems_control.h
Inc/main.h
Inc/motion_fx_manager.h
Inc/RTE_Components.h
Inc/sensor_unicleo_id.h
Inc/serial_cmd.h
Inc/serial_protocol.h
Inc/stm32f4xx_hal_conf.h
Inc/stm32f4xx_it.h
Inc/stm32f4xx_nucleo_bus.h
Inc/stm32f4xx_nucleo_conf.h
Inc/stm32f4xx_nucleo_errno.h
Inc/stm32f4xx_nucleo.h
MDK-ARM/DataLogFusion.uvoptx
MDK-ARM/DataLogFusion.uvprojx
MDK-ARM/startup_stm32f401xe.s
private_keys.json
radio/command_post/agents.py
radio/command_post/dtmf_rx.py
radio/command_post/main.py
radio/command_post/requirements.txt
radio/vehicle/detector.py
radio/vehicle/dtmf_tx.py
radio/vehicle/main.py
radio/vehicle/requirements.txt
Raspberry-Pi-Hardware-Component-Samples/.gitignore
[423 more files omitted for size]
```

### Dependencies

- backend/requirements.txt: deepgram-sdk@==3.4.0, fastapi@>=0.111.0, httpx@>=0.25.0, openai, pyserial@>=3.5, python-dotenv@>=1.0.0, redis@>=5.0.0, sounddevice@>=0.4.6, stripe, uagents, uvicorn[standard]@>=0.30.0
- frontend/package.json: @phosphor-icons/react@^2.1.10, @react-three/drei@^9.122.0, @react-three/fiber@^8.18.0, @types/papaparse@^5.5.2, @types/react@^18.2.37, @types/react-dom@^18.2.15, @types/three@^0.184.1, @typescript-eslint/eslint-plugin@^6.10.0, @typescript-eslint/parser@^6.10.0, @vitejs/plugin-react@^4.2.0, eslint@^8.53.0, eslint-plugin-react-hooks@^4.6.0, eslint-plugin-react-refresh@^0.4.4, lucide-react@^1.21.0, motion@^12.40.0, papaparse@^5.5.4, react@^18.2.0, react-dom@^18.2.0, recharts@^3.8.1, three@^0.184.0, typescript@^5.2.2, vite@^5.0.0
- radio/command_post/requirements.txt: anthropic, httpx, numpy, python-dotenv, sounddevice, uagents
- radio/vehicle/requirements.txt: numpy, python-dotenv, redis

### Recent commits (newest first)

- Update README.md
- update
- Client
- Update agent.py
- update seed
- Payment protocol agent
- Update README.md
- demo video
- videos
- hide inc. panel for now
- fix popup
- fix frontend accelerometer
- fix frontend detection and safe float
- fix rollover detection
- orchestrator
- orchestrator
- [can revert if not working] default hide inc. panel
- [can revert if not working] correct total vehicles count
- [can revert if not working] v1 dispatch status
- rebrand

## Key source files (fetched from GitHub, selected and truncated for size)

### CLAUDE.md

```markdown
# CLAUDE.md

Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.

**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.

## 1. Think Before Coding

**Don't assume. Don't hide confusion. Surface tradeoffs.**

Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.

## 2. Simplicity First

**Minimum code that solves the problem. Nothing speculative.**

- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If you write 200 lines and it could be 50, rewrite it.

Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.

## 3. Surgical Changes

**Touch only what you must. Clean up only your own mess.**

When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.

When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.

The test: Every changed line should trace directly to the user's request.

## 4. Goal-Driven Execution

**Define success criteria. Loop until verified.**

Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"

For multi-step tasks, state a brief plan:
```
1. [Step] → verify: [check]
2. [Step] → verify: [check]
3. [Step] → verify: [check]
```

Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.

---

**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.

```

### redis-stream/README_QNX.md

```markdown
# QNX Streaming to Redis Database

Streams live MEMS sensor data from the STM32 board (connected via USB-serial at
`/dev/serusb1`) to the shared Redis Cloud stream **`/data/mems`** using a
single, dependency-free C program: **`main.c`**.

No external libraries are required — only standard POSIX sockets and termios,
which QNX Neutrino supports natively.

---

## File Overview

| File | Description |
|------|-------------|
| `main.c` | Self-contained C streamer (QNX / any POSIX target) |
| `redis_stream.py` | Python streamer (Windows / Linux / WSL2) |
| `README.md` | General setup notes |
| `README_QNX.md` | This file — QNX-specific build instructions |

---

## Redis Stream Details

| Property | Value |
|----------|-------|
| **Endpoint** | `hospitable-van-guitar-57111.db.redis.io:17434` |
| **Stream key** | `/data/mems` |
| **User** | `default` |
| **Fields per entry** | `ts, acc_x, acc_y, acc_z, gyr_x, gyr_y, gyr_z, mag_x, mag_y, mag_z, press, roll, pitch, yaw` |
| **Protocol** | Raw RESP over TCP (no TLS) |

---

## Detecting the Serial Device on QNX

When the STM32 board is connected via USB, QNX exposes it through a
**USB-serial resource manager** (`devc-serusb`).  Use the steps below to
find the correct device path before running the streamer.

### 1. List available serial devices

```sh
ls /dev/ser*
```

QNX may enumerate the USB-serial adapter as either:
- **`/dev/serusb1`** — when `devc-serusb` creates a dedicated namespace
- **`/dev/ser10`** (or similar number) — when the system `devc-serusb` assigns the next available serial slot

Use whichever path appears. Confirm data is flowing:

```sh
cat /dev/ser10        # adjust number as needed
```

You should see CSV lines scrolling at ~100 Hz. Press `Ctrl+C` to stop.

### 3. If no device appears — start the USB-serial driver

QNX does not always auto-start `devc-serusb`.  Start it manually:

```sh
chmod +x devc-serusb
devc-serusb &
```

Then re-check `ls /dev/serusb*`.  On some QNX images the driver is
`devc-serusb2` or needs a specific USB path argument — check your BSP docs.

### 4. Pass the device to the streamer

```sh
# Use the detected device (default is already /dev/serusb1)
./mems_stream /dev/serusb1

# If enumerated as serusb2, serusb3, etc.
./mems_stream /dev/serusb2
```

---

## Building on QNX (native compile on the target)

If your QNX image includes a C compiler (`cc`):

```sh
# first on host machine copy over

scp -o MACs=hmac-sha2-256 main.c qnxuser@172.20.10.7:/data/home/qnxuser

# On the QNX Raspberry Pi target
cc -o mems_stream main.c -lsocket
```
# Default: /dev/serusb1 @ 115200 baud
./mems_stream

# Override serial device
./mems_stream /dev/serusb2
```

The program prints a startup banner and then logs a line every 10 samples
(~100 ms at 100 Hz):

```
==================================================
 STM32 MEMS → Redis Streamer  (QNX / C)
==================================================
Serial device : /dev/serusb1  @ 115200 baud
Redis endpoint: hospitable-van-guitar-
[truncated — 669 more characters]
```

### backend/requirements.txt

```
fastapi>=0.111.0
uvicorn[standard]>=0.30.0
redis>=5.0.0
python-dotenv>=1.0.0

# Producer (serial → Redis, run separately when STM32 board is connected)
pyserial>=3.5
deepgram-sdk==3.4.0
httpx>=0.25.0
uagents
openai
sounddevice>=0.4.6
stripe

```

### frontend/package.json

```
{
  "name": "frontend",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@phosphor-icons/react": "^2.1.10",
    "@react-three/drei": "^9.122.0",
    "@react-three/fiber": "^8.18.0",
    "lucide-react": "^1.21.0",
    "motion": "^12.40.0",
    "papaparse": "^5.5.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "recharts": "^3.8.1",
    "three": "^0.184.0"
  },
  "devDependencies": {
    "@types/papaparse": "^5.5.2",
    "@types/react": "^18.2.37",
    "@types/react-dom": "^18.2.15",
    "@types/three": "^0.184.1",
    "@typescript-eslint/eslint-plugin": "^6.10.0",
    "@typescript-eslint/parser": "^6.10.0",
    "@vitejs/plugin-react": "^4.2.0",
    "eslint": "^8.53.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.4",
    "typescript": "^5.2.2",
    "vite": "^5.0.0"
  }
}

```

### radio/vehicle/requirements.txt

```
redis
numpy
python-dotenv

```

### radio/command_post/requirements.txt

```
sounddevice
numpy
uagents
anthropic
httpx
python-dotenv

```

### backend/main.py

```python
"""
main.py
-------
Vanguard Telematics Backend — Entry Point

Runs the consumer API server (FastAPI + uvicorn).
The API reads live data from Redis Cloud and serves it to the dashboard.

Usage:
  python main.py
  # or directly:
  uvicorn api:app --host 0.0.0.0 --port 8000 --reload
"""

import os
import uvicorn
from config import API_HOST, API_PORT

if __name__ == "__main__":
    host = API_HOST
    port = API_PORT

    print(f"Starting Vanguard Telematics API on http://{host}:{port}")
    print("  GET /health    — Redis health check")
    print("  GET /latest    — latest sensor snapshot")
    print("  GET /history   — recent readings")
    print("  GET /stream    — live SSE feed")

    uvicorn.run("api:app", host=host, port=port, reload=False, log_level="info")

```

### frontend/src/main.tsx

```typescript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

```

### radio/vehicle/main.py

```python
from detector import run as watch
from dtmf_tx import transmit

EVENT_NAMES = {
    '1': 'ROLLOVER',
    '2': 'HARD IMPACT',
    '3': 'SUSTAINED TILT',
    '4': 'SPIN-OUT',
    '5': 'AIRBORNE',
    '6': 'POST-CRASH STILLNESS',
}


def on_event(event_type: str) -> None:
    print(f"[ALERT] {EVENT_NAMES[event_type]} detected → transmitting *{event_type}#")
    transmit(event_type)


if __name__ == "__main__":
    print("Vehicle detector running. Watching Redis stream...")
    watch(on_event)

```

### radio/command_post/main.py

```python
"""
Command post entry point.
Starts the fetch.ai agent bureau in a background thread, then blocks on DTMF mic input.
"""
import threading
import time

from agents import bureau, dispatch
from dtmf_rx import listen


def on_dtmf(event_type: str) -> None:
    print(f"[RX] DTMF decoded → event_type={event_type}")
    dispatch(event_type)   # puts into queue, picked up by MonitorAgent on next poll


if __name__ == "__main__":
    threading.Thread(target=bureau.run, daemon=True).start()
    time.sleep(2)          # let agents register before mic input starts
    print("[RX] Command post ready. Agents running.")
    listen(on_dtmf)        # blocks forever on mic input

```

[168 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]