Central Intelligence Hub for the Herd-Link Dairy Monitoring System.
This Rust-based service runs on a Raspberry Pi 5 (or similar edge server). It acts as the brain of the operation, receiving high-frequency telemetry from ESP32-C3 Smart Collars, processing behavior analytics in real-time, and serving insights to mobile applications via a REST API.
Uses physics-based heuristics on 6-axis IMU data to classify cow states instantly:
- Grazing: Head down (Horizontal) + Moderate rhythmic movement.
- Rumination (Chewing Cud): Low body movement + High rhythmic head motion (Gyro Variance).
- Lying: Head down (Horizontal) + Stillness.
- Standing (Loafing): Head up (Vertical) + Stillness.
- Walking: Head up + High activity (Jerk).
- Estrus (In Heat): Sustained High Activity + Elevated Body Temperature (>39°C).
- Alert High Activity: Panic/thrashing detected via motion interrupt or extreme jerk.
- Alert Low Activity: Detecting isolated "still" cows while the herd is active (Lameness/Sickness).
- Unknown State: Sensor error flag (
err == 1) received from firmware. - State Smoothing: Eliminates flickering via a majority vote across the last 5 received packets (most frequent state wins).
Full details on veterinary logic: Health & Behavior Insights
- Fever Detection: Automatic flagging of illness (
fever: true) when Body Temp > Threshold (Dynamic based on Herd Average) without exercise. - Mastitis Risk: Intelligent calculation (Fever + Low Rumination = High Risk).
- Auto-Cleanup: Runs hourly to prevent disk overflow.
- Priority Deletion: When disk usage > 85%, the system automatically prunes bulky raw data (Audio/IMU logs) older than 7 days while preserving critical health insights and state history.
- Collaborative Filtering: Compares individual cow data against the Herd Average.
- Dynamic Thresholds: Automatically adjusts fever thresholds on hot days to prevent false alarms.
- Behavioral Baselines: Tracks 7-day rolling averages for each cow.
- Hyperactivity: Detects Estrus if activity > 3x individual baseline (even if absolute threshold isn't met).
- Hypoactivity: Detects Lameness/Isolation if activity drops when the herd is active.
- Estrus Reliability Score: Improves detection accuracy by tracking cycles.
- High Confidence (95%): If a new Estrus alert occurs 18-24 days after a previous one (typical cycle).
- Low Confidence (50%): First occurrence or irregular timing.
- Daily Lameness Scoring: Comparison of individual walking time vs. Herd Average.
- Score 0 (Normal): Walking within normal range of herd.
- Score 2 (Mild): Walking < 50% of Herd Average.
- Score 3 (Severe): Walking < 20% of Herd Average (High risk of isolation/injury).
- Bloat / Acute Pain: Detects panic thrashing without fever (
jerk > 40,gy_var > 15,!fever— using dynamic threshold 39.5°C or 40.0°C depending on herd average). - Respiratory Disease (BRD): Placeholder for AI-based Cough Detection + Fever correlation.
- Heat Stress (THI): Automatically calculates the Temperature-Humidity Index (NRC Formula) using ambient sensor data.
- Cough & Distress Monitoring: Supports storage of Audio Fingerprints (MFCCs) sent by collars.
- Privacy & Bandwidth: Stores mathematical feature arrays (BLOBs) instead of raw audio, enabling privacy-preserving AI analysis for respiratory health.
- Sensor Health: Monitors Battery Voltage (
vbat) and Wi-Fi Signal Strength (rssi) for every device. - Dead Zone Mapping: Use RSSI data to find Wi-Fi dead spots in the barn.
Alerts Logic: Alerts Documentation
- Historical Trends: Daily aggregation of health stats (Avg Temp, Total Lying Time, etc.).
- Active Alerts: Real-time generation of alerts for Fever, Heat Stress, and Bloat.
- Cow Registry: Map Device IDs (MAC Addresses) to Cow Names/Breeds.
- Farm Isolation: Each node generates a unique Farm UUID upon setup to differentiate data in future cloud exports.
- API Authentication: All operational endpoints are secured via
Authorization: Bearer <KEY>. - Claiming Flow: First-time setup requires the farmer to "Claim" the node via the app, generating a permanent API Key.
- Hybrid Architecture: The node functions as an Edge Server, processing raw data locally.
- Aggregated Sync: Automatically pushes "Insights" (Daily Stats & Alerts) to a central Supabase database every 60 seconds.
- Resilience: Buffers data locally if internet is lost, ensuring zero data loss during outages.
- Global Access: Enables the mobile app to fetch farm status from anywhere in the world via the cloud, bypassing CGNAT issues.
- For Firmware Developers: ESP32 Firmware Guide - Detailed protocol and sensor requirements.
- For Mobile App Developers: Mobile App Integration Guide - API usage, data visualization, and alerts.
Data Flow Diagram: Data Flow & Models Cloud Strategy: Hybrid Cloud & Scaling
- Sensors (ESP32-C3): Wake-on-Motion -> Record IMU/Audio -> Send UDP Packet -> Deep Sleep.
- Ingestion (UDP 4210): High-performance asynchronous listener (Tokio) receives packets.
- Processing (Rust):
- Deserializes JSON.
- Calculates THI, Fever, Mastitis Risk, Bloat Risk, and Behavior State.
- Updates
telemetry_v7SQLite database. - Triggers Alerts if thresholds are breached.
- Cloud Sync (Push): Background service uploads aggregated data to Supabase.
- API (HTTP 3000): Axum web server exposes data to mobile apps.
Note: All endpoints (except Status, Setup, and Login) require the header Authorization: Bearer <YOUR_API_KEY>.
POST /api/setup
Claim a new node. Payload: { "farm_name": "...", "password": "..." }. Returns { "token": "..." }.
POST /api/login
Retrieve API Key. Payload: { "password": "..." }.
GET /api/telemetry?limit=50
Returns the most recent records with full analytics.
GET /api/cows
Returns all registered cows.
POST /api/cows/register
Register or update a cow profile.
{
"device_id": "A1:B2:C3:D4:E5:F6",
"name": "Bessie",
"breed": "Holstein",
"age_years": 4,
"notes": "History of mastitis"
}GET /api/alerts
Returns a list of currently active health alerts.
POST /api/alerts/:id/resolve
Marks an alert as resolved (inactive).
GET /api/stats/daily?date=YYYY-MM-DD
Returns summarized data for all cows on a specific date.
GET /api/status
Returns "Herd-Link Node Online".
- Rust (Cargo) installed.
- SQLite (bundled).
# Start the server (Listens on UDP 4210 & TCP 3000)
cargo runThe system stores all data in herdlink.db.
High-frequency raw data and comprehensive analytics.
| Field | Type | Description |
|---|---|---|
id |
INTEGER | Unique Record ID (Primary Key) |
device_id |
TEXT | MAC Address of Collar |
esp_timestamp |
INTEGER | Original timestamp from ESP32 |
state |
TEXT | Grazing, Rumination, Lying, Standing, Walking, Estrus, AlertHighActivity, AlertLowActivity, UnknownState |
body_temp |
REAL | Body Temp (°C) |
env_temp |
REAL | Barn Temp (°C) |
env_hum |
REAL | Barn Humidity (%) |
thi |
REAL | Temperature-Humidity Index (Heat Stress) |
fever |
BOOLEAN | Fever flag (0/1) |
mastitis_risk |
INTEGER | Mastitis Risk Score (0-100) |
lameness_score |
INTEGER | Lameness Severity Score (0=Normal, 1=Subtle, 2=Mild, 3=Warning/Alert) |
calving_flag |
BOOLEAN | Potential calving detection |
brd_risk |
INTEGER | Respiratory Disease Risk (0-100) |
bloat_risk |
INTEGER | Bloat Risk Score (0-100) |
jerk |
REAL | Motion Intensity |
ax, ay, az |
REAL | 3-axis Accelerometer data |
gx, gy, gz |
REAL | 3-axis Gyroscope data |
gy_var |
REAL | Gyroscope pitch-axis variance (key for Rumination detection) |
seq |
INTEGER | Packet sequence number |
mot_int |
INTEGER | Motion intensity (raw) |
err |
INTEGER | Error codes from firmware |
vbat |
REAL | Battery Voltage (V) |
rssi |
INTEGER | Wi-Fi Signal Strength (dBm) |
audio_features |
TEXT | MFCC JSON Array |
herd_temp |
REAL | Live Herd Average Temp at time of packet |
server_timestamp |
DATETIME | Server-side ingestion time |
Aggregated historical health and behavior data.
| Field | Type | Description |
|---|---|---|
id |
INTEGER | Unique Record ID (Primary Key) |
date |
TEXT | ISO Date (YYYY-MM-DD) |
device_id |
TEXT | MAC Address |
avg_temp |
REAL | Average Daily Body Temp |
min_temp |
REAL | Minimum Daily Body Temp |
max_temp |
REAL | Maximum Daily Body Temp |
total_rumination |
INTEGER | Total minutes spent ruminating |
total_lying |
INTEGER | Total minutes spent lying |
total_walking |
INTEGER | Total minutes spent walking |
avg_thi |
REAL | Average daily Heat Stress Index |
alerts_count |
INTEGER | Total alerts triggered for the day |
lameness_score |
INTEGER | Daily Lameness Score (0=Normal, 2=Mild, 3=Severe) |
estrus_confidence |
INTEGER | Reliability of Estrus detection (0-100%) |
Active health warnings and notification history.
| Field | Type | Description |
|---|---|---|
id |
INTEGER | Alert ID |
device_id |
TEXT | MAC Address |
alert_type |
TEXT | "Fever", "Bloat", "Heat Stress", etc. |
message |
TEXT | Human-readable details |
is_active |
BOOLEAN | True (1) if unresolved |
timestamp |
DATETIME | Time of alert generation |
Identity and profile registry.
| Field | Type | Description |
|---|---|---|
device_id |
TEXT | MAC Address (Primary Key) |
name |
TEXT | Cow Name/Identifier |
breed |
TEXT | Breed |
age_years |
INTEGER | Age |
notes |
TEXT | Veterinary or behavioral notes |
last_seen |
DATETIME | Last packet received from this device |
Stores farm identity and security credentials (Single Row).
| Field | Type | Description |
|---|---|---|
id |
INTEGER | Primary Key (Always 1) |
farm_name |
TEXT | Human-readable name |
farm_uuid |
TEXT | Unique Farm ID for data export |
api_key |
TEXT | Bearer Token for API access |
password |
TEXT | Password for adding new devices |