Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
187 lines (153 loc) · 4.69 KB
/
Copy pathserver.js
File metadata and controls
187 lines (153 loc) · 4.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const dgram = require('dgram');
const path = require('path');
const { parseForzaTelemetry, carClassToText, drivetrainToText } = require('./forzaParser');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
transports: ['websocket'],
cors: { origin: '*' }
});
const udp = dgram.createSocket('udp4');
const UDP_PORT = Number(process.env.FH5_UDP_PORT || 5300);
const UDP_HOST = process.env.FH5_UDP_HOST || '0.0.0.0';
const WEB_PORT = Number(process.env.PORT || 3000);
const TELEMETRY_BYTES = 323;
const stats = {
packets: 0,
parsed: 0,
dropped: 0,
parseErrors: 0,
startedAt: new Date().toISOString()
};
let latestTelemetry = null;
app.use(express.static(path.join(__dirname, 'public')));
app.get('/api/telemetry/latest', (_req, res) => {
if (!latestTelemetry) {
res.status(204).end();
return;
}
res.json(latestTelemetry);
});
app.get('/api/stats', (_req, res) => {
res.json({
...stats,
clients: io.engine.clientsCount,
udpPort: UDP_PORT,
webPort: WEB_PORT,
lastPacketAt: latestTelemetry?.receivedAt || null
});
});
function clamp(v, min, max) {
return Math.max(min, Math.min(max, v));
}
function toFuelPercent(v) {
const n = Number(v);
if (!Number.isFinite(n)) return 0;
const percent = n <= 1.2 ? n * 100 : n;
return clamp(percent, 0, 100);
}
function psiToBar(psi) {
const n = Number(psi);
if (!Number.isFinite(n)) return 0;
return n * 0.0689475729;
}
function gearToText(raw) {
if (raw === 0) return 'R';
if (raw === 1) return 'N';
return String(Math.max(1, raw - 1));
}
io.on('connection', (socket) => {
console.log('[socket] connected:', socket.id);
if (latestTelemetry) {
socket.emit('telemetry', latestTelemetry);
}
socket.on('disconnect', (reason) => {
console.log('[socket] disconnected:', socket.id, reason);
});
});
udp.on('message', (msg, rinfo) => {
stats.packets += 1;
if (msg.length < TELEMETRY_BYTES) {
stats.dropped += 1;
return;
}
try {
const packet = msg.length === TELEMETRY_BYTES ? msg : msg.subarray(0, TELEMETRY_BYTES);
const p = parseForzaTelemetry(packet);
const data = {
isRaceOn: p.isRaceOn,
timeStampMS: p.timeStampMS,
rpm: Math.round(p.currentEngineRpm),
maxRpm: Math.round(p.engineMaxRpm),
idleRpm: Math.round(p.engineIdleRpm),
speed: Math.round(p.speedKph),
speedMps: p.speed,
speedMph: Math.round(p.speedMph),
power: p.power,
torque: p.torque,
boost: Number(psiToBar(p.boost).toFixed(2)),
boostPsi: Number((Number(p.boost) || 0).toFixed(2)),
fuel: Number(toFuelPercent(p.fuel).toFixed(2)),
bestLap: p.bestLap,
lastLap: p.lastLap,
currentLap: p.currentLap,
currentRaceTime: p.currentRaceTime,
lapNumber: p.lapNumber,
racePosition: p.racePosition,
throttle: p.throttle,
throttleRaw: p.throttleRaw,
brake: p.brake,
brakeRaw: p.brakeRaw,
clutch: p.clutch,
clutchRaw: p.clutchRaw,
handbrake: p.handbrake,
handbrakeRaw: p.handbrakeRaw,
gear: gearToText(p.gearRaw),
gearRaw: p.gearRaw,
steer: p.steer,
carOrdinal: p.ordinal,
carClass: carClassToText(p.carClass),
carPerformanceIndex: p.carPerformanceIndex,
drivetrain: drivetrainToText(p.drivetrainType),
numOfCylinders: p.numOfCylinders,
carType: p.carType,
packetBytes: msg.length,
receivedAt: Date.now(),
source: `${rinfo.address}:${rinfo.port}`
};
stats.parsed += 1;
latestTelemetry = data;
io.emit('telemetry', data);
} catch (err) {
stats.parseErrors += 1;
console.error('[udp parse error]', err.message);
}
});
udp.on('listening', () => {
const addr = udp.address();
console.log(`[udp] listening on ${addr.address}:${addr.port}`);
console.log(`[udp] expect >= ${TELEMETRY_BYTES} bytes; auto-trim extra bytes`);
});
udp.on('error', (err) => {
if (err && err.code === 'EADDRINUSE') {
console.error(`[udp error] port ${UDP_PORT} is already in use. Stop the other process or change FH5_UDP_PORT.`);
return;
}
console.error('[udp error]', err);
});
udp.bind(UDP_PORT, UDP_HOST);
server.on('error', (err) => {
if (err && err.code === 'EADDRINUSE') {
console.error(`[web error] port ${WEB_PORT} is already in use. Stop the other process or set PORT.`);
return;
}
console.error('[web error]', err);
});
server.listen(WEB_PORT, () => {
console.log(`[web] http://localhost:${WEB_PORT}`);
console.log(`[api] http://localhost:${WEB_PORT}/api/telemetry/latest`);
console.log(`[api] http://localhost:${WEB_PORT}/api/stats`);
});