|
| 1 | +const WebSocket = require('ws'); |
| 2 | +const readline = require('readline'); |
| 3 | + |
| 4 | +let connected = false; |
| 5 | + |
| 6 | +const wss = new WebSocket.Server({ port: 8000, clientTracking: true }); |
| 7 | + |
| 8 | +function broadcast(message) { |
| 9 | + for (const client of wss.clients) { |
| 10 | + if (client.readyState == WebSocket.OPEN) { |
| 11 | + client.send(message); |
| 12 | + } |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +function sendData() { |
| 17 | + setTimeout(sendData, 500); |
| 18 | + if (!connected) return; |
| 19 | + |
| 20 | + broadcast(JSON.stringify({ type: 'json', data: { altitude: Math.random() * 100 }})); |
| 21 | + broadcast(JSON.stringify({ |
| 22 | + type: 'json', |
| 23 | + data: { |
| 24 | + position: { |
| 25 | + latDeg: Math.floor(Math.random() * 360 - 180), |
| 26 | + longDeg: Math.floor(Math.random() * 360 - 180), |
| 27 | + latMin: Math.random() * 60, |
| 28 | + longMin: Math.random() * 60, |
| 29 | + satellites: Math.floor(Math.random() * 3 + 5), |
| 30 | + }, |
| 31 | + }, |
| 32 | + })); |
| 33 | + broadcast(JSON.stringify({ type: 'json', data: { airspeed: Math.random() * 50 }})); |
| 34 | + // still need orientation...that may end up in a different format |
| 35 | +} |
| 36 | + |
| 37 | +wss.on('connection', client => { |
| 38 | + client.send(JSON.stringify({ type: 'status', status: connected ? 'open' : 'closed' })); |
| 39 | +}); |
| 40 | + |
| 41 | +console.log('Listening on port 8000. Press enter to toggle whether port is connected.'); |
| 42 | +process.stdout.write('Port is disconnected.'); |
| 43 | + |
| 44 | +const rl = readline.createInterface({ |
| 45 | + input: process.stdin, |
| 46 | + output: process.stdout, |
| 47 | + terminal: false, |
| 48 | +}); |
| 49 | + |
| 50 | +rl.on('line', line => { |
| 51 | + connected = !connected; |
| 52 | + process.stdout.write(`Port is ${connected ? 'connected' : 'disconnected'}.`); |
| 53 | + broadcast(JSON.stringify({ type: 'status', status: connected ? 'open' : 'closed' })); |
| 54 | +}); |
| 55 | + |
| 56 | +sendData(); |
0 commit comments