1+ import { WebSocketServer } from "ws" ;
2+
3+ export const telemetryState = {
4+ altitude : 120 ,
5+ speed : 8.5 ,
6+ battery : 78 ,
7+ gps : "RTK Fixed" ,
8+ heading : 142 ,
9+ } ;
10+
11+ function jitter ( n , amp ) {
12+ return n + ( Math . random ( ) * 2 - 1 ) * amp ;
13+ }
14+
15+ function tickMock ( ) {
16+ telemetryState . altitude = Math . max ( 0 , jitter ( telemetryState . altitude , 0.8 ) ) ;
17+ telemetryState . speed = Math . max ( 0 , jitter ( telemetryState . speed , 0.2 ) ) ;
18+ telemetryState . battery = Math . max ( 0 , telemetryState . battery - Math . random ( ) * 0.02 ) ;
19+ telemetryState . heading = ( telemetryState . heading + Math . random ( ) * 2 ) % 360 ;
20+
21+ // GPS status pseudo
22+ const r = Math . random ( ) ;
23+ telemetryState . gps = r < 0.92 ? "RTK Fixed" : r < 0.98 ? "RTK Float" : "3D Fix" ;
24+ }
25+
26+ export function attachTelemetryWs ( httpServer ) {
27+ const wss = new WebSocketServer ( { server : httpServer , path : "/ws/telemetry" } ) ;
28+
29+ wss . on ( "connection" , ( ws ) => {
30+ ws . send ( JSON . stringify ( { type : "telemetry" , data : telemetryState , ts : Date . now ( ) } ) ) ;
31+
32+ ws . on ( "message" , ( raw ) => {
33+ // future: allow client subscriptions, rate control, etc.
34+ try {
35+ const msg = JSON . parse ( String ( raw ) ) ;
36+ if ( msg ?. type === "ping" ) ws . send ( JSON . stringify ( { type : "pong" , ts : Date . now ( ) } ) ) ;
37+ } catch ( _ ) { }
38+ } ) ;
39+ } ) ;
40+
41+ // broadcast loop
42+ setInterval ( ( ) => {
43+ tickMock ( ) ;
44+ const payload = JSON . stringify ( { type : "telemetry" , data : telemetryState , ts : Date . now ( ) } ) ;
45+ for ( const client of wss . clients ) {
46+ if ( client . readyState === 1 ) client . send ( payload ) ;
47+ }
48+ } , 500 ) ;
49+
50+ console . log ( "[DroneHybrid] WS telemetry ready at /ws/telemetry" ) ;
51+ }
0 commit comments