Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# Sir,
|
| 2 |
|
| 3 |
from fastapi import FastAPI, WebSocket
|
| 4 |
from fastapi.responses import HTMLResponse, StreamingResponse
|
|
@@ -23,64 +23,78 @@ async def stream():
|
|
| 23 |
body{margin:0;padding:20px;background:#eef6fc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;}
|
| 24 |
h1{color:#034f84;}
|
| 25 |
#status{font-weight:bold;color:#fc3d03;margin:10px 0;}
|
| 26 |
-
#streams{display:flex;gap:10px;width:100%;max-width:680px;}
|
| 27 |
video{border:2px solid #034f84;border-radius:8px;width:50%;height:auto;}
|
|
|
|
|
|
|
| 28 |
</style>
|
| 29 |
</head>
|
| 30 |
<body>
|
| 31 |
<h1>Emerson Telemetry Stream</h1>
|
| 32 |
-
<
|
| 33 |
-
<
|
|
|
|
| 34 |
<video id="video-back" autoplay muted playsinline></video>
|
| 35 |
<video id="video-front" autoplay muted playsinline></video>
|
| 36 |
</div>
|
| 37 |
<script>
|
|
|
|
| 38 |
const statusEl = document.getElementById('status');
|
| 39 |
-
let buffer = []
|
| 40 |
-
|
| 41 |
function initWS() {
|
| 42 |
ws = new WebSocket(`wss://${location.host}/ws`);
|
| 43 |
-
ws.onopen = () => { statusEl.textContent='
|
| 44 |
ws.onclose = () => statusEl.textContent='Disconnected';
|
| 45 |
ws.onerror = () => statusEl.textContent='WebSocket error';
|
| 46 |
}
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
function sendTelemetry() {
|
| 49 |
const backV = document.getElementById('video-back');
|
| 50 |
const frontV = document.getElementById('video-front');
|
| 51 |
if(!backV.videoWidth || !frontV.videoWidth) return;
|
|
|
|
| 52 |
const cb = document.createElement('canvas'); cb.width=backV.videoWidth; cb.height=backV.videoHeight;
|
| 53 |
cb.getContext('2d').drawImage(backV,0,0);
|
| 54 |
const cf = document.createElement('canvas'); cf.width=frontV.videoWidth; cf.height=frontV.videoHeight;
|
| 55 |
cf.getContext('2d').drawImage(frontV,0,0);
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
| 63 |
}
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
}
|
| 68 |
-
|
| 69 |
-
Promise.all([
|
| 70 |
-
navigator.mediaDevices.getUserMedia({ video:{ facingMode:'environment' } }),
|
| 71 |
-
navigator.mediaDevices.getUserMedia({ video:{ facingMode:'user' } })
|
| 72 |
-
]).then(([backStream, frontStream])=>{
|
| 73 |
-
document.getElementById('video-back').srcObject=backStream;
|
| 74 |
-
document.getElementById('video-front').srcObject=frontStream;
|
| 75 |
-
statusEl.textContent = navigator.onLine ? 'Connected' : 'Waiting for Emerson...';
|
| 76 |
-
initWS();
|
| 77 |
-
window.addEventListener('online', ()=>flushBuffer());
|
| 78 |
-
window.addEventListener('offline', ()=>statusEl.textContent='Waiting for Emerson...');
|
| 79 |
-
setInterval(sendTelemetry,1000);
|
| 80 |
-
}).catch(err=>{
|
| 81 |
-
console.error('Camera error',err);
|
| 82 |
-
statusEl.textContent='Camera permission needed';
|
| 83 |
-
});
|
| 84 |
</script>
|
| 85 |
</body>
|
| 86 |
</html>
|
|
@@ -123,28 +137,28 @@ async def dashboard():
|
|
| 123 |
<a href="/download-csv" download="telemetry.csv">Download CSV</a>
|
| 124 |
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
|
| 125 |
<script>
|
| 126 |
-
const statusEl=document.getElementById('status');
|
| 127 |
-
const speedEl=document.getElementById('speed');
|
| 128 |
-
const altEl=document.getElementById('altitude');
|
| 129 |
-
const imgBack=document.getElementById('img-back');
|
| 130 |
-
const imgFront=document.getElementById('img-front');
|
| 131 |
-
const map=L.map('map')
|
| 132 |
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19}).addTo(map);
|
| 133 |
-
const marker=L.marker([0,0]).addTo(map);
|
| 134 |
-
|
| 135 |
-
ws
|
| 136 |
-
ws.
|
| 137 |
-
ws.
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
marker.setLatLng([
|
| 145 |
-
map.setView([
|
| 146 |
-
imgBack.src=d.images.back;
|
| 147 |
-
imgFront.src=d.images.front;
|
| 148 |
};
|
| 149 |
</script>
|
| 150 |
</body>
|
|
@@ -155,30 +169,30 @@ async def dashboard():
|
|
| 155 |
@app.get("/download-csv")
|
| 156 |
async def download_csv():
|
| 157 |
def iter_csv():
|
| 158 |
-
si=StringIO()
|
| 159 |
-
writer=csv.writer(si)
|
| 160 |
writer.writerow(["timestamp","latitude","longitude","altitude","speed","back_image","front_image"])
|
| 161 |
for d in telemetry_data:
|
| 162 |
writer.writerow([
|
| 163 |
d["timestamp"],d["gps"]["latitude"],d["gps"]["longitude"],
|
| 164 |
d["gps"]["altitude"],d["gps"]["speed"],
|
| 165 |
d["images"]["back"],d["images"]["front"]
|
| 166 |
-
])
|
| 167 |
yield si.getvalue(); si.seek(0); si.truncate(0)
|
| 168 |
return StreamingResponse(iter_csv(),media_type="text/csv")
|
| 169 |
|
| 170 |
@app.websocket("/ws")
|
| 171 |
async def websocket_endpoint(ws:WebSocket):
|
| 172 |
-
await ws.accept();dashboard_connections.append(ws)
|
| 173 |
try:
|
| 174 |
while True:
|
| 175 |
-
msg=await ws.receive_text();obj=json.loads(msg)
|
| 176 |
telemetry_data.append(obj)
|
| 177 |
for conn in dashboard_connections:
|
| 178 |
-
try:await conn.send_text(json.dumps(obj))
|
| 179 |
-
except:dashboard_connections.remove(conn)
|
| 180 |
except:
|
| 181 |
dashboard_connections.remove(ws)
|
| 182 |
|
| 183 |
-
if __name__ =="__main__":
|
| 184 |
-
uvicorn.run(app,host="0.0.0.0",port=7860)
|
|
|
|
| 1 |
+
# Sir, updated to require user interaction to start streaming, request camera and GPS permissions with high accuracy, and fix dashboard map centering on first real telemetry.
|
| 2 |
|
| 3 |
from fastapi import FastAPI, WebSocket
|
| 4 |
from fastapi.responses import HTMLResponse, StreamingResponse
|
|
|
|
| 23 |
body{margin:0;padding:20px;background:#eef6fc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;}
|
| 24 |
h1{color:#034f84;}
|
| 25 |
#status{font-weight:bold;color:#fc3d03;margin:10px 0;}
|
| 26 |
+
#streams{display:flex;gap:10px;width:100%;max-width:680px;margin-top:10px;}
|
| 27 |
video{border:2px solid #034f84;border-radius:8px;width:50%;height:auto;}
|
| 28 |
+
button{padding:10px 20px;font-size:1rem;border:none;border-radius:5px;background:#034f84;color:white;cursor:pointer;}
|
| 29 |
+
button:disabled{background:#ccc;cursor:default;}
|
| 30 |
</style>
|
| 31 |
</head>
|
| 32 |
<body>
|
| 33 |
<h1>Emerson Telemetry Stream</h1>
|
| 34 |
+
<button id="start">Start Streaming</button>
|
| 35 |
+
<p id="status">Click "Start Streaming" to begin.</p>
|
| 36 |
+
<div id="streams" style="display:none;">
|
| 37 |
<video id="video-back" autoplay muted playsinline></video>
|
| 38 |
<video id="video-front" autoplay muted playsinline></video>
|
| 39 |
</div>
|
| 40 |
<script>
|
| 41 |
+
const startBtn = document.getElementById('start');
|
| 42 |
const statusEl = document.getElementById('status');
|
| 43 |
+
let ws, buffer = [];
|
|
|
|
| 44 |
function initWS() {
|
| 45 |
ws = new WebSocket(`wss://${location.host}/ws`);
|
| 46 |
+
ws.onopen = () => { statusEl.textContent='Streaming'; flushBuffer(); };
|
| 47 |
ws.onclose = () => statusEl.textContent='Disconnected';
|
| 48 |
ws.onerror = () => statusEl.textContent='WebSocket error';
|
| 49 |
}
|
| 50 |
+
function flushBuffer() {
|
| 51 |
+
while(buffer.length && ws.readyState===WebSocket.OPEN) {
|
| 52 |
+
ws.send(buffer.shift());
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
function sendTelemetry() {
|
| 56 |
const backV = document.getElementById('video-back');
|
| 57 |
const frontV = document.getElementById('video-front');
|
| 58 |
if(!backV.videoWidth || !frontV.videoWidth) return;
|
| 59 |
+
// capture images
|
| 60 |
const cb = document.createElement('canvas'); cb.width=backV.videoWidth; cb.height=backV.videoHeight;
|
| 61 |
cb.getContext('2d').drawImage(backV,0,0);
|
| 62 |
const cf = document.createElement('canvas'); cf.width=frontV.videoWidth; cf.height=frontV.videoHeight;
|
| 63 |
cf.getContext('2d').drawImage(frontV,0,0);
|
| 64 |
+
// request high-accuracy GPS
|
| 65 |
+
navigator.geolocation.getCurrentPosition(pos => {
|
| 66 |
+
const data = { timestamp: Date.now(), gps: { latitude: pos.coords.latitude, longitude: pos.coords.longitude, altitude: pos.coords.altitude, speed: pos.coords.speed }, images: { back: cb.toDataURL('image/jpeg'), front: cf.toDataURL('image/jpeg') } };
|
| 67 |
+
const msg = JSON.stringify(data);
|
| 68 |
+
if(ws.readyState===WebSocket.OPEN) ws.send(msg); else buffer.push(msg);
|
| 69 |
+
}, err => {
|
| 70 |
+
console.error('GPS error', err);
|
| 71 |
+
statusEl.textContent='GPS permission needed';
|
| 72 |
+
}, { enableHighAccuracy: true });
|
| 73 |
}
|
| 74 |
+
async function startStreaming() {
|
| 75 |
+
startBtn.disabled = true;
|
| 76 |
+
try {
|
| 77 |
+
// ask for camera permission
|
| 78 |
+
const [backStream, frontStream] = await Promise.all([
|
| 79 |
+
navigator.mediaDevices.getUserMedia({ video:{ facingMode:'environment' } }),
|
| 80 |
+
navigator.mediaDevices.getUserMedia({ video:{ facingMode:'user' } })
|
| 81 |
+
]);
|
| 82 |
+
document.getElementById('video-back').srcObject = backStream;
|
| 83 |
+
document.getElementById('video-front').srcObject = frontStream;
|
| 84 |
+
document.getElementById('streams').style.display = 'flex';
|
| 85 |
+
statusEl.textContent = 'Initializing...';
|
| 86 |
+
// ask for GPS permission
|
| 87 |
+
navigator.geolocation.getCurrentPosition(() => {}, err => { console.error('GPS permission needed', err); statusEl.textContent='GPS permission needed'; }, { enableHighAccuracy: true });
|
| 88 |
+
initWS();
|
| 89 |
+
window.addEventListener('online', () => flushBuffer());
|
| 90 |
+
window.addEventListener('offline', () => statusEl.textContent='Waiting for Emerson...');
|
| 91 |
+
setInterval(sendTelemetry, 1000);
|
| 92 |
+
} catch (err) {
|
| 93 |
+
console.error('Permission error', err);
|
| 94 |
+
statusEl.textContent = 'Camera permission needed';
|
| 95 |
+
}
|
| 96 |
}
|
| 97 |
+
startBtn.addEventListener('click', startStreaming);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
</script>
|
| 99 |
</body>
|
| 100 |
</html>
|
|
|
|
| 137 |
<a href="/download-csv" download="telemetry.csv">Download CSV</a>
|
| 138 |
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
|
| 139 |
<script>
|
| 140 |
+
const statusEl = document.getElementById('status');
|
| 141 |
+
const speedEl = document.getElementById('speed');
|
| 142 |
+
const altEl = document.getElementById('altitude');
|
| 143 |
+
const imgBack = document.getElementById('img-back');
|
| 144 |
+
const imgFront = document.getElementById('img-front');
|
| 145 |
+
const map = L.map('map');
|
| 146 |
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19}).addTo(map);
|
| 147 |
+
const marker = L.marker([0,0]).addTo(map);
|
| 148 |
+
let first = true;
|
| 149 |
+
const ws = new WebSocket(`wss://${location.host}/ws`);
|
| 150 |
+
ws.onopen = ()=> statusEl.textContent='Connected';
|
| 151 |
+
ws.onclose = ()=> statusEl.textContent='Disconnected';
|
| 152 |
+
ws.onmessage = evt => {
|
| 153 |
+
const d = JSON.parse(evt.data);
|
| 154 |
+
statusEl.textContent = 'Streaming';
|
| 155 |
+
speedEl.innerHTML = `Speed:<br>${d.gps.speed!=null?d.gps.speed.toFixed(2):'--'} m/s`;
|
| 156 |
+
altEl.innerHTML = `Altitude:<br>${d.gps.altitude!=null?d.gps.altitude.toFixed(1):'--'} m`;
|
| 157 |
+
const lat = d.gps.latitude, lon = d.gps.longitude;
|
| 158 |
+
marker.setLatLng([lat,lon]);
|
| 159 |
+
if(first){ map.setView([lat,lon],13); first = false;} else map.setView([lat,lon],map.getZoom());
|
| 160 |
+
imgBack.src = d.images.back;
|
| 161 |
+
imgFront.src = d.images.front;
|
| 162 |
};
|
| 163 |
</script>
|
| 164 |
</body>
|
|
|
|
| 169 |
@app.get("/download-csv")
|
| 170 |
async def download_csv():
|
| 171 |
def iter_csv():
|
| 172 |
+
si = StringIO()
|
| 173 |
+
writer = csv.writer(si)
|
| 174 |
writer.writerow(["timestamp","latitude","longitude","altitude","speed","back_image","front_image"])
|
| 175 |
for d in telemetry_data:
|
| 176 |
writer.writerow([
|
| 177 |
d["timestamp"],d["gps"]["latitude"],d["gps"]["longitude"],
|
| 178 |
d["gps"]["altitude"],d["gps"]["speed"],
|
| 179 |
d["images"]["back"],d["images"]["front"]
|
| 180 |
+
])
|
| 181 |
yield si.getvalue(); si.seek(0); si.truncate(0)
|
| 182 |
return StreamingResponse(iter_csv(),media_type="text/csv")
|
| 183 |
|
| 184 |
@app.websocket("/ws")
|
| 185 |
async def websocket_endpoint(ws:WebSocket):
|
| 186 |
+
await ws.accept(); dashboard_connections.append(ws)
|
| 187 |
try:
|
| 188 |
while True:
|
| 189 |
+
msg = await ws.receive_text(); obj = json.loads(msg)
|
| 190 |
telemetry_data.append(obj)
|
| 191 |
for conn in dashboard_connections:
|
| 192 |
+
try: await conn.send_text(json.dumps(obj))
|
| 193 |
+
except: dashboard_connections.remove(conn)
|
| 194 |
except:
|
| 195 |
dashboard_connections.remove(ws)
|
| 196 |
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|