feat: add CORS support and enhance session routes for better sensor management
This commit is contained in:
78
realtime/client-example.js
Normal file
78
realtime/client-example.js
Normal file
@@ -0,0 +1,78 @@
|
||||
const WebSocket = require('ws');
|
||||
const { encode } = require('@msgpack/msgpack');
|
||||
|
||||
const SERVER_URL = process.env.SERVER_URL || 'http://localhost:3000';
|
||||
const WS_URL = process.env.WS_URL || 'ws://localhost:3000';
|
||||
const SENSOR_NAME = process.env.SENSOR_NAME || 'sensor-01';
|
||||
const SENSOR_CODE = process.env.SENSOR_CODE || 'password123';
|
||||
|
||||
async function authenticate() {
|
||||
const res = await fetch(`${SERVER_URL}/connect/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: SENSOR_NAME, code: SENSOR_CODE }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new Error(`Auth failed: ${err.error}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
console.log('Authenticated, token received');
|
||||
return data.t;
|
||||
}
|
||||
|
||||
function connectWebSocket(token) {
|
||||
const ws = new WebSocket(`${WS_URL}?token=${token}`);
|
||||
|
||||
ws.on('open', () => {
|
||||
console.log('WebSocket connected');
|
||||
startSendingData(ws);
|
||||
});
|
||||
|
||||
ws.on('pong', () => {
|
||||
// Keepalive pong received
|
||||
});
|
||||
|
||||
ws.on('close', (code, reason) => {
|
||||
console.log(`WebSocket closed: ${code} ${reason}`);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
ws.on('error', (err) => {
|
||||
console.error('WebSocket error:', err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function startSendingData(ws) {
|
||||
setInterval(() => {
|
||||
if (ws.readyState !== WebSocket.OPEN) return;
|
||||
|
||||
const packet = {
|
||||
ts: Date.now(),
|
||||
t: 20 + Math.random() * 10, // temperature °C
|
||||
h: 50 + Math.random() * 30, // humidity %
|
||||
spd: Math.random() * 30, // speed
|
||||
cog: Math.random() * 360, // course over ground
|
||||
sog: 5 + Math.random() * 10, // speed over ground kn
|
||||
hdg: Math.random() * 360, // heading true
|
||||
lat: 43.7230 + Math.random() * 0.01, // latitude
|
||||
lon: 10.3966 + Math.random() * 0.01, // longitude
|
||||
};
|
||||
|
||||
ws.send(Buffer.from(encode(packet)));
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const token = await authenticate();
|
||||
connectWebSocket(token);
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in New Issue
Block a user