ebc33a78b7
- server/: Node bridge (datarefs/commands, navdata, CIFP procedures, flight plan) - web/: React cockpit (PFD/MFD/Map, VFR six-pack, AFCS, FMS CDU), PWA, collapsible sidebar - desktop/: Tauri 2 launcher (Bun sidecar, system tray, updater) + Linux build via Docker - scripts/: prep-desktop, build-linux, Gitea release + latest.json Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
306 lines
12 KiB
JavaScript
306 lines
12 KiB
JavaScript
// X-Plane Glass Cockpit — Bridge
|
|
// -------------------------------------------------------------------------
|
|
// Connects to X-Plane 12's built-in web API (localhost only), resolves
|
|
// dataref/command names to per-session IDs, subscribes to live values, and
|
|
// fans them out over a LAN-facing WebSocket to any number of tablets/laptops.
|
|
// Also serves the built React UI.
|
|
|
|
import express from 'express';
|
|
import { WebSocketServer, WebSocket as WsClient } from 'ws';
|
|
import http from 'node:http';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { CONFIG, DATAREFS, WRITABLE_DATAREFS, COMMANDS } from './config.js';
|
|
import { loadNavData, search as navSearch, navStatus, nearest as navNearest, bbox as navBbox, runwaysNear as navRunways } from './navdata.js';
|
|
import { parseProcedures, procedureLegs as procLegs } from './procedures.js';
|
|
import * as fp from './flightplan.js';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
// WEB_DIST can be overridden (e.g. the desktop app points it at the cockpit
|
|
// files it bundles as a resource); otherwise default to ../web/dist.
|
|
const WEB_DIST = process.env.WEB_DIST || path.join(__dirname, '..', 'web', 'dist');
|
|
const REST = `http://${CONFIG.xplaneHost}:${CONFIG.xplanePort}${CONFIG.xplaneApiBase}`;
|
|
const WS_URL = `ws://${CONFIG.xplaneHost}:${CONFIG.xplanePort}${CONFIG.xplaneApiBase}`;
|
|
|
|
const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
|
|
|
|
// ---- shared state ---------------------------------------------------------
|
|
const state = {
|
|
xpConnected: false,
|
|
values: {}, // alias -> latest value
|
|
drefIdToAlias: new Map(), // X-Plane dataref id -> our alias
|
|
drefNameToId: new Map(), // sim/... -> id
|
|
cmdNameToId: new Map(), // sim/... -> id
|
|
xpSocket: null,
|
|
reqId: 1,
|
|
};
|
|
|
|
const clients = new Set(); // connected browser sockets
|
|
|
|
// ---- helpers --------------------------------------------------------------
|
|
function broadcast(obj) {
|
|
const msg = JSON.stringify(obj);
|
|
for (const c of clients) {
|
|
if (c.readyState === WsClient.OPEN) c.send(msg);
|
|
}
|
|
}
|
|
|
|
function broadcastPlan() {
|
|
broadcast({ type: 'flightplan', data: fp.getPlan() });
|
|
}
|
|
|
|
async function fetchAllByName(resource, names) {
|
|
// X-Plane's list endpoints can be filtered by name. We query each name so we
|
|
// don't pull the full ~15k dataref catalogue.
|
|
const map = new Map();
|
|
await Promise.all(
|
|
[...new Set(names)].map(async (name) => {
|
|
try {
|
|
const url = `${REST}/${resource}?filter[name]=${encodeURIComponent(name)}`;
|
|
const res = await fetch(url, { headers: { Accept: 'application/json' } });
|
|
if (!res.ok) return;
|
|
const body = await res.json();
|
|
const item = (body.data || []).find((d) => d.name === name);
|
|
if (item) map.set(name, item.id);
|
|
else log(`! ${resource} not found: ${name}`);
|
|
} catch (e) {
|
|
log(`! lookup failed for ${name}: ${e.message}`);
|
|
}
|
|
})
|
|
);
|
|
return map;
|
|
}
|
|
|
|
// ---- X-Plane connection ---------------------------------------------------
|
|
async function resolveIds() {
|
|
const drefNames = Object.values(DATAREFS);
|
|
const cmdNames = Object.values(COMMANDS);
|
|
state.drefNameToId = await fetchAllByName('datarefs', [
|
|
...drefNames,
|
|
...Object.values(WRITABLE_DATAREFS),
|
|
]);
|
|
state.cmdNameToId = await fetchAllByName('commands', cmdNames);
|
|
|
|
// build reverse map id -> alias for incoming updates
|
|
state.drefIdToAlias.clear();
|
|
for (const [alias, name] of Object.entries(DATAREFS)) {
|
|
const id = state.drefNameToId.get(name);
|
|
if (id != null) state.drefIdToAlias.set(id, alias);
|
|
}
|
|
log(`resolved ${state.drefNameToId.size} datarefs, ${state.cmdNameToId.size} commands`);
|
|
}
|
|
|
|
function subscribeValues() {
|
|
const datarefs = [];
|
|
for (const id of state.drefIdToAlias.keys()) datarefs.push({ id });
|
|
if (!datarefs.length) return;
|
|
state.xpSocket.send(
|
|
JSON.stringify({
|
|
req_id: state.reqId++,
|
|
type: 'dataref_subscribe_values',
|
|
params: { datarefs },
|
|
})
|
|
);
|
|
log(`subscribed to ${datarefs.length} datarefs`);
|
|
}
|
|
|
|
function connectXPlane() {
|
|
log(`connecting to X-Plane @ ${WS_URL} ...`);
|
|
let sock;
|
|
try {
|
|
sock = new WsClient(WS_URL);
|
|
} catch (e) {
|
|
log('X-Plane connect threw, retrying in 3s:', e.message);
|
|
return setTimeout(connectXPlane, 3000);
|
|
}
|
|
state.xpSocket = sock;
|
|
|
|
sock.on('open', async () => {
|
|
try {
|
|
await resolveIds();
|
|
subscribeValues();
|
|
state.xpConnected = true;
|
|
broadcast({ type: 'status', xpConnected: true });
|
|
log('X-Plane connected ✓');
|
|
} catch (e) {
|
|
log('setup after connect failed:', e.message);
|
|
}
|
|
});
|
|
|
|
sock.on('message', (raw) => {
|
|
let msg;
|
|
try { msg = JSON.parse(raw); } catch { return; }
|
|
if (msg.type === 'dataref_update_values' && msg.data) {
|
|
const patch = {};
|
|
for (const [id, value] of Object.entries(msg.data)) {
|
|
const alias = state.drefIdToAlias.get(Number(id));
|
|
if (alias) { state.values[alias] = value; patch[alias] = value; }
|
|
}
|
|
if (Object.keys(patch).length) broadcast({ type: 'values', data: patch });
|
|
}
|
|
});
|
|
|
|
const onDown = (why) => {
|
|
if (state.xpConnected) log(`X-Plane disconnected (${why})`);
|
|
state.xpConnected = false;
|
|
broadcast({ type: 'status', xpConnected: false });
|
|
if (state.xpSocket === sock) state.xpSocket = null;
|
|
setTimeout(connectXPlane, 3000);
|
|
};
|
|
sock.on('close', () => onDown('close'));
|
|
sock.on('error', (e) => onDown(e.message));
|
|
}
|
|
|
|
// ---- commands coming FROM the browser ------------------------------------
|
|
function handleClientMessage(msg) {
|
|
// --- flight plan (works even without a sim connection) ---
|
|
if (msg.type === 'fp_set') { fp.setPlan(msg.plan); return broadcastPlan(); }
|
|
if (msg.type === 'fp_add') {
|
|
const r = fp.addWaypoint(msg.ident);
|
|
if (!r.ok) return; // silently ignore unknown idents
|
|
return broadcastPlan();
|
|
}
|
|
if (msg.type === 'fp_remove') { fp.removeWaypoint(msg.index); return broadcastPlan(); }
|
|
if (msg.type === 'fp_active') { fp.setActiveLeg(msg.index); return broadcastPlan(); }
|
|
if (msg.type === 'fp_clear') { fp.setPlan({ waypoints: [] }); return broadcastPlan(); }
|
|
if (msg.type === 'fp_export') {
|
|
const r = fp.exportFms(msg.name || 'WEBFPL');
|
|
broadcast({ type: 'fp_export_result', ...r });
|
|
return;
|
|
}
|
|
|
|
// --- everything below talks to X-Plane; needs a live sim socket ---
|
|
if (!state.xpSocket || state.xpSocket.readyState !== WsClient.OPEN) return;
|
|
|
|
if (msg.type === 'command') {
|
|
const name = COMMANDS[msg.name];
|
|
const id = name && state.cmdNameToId.get(name);
|
|
if (id == null) return log(`! unknown command alias: ${msg.name}`);
|
|
state.xpSocket.send(
|
|
JSON.stringify({
|
|
req_id: state.reqId++,
|
|
type: 'command_set_is_active',
|
|
params: { commands: [{ id, is_active: true, duration: msg.duration ?? 0 }] },
|
|
})
|
|
);
|
|
} else if (msg.type === 'setDataref') {
|
|
const name = WRITABLE_DATAREFS[msg.name];
|
|
const id = name && state.drefNameToId.get(name);
|
|
if (id == null) return log(`! unknown writable dataref alias: ${msg.name}`);
|
|
state.xpSocket.send(
|
|
JSON.stringify({
|
|
req_id: state.reqId++,
|
|
type: 'dataref_set_values',
|
|
params: { datarefs: [{ id, value: Number(msg.value) }] },
|
|
})
|
|
);
|
|
}
|
|
}
|
|
|
|
// ---- HTTP + LAN WebSocket server -----------------------------------------
|
|
const app = express();
|
|
// Allow the desktop launcher (a different origin) to read the JSON API. LAN-only
|
|
// by design, so a wildcard here is harmless and keeps tablets/the app simple.
|
|
app.use('/api', (_req, res, next) => { res.set('Access-Control-Allow-Origin', '*'); next(); });
|
|
app.get('/api/health', (_req, res) =>
|
|
res.json({ xpConnected: state.xpConnected, datarefs: state.drefIdToAlias.size, clients: clients.size, nav: navStatus() })
|
|
);
|
|
// Waypoint / navaid / airport search from X-Plane's own nav database.
|
|
app.get('/api/nav/search', (req, res) => res.json(navSearch(req.query.q || '', 25)));
|
|
// NEAREST airports/navaids to a point (NRST page).
|
|
app.get('/api/nav/nearest', (req, res) =>
|
|
res.json(navNearest(+req.query.lat, +req.query.lon, { count: +req.query.count || 15, type: req.query.type || 'apt' }))
|
|
);
|
|
// Features inside a map window (airports/navaids/fixes) for the moving map.
|
|
app.get('/api/nav/bbox', (req, res) =>
|
|
res.json(navBbox(+req.query.s, +req.query.w, +req.query.n, +req.query.e,
|
|
(req.query.types || 'apt,vor,ndb').split(','), +req.query.limit || 800))
|
|
);
|
|
// Runways near a point — drawn in the PFD synthetic-vision view.
|
|
app.get('/api/nav/runways', (req, res) =>
|
|
res.json(navRunways(+req.query.lat, +req.query.lon, +req.query.radius || 12))
|
|
);
|
|
// PROC: an airport's procedures (SIDs/STARs/approaches) and the resolved leg
|
|
// fixes for a chosen procedure+transition (from X-Plane's CIFP data).
|
|
app.get('/api/nav/procs', (req, res) => {
|
|
const p = parseProcedures(String(req.query.icao || ''));
|
|
if (!p) return res.status(404).json({ error: 'no procedures for ' + req.query.icao });
|
|
res.json({ icao: p.icao, runways: p.runways, sids: p.sids, stars: p.stars, approaches: p.approaches });
|
|
});
|
|
app.get('/api/nav/proc', (req, res) =>
|
|
res.json(procLegs(String(req.query.icao || ''), req.query.type, req.query.name, req.query.trans))
|
|
);
|
|
app.use(express.static(WEB_DIST));
|
|
// SPA fallback so client-side routes work.
|
|
app.get('*', (_req, res) => res.sendFile(path.join(WEB_DIST, 'index.html')));
|
|
|
|
const server = http.createServer(app);
|
|
const wss = new WebSocketServer({ server, path: '/ws' });
|
|
|
|
wss.on('connection', (ws) => {
|
|
clients.add(ws);
|
|
log(`browser connected (${clients.size} total)`);
|
|
// send current snapshot immediately so the UI isn't blank
|
|
ws.send(JSON.stringify({ type: 'status', xpConnected: state.xpConnected }));
|
|
ws.send(JSON.stringify({ type: 'values', data: state.values }));
|
|
ws.send(JSON.stringify({ type: 'flightplan', data: fp.getPlan() }));
|
|
|
|
ws.on('message', (raw) => {
|
|
try { handleClientMessage(JSON.parse(raw)); } catch { /* ignore */ }
|
|
});
|
|
ws.on('close', () => { clients.delete(ws); log(`browser left (${clients.size} total)`); });
|
|
ws.on('error', () => clients.delete(ws));
|
|
});
|
|
|
|
// ---- demo mode: synthetic values when there's no X-Plane (for previews) ---
|
|
function startDemo() {
|
|
log('DEMO mode — emitting synthetic values, not connecting to X-Plane');
|
|
state.xpConnected = true;
|
|
Object.assign(state.values, {
|
|
airspeed: 124, altitude: 5500, vspeed: 320, pitch: 4.5, roll: -12,
|
|
heading: 87, slip: 0.3, gForce: 1.04, oat: 9,
|
|
apState: (1 << 0) | (1 << 1) | (1 << 14), // FD + HDG + ALT
|
|
apEngaged: 1, apHdgBug: 90, apAltBug: 6000, apVsBug: 500, apSpdBug: 120,
|
|
lat: 47.45, lon: -122.31, track: 90, groundspeed: 64, gpsDistNm: 18.4, gpsBearing: 92,
|
|
// radios (XP freq units: nav/com in 10 kHz, e.g. 11030 = 110.30)
|
|
nav1: 11030, nav1Sb: 11150, nav2: 11380, nav2Sb: 10890,
|
|
com1: 12190, com1Sb: 13000, com2: 12475, com2Sb: 12180,
|
|
// HSI / data fields
|
|
obsCrs: 175, hsiDef: -0.6, hsiToFrom: 1, navBearing: 168, gsDef: 0.7,
|
|
baro: 29.92, tas: 131, windSpd: 14, windDir: 240,
|
|
xpdrCode: 1200, xpdrMode: 2, fdPitch: 5, fdRoll: -10,
|
|
// engine strip (arrays, like the sim)
|
|
engRpm: [2410], fuelFlow: [0.0072], oilTemp: [88], oilPress: [52], egt: [720],
|
|
fuelQty: [60, 58], volts: [28.0], amps: [12],
|
|
});
|
|
// a sample plan so the map/FMS show something in demo mode
|
|
fp.setPlan({ name: 'DEMO', waypoints: [
|
|
{ id: 'KSEA', lat: 47.449, lon: -122.309, type: 'APT' },
|
|
{ id: 'SEA', lat: 47.435, lon: -122.310, type: 'VOR', alt: 4000 },
|
|
{ id: 'KPDX', lat: 45.589, lon: -122.597, type: 'APT', alt: 1200 },
|
|
]});
|
|
let t = 0;
|
|
setInterval(() => {
|
|
t += 0.1;
|
|
state.values.roll = -12 + Math.sin(t) * 4;
|
|
state.values.pitch = 4.5 + Math.cos(t * 0.7) * 1.5;
|
|
state.values.heading = (87 + Math.sin(t * 0.3) * 3 + 360) % 360;
|
|
state.values.track = state.values.heading;
|
|
state.values.altitude = 5500 + Math.sin(t * 0.5) * 40;
|
|
state.values.airspeed = 124 + Math.sin(t * 0.4) * 3;
|
|
// creep south-east so the aircraft visibly moves on the map
|
|
state.values.lat -= 0.0006;
|
|
state.values.lon -= 0.0009;
|
|
broadcast({ type: 'status', xpConnected: true });
|
|
broadcast({ type: 'values', data: state.values });
|
|
}, 100);
|
|
}
|
|
|
|
server.listen(CONFIG.bridgePort, CONFIG.bridgeHost, () => {
|
|
log(`Bridge UI: http://${CONFIG.bridgeHost}:${CONFIG.bridgePort}`);
|
|
log(`On tablets: http://<this-PC-LAN-IP>:${CONFIG.bridgePort}`);
|
|
loadNavData(); // async; FMS resolves idents once ready
|
|
if (process.env.DEMO) startDemo();
|
|
else connectXPlane();
|
|
});
|