from fastapi import APIRouter, WebSocket, WebSocketDisconnect
Browse filesfrom fastapi import HTTPException
import time, uuid
router = APIRouter()
# In-memory registry (swap to Redis/DB in prod)
DEVICES = {} # device_id -> {type, battery, last_seen, session_id}
SESSIONS = {} # session_id -> {"created_at": ts, "device_id": Optional[str], "telemetry": []}
CLIENTS = {} # session_id -> set(WebSocket)
def now() -> int:
return int(time.time())
@router .get("/status")
async def status():
connected = sum(1 for d in DEVICES.values() if d.get("last_seen",0) > now()-120)
return {
"connected": connected,
"devices": [
dict(id=dev_id, **data) for dev_id, data in DEVICES.items()
],
"sessions": list(SESSIONS.keys())
}
@router .post("/session")
async def create_session():
sid = uuid.uuid4().hex
SESSIONS[sid] = {"created_at": now(), "device_id": None, "telemetry": []}
return {"session_id": sid, "session_url": f"https://xr.agrosynth.local/pair/{sid}"}
@router .post("/bind")
async def bind_device(session_id: str, device_id: str, device_type: str = "AR Glasses"):
if session_id not in SESSIONS:
raise HTTPException(404, "session not found")
SESSIONS[session_id]["device_id"] = device_id
DEVICES[device_id] = {
"type": device_type, "battery": 100, "last_seen": now(), "session_id": session_id
}
return {"ok": True}
@router .websocket("/ws/{session_id}")
async def ws(session: WebSocket, session_id: str):
if session_id not in SESSIONS:
await session.close(code=1008)
return
await session.accept()
CLIENTS.setdefault(session_id, set()).add(session)
try:
while True:
msg = await session.receive_json()
# Expected message shapes:
# {"kind":"hello","device_id":"rb-123","device_type":"AR Glasses"}
# {"kind":"telemetry","device_id":"rb-123","battery":88,"pose":{"lat":..,"lon":..}}
# {"kind":"event","device_id":"rb-123","name":"capture","data":{...}}
k = msg.get("kind")
if k == "hello":
dev_id = msg.get("device_id") or f"dev-{uuid.uuid4().hex[:6]}"
DEVICES[dev_id] = {
"type": msg.get("device_type","AR Glasses"),
"battery": msg.get("battery",100),
"last_seen": now(),
"session_id": session_id
}
SESSIONS[session_id]["device_id"] = dev_id
await broadcast(session_id, {"kind":"system","message":f"{dev_id} connected"})
elif k == "telemetry":
dev_id = msg.get("device_id")
if dev_id:
d = DEVICES.setdefault(dev_id, {"type":"Unknown","battery":0,"last_seen":0,"session_id":session_id})
d["battery"] = msg.get("battery", d["battery"])
d["last_seen"] = now()
payload = {"ts": now(), "data": msg}
SESSIONS[session_id]["telemetry"].append(payload)
await broadcast(session_id, {"kind":"telemetry","payload":payload})
elif k == "event":
await broadcast(session_id, {"kind":"event","payload":msg})
else:
await broadcast(session_id, {"kind":"echo","payload":msg})
except WebSocketDisconnect:
pass
finally:
CLIENTS[session_id].discard(session)
if not CLIENTS[session_id]:
CLIENTS.pop(session_id, None)
async def broadcast(session_id: str, message: dict):
for ws in list(CLIENTS.get(session_id, set())):
try:
await ws.send_json(message)
except Exception:
CLIENTS[session_id].discard(ws)
from .routers import xr
app.include_router(xr.router, prefix="/api/v1/xr", tags=["xr"])
"use client";
import { useEffect, useRef, useState } from "react";
import { QRCodeCanvas } from "qrcode.react";
type XRStatus = {
connected: number;
devices: Array<{ id: string; type: string; battery: number; last_seen?: number; session_id?: string }>;
sessions: string[];
};
export default function XRToolsPage() {
const [status, setStatus] = useState<XRStatus | null>(null);
const [session, setSession] = useState<{ session_id: string; session_url: string } | null>(null);
const [events, setEvents] = useState<string[]>([]);
const wsRef = useRef<WebSocket | null>(null);
async function loadStatus() {
const r = await fetch("/api/proxy/api/v1/xr/status", { cache: "no-store" });
setStatus(await r.json());
}
async function createSession() {
const r = await fetch("/api/proxy/api/v1/xr/session", { method: "POST" });
const j = await r.json();
setSession(j);
// open websocket
const url = (process.env.NEXT_PUBLIC_WS || "ws://localhost:8000").replace(/\/+$/,"");
const ws = new WebSocket(`${url}/api/v1/xr/ws/${j.session_id}`);
ws.onmessage = evt => {
setEvents(e => [`${new Date().toLocaleTimeString()} ${evt.data}`, ...e].slice(0,100));
};
ws.onopen = () => setEvents(e => [`${new Date().toLocaleTimeString()} [ws] connected`, ...e]);
ws.onclose = () => setEvents(e => [`${new Date().toLocaleTimeString()} [ws] closed`, ...e]);
wsRef.current = ws;
}
useEffect(() => { loadStatus(); const t = setInterval(loadStatus, 4000); return () => clearInterval(t); }, []);
return (
<div>
<h1 className="text-2xl font-semibold mb-4">XR Tools</h1>
<div className="grid md:grid-cols-3 gap-6">
<div className="border rounded-xl p-4">
<div className="font-semibold mb-2">Device Status</div>
<pre className="text-xs bg-gray-50 p-3 rounded h-64 overflow-auto">{JSON.stringify(status, null, 2)}</pre>
<button onClick={loadStatus} className="mt-3 px-3 py-2 rounded border">Refresh</button>
</div>
<div className="border rounded-xl p-4">
<div className="font-semibold mb-2">Pair a Device</div>
<button onClick={createSession} className="px-4 py-2 rounded bg-black text-white">Generate Session</button>
{session && (
<div className="mt-4 flex gap-4 items-center">
<QRCodeCanvas value={session.session_url} size={160} />
<div className="text-sm">
Scan with your Meta Ray-Ban companion phone browser or any mobile camera.<br/>
<a className="text-blue-600 underline" href={session.session_url} target="_blank">{session.session_url}</a>
<div className="mt-2 text-xs text-gray-500">
WebSocket: <code>/api/v1/xr/ws/{session.session_id}</code>
</div>
</div>
</div>
)}
</div>
<div className="border rounded-xl p-4">
<div className="font-semibold mb-2">Live Telemetry / Events</div>
<div className="text-xs bg-gray-50 p-3 rounded h-64 overflow-auto whitespace-pre-wrap">
{events.map((e, i) => <div key={i}>{e}</div>)}
</div>
</div>
</div>
<div className="border rounded-xl p-4 mt-6">
<div className="font-semibold mb-2">Device Simulator</div>
<p className="text-sm text-gray-500">Open the simulator to send telemetry without hardware.</p>
<a className="inline-block mt-2 px-3 py-2 rounded border" href="/xr-tools/dev-simulator" target="_blank">Open Simulator</a>
</div>
</div>
);
}
pnpm add qrcode.react
"use client";
import { useEffect, useState } from "react";
export default function PairPage({ params }: { params: { sid: string } }) {
const [deviceId, setDeviceId] = useState<string>("");
const [status, setStatus] = useState<string>("");
async function bind() {
if (!deviceId) { setStatus("Enter a device id"); return; }
const body = new URLSearchParams({ session_id: params.sid, device_id: deviceId, device_type: "AR Glasses" });
const r = await fetch("/api/proxy/api/v1/xr/bind", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body });
setStatus(r.ok ? "Paired!" : `Error ${r.status}`);
}
// Optional: send a hello on websocket immediately after pairing using fetch + server WS will see telemetry later via simulator/app.
useEffect(()=>{ setDeviceId(`rb-${Math.random().toString(36).slice(2,8)}`); },[]);
return (
<div className="max-w-md mx-auto p-6">
<h1 className="text-2xl font-semibold">Pair Device</h1>
<p className="text-sm text-gray-600 mt-1">Session: <code>{params.sid}</code></p>
<label className="block text-sm mt-4">Device ID</label>
<input className="border rounded w-full p-2" value={deviceId} onChange={e=>setDeviceId(e.target.value)} />
<button onClick={bind} className="mt-3 px-4 py-2 rounded bg-black text-white">Bind</button>
{status && <div className="text-sm mt-2">{status}</div>}
<div className="text-xs text-gray-500 mt-4">
After pairing, your device or mobile app should connect to the session WebSocket to stream telemetry.
</div>
</div>
);
}
"use client";
import { useEffect, useRef, useState } from "react";
export default function DevSimulator() {
const [sessionId, setSessionId] = useState("");
const [deviceId, setDeviceId] = useState(`rb-${Math.random().toString(36).slice(2,8)}`);
const [battery, setBattery] = useState(92);
const [log, setLog] = useState<string[]>([]);
const wsRef = useRef<WebSocket|null>(null);
function pushLog(s:string){ setLog(l => [`${new Date().toLocaleTimeString()} ${s}`, ...l].slice(0,100)); }
function connect() {
if(!sessionId) { pushLog("Enter session id"); return; }
const url = (process.env.NEXT_PUBLIC_WS || "ws://localhost:8000").replace(/\/+$/,"");
const ws = new WebSocket(`${url}/api/v1/xr/ws/${sessionId}`);
ws.onopen = () => {
pushLog("[ws] open");
ws.send(JSON.stringify({ kind:"hello", device_id: deviceId, device_type: "AR Glasses", battery }));
};
ws.onmessage = (e) => pushLog(`<- ${e.data}`);
ws.onclose = () => pushLog("[ws] closed");
ws.onerror = (e) => pushLog(`[ws] error ${String(e)}`);
wsRef.current = ws;
}
function sendTelemetry() {
const ws = wsRef.current;
- analytics.html +274 -0
- dashboard.html +1 -1
- field-maps.html +1 -1
- prompts.txt +740 -0
|
@@ -0,0 +1,274 @@
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>Analytics - Agrosynth OS</title>
|
| 7 |
+
<script src="https://cdn.tailwindcss.com"></script>
|
| 8 |
+
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
| 9 |
+
<script src="https://unpkg.com/feather-icons"></script>
|
| 10 |
+
<style>
|
| 11 |
+
.chart-container {
|
| 12 |
+
height: 300px;
|
| 13 |
+
}
|
| 14 |
+
</style>
|
| 15 |
+
</head>
|
| 16 |
+
<body class="bg-gray-50 font-sans antialiased">
|
| 17 |
+
<div class="flex h-screen overflow-hidden">
|
| 18 |
+
<!-- Sidebar -->
|
| 19 |
+
<div class="bg-white shadow-md w-64 flex flex-col">
|
| 20 |
+
<div class="flex items-center justify-center h-16 px-4 border-b">
|
| 21 |
+
<div class="flex items-center">
|
| 22 |
+
<i data-feather="layers" class="text-green-600 h-6 w-6"></i>
|
| 23 |
+
<span class="ml-2 text-lg font-bold text-gray-900">Agrosynth OS</span>
|
| 24 |
+
</div>
|
| 25 |
+
</div>
|
| 26 |
+
<nav class="flex-1 overflow-y-auto py-4">
|
| 27 |
+
<div class="px-4 space-y-1">
|
| 28 |
+
<a href="/dashboard" class="flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900">
|
| 29 |
+
<i data-feather="home" class="text-gray-500 h-5 w-5"></i>
|
| 30 |
+
<span class="ml-3">Dashboard</span>
|
| 31 |
+
</a>
|
| 32 |
+
<a href="/field-maps" class="flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900">
|
| 33 |
+
<i data-feather="map" class="text-gray-500 h-5 w-5"></i>
|
| 34 |
+
<span class="ml-3">Field Maps</span>
|
| 35 |
+
</a>
|
| 36 |
+
<a href="/analytics" class="flex items-center px-2 py-2 text-sm font-medium rounded-md bg-green-50 text-green-700">
|
| 37 |
+
<i data-feather="activity" class="text-green-600 h-5 w-5"></i>
|
| 38 |
+
<span class="ml-3">Analytics</span>
|
| 39 |
+
</a>
|
| 40 |
+
</div>
|
| 41 |
+
</nav>
|
| 42 |
+
</div>
|
| 43 |
+
|
| 44 |
+
<!-- Main content -->
|
| 45 |
+
<div class="flex-1 overflow-auto">
|
| 46 |
+
<header class="bg-white shadow-sm">
|
| 47 |
+
<div class="flex justify-between items-center px-4 py-4 sm:px-6">
|
| 48 |
+
<h1 class="text-xl font-semibold text-gray-900">Analytics</h1>
|
| 49 |
+
</div>
|
| 50 |
+
</header>
|
| 51 |
+
|
| 52 |
+
<main class="p-4 sm:p-6">
|
| 53 |
+
<div id="analytics-container">
|
| 54 |
+
<div class="rounded-xl border p-6 text-sm text-gray-500">Loading analytics...</div>
|
| 55 |
+
</div>
|
| 56 |
+
</main>
|
| 57 |
+
</div>
|
| 58 |
+
</div>
|
| 59 |
+
|
| 60 |
+
<script>
|
| 61 |
+
feather.replace();
|
| 62 |
+
|
| 63 |
+
// Fetch analytics data with error handling
|
| 64 |
+
(async () => {
|
| 65 |
+
try {
|
| 66 |
+
const r = await fetch('/api/proxy/api/v1/farms/analytics');
|
| 67 |
+
const text = await r.text();
|
| 68 |
+
const data = JSON.parse(text);
|
| 69 |
+
const container = document.getElementById('analytics-container');
|
| 70 |
+
|
| 71 |
+
container.innerHTML = `
|
| 72 |
+
<h1 class="text-2xl font-semibold mb-4">Analytics</h1>
|
| 73 |
+
<div class="grid md:grid-cols-2 gap-6">
|
| 74 |
+
<div class="border rounded-xl p-4">
|
| 75 |
+
<div class="font-semibold mb-2">Yield Trend (t/ha)</div>
|
| 76 |
+
<div class="chart-container">
|
| 77 |
+
<canvas id="yieldChart"></canvas>
|
| 78 |
+
</div>
|
| 79 |
+
</div>
|
| 80 |
+
<div class="border rounded-xl p-4">
|
| 81 |
+
<div class="font-semibold mb-2">Soil Moisture (%)</div>
|
| 82 |
+
<div class="chart-container">
|
| 83 |
+
<canvas id="moistureChart"></canvas>
|
| 84 |
+
</div>
|
| 85 |
+
</div>
|
| 86 |
+
</div>
|
| 87 |
+
`;
|
| 88 |
+
|
| 89 |
+
// Yield Chart
|
| 90 |
+
const yieldCtx = document.getElementById('yieldChart').getContext('2d');
|
| 91 |
+
new Chart(yieldCtx, {
|
| 92 |
+
type: 'line',
|
| 93 |
+
data: {
|
| 94 |
+
labels: data.yield.labels,
|
| 95 |
+
datasets: [{
|
| 96 |
+
label: 'Yield (t/ha)',
|
| 97 |
+
data: data.yield.values,
|
| 98 |
+
borderColor: '#22c55e',
|
| 99 |
+
backgroundColor: 'rgba(34, 197, 94, 0.1)',
|
| 100 |
+
borderWidth: 2,
|
| 101 |
+
tension: 0.4,
|
| 102 |
+
fill: true
|
| 103 |
+
}]
|
| 104 |
+
},
|
| 105 |
+
options: {
|
| 106 |
+
responsive: true,
|
| 107 |
+
maintainAspectRatio: false,
|
| 108 |
+
plugins: {
|
| 109 |
+
legend: { display: false },
|
| 110 |
+
tooltip: {
|
| 111 |
+
callbacks: {
|
| 112 |
+
label: (context) => `${context.dataset.label}: ${context.parsed.y} t/ha`
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
},
|
| 116 |
+
scales: {
|
| 117 |
+
y: {
|
| 118 |
+
beginAtZero: false,
|
| 119 |
+
min: Math.min(...data.yield.values) - 0.5,
|
| 120 |
+
max: Math.max(...data.yield.values) + 0.5
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
// Moisture Chart
|
| 127 |
+
const moistureCtx = document.getElementById('moistureChart').getContext('2d');
|
| 128 |
+
new Chart(moistureCtx, {
|
| 129 |
+
type: 'line',
|
| 130 |
+
data: {
|
| 131 |
+
labels: data.moisture.labels,
|
| 132 |
+
datasets: [{
|
| 133 |
+
label: 'Soil Moisture (%)',
|
| 134 |
+
data: data.moisture.values,
|
| 135 |
+
borderColor: '#3b82f6',
|
| 136 |
+
backgroundColor: 'rgba(59, 130, 246, 0.1)',
|
| 137 |
+
borderWidth: 2,
|
| 138 |
+
tension: 0.4,
|
| 139 |
+
fill: true
|
| 140 |
+
}]
|
| 141 |
+
},
|
| 142 |
+
options: {
|
| 143 |
+
responsive: true,
|
| 144 |
+
maintainAspectRatio: false,
|
| 145 |
+
plugins: {
|
| 146 |
+
legend: { display: false },
|
| 147 |
+
tooltip: {
|
| 148 |
+
callbacks: {
|
| 149 |
+
label: (context) => `${context.dataset.label}: ${context.parsed.y}%`
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
},
|
| 153 |
+
scales: {
|
| 154 |
+
y: {
|
| 155 |
+
beginAtZero: false,
|
| 156 |
+
min: Math.min(...data.moisture.values) - 5,
|
| 157 |
+
max: Math.max(...data.moisture.values) + 5
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
});
|
| 162 |
+
})
|
| 163 |
+
// Render charts with the data
|
| 164 |
+
const container = document.getElementById('analytics-container');
|
| 165 |
+
container.innerHTML = `
|
| 166 |
+
<h1 class="text-2xl font-semibold mb-4">Analytics</h1>
|
| 167 |
+
<div class="grid md:grid-cols-2 gap-6">
|
| 168 |
+
<div class="border rounded-xl p-4">
|
| 169 |
+
<div class="font-semibold mb-2">Yield Trend (t/ha)</div>
|
| 170 |
+
<div class="chart-container">
|
| 171 |
+
<canvas id="yieldChart"></canvas>
|
| 172 |
+
</div>
|
| 173 |
+
</div>
|
| 174 |
+
<div class="border rounded-xl p-4">
|
| 175 |
+
<div class="font-semibold mb-2">Soil Moisture (%)</div>
|
| 176 |
+
<div class="chart-container">
|
| 177 |
+
<canvas id="moistureChart"></canvas>
|
| 178 |
+
</div>
|
| 179 |
+
</div>
|
| 180 |
+
</div>
|
| 181 |
+
`;
|
| 182 |
+
|
| 183 |
+
// Yield Chart
|
| 184 |
+
const yieldCtx = document.getElementById('yieldChart').getContext('2d');
|
| 185 |
+
new Chart(yieldCtx, {
|
| 186 |
+
type: 'line',
|
| 187 |
+
data: {
|
| 188 |
+
labels: data.yield.labels,
|
| 189 |
+
datasets: [{
|
| 190 |
+
label: 'Yield (t/ha)',
|
| 191 |
+
data: data.yield.values,
|
| 192 |
+
borderColor: '#22c55e',
|
| 193 |
+
backgroundColor: 'rgba(34, 197, 94, 0.1)',
|
| 194 |
+
borderWidth: 2,
|
| 195 |
+
tension: 0.4,
|
| 196 |
+
fill: true
|
| 197 |
+
}]
|
| 198 |
+
},
|
| 199 |
+
options: {
|
| 200 |
+
responsive: true,
|
| 201 |
+
maintainAspectRatio: false,
|
| 202 |
+
plugins: {
|
| 203 |
+
legend: { display: false },
|
| 204 |
+
tooltip: {
|
| 205 |
+
callbacks: {
|
| 206 |
+
label: (context) => `${context.dataset.label}: ${context.parsed.y} t/ha`
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
},
|
| 210 |
+
scales: {
|
| 211 |
+
y: {
|
| 212 |
+
beginAtZero: false,
|
| 213 |
+
min: Math.min(...data.yield.values) - 0.5,
|
| 214 |
+
max: Math.max(...data.yield.values) + 0.5
|
| 215 |
+
}
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
});
|
| 219 |
+
|
| 220 |
+
// Moisture Chart
|
| 221 |
+
const moistureCtx = document.getElementById('moistureChart').getContext('2d');
|
| 222 |
+
new Chart(moistureCtx, {
|
| 223 |
+
type: 'line',
|
| 224 |
+
data: {
|
| 225 |
+
labels: data.moisture.labels,
|
| 226 |
+
datasets: [{
|
| 227 |
+
label: 'Soil Moisture (%)',
|
| 228 |
+
data: data.moisture.values,
|
| 229 |
+
borderColor: '#3b82f6',
|
| 230 |
+
backgroundColor: 'rgba(59, 130, 246, 0.1)',
|
| 231 |
+
borderWidth: 2,
|
| 232 |
+
tension: 0.4,
|
| 233 |
+
fill: true
|
| 234 |
+
}]
|
| 235 |
+
},
|
| 236 |
+
options: {
|
| 237 |
+
responsive: true,
|
| 238 |
+
maintainAspectRatio: false,
|
| 239 |
+
plugins: {
|
| 240 |
+
legend: { display: false },
|
| 241 |
+
tooltip: {
|
| 242 |
+
callbacks: {
|
| 243 |
+
label: (context) => `${context.dataset.label}: ${context.parsed.y}%`
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
},
|
| 247 |
+
scales: {
|
| 248 |
+
y: {
|
| 249 |
+
beginAtZero: false,
|
| 250 |
+
min: Math.min(...data.moisture.values) - 5,
|
| 251 |
+
max: Math.max(...data.moisture.values) + 5
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
});
|
| 256 |
+
} catch (e) {
|
| 257 |
+
const container = document.getElementById('analytics-container');
|
| 258 |
+
container.innerHTML = `
|
| 259 |
+
<div class="rounded-xl border p-6">
|
| 260 |
+
<h1 class="text-2xl font-semibold mb-4">Analytics</h1>
|
| 261 |
+
<div class="text-red-600">
|
| 262 |
+
Failed to load analytics data: ${e}
|
| 263 |
+
</div>
|
| 264 |
+
<button onclick="window.location.reload()"
|
| 265 |
+
class="mt-4 px-4 py-2 bg-primary-600 text-white rounded hover:bg-primary-700">
|
| 266 |
+
Retry
|
| 267 |
+
</button>
|
| 268 |
+
</div>
|
| 269 |
+
`;
|
| 270 |
+
}
|
| 271 |
+
})();
|
| 272 |
+
</script>
|
| 273 |
+
</body>
|
| 274 |
+
</html>
|
|
@@ -72,7 +72,7 @@
|
|
| 72 |
<i data-feather="map" class="text-gray-500 h-5 w-5"></i>
|
| 73 |
<span class="ml-3 sidebar-text">Field Maps</span>
|
| 74 |
</a>
|
| 75 |
-
<a href="
|
| 76 |
<i data-feather="activity" class="text-gray-500 h-5 w-5"></i>
|
| 77 |
<span class="ml-3 sidebar-text">Analytics</span>
|
| 78 |
</a>
|
|
|
|
| 72 |
<i data-feather="map" class="text-gray-500 h-5 w-5"></i>
|
| 73 |
<span class="ml-3 sidebar-text">Field Maps</span>
|
| 74 |
</a>
|
| 75 |
+
<a href="/analytics" class="flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900">
|
| 76 |
<i data-feather="activity" class="text-gray-500 h-5 w-5"></i>
|
| 77 |
<span class="ml-3 sidebar-text">Analytics</span>
|
| 78 |
</a>
|
|
@@ -32,7 +32,7 @@
|
|
| 32 |
<i data-feather="map" class="text-green-600 h-5 w-5"></i>
|
| 33 |
<span class="ml-3">Field Maps</span>
|
| 34 |
</a>
|
| 35 |
-
<a href="
|
| 36 |
<i data-feather="activity" class="text-gray-500 h-5 w-5"></i>
|
| 37 |
<span class="ml-3">Analytics</span>
|
| 38 |
</a>
|
|
|
|
| 32 |
<i data-feather="map" class="text-green-600 h-5 w-5"></i>
|
| 33 |
<span class="ml-3">Field Maps</span>
|
| 34 |
</a>
|
| 35 |
+
<a href="/analytics" class="flex items-center px-2 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900">
|
| 36 |
<i data-feather="activity" class="text-gray-500 h-5 w-5"></i>
|
| 37 |
<span class="ml-3">Analytics</span>
|
| 38 |
</a>
|
|
@@ -782,3 +782,743 @@ async def ndvi_tile(field_id: str):
|
|
| 782 |
return Response(content=png, media_type="image/png")
|
| 783 |
from .routers import datasets
|
| 784 |
app.include_router(datasets.router, prefix="/api/v1/datasets", tags=["datasets"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 782 |
return Response(content=png, media_type="image/png")
|
| 783 |
from .routers import datasets
|
| 784 |
app.include_router(datasets.router, prefix="/api/v1/datasets", tags=["datasets"])
|
| 785 |
+
|
| 786 |
+
pnpm add chart.js react-chartjs-2
|
| 787 |
+
|
| 788 |
+
"use client";
|
| 789 |
+
import { useEffect, useMemo, useState } from "react";
|
| 790 |
+
import { Line } from "react-chartjs-2";
|
| 791 |
+
import {
|
| 792 |
+
Chart,
|
| 793 |
+
LineElement,
|
| 794 |
+
PointElement,
|
| 795 |
+
LinearScale,
|
| 796 |
+
CategoryScale,
|
| 797 |
+
Tooltip,
|
| 798 |
+
Legend,
|
| 799 |
+
Filler,
|
| 800 |
+
} from "chart.js";
|
| 801 |
+
|
| 802 |
+
Chart.register(LineElement, PointElement, LinearScale, CategoryScale, Tooltip, Legend, Filler);
|
| 803 |
+
|
| 804 |
+
type Series = { labels: string[]; values: number[] };
|
| 805 |
+
type AnalyticsPayload = {
|
| 806 |
+
yield: Series;
|
| 807 |
+
moisture: Series;
|
| 808 |
+
notes?: string;
|
| 809 |
+
};
|
| 810 |
+
|
| 811 |
+
export default function AnalyticsPage() {
|
| 812 |
+
const [data, setData] = useState<AnalyticsPayload | null>(null);
|
| 813 |
+
const [loading, setLoading] = useState(true);
|
| 814 |
+
const [err, setErr] = useState<string | null>(null);
|
| 815 |
+
|
| 816 |
+
useEffect(() => {
|
| 817 |
+
fetch("/api/proxy/api/v1/farms/analytics")
|
| 818 |
+
.then(r => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
|
| 819 |
+
.then((j) => setData(j))
|
| 820 |
+
.catch((e) => setErr(String(e)))
|
| 821 |
+
.finally(() => setLoading(false));
|
| 822 |
+
}, []);
|
| 823 |
+
|
| 824 |
+
const yieldChart = useMemo(() => {
|
| 825 |
+
if (!data) return null;
|
| 826 |
+
return {
|
| 827 |
+
labels: data.yield.labels,
|
| 828 |
+
datasets: [
|
| 829 |
+
{
|
| 830 |
+
label: "Yield (t/ha)",
|
| 831 |
+
data: data.yield.values,
|
| 832 |
+
fill: true,
|
| 833 |
+
},
|
| 834 |
+
],
|
| 835 |
+
};
|
| 836 |
+
}, [data]);
|
| 837 |
+
|
| 838 |
+
const moistureChart = useMemo(() => {
|
| 839 |
+
if (!data) return null;
|
| 840 |
+
return {
|
| 841 |
+
labels: data.moisture.labels,
|
| 842 |
+
datasets: [
|
| 843 |
+
{
|
| 844 |
+
label: "Soil Moisture (%)",
|
| 845 |
+
data: data.moisture.values,
|
| 846 |
+
fill: true,
|
| 847 |
+
},
|
| 848 |
+
],
|
| 849 |
+
};
|
| 850 |
+
}, [data]);
|
| 851 |
+
|
| 852 |
+
if (loading) return <div className="rounded-xl border p-6 text-sm text-gray-500">Loading analytics…</div>;
|
| 853 |
+
if (err) return <div className="rounded-xl border p-6 text-sm text-red-600">Error: {err}</div>;
|
| 854 |
+
if (!data) return <div className="rounded-xl border p-6 text-sm">No analytics available.</div>;
|
| 855 |
+
|
| 856 |
+
const opts = { responsive: true, plugins: { legend: { display: false } } };
|
| 857 |
+
|
| 858 |
+
return (
|
| 859 |
+
<div>
|
| 860 |
+
<h1 className="text-2xl font-semibold mb-4">Analytics</h1>
|
| 861 |
+
<div className="grid md:grid-cols-2 gap-6">
|
| 862 |
+
<div className="border rounded-xl p-4">
|
| 863 |
+
<div className="font-semibold mb-2">Yield Trend (t/ha)</div>
|
| 864 |
+
<Line data={yieldChart as any} options={opts as any} />
|
| 865 |
+
</div>
|
| 866 |
+
<div className="border rounded-xl p-4">
|
| 867 |
+
<div className="font-semibold mb-2">Soil Moisture (%)</div>
|
| 868 |
+
<Line data={moistureChart as any} options={opts as any} />
|
| 869 |
+
</div>
|
| 870 |
+
</div>
|
| 871 |
+
{data.notes && <p className="text-xs text-gray-500 mt-3">{data.notes}</p>}
|
| 872 |
+
</div>
|
| 873 |
+
);
|
| 874 |
+
}
|
| 875 |
+
|
| 876 |
+
from fastapi import APIRouter
|
| 877 |
+
|
| 878 |
+
router = APIRouter()
|
| 879 |
+
|
| 880 |
+
# ... keep your existing endpoints (summary, profile, etc.)
|
| 881 |
+
|
| 882 |
+
@router.get("/analytics")
|
| 883 |
+
async def analytics():
|
| 884 |
+
# Example monthly series; replace with real DB/ML output when ready.
|
| 885 |
+
labels = ["Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov"]
|
| 886 |
+
yield_values = [3.6, 3.9, 4.0, 4.1, 4.2, 4.25, 4.3, 4.35]
|
| 887 |
+
moisture_values = [55, 57, 60, 63, 62, 61, 59, 58]
|
| 888 |
+
|
| 889 |
+
return {
|
| 890 |
+
"yield": {"labels": labels, "values": yield_values},
|
| 891 |
+
"moisture": {"labels": labels, "values": moisture_values},
|
| 892 |
+
"notes": "Demo data served by FastAPI; wire to your feature store or AI service next.",
|
| 893 |
+
}
|
| 894 |
+
|
| 895 |
+
from .routers import farms
|
| 896 |
+
app.include_router(farms.router, prefix="/api/v1/farms", tags=["farms"])
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
import { NextRequest, NextResponse } from "next/server";
|
| 900 |
+
|
| 901 |
+
// MUST be a full URL with protocol (no trailing slash)
|
| 902 |
+
const BACKEND = (process.env.NEXT_PUBLIC_API || "http://localhost:8000").replace(/\/+$/,"");
|
| 903 |
+
|
| 904 |
+
async function forward(req: NextRequest, method: "GET" | "POST", params: { path: string[] }) {
|
| 905 |
+
// Build URL safely
|
| 906 |
+
const tail = params.path.join("/");
|
| 907 |
+
const qs = method === "GET" ? req.nextUrl.search || "" : "";
|
| 908 |
+
const url = `${BACKEND}/${tail}${qs}`;
|
| 909 |
+
|
| 910 |
+
const init: RequestInit = {
|
| 911 |
+
method,
|
| 912 |
+
headers: {
|
| 913 |
+
// Only pass through what we actually need
|
| 914 |
+
authorization: req.headers.get("authorization") || "",
|
| 915 |
+
"content-type": req.headers.get("content-type") || "application/json",
|
| 916 |
+
},
|
| 917 |
+
body: method === "POST" ? await req.text() : undefined,
|
| 918 |
+
// avoid sending cookies/credentials cross-origin unless you intend to
|
| 919 |
+
cache: "no-store",
|
| 920 |
+
};
|
| 921 |
+
|
| 922 |
+
const r = await fetch(url, init);
|
| 923 |
+
|
| 924 |
+
// Read body as text first; we’ll return it as JSON unless upstream says otherwise
|
| 925 |
+
const bodyText = await r.text();
|
| 926 |
+
|
| 927 |
+
// Force a sane content-type so NextResponse doesn’t choke
|
| 928 |
+
const contentType =
|
| 929 |
+
r.headers.get("content-type")?.includes("application/json")
|
| 930 |
+
? "application/json; charset=utf-8"
|
| 931 |
+
: "text/plain; charset=utf-8";
|
| 932 |
+
|
| 933 |
+
return new NextResponse(bodyText, {
|
| 934 |
+
status: r.status,
|
| 935 |
+
headers: { "content-type": contentType },
|
| 936 |
+
});
|
| 937 |
+
}
|
| 938 |
+
|
| 939 |
+
export const GET = (req: NextRequest, ctx: any) => forward(req, "GET", ctx.params);
|
| 940 |
+
export const POST = (req: NextRequest, ctx: any) => forward(req, "POST", ctx.params);
|
| 941 |
+
|
| 942 |
+
NEXT_PUBLIC_API=http://localhost:8000
|
| 943 |
+
|
| 944 |
+
@router.get("/analytics")
|
| 945 |
+
async def analytics():
|
| 946 |
+
labels = ["Apr","May","Jun","Jul","Aug","Sep","Oct","Nov"]
|
| 947 |
+
return {
|
| 948 |
+
"yield": {"labels": labels, "values": [3.6,3.9,4.0,4.1,4.2,4.25,4.3,4.35]},
|
| 949 |
+
"moisture": {"labels": labels, "values": [55,57,60,63,62,61,59,58]},
|
| 950 |
+
}
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
useEffect(() => {
|
| 954 |
+
(async () => {
|
| 955 |
+
try {
|
| 956 |
+
const r = await fetch("/api/proxy/api/v1/farms/analytics");
|
| 957 |
+
const text = await r.text();
|
| 958 |
+
const json = JSON.parse(text);
|
| 959 |
+
setData(json);
|
| 960 |
+
} catch (e) {
|
| 961 |
+
setErr(String(e));
|
| 962 |
+
} finally {
|
| 963 |
+
setLoading(false);
|
| 964 |
+
}
|
| 965 |
+
})();
|
| 966 |
+
}, []);
|
| 967 |
+
|
| 968 |
+
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
| 969 |
+
from fastapi import HTTPException
|
| 970 |
+
import time, uuid
|
| 971 |
+
|
| 972 |
+
router = APIRouter()
|
| 973 |
+
|
| 974 |
+
# In-memory registry (swap to Redis/DB in prod)
|
| 975 |
+
DEVICES = {} # device_id -> {type, battery, last_seen, session_id}
|
| 976 |
+
SESSIONS = {} # session_id -> {"created_at": ts, "device_id": Optional[str], "telemetry": []}
|
| 977 |
+
CLIENTS = {} # session_id -> set(WebSocket)
|
| 978 |
+
|
| 979 |
+
def now() -> int:
|
| 980 |
+
return int(time.time())
|
| 981 |
+
|
| 982 |
+
@router.get("/status")
|
| 983 |
+
async def status():
|
| 984 |
+
connected = sum(1 for d in DEVICES.values() if d.get("last_seen",0) > now()-120)
|
| 985 |
+
return {
|
| 986 |
+
"connected": connected,
|
| 987 |
+
"devices": [
|
| 988 |
+
dict(id=dev_id, **data) for dev_id, data in DEVICES.items()
|
| 989 |
+
],
|
| 990 |
+
"sessions": list(SESSIONS.keys())
|
| 991 |
+
}
|
| 992 |
+
|
| 993 |
+
@router.post("/session")
|
| 994 |
+
async def create_session():
|
| 995 |
+
sid = uuid.uuid4().hex
|
| 996 |
+
SESSIONS[sid] = {"created_at": now(), "device_id": None, "telemetry": []}
|
| 997 |
+
return {"session_id": sid, "session_url": f"https://xr.agrosynth.local/pair/{sid}"}
|
| 998 |
+
|
| 999 |
+
@router.post("/bind")
|
| 1000 |
+
async def bind_device(session_id: str, device_id: str, device_type: str = "AR Glasses"):
|
| 1001 |
+
if session_id not in SESSIONS:
|
| 1002 |
+
raise HTTPException(404, "session not found")
|
| 1003 |
+
SESSIONS[session_id]["device_id"] = device_id
|
| 1004 |
+
DEVICES[device_id] = {
|
| 1005 |
+
"type": device_type, "battery": 100, "last_seen": now(), "session_id": session_id
|
| 1006 |
+
}
|
| 1007 |
+
return {"ok": True}
|
| 1008 |
+
|
| 1009 |
+
@router.websocket("/ws/{session_id}")
|
| 1010 |
+
async def ws(session: WebSocket, session_id: str):
|
| 1011 |
+
if session_id not in SESSIONS:
|
| 1012 |
+
await session.close(code=1008)
|
| 1013 |
+
return
|
| 1014 |
+
await session.accept()
|
| 1015 |
+
CLIENTS.setdefault(session_id, set()).add(session)
|
| 1016 |
+
try:
|
| 1017 |
+
while True:
|
| 1018 |
+
msg = await session.receive_json()
|
| 1019 |
+
# Expected message shapes:
|
| 1020 |
+
# {"kind":"hello","device_id":"rb-123","device_type":"AR Glasses"}
|
| 1021 |
+
# {"kind":"telemetry","device_id":"rb-123","battery":88,"pose":{"lat":..,"lon":..}}
|
| 1022 |
+
# {"kind":"event","device_id":"rb-123","name":"capture","data":{...}}
|
| 1023 |
+
k = msg.get("kind")
|
| 1024 |
+
if k == "hello":
|
| 1025 |
+
dev_id = msg.get("device_id") or f"dev-{uuid.uuid4().hex[:6]}"
|
| 1026 |
+
DEVICES[dev_id] = {
|
| 1027 |
+
"type": msg.get("device_type","AR Glasses"),
|
| 1028 |
+
"battery": msg.get("battery",100),
|
| 1029 |
+
"last_seen": now(),
|
| 1030 |
+
"session_id": session_id
|
| 1031 |
+
}
|
| 1032 |
+
SESSIONS[session_id]["device_id"] = dev_id
|
| 1033 |
+
await broadcast(session_id, {"kind":"system","message":f"{dev_id} connected"})
|
| 1034 |
+
elif k == "telemetry":
|
| 1035 |
+
dev_id = msg.get("device_id")
|
| 1036 |
+
if dev_id:
|
| 1037 |
+
d = DEVICES.setdefault(dev_id, {"type":"Unknown","battery":0,"last_seen":0,"session_id":session_id})
|
| 1038 |
+
d["battery"] = msg.get("battery", d["battery"])
|
| 1039 |
+
d["last_seen"] = now()
|
| 1040 |
+
payload = {"ts": now(), "data": msg}
|
| 1041 |
+
SESSIONS[session_id]["telemetry"].append(payload)
|
| 1042 |
+
await broadcast(session_id, {"kind":"telemetry","payload":payload})
|
| 1043 |
+
elif k == "event":
|
| 1044 |
+
await broadcast(session_id, {"kind":"event","payload":msg})
|
| 1045 |
+
else:
|
| 1046 |
+
await broadcast(session_id, {"kind":"echo","payload":msg})
|
| 1047 |
+
except WebSocketDisconnect:
|
| 1048 |
+
pass
|
| 1049 |
+
finally:
|
| 1050 |
+
CLIENTS[session_id].discard(session)
|
| 1051 |
+
if not CLIENTS[session_id]:
|
| 1052 |
+
CLIENTS.pop(session_id, None)
|
| 1053 |
+
|
| 1054 |
+
async def broadcast(session_id: str, message: dict):
|
| 1055 |
+
for ws in list(CLIENTS.get(session_id, set())):
|
| 1056 |
+
try:
|
| 1057 |
+
await ws.send_json(message)
|
| 1058 |
+
except Exception:
|
| 1059 |
+
CLIENTS[session_id].discard(ws)
|
| 1060 |
+
from .routers import xr
|
| 1061 |
+
app.include_router(xr.router, prefix="/api/v1/xr", tags=["xr"])
|
| 1062 |
+
|
| 1063 |
+
"use client";
|
| 1064 |
+
import { useEffect, useRef, useState } from "react";
|
| 1065 |
+
import { QRCodeCanvas } from "qrcode.react";
|
| 1066 |
+
|
| 1067 |
+
type XRStatus = {
|
| 1068 |
+
connected: number;
|
| 1069 |
+
devices: Array<{ id: string; type: string; battery: number; last_seen?: number; session_id?: string }>;
|
| 1070 |
+
sessions: string[];
|
| 1071 |
+
};
|
| 1072 |
+
|
| 1073 |
+
export default function XRToolsPage() {
|
| 1074 |
+
const [status, setStatus] = useState<XRStatus | null>(null);
|
| 1075 |
+
const [session, setSession] = useState<{ session_id: string; session_url: string } | null>(null);
|
| 1076 |
+
const [events, setEvents] = useState<string[]>([]);
|
| 1077 |
+
const wsRef = useRef<WebSocket | null>(null);
|
| 1078 |
+
|
| 1079 |
+
async function loadStatus() {
|
| 1080 |
+
const r = await fetch("/api/proxy/api/v1/xr/status", { cache: "no-store" });
|
| 1081 |
+
setStatus(await r.json());
|
| 1082 |
+
}
|
| 1083 |
+
|
| 1084 |
+
async function createSession() {
|
| 1085 |
+
const r = await fetch("/api/proxy/api/v1/xr/session", { method: "POST" });
|
| 1086 |
+
const j = await r.json();
|
| 1087 |
+
setSession(j);
|
| 1088 |
+
// open websocket
|
| 1089 |
+
const url = (process.env.NEXT_PUBLIC_WS || "ws://localhost:8000").replace(/\/+$/,"");
|
| 1090 |
+
const ws = new WebSocket(`${url}/api/v1/xr/ws/${j.session_id}`);
|
| 1091 |
+
ws.onmessage = evt => {
|
| 1092 |
+
setEvents(e => [`${new Date().toLocaleTimeString()} ${evt.data}`, ...e].slice(0,100));
|
| 1093 |
+
};
|
| 1094 |
+
ws.onopen = () => setEvents(e => [`${new Date().toLocaleTimeString()} [ws] connected`, ...e]);
|
| 1095 |
+
ws.onclose = () => setEvents(e => [`${new Date().toLocaleTimeString()} [ws] closed`, ...e]);
|
| 1096 |
+
wsRef.current = ws;
|
| 1097 |
+
}
|
| 1098 |
+
|
| 1099 |
+
useEffect(() => { loadStatus(); const t = setInterval(loadStatus, 4000); return () => clearInterval(t); }, []);
|
| 1100 |
+
|
| 1101 |
+
return (
|
| 1102 |
+
<div>
|
| 1103 |
+
<h1 className="text-2xl font-semibold mb-4">XR Tools</h1>
|
| 1104 |
+
|
| 1105 |
+
<div className="grid md:grid-cols-3 gap-6">
|
| 1106 |
+
<div className="border rounded-xl p-4">
|
| 1107 |
+
<div className="font-semibold mb-2">Device Status</div>
|
| 1108 |
+
<pre className="text-xs bg-gray-50 p-3 rounded h-64 overflow-auto">{JSON.stringify(status, null, 2)}</pre>
|
| 1109 |
+
<button onClick={loadStatus} className="mt-3 px-3 py-2 rounded border">Refresh</button>
|
| 1110 |
+
</div>
|
| 1111 |
+
|
| 1112 |
+
<div className="border rounded-xl p-4">
|
| 1113 |
+
<div className="font-semibold mb-2">Pair a Device</div>
|
| 1114 |
+
<button onClick={createSession} className="px-4 py-2 rounded bg-black text-white">Generate Session</button>
|
| 1115 |
+
{session && (
|
| 1116 |
+
<div className="mt-4 flex gap-4 items-center">
|
| 1117 |
+
<QRCodeCanvas value={session.session_url} size={160} />
|
| 1118 |
+
<div className="text-sm">
|
| 1119 |
+
Scan with your Meta Ray-Ban companion phone browser or any mobile camera.<br/>
|
| 1120 |
+
<a className="text-blue-600 underline" href={session.session_url} target="_blank">{session.session_url}</a>
|
| 1121 |
+
<div className="mt-2 text-xs text-gray-500">
|
| 1122 |
+
WebSocket: <code>/api/v1/xr/ws/{session.session_id}</code>
|
| 1123 |
+
</div>
|
| 1124 |
+
</div>
|
| 1125 |
+
</div>
|
| 1126 |
+
)}
|
| 1127 |
+
</div>
|
| 1128 |
+
|
| 1129 |
+
<div className="border rounded-xl p-4">
|
| 1130 |
+
<div className="font-semibold mb-2">Live Telemetry / Events</div>
|
| 1131 |
+
<div className="text-xs bg-gray-50 p-3 rounded h-64 overflow-auto whitespace-pre-wrap">
|
| 1132 |
+
{events.map((e, i) => <div key={i}>{e}</div>)}
|
| 1133 |
+
</div>
|
| 1134 |
+
</div>
|
| 1135 |
+
</div>
|
| 1136 |
+
|
| 1137 |
+
<div className="border rounded-xl p-4 mt-6">
|
| 1138 |
+
<div className="font-semibold mb-2">Device Simulator</div>
|
| 1139 |
+
<p className="text-sm text-gray-500">Open the simulator to send telemetry without hardware.</p>
|
| 1140 |
+
<a className="inline-block mt-2 px-3 py-2 rounded border" href="/xr-tools/dev-simulator" target="_blank">Open Simulator</a>
|
| 1141 |
+
</div>
|
| 1142 |
+
</div>
|
| 1143 |
+
);
|
| 1144 |
+
}
|
| 1145 |
+
|
| 1146 |
+
pnpm add qrcode.react
|
| 1147 |
+
|
| 1148 |
+
"use client";
|
| 1149 |
+
import { useEffect, useState } from "react";
|
| 1150 |
+
|
| 1151 |
+
export default function PairPage({ params }: { params: { sid: string } }) {
|
| 1152 |
+
const [deviceId, setDeviceId] = useState<string>("");
|
| 1153 |
+
const [status, setStatus] = useState<string>("");
|
| 1154 |
+
|
| 1155 |
+
async function bind() {
|
| 1156 |
+
if (!deviceId) { setStatus("Enter a device id"); return; }
|
| 1157 |
+
const body = new URLSearchParams({ session_id: params.sid, device_id: deviceId, device_type: "AR Glasses" });
|
| 1158 |
+
const r = await fetch("/api/proxy/api/v1/xr/bind", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body });
|
| 1159 |
+
setStatus(r.ok ? "Paired!" : `Error ${r.status}`);
|
| 1160 |
+
}
|
| 1161 |
+
|
| 1162 |
+
// Optional: send a hello on websocket immediately after pairing using fetch + server WS will see telemetry later via simulator/app.
|
| 1163 |
+
useEffect(()=>{ setDeviceId(`rb-${Math.random().toString(36).slice(2,8)}`); },[]);
|
| 1164 |
+
|
| 1165 |
+
return (
|
| 1166 |
+
<div className="max-w-md mx-auto p-6">
|
| 1167 |
+
<h1 className="text-2xl font-semibold">Pair Device</h1>
|
| 1168 |
+
<p className="text-sm text-gray-600 mt-1">Session: <code>{params.sid}</code></p>
|
| 1169 |
+
<label className="block text-sm mt-4">Device ID</label>
|
| 1170 |
+
<input className="border rounded w-full p-2" value={deviceId} onChange={e=>setDeviceId(e.target.value)} />
|
| 1171 |
+
<button onClick={bind} className="mt-3 px-4 py-2 rounded bg-black text-white">Bind</button>
|
| 1172 |
+
{status && <div className="text-sm mt-2">{status}</div>}
|
| 1173 |
+
<div className="text-xs text-gray-500 mt-4">
|
| 1174 |
+
After pairing, your device or mobile app should connect to the session WebSocket to stream telemetry.
|
| 1175 |
+
</div>
|
| 1176 |
+
</div>
|
| 1177 |
+
);
|
| 1178 |
+
}
|
| 1179 |
+
|
| 1180 |
+
"use client";
|
| 1181 |
+
import { useEffect, useRef, useState } from "react";
|
| 1182 |
+
|
| 1183 |
+
export default function DevSimulator() {
|
| 1184 |
+
const [sessionId, setSessionId] = useState("");
|
| 1185 |
+
const [deviceId, setDeviceId] = useState(`rb-${Math.random().toString(36).slice(2,8)}`);
|
| 1186 |
+
const [battery, setBattery] = useState(92);
|
| 1187 |
+
const [log, setLog] = useState<string[]>([]);
|
| 1188 |
+
const wsRef = useRef<WebSocket|null>(null);
|
| 1189 |
+
|
| 1190 |
+
function pushLog(s:string){ setLog(l => [`${new Date().toLocaleTimeString()} ${s}`, ...l].slice(0,100)); }
|
| 1191 |
+
|
| 1192 |
+
function connect() {
|
| 1193 |
+
if(!sessionId) { pushLog("Enter session id"); return; }
|
| 1194 |
+
const url = (process.env.NEXT_PUBLIC_WS || "ws://localhost:8000").replace(/\/+$/,"");
|
| 1195 |
+
const ws = new WebSocket(`${url}/api/v1/xr/ws/${sessionId}`);
|
| 1196 |
+
ws.onopen = () => {
|
| 1197 |
+
pushLog("[ws] open");
|
| 1198 |
+
ws.send(JSON.stringify({ kind:"hello", device_id: deviceId, device_type: "AR Glasses", battery }));
|
| 1199 |
+
};
|
| 1200 |
+
ws.onmessage = (e) => pushLog(`<- ${e.data}`);
|
| 1201 |
+
ws.onclose = () => pushLog("[ws] closed");
|
| 1202 |
+
ws.onerror = (e) => pushLog(`[ws] error ${String(e)}`);
|
| 1203 |
+
wsRef.current = ws;
|
| 1204 |
+
}
|
| 1205 |
+
|
| 1206 |
+
function sendTelemetry() {
|
| 1207 |
+
const ws = wsRef.current;
|
| 1208 |
+
if (!ws || ws.readyState !== 1) { pushLog("ws not connected"); return; }
|
| 1209 |
+
const payload = {
|
| 1210 |
+
kind: "telemetry",
|
| 1211 |
+
device_id: deviceId,
|
| 1212 |
+
battery,
|
| 1213 |
+
pose: { lat: 40.73 + Math.random()/100, lon: -73.93 + Math.random()/100 },
|
| 1214 |
+
sensors: { temp_c: 24 + Math.random()*2, light: 300 + Math.random()*50 },
|
| 1215 |
+
};
|
| 1216 |
+
ws.send(JSON.stringify(payload));
|
| 1217 |
+
pushLog(`-> telemetry ${JSON.stringify(payload)}`);
|
| 1218 |
+
}
|
| 1219 |
+
|
| 1220 |
+
return (
|
| 1221 |
+
<div className="max-w-xl mx-auto p-6">
|
| 1222 |
+
<h1 className="text-2xl font-semibold">XR Device Simulator</h1>
|
| 1223 |
+
<label className="block text-sm mt-4">Session ID</label>
|
| 1224 |
+
<input className="border rounded w-full p-2" value={sessionId} onChange={e=>setSessionId(e.target.value)} placeholder="paste session id"/>
|
| 1225 |
+
<label className="block text-sm mt-3">Device ID</label>
|
| 1226 |
+
<input className="border rounded w-full p-2" value={deviceId} onChange={e=>setDeviceId(e.target.value)} />
|
| 1227 |
+
<label className="block text-sm mt-3">Battery</label>
|
| 1228 |
+
<input type="number" className="border rounded w-full p-2" value={battery} onChange={e=>setBattery(Number(e.target.value))} />
|
| 1229 |
+
<div className="mt-3 flex gap-2">
|
| 1230 |
+
<button onClick={connect} className="px-3 py-2 rounded bg-black text-white">Connect</button>
|
| 1231 |
+
<button onClick={sendTelemetry} className="px-3 py-2 rounded border">Send Telemetry</button>
|
| 1232 |
+
</div>
|
| 1233 |
+
<div className="mt-4 text-xs bg-gray-50 border rounded p-3 h-64 overflow-auto whitespace-pre-wrap">
|
| 1234 |
+
{log.map((l,i)=><div key={i}>{l}</div>)}
|
| 1235 |
+
</div>
|
| 1236 |
+
</div>
|
| 1237 |
+
);
|
| 1238 |
+
}
|
| 1239 |
+
|
| 1240 |
+
NEXT_PUBLIC_API=http://localhost:8000
|
| 1241 |
+
NEXT_PUBLIC_WS=ws://localhost:8000
|
| 1242 |
+
|
| 1243 |
+
{"kind":"hello","device_id":"rb-123","device_type":"AR Glasses","battery":94}
|
| 1244 |
+
{"kind":"telemetry","device_id":"rb-123","battery":93,"pose":{"lat":..,"lon":..},"sensors":{"light":..}}
|
| 1245 |
+
{"kind":"event","device_id":"rb-123","name":"photo_captured","data":{"uri":"..."}}
|
| 1246 |
+
|
| 1247 |
+
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
| 1248 |
+
from fastapi import HTTPException
|
| 1249 |
+
import time, uuid
|
| 1250 |
+
|
| 1251 |
+
router = APIRouter()
|
| 1252 |
+
|
| 1253 |
+
# In-memory registry (swap to Redis/DB in prod)
|
| 1254 |
+
DEVICES = {} # device_id -> {type, battery, last_seen, session_id}
|
| 1255 |
+
SESSIONS = {} # session_id -> {"created_at": ts, "device_id": Optional[str], "telemetry": []}
|
| 1256 |
+
CLIENTS = {} # session_id -> set(WebSocket)
|
| 1257 |
+
|
| 1258 |
+
def now() -> int:
|
| 1259 |
+
return int(time.time())
|
| 1260 |
+
|
| 1261 |
+
@router.get("/status")
|
| 1262 |
+
async def status():
|
| 1263 |
+
connected = sum(1 for d in DEVICES.values() if d.get("last_seen",0) > now()-120)
|
| 1264 |
+
return {
|
| 1265 |
+
"connected": connected,
|
| 1266 |
+
"devices": [
|
| 1267 |
+
dict(id=dev_id, **data) for dev_id, data in DEVICES.items()
|
| 1268 |
+
],
|
| 1269 |
+
"sessions": list(SESSIONS.keys())
|
| 1270 |
+
}
|
| 1271 |
+
|
| 1272 |
+
@router.post("/session")
|
| 1273 |
+
async def create_session():
|
| 1274 |
+
sid = uuid.uuid4().hex
|
| 1275 |
+
SESSIONS[sid] = {"created_at": now(), "device_id": None, "telemetry": []}
|
| 1276 |
+
return {"session_id": sid, "session_url": f"https://xr.agrosynth.local/pair/{sid}"}
|
| 1277 |
+
|
| 1278 |
+
@router.post("/bind")
|
| 1279 |
+
async def bind_device(session_id: str, device_id: str, device_type: str = "AR Glasses"):
|
| 1280 |
+
if session_id not in SESSIONS:
|
| 1281 |
+
raise HTTPException(404, "session not found")
|
| 1282 |
+
SESSIONS[session_id]["device_id"] = device_id
|
| 1283 |
+
DEVICES[device_id] = {
|
| 1284 |
+
"type": device_type, "battery": 100, "last_seen": now(), "session_id": session_id
|
| 1285 |
+
}
|
| 1286 |
+
return {"ok": True}
|
| 1287 |
+
|
| 1288 |
+
@router.websocket("/ws/{session_id}")
|
| 1289 |
+
async def ws(session: WebSocket, session_id: str):
|
| 1290 |
+
if session_id not in SESSIONS:
|
| 1291 |
+
await session.close(code=1008)
|
| 1292 |
+
return
|
| 1293 |
+
await session.accept()
|
| 1294 |
+
CLIENTS.setdefault(session_id, set()).add(session)
|
| 1295 |
+
try:
|
| 1296 |
+
while True:
|
| 1297 |
+
msg = await session.receive_json()
|
| 1298 |
+
# Expected message shapes:
|
| 1299 |
+
# {"kind":"hello","device_id":"rb-123","device_type":"AR Glasses"}
|
| 1300 |
+
# {"kind":"telemetry","device_id":"rb-123","battery":88,"pose":{"lat":..,"lon":..}}
|
| 1301 |
+
# {"kind":"event","device_id":"rb-123","name":"capture","data":{...}}
|
| 1302 |
+
k = msg.get("kind")
|
| 1303 |
+
if k == "hello":
|
| 1304 |
+
dev_id = msg.get("device_id") or f"dev-{uuid.uuid4().hex[:6]}"
|
| 1305 |
+
DEVICES[dev_id] = {
|
| 1306 |
+
"type": msg.get("device_type","AR Glasses"),
|
| 1307 |
+
"battery": msg.get("battery",100),
|
| 1308 |
+
"last_seen": now(),
|
| 1309 |
+
"session_id": session_id
|
| 1310 |
+
}
|
| 1311 |
+
SESSIONS[session_id]["device_id"] = dev_id
|
| 1312 |
+
await broadcast(session_id, {"kind":"system","message":f"{dev_id} connected"})
|
| 1313 |
+
elif k == "telemetry":
|
| 1314 |
+
dev_id = msg.get("device_id")
|
| 1315 |
+
if dev_id:
|
| 1316 |
+
d = DEVICES.setdefault(dev_id, {"type":"Unknown","battery":0,"last_seen":0,"session_id":session_id})
|
| 1317 |
+
d["battery"] = msg.get("battery", d["battery"])
|
| 1318 |
+
d["last_seen"] = now()
|
| 1319 |
+
payload = {"ts": now(), "data": msg}
|
| 1320 |
+
SESSIONS[session_id]["telemetry"].append(payload)
|
| 1321 |
+
await broadcast(session_id, {"kind":"telemetry","payload":payload})
|
| 1322 |
+
elif k == "event":
|
| 1323 |
+
await broadcast(session_id, {"kind":"event","payload":msg})
|
| 1324 |
+
else:
|
| 1325 |
+
await broadcast(session_id, {"kind":"echo","payload":msg})
|
| 1326 |
+
except WebSocketDisconnect:
|
| 1327 |
+
pass
|
| 1328 |
+
finally:
|
| 1329 |
+
CLIENTS[session_id].discard(session)
|
| 1330 |
+
if not CLIENTS[session_id]:
|
| 1331 |
+
CLIENTS.pop(session_id, None)
|
| 1332 |
+
|
| 1333 |
+
async def broadcast(session_id: str, message: dict):
|
| 1334 |
+
for ws in list(CLIENTS.get(session_id, set())):
|
| 1335 |
+
try:
|
| 1336 |
+
await ws.send_json(message)
|
| 1337 |
+
except Exception:
|
| 1338 |
+
CLIENTS[session_id].discard(ws)
|
| 1339 |
+
from .routers import xr
|
| 1340 |
+
app.include_router(xr.router, prefix="/api/v1/xr", tags=["xr"])
|
| 1341 |
+
|
| 1342 |
+
"use client";
|
| 1343 |
+
import { useEffect, useRef, useState } from "react";
|
| 1344 |
+
import { QRCodeCanvas } from "qrcode.react";
|
| 1345 |
+
|
| 1346 |
+
type XRStatus = {
|
| 1347 |
+
connected: number;
|
| 1348 |
+
devices: Array<{ id: string; type: string; battery: number; last_seen?: number; session_id?: string }>;
|
| 1349 |
+
sessions: string[];
|
| 1350 |
+
};
|
| 1351 |
+
|
| 1352 |
+
export default function XRToolsPage() {
|
| 1353 |
+
const [status, setStatus] = useState<XRStatus | null>(null);
|
| 1354 |
+
const [session, setSession] = useState<{ session_id: string; session_url: string } | null>(null);
|
| 1355 |
+
const [events, setEvents] = useState<string[]>([]);
|
| 1356 |
+
const wsRef = useRef<WebSocket | null>(null);
|
| 1357 |
+
|
| 1358 |
+
async function loadStatus() {
|
| 1359 |
+
const r = await fetch("/api/proxy/api/v1/xr/status", { cache: "no-store" });
|
| 1360 |
+
setStatus(await r.json());
|
| 1361 |
+
}
|
| 1362 |
+
|
| 1363 |
+
async function createSession() {
|
| 1364 |
+
const r = await fetch("/api/proxy/api/v1/xr/session", { method: "POST" });
|
| 1365 |
+
const j = await r.json();
|
| 1366 |
+
setSession(j);
|
| 1367 |
+
// open websocket
|
| 1368 |
+
const url = (process.env.NEXT_PUBLIC_WS || "ws://localhost:8000").replace(/\/+$/,"");
|
| 1369 |
+
const ws = new WebSocket(`${url}/api/v1/xr/ws/${j.session_id}`);
|
| 1370 |
+
ws.onmessage = evt => {
|
| 1371 |
+
setEvents(e => [`${new Date().toLocaleTimeString()} ${evt.data}`, ...e].slice(0,100));
|
| 1372 |
+
};
|
| 1373 |
+
ws.onopen = () => setEvents(e => [`${new Date().toLocaleTimeString()} [ws] connected`, ...e]);
|
| 1374 |
+
ws.onclose = () => setEvents(e => [`${new Date().toLocaleTimeString()} [ws] closed`, ...e]);
|
| 1375 |
+
wsRef.current = ws;
|
| 1376 |
+
}
|
| 1377 |
+
|
| 1378 |
+
useEffect(() => { loadStatus(); const t = setInterval(loadStatus, 4000); return () => clearInterval(t); }, []);
|
| 1379 |
+
|
| 1380 |
+
return (
|
| 1381 |
+
<div>
|
| 1382 |
+
<h1 className="text-2xl font-semibold mb-4">XR Tools</h1>
|
| 1383 |
+
|
| 1384 |
+
<div className="grid md:grid-cols-3 gap-6">
|
| 1385 |
+
<div className="border rounded-xl p-4">
|
| 1386 |
+
<div className="font-semibold mb-2">Device Status</div>
|
| 1387 |
+
<pre className="text-xs bg-gray-50 p-3 rounded h-64 overflow-auto">{JSON.stringify(status, null, 2)}</pre>
|
| 1388 |
+
<button onClick={loadStatus} className="mt-3 px-3 py-2 rounded border">Refresh</button>
|
| 1389 |
+
</div>
|
| 1390 |
+
|
| 1391 |
+
<div className="border rounded-xl p-4">
|
| 1392 |
+
<div className="font-semibold mb-2">Pair a Device</div>
|
| 1393 |
+
<button onClick={createSession} className="px-4 py-2 rounded bg-black text-white">Generate Session</button>
|
| 1394 |
+
{session && (
|
| 1395 |
+
<div className="mt-4 flex gap-4 items-center">
|
| 1396 |
+
<QRCodeCanvas value={session.session_url} size={160} />
|
| 1397 |
+
<div className="text-sm">
|
| 1398 |
+
Scan with your Meta Ray-Ban companion phone browser or any mobile camera.<br/>
|
| 1399 |
+
<a className="text-blue-600 underline" href={session.session_url} target="_blank">{session.session_url}</a>
|
| 1400 |
+
<div className="mt-2 text-xs text-gray-500">
|
| 1401 |
+
WebSocket: <code>/api/v1/xr/ws/{session.session_id}</code>
|
| 1402 |
+
</div>
|
| 1403 |
+
</div>
|
| 1404 |
+
</div>
|
| 1405 |
+
)}
|
| 1406 |
+
</div>
|
| 1407 |
+
|
| 1408 |
+
<div className="border rounded-xl p-4">
|
| 1409 |
+
<div className="font-semibold mb-2">Live Telemetry / Events</div>
|
| 1410 |
+
<div className="text-xs bg-gray-50 p-3 rounded h-64 overflow-auto whitespace-pre-wrap">
|
| 1411 |
+
{events.map((e, i) => <div key={i}>{e}</div>)}
|
| 1412 |
+
</div>
|
| 1413 |
+
</div>
|
| 1414 |
+
</div>
|
| 1415 |
+
|
| 1416 |
+
<div className="border rounded-xl p-4 mt-6">
|
| 1417 |
+
<div className="font-semibold mb-2">Device Simulator</div>
|
| 1418 |
+
<p className="text-sm text-gray-500">Open the simulator to send telemetry without hardware.</p>
|
| 1419 |
+
<a className="inline-block mt-2 px-3 py-2 rounded border" href="/xr-tools/dev-simulator" target="_blank">Open Simulator</a>
|
| 1420 |
+
</div>
|
| 1421 |
+
</div>
|
| 1422 |
+
);
|
| 1423 |
+
}
|
| 1424 |
+
|
| 1425 |
+
pnpm add qrcode.react
|
| 1426 |
+
|
| 1427 |
+
"use client";
|
| 1428 |
+
import { useEffect, useState } from "react";
|
| 1429 |
+
|
| 1430 |
+
export default function PairPage({ params }: { params: { sid: string } }) {
|
| 1431 |
+
const [deviceId, setDeviceId] = useState<string>("");
|
| 1432 |
+
const [status, setStatus] = useState<string>("");
|
| 1433 |
+
|
| 1434 |
+
async function bind() {
|
| 1435 |
+
if (!deviceId) { setStatus("Enter a device id"); return; }
|
| 1436 |
+
const body = new URLSearchParams({ session_id: params.sid, device_id: deviceId, device_type: "AR Glasses" });
|
| 1437 |
+
const r = await fetch("/api/proxy/api/v1/xr/bind", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body });
|
| 1438 |
+
setStatus(r.ok ? "Paired!" : `Error ${r.status}`);
|
| 1439 |
+
}
|
| 1440 |
+
|
| 1441 |
+
// Optional: send a hello on websocket immediately after pairing using fetch + server WS will see telemetry later via simulator/app.
|
| 1442 |
+
useEffect(()=>{ setDeviceId(`rb-${Math.random().toString(36).slice(2,8)}`); },[]);
|
| 1443 |
+
|
| 1444 |
+
return (
|
| 1445 |
+
<div className="max-w-md mx-auto p-6">
|
| 1446 |
+
<h1 className="text-2xl font-semibold">Pair Device</h1>
|
| 1447 |
+
<p className="text-sm text-gray-600 mt-1">Session: <code>{params.sid}</code></p>
|
| 1448 |
+
<label className="block text-sm mt-4">Device ID</label>
|
| 1449 |
+
<input className="border rounded w-full p-2" value={deviceId} onChange={e=>setDeviceId(e.target.value)} />
|
| 1450 |
+
<button onClick={bind} className="mt-3 px-4 py-2 rounded bg-black text-white">Bind</button>
|
| 1451 |
+
{status && <div className="text-sm mt-2">{status}</div>}
|
| 1452 |
+
<div className="text-xs text-gray-500 mt-4">
|
| 1453 |
+
After pairing, your device or mobile app should connect to the session WebSocket to stream telemetry.
|
| 1454 |
+
</div>
|
| 1455 |
+
</div>
|
| 1456 |
+
);
|
| 1457 |
+
}
|
| 1458 |
+
|
| 1459 |
+
"use client";
|
| 1460 |
+
import { useEffect, useRef, useState } from "react";
|
| 1461 |
+
|
| 1462 |
+
export default function DevSimulator() {
|
| 1463 |
+
const [sessionId, setSessionId] = useState("");
|
| 1464 |
+
const [deviceId, setDeviceId] = useState(`rb-${Math.random().toString(36).slice(2,8)}`);
|
| 1465 |
+
const [battery, setBattery] = useState(92);
|
| 1466 |
+
const [log, setLog] = useState<string[]>([]);
|
| 1467 |
+
const wsRef = useRef<WebSocket|null>(null);
|
| 1468 |
+
|
| 1469 |
+
function pushLog(s:string){ setLog(l => [`${new Date().toLocaleTimeString()} ${s}`, ...l].slice(0,100)); }
|
| 1470 |
+
|
| 1471 |
+
function connect() {
|
| 1472 |
+
if(!sessionId) { pushLog("Enter session id"); return; }
|
| 1473 |
+
const url = (process.env.NEXT_PUBLIC_WS || "ws://localhost:8000").replace(/\/+$/,"");
|
| 1474 |
+
const ws = new WebSocket(`${url}/api/v1/xr/ws/${sessionId}`);
|
| 1475 |
+
ws.onopen = () => {
|
| 1476 |
+
pushLog("[ws] open");
|
| 1477 |
+
ws.send(JSON.stringify({ kind:"hello", device_id: deviceId, device_type: "AR Glasses", battery }));
|
| 1478 |
+
};
|
| 1479 |
+
ws.onmessage = (e) => pushLog(`<- ${e.data}`);
|
| 1480 |
+
ws.onclose = () => pushLog("[ws] closed");
|
| 1481 |
+
ws.onerror = (e) => pushLog(`[ws] error ${String(e)}`);
|
| 1482 |
+
wsRef.current = ws;
|
| 1483 |
+
}
|
| 1484 |
+
|
| 1485 |
+
function sendTelemetry() {
|
| 1486 |
+
const ws = wsRef.current;
|
| 1487 |
+
if (!ws || ws.readyState !== 1) { pushLog("ws not connected"); return; }
|
| 1488 |
+
const payload = {
|
| 1489 |
+
kind: "telemetry",
|
| 1490 |
+
device_id: deviceId,
|
| 1491 |
+
battery,
|
| 1492 |
+
pose: { lat: 40.73 + Math.random()/100, lon: -73.93 + Math.random()/100 },
|
| 1493 |
+
sensors: { temp_c: 24 + Math.random()*2, light: 300 + Math.random()*50 },
|
| 1494 |
+
};
|
| 1495 |
+
ws.send(JSON.stringify(payload));
|
| 1496 |
+
pushLog(`-> telemetry ${JSON.stringify(payload)}`);
|
| 1497 |
+
}
|
| 1498 |
+
|
| 1499 |
+
return (
|
| 1500 |
+
<div className="max-w-xl mx-auto p-6">
|
| 1501 |
+
<h1 className="text-2xl font-semibold">XR Device Simulator</h1>
|
| 1502 |
+
<label className="block text-sm mt-4">Session ID</label>
|
| 1503 |
+
<input className="border rounded w-full p-2" value={sessionId} onChange={e=>setSessionId(e.target.value)} placeholder="paste session id"/>
|
| 1504 |
+
<label className="block text-sm mt-3">Device ID</label>
|
| 1505 |
+
<input className="border rounded w-full p-2" value={deviceId} onChange={e=>setDeviceId(e.target.value)} />
|
| 1506 |
+
<label className="block text-sm mt-3">Battery</label>
|
| 1507 |
+
<input type="number" className="border rounded w-full p-2" value={battery} onChange={e=>setBattery(Number(e.target.value))} />
|
| 1508 |
+
<div className="mt-3 flex gap-2">
|
| 1509 |
+
<button onClick={connect} className="px-3 py-2 rounded bg-black text-white">Connect</button>
|
| 1510 |
+
<button onClick={sendTelemetry} className="px-3 py-2 rounded border">Send Telemetry</button>
|
| 1511 |
+
</div>
|
| 1512 |
+
<div className="mt-4 text-xs bg-gray-50 border rounded p-3 h-64 overflow-auto whitespace-pre-wrap">
|
| 1513 |
+
{log.map((l,i)=><div key={i}>{l}</div>)}
|
| 1514 |
+
</div>
|
| 1515 |
+
</div>
|
| 1516 |
+
);
|
| 1517 |
+
}
|
| 1518 |
+
|
| 1519 |
+
NEXT_PUBLIC_API=http://localhost:8000
|
| 1520 |
+
NEXT_PUBLIC_WS=ws://localhost:8000
|
| 1521 |
+
|
| 1522 |
+
{"kind":"hello","device_id":"rb-123","device_type":"AR Glasses","battery":94}
|
| 1523 |
+
{"kind":"telemetry","device_id":"rb-123","battery":93,"pose":{"lat":..,"lon":..},"sensors":{"light":..}}
|
| 1524 |
+
{"kind":"event","device_id":"rb-123","name":"photo_captured","data":{"uri":"..."}}
|