overlays-server 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README-tr.md +292 -0
- package/README.md +295 -2
- package/config.example.json +40 -0
- package/dist/app.d.ts +19 -0
- package/dist/app.js +127 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +176 -0
- package/dist/config.d.ts +62 -0
- package/dist/config.js +115 -0
- package/dist/core/driver.d.ts +56 -0
- package/dist/core/driver.js +5 -0
- package/dist/core/hub.d.ts +100 -0
- package/dist/core/hub.js +280 -0
- package/dist/core/last-position.d.ts +23 -0
- package/dist/core/last-position.js +67 -0
- package/dist/core/protocol.d.ts +56 -0
- package/dist/core/protocol.js +27 -0
- package/dist/core/registry.d.ts +9 -0
- package/dist/core/registry.js +29 -0
- package/dist/core/types.d.ts +83 -0
- package/dist/core/types.js +2 -0
- package/dist/drivers/ddpai/http-api.d.ts +30 -0
- package/dist/drivers/ddpai/http-api.js +84 -0
- package/dist/drivers/ddpai/index.d.ts +20 -0
- package/dist/drivers/ddpai/index.js +107 -0
- package/dist/drivers/ddpai/messages.d.ts +29 -0
- package/dist/drivers/ddpai/messages.js +76 -0
- package/dist/drivers/index.d.ts +6 -0
- package/dist/drivers/index.js +8 -0
- package/dist/drivers/simulator.d.ts +13 -0
- package/dist/drivers/simulator.js +64 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +26 -0
- package/dist/lib/delimited.d.ts +21 -0
- package/dist/lib/delimited.js +51 -0
- package/dist/lib/log.d.ts +27 -0
- package/dist/lib/log.js +80 -0
- package/dist/lib/nmea.d.ts +57 -0
- package/dist/lib/nmea.js +141 -0
- package/dist/lib/options.d.ts +29 -0
- package/dist/lib/options.js +85 -0
- package/dist/lib/reconnecting-tcp.d.ts +35 -0
- package/dist/lib/reconnecting-tcp.js +91 -0
- package/dist/lib/redact.d.ts +10 -0
- package/dist/lib/redact.js +30 -0
- package/dist/tools/probe.d.ts +37 -0
- package/dist/tools/probe.js +208 -0
- package/dist/transports/diagnostics.d.ts +65 -0
- package/dist/transports/diagnostics.js +49 -0
- package/dist/transports/feed.d.ts +22 -0
- package/dist/transports/feed.js +78 -0
- package/dist/transports/http-server.d.ts +39 -0
- package/dist/transports/http-server.js +196 -0
- package/dist/transports/security.d.ts +15 -0
- package/dist/transports/security.js +78 -0
- package/dist/transports/status-page.d.ts +7 -0
- package/dist/transports/status-page.js +204 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +4 -0
- package/docs/architecture.md +85 -0
- package/docs/data.md +87 -0
- package/docs/devices/README.md +29 -0
- package/docs/devices/ddpai.md +99 -0
- package/docs/drivers.md +130 -0
- package/docs/new-device.md +94 -0
- package/docs/protocol.md +160 -0
- package/docs/remote.md +126 -0
- package/docs/testing-locally.md +150 -0
- package/docs/windows-network.md +58 -0
- package/package.json +72 -4
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
export class DdpaiApiError extends Error {
|
|
2
|
+
name = 'DdpaiApiError';
|
|
3
|
+
}
|
|
4
|
+
export async function ddpaiCommand(host, port, cmd, options = {}) {
|
|
5
|
+
const timeout = AbortSignal.timeout(options.timeoutMs ?? 3000);
|
|
6
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
7
|
+
const url = `http://${host}:${port}/vcam/cmd.cgi?cmd=${encodeURIComponent(cmd)}`;
|
|
8
|
+
const res = await fetch(url, { signal });
|
|
9
|
+
if (!res.ok)
|
|
10
|
+
throw new DdpaiApiError(`${cmd}: HTTP ${res.status}`);
|
|
11
|
+
let body;
|
|
12
|
+
try {
|
|
13
|
+
body = await res.json();
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw new DdpaiApiError(`${cmd}: reply is not JSON`);
|
|
17
|
+
}
|
|
18
|
+
const reply = body;
|
|
19
|
+
if (reply.errcode !== 0)
|
|
20
|
+
throw new DdpaiApiError(`${cmd}: errcode ${String(reply.errcode)}`);
|
|
21
|
+
if (typeof reply.data === 'string') {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(reply.data);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return reply.data;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return reply.data;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Fields that identify the camera or its owner, or unlock it. Matched by name so unknown firmwares that add e.g.
|
|
33
|
+
* `wifi_pwd` or `bt_mac` stay covered. Seen on N5 Pro: password, nickname (Wi-Fi name), ordernum, uuid, sn, macaddr,
|
|
34
|
+
* chipsn, btmacaddr, random, upgrade_key.
|
|
35
|
+
*/
|
|
36
|
+
const SECRET_FIELD = /pass|pwd|psk|ssid|token|secret|key|serial|(^|_)sn$|chipsn|uuid|imei|mac|nick|order|random|account|user|phone|mail/i;
|
|
37
|
+
/**
|
|
38
|
+
* Everything usable from API_GetBaseInfo: model, firmware, memory card, camera count, RTSP streams, and every other
|
|
39
|
+
* non-secret field under `details`.
|
|
40
|
+
*/
|
|
41
|
+
export function pickDeviceInfo(data, options, now = Date.now()) {
|
|
42
|
+
const d = data && typeof data === 'object' ? data : {};
|
|
43
|
+
const text = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
|
|
44
|
+
const count = (v) => {
|
|
45
|
+
const n = typeof v === 'string' && v.trim() !== '' ? Number(v) : v;
|
|
46
|
+
return typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : undefined;
|
|
47
|
+
};
|
|
48
|
+
const model = text(d.model)?.replace(/^DDPAI\s+/i, '');
|
|
49
|
+
const firmware = text(d.version);
|
|
50
|
+
// Memory card size and free space. Unit inferred from an N5 Pro with a 512 GB card: sdcapacity 499939456 → KiB
|
|
51
|
+
// (476.8 GiB). 0 / missing when no card is inserted.
|
|
52
|
+
const capacityKiB = count(d.sdcapacity);
|
|
53
|
+
const spareKiB = count(d.sdspare);
|
|
54
|
+
const storage = capacityKiB && spareKiB !== undefined ? { totalBytes: capacityKiB * 1024, freeBytes: Math.min(spareKiB, capacityKiB) * 1024 } : undefined;
|
|
55
|
+
const cameras = count(d.sensor_cnt);
|
|
56
|
+
const host = options.host.includes(':') ? `[${options.host}]` : options.host;
|
|
57
|
+
const rtsp = (channel) => `rtsp://${host}:${options.rtspPort}/liveRTSP/${channel}`;
|
|
58
|
+
// av4 = front, av5 = rear (live preview sub-streams; the full resolution recording is not streamed).
|
|
59
|
+
const streams = [{ name: 'front', url: rtsp('av4') }, ...(cameras !== undefined && cameras >= 2 ? [{ name: 'rear', url: rtsp('av5') }] : [])];
|
|
60
|
+
const details = {};
|
|
61
|
+
for (const [key, value] of Object.entries(d)) {
|
|
62
|
+
if (key === 'model' || key === 'version' || SECRET_FIELD.test(key))
|
|
63
|
+
continue;
|
|
64
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
65
|
+
details[key] = value;
|
|
66
|
+
else if (typeof value === 'string' && value.length <= 120)
|
|
67
|
+
details[key] = value;
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
vendor: 'DDPAI',
|
|
71
|
+
...(model && { model }),
|
|
72
|
+
...(firmware && { firmware }),
|
|
73
|
+
...(storage && { storage }),
|
|
74
|
+
...(cameras !== undefined && { cameras }),
|
|
75
|
+
streams,
|
|
76
|
+
details,
|
|
77
|
+
updatedAt: now,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
export async function fetchDeviceInfo(options) {
|
|
81
|
+
const data = await ddpaiCommand(options.host, options.httpPort, 'API_GetBaseInfo', options);
|
|
82
|
+
return pickDeviceInfo(data, options);
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=http-api.js.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface DdpaiOptions {
|
|
2
|
+
/** Camera address on its own Wi-Fi. DDPAI uses 193.168.0.1 (a public block, not 192.168!). */
|
|
3
|
+
host: string;
|
|
4
|
+
/** Live telemetry stream. */
|
|
5
|
+
telemetryPort: number;
|
|
6
|
+
/** HTTP API, read-only: model, firmware, memory card, camera count. */
|
|
7
|
+
httpPort: number;
|
|
8
|
+
/** RTSP port, for the stream URLs in the device info. */
|
|
9
|
+
rtspPort: number;
|
|
10
|
+
deviceInfo: boolean;
|
|
11
|
+
/** Re-read the device info this often (memory card free space changes while recording). 0 = once per connection. */
|
|
12
|
+
deviceInfoIntervalMs: number;
|
|
13
|
+
/** Publish G-sensor samples (~16 Hz). */
|
|
14
|
+
motion: boolean;
|
|
15
|
+
/** Pass every other message type through as events. */
|
|
16
|
+
events: boolean;
|
|
17
|
+
/** Reconnect when the stream is silent this long. The camera sends G-sensor data many times a second. */
|
|
18
|
+
idleTimeoutMs: number;
|
|
19
|
+
}
|
|
20
|
+
export declare const ddpaiDriver: import("../../core/driver.ts").Driver<DdpaiOptions>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { defineDriver } from '../../core/driver.js';
|
|
2
|
+
import { DelimitedDecoder } from '../../lib/delimited.js';
|
|
3
|
+
import { errorMessage } from '../../lib/log.js';
|
|
4
|
+
import { ReconnectingTcpClient } from '../../lib/reconnecting-tcp.js';
|
|
5
|
+
import { fetchDeviceInfo } from './http-api.js';
|
|
6
|
+
import { decodeDdpaiFrame, gpsMessageToFix } from './messages.js';
|
|
7
|
+
export const ddpaiDriver = defineDriver({
|
|
8
|
+
id: 'ddpai',
|
|
9
|
+
name: 'DDPAI dashcam',
|
|
10
|
+
description: 'Live GPS and G-sensor from DDPAI dashcams over their Wi-Fi (TCP 6100). Tested: N5 Pro.',
|
|
11
|
+
capabilities: ['gps', 'motion', 'device', 'events'],
|
|
12
|
+
parseOptions: (o) => ({
|
|
13
|
+
host: o.string('host', '193.168.0.1'),
|
|
14
|
+
telemetryPort: o.port('telemetryPort', 6100),
|
|
15
|
+
httpPort: o.port('httpPort', 80),
|
|
16
|
+
rtspPort: o.port('rtspPort', 554),
|
|
17
|
+
deviceInfo: o.boolean('deviceInfo', true),
|
|
18
|
+
deviceInfoIntervalMs: o.number('deviceInfoIntervalMs', 60_000, { min: 0, integer: true }),
|
|
19
|
+
motion: o.boolean('motion', true),
|
|
20
|
+
events: o.boolean('events', true),
|
|
21
|
+
idleTimeoutMs: o.number('idleTimeoutMs', 6000, { min: 0, integer: true }),
|
|
22
|
+
}),
|
|
23
|
+
create(ctx, options) {
|
|
24
|
+
const decoder = new DelimitedDecoder({ delimiter: 0x00 });
|
|
25
|
+
const unknownSeen = new Set();
|
|
26
|
+
let infoTimer;
|
|
27
|
+
const loadDeviceInfo = () => {
|
|
28
|
+
if (!options.deviceInfo || ctx.signal.aborted)
|
|
29
|
+
return;
|
|
30
|
+
fetchDeviceInfo({ host: options.host, httpPort: options.httpPort, rtspPort: options.rtspPort, signal: ctx.signal })
|
|
31
|
+
.then((info) => ctx.setDevice(info))
|
|
32
|
+
.catch((err) => ctx.log.debug(`device info unavailable: ${errorMessage(err)}`));
|
|
33
|
+
};
|
|
34
|
+
const scheduleDeviceInfo = () => {
|
|
35
|
+
clearInterval(infoTimer);
|
|
36
|
+
loadDeviceInfo();
|
|
37
|
+
if (options.deviceInfo && options.deviceInfoIntervalMs > 0) {
|
|
38
|
+
infoTimer = setInterval(loadDeviceInfo, options.deviceInfoIntervalMs);
|
|
39
|
+
infoTimer.unref();
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const handleFrame = (frame) => {
|
|
43
|
+
ctx.recordRaw(frame);
|
|
44
|
+
const msg = decodeDdpaiFrame(frame);
|
|
45
|
+
if (!msg) {
|
|
46
|
+
ctx.log.debug(`unparsed frame: ${frame.slice(0, 120)}`);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
switch (msg.kind) {
|
|
50
|
+
case 'gps': {
|
|
51
|
+
const fix = gpsMessageToFix(msg);
|
|
52
|
+
if (fix)
|
|
53
|
+
ctx.publishFix(fix);
|
|
54
|
+
else
|
|
55
|
+
ctx.publishNoFix({ ...(msg.gga?.satellites !== undefined && { satellites: msg.gga.satellites }) });
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
case 'gsensor':
|
|
59
|
+
if (options.motion)
|
|
60
|
+
ctx.publishMotion(msg.sample);
|
|
61
|
+
break;
|
|
62
|
+
case 'other':
|
|
63
|
+
// Logged once per type: helps map the rest of the protocol (ADAS, alerts, ...).
|
|
64
|
+
if (!unknownSeen.has(msg.msgid)) {
|
|
65
|
+
unknownSeen.add(msg.msgid);
|
|
66
|
+
ctx.log.info(`new message type ${msg.msgid} (please report it: docs/new-device.md)`);
|
|
67
|
+
}
|
|
68
|
+
if (options.events)
|
|
69
|
+
ctx.publishEvent({ name: msg.msgid, data: msg.data, timestamp: Date.now() });
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const client = new ReconnectingTcpClient({
|
|
74
|
+
host: options.host,
|
|
75
|
+
port: options.telemetryPort,
|
|
76
|
+
idleTimeoutMs: options.idleTimeoutMs,
|
|
77
|
+
log: ctx.log,
|
|
78
|
+
onConnect: () => {
|
|
79
|
+
decoder.reset();
|
|
80
|
+
ctx.setLink('online');
|
|
81
|
+
scheduleDeviceInfo();
|
|
82
|
+
},
|
|
83
|
+
onData: (chunk) => {
|
|
84
|
+
const frames = decoder.push(chunk, (bytes) => ctx.log.warn(`dropped an oversized frame (${bytes} bytes)`));
|
|
85
|
+
for (const frame of frames)
|
|
86
|
+
handleFrame(frame);
|
|
87
|
+
},
|
|
88
|
+
onDisconnect: (reason, wasConnected) => {
|
|
89
|
+
const target = `${options.host}:${options.telemetryPort}`;
|
|
90
|
+
const hint = wasConnected ? '' : ' (is this PC connected to the camera Wi-Fi?)';
|
|
91
|
+
clearInterval(infoTimer);
|
|
92
|
+
ctx.setLink(wasConnected ? 'offline' : 'connecting', `${target}: ${reason}${hint}`);
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
return {
|
|
96
|
+
start() {
|
|
97
|
+
ctx.setLink('connecting', `${options.host}:${options.telemetryPort}`);
|
|
98
|
+
client.start();
|
|
99
|
+
},
|
|
100
|
+
stop() {
|
|
101
|
+
clearInterval(infoTimer);
|
|
102
|
+
client.stop();
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DDPAI telemetry stream (TCP 6100), verified on an N5 Pro (DN2509, firmware v8.0.0.10):
|
|
3
|
+
* NUL separated JSON frames `{"msgid": "...", "data": "<JSON string>"}`, the inner JSON encoded as a string.
|
|
4
|
+
*
|
|
5
|
+
* MSG_GpsData ~1 Hz {"gpsdata": "$GPRMC,...*CS\n", "ggadata": "$GPGGA,...*CS\n"}
|
|
6
|
+
* MSG_GsensorData ~16 Hz {"gsensordata": "$GSENSOR,x,y,z,epochMs"} x/y/z in milli-g
|
|
7
|
+
*/
|
|
8
|
+
import { type GgaSentence, type RmcSentence } from '../../lib/nmea.ts';
|
|
9
|
+
import type { GpsFix, MotionSample } from '../../core/types.ts';
|
|
10
|
+
export type DdpaiMessage = {
|
|
11
|
+
kind: 'gps';
|
|
12
|
+
rmc?: RmcSentence;
|
|
13
|
+
gga?: GgaSentence;
|
|
14
|
+
} | {
|
|
15
|
+
kind: 'gsensor';
|
|
16
|
+
sample: MotionSample;
|
|
17
|
+
} | {
|
|
18
|
+
kind: 'other';
|
|
19
|
+
msgid: string;
|
|
20
|
+
data: unknown;
|
|
21
|
+
};
|
|
22
|
+
/** Decodes one frame. Returns `undefined` for anything that is not a DDPAI message. */
|
|
23
|
+
export declare function decodeDdpaiFrame(frame: string): DdpaiMessage | undefined;
|
|
24
|
+
/** `$GSENSOR,x,y,z,epochMs` (milli-g) to g. */
|
|
25
|
+
export declare function parseGsensor(line: string): MotionSample | undefined;
|
|
26
|
+
/** A GPS message as a fix, or `undefined` while the receiver has no lock. */
|
|
27
|
+
export declare function gpsMessageToFix(msg: Extract<DdpaiMessage, {
|
|
28
|
+
kind: 'gps';
|
|
29
|
+
}>, now?: number): GpsFix | undefined;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DDPAI telemetry stream (TCP 6100), verified on an N5 Pro (DN2509, firmware v8.0.0.10):
|
|
3
|
+
* NUL separated JSON frames `{"msgid": "...", "data": "<JSON string>"}`, the inner JSON encoded as a string.
|
|
4
|
+
*
|
|
5
|
+
* MSG_GpsData ~1 Hz {"gpsdata": "$GPRMC,...*CS\n", "ggadata": "$GPGGA,...*CS\n"}
|
|
6
|
+
* MSG_GsensorData ~16 Hz {"gsensordata": "$GSENSOR,x,y,z,epochMs"} x/y/z in milli-g
|
|
7
|
+
*/
|
|
8
|
+
import { parseGga, parseRmc } from '../../lib/nmea.js';
|
|
9
|
+
/** The camera computes NMEA checksums for `$GN` and sends `$GP` (see ChecksumMode). */
|
|
10
|
+
const NMEA_OPTIONS = { checksum: 'any-talker' };
|
|
11
|
+
function parseJson(text) {
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(text);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function record(v) {
|
|
20
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
|
|
21
|
+
}
|
|
22
|
+
/** Decodes one frame. Returns `undefined` for anything that is not a DDPAI message. */
|
|
23
|
+
export function decodeDdpaiFrame(frame) {
|
|
24
|
+
const outer = record(parseJson(frame.trim()));
|
|
25
|
+
if (!outer || typeof outer.msgid !== 'string')
|
|
26
|
+
return undefined;
|
|
27
|
+
const data = typeof outer.data === 'string' ? (parseJson(outer.data) ?? outer.data) : outer.data;
|
|
28
|
+
const inner = record(data);
|
|
29
|
+
switch (outer.msgid) {
|
|
30
|
+
case 'MSG_GpsData': {
|
|
31
|
+
if (!inner)
|
|
32
|
+
return undefined;
|
|
33
|
+
const rmc = typeof inner.gpsdata === 'string' ? parseRmc(inner.gpsdata, NMEA_OPTIONS) : undefined;
|
|
34
|
+
const gga = typeof inner.ggadata === 'string' ? parseGga(inner.ggadata, NMEA_OPTIONS) : undefined;
|
|
35
|
+
if (!rmc && !gga)
|
|
36
|
+
return undefined;
|
|
37
|
+
return { kind: 'gps', ...(rmc && { rmc }), ...(gga && { gga }) };
|
|
38
|
+
}
|
|
39
|
+
case 'MSG_GsensorData': {
|
|
40
|
+
const sample = typeof inner?.gsensordata === 'string' ? parseGsensor(inner.gsensordata) : undefined;
|
|
41
|
+
return sample ? { kind: 'gsensor', sample } : undefined;
|
|
42
|
+
}
|
|
43
|
+
default:
|
|
44
|
+
return { kind: 'other', msgid: outer.msgid, data };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** `$GSENSOR,x,y,z,epochMs` (milli-g) to g. */
|
|
48
|
+
export function parseGsensor(line) {
|
|
49
|
+
const parts = line.trim().split(',');
|
|
50
|
+
if (parts[0] !== '$GSENSOR' || parts.length < 5)
|
|
51
|
+
return undefined;
|
|
52
|
+
const [x, y, z, t] = parts.slice(1, 5).map(Number);
|
|
53
|
+
if (![x, y, z, t].every((n) => Number.isFinite(n)))
|
|
54
|
+
return undefined;
|
|
55
|
+
return { x: x / 1000, y: y / 1000, z: z / 1000, timestamp: t };
|
|
56
|
+
}
|
|
57
|
+
/** A GPS message as a fix, or `undefined` while the receiver has no lock. */
|
|
58
|
+
export function gpsMessageToFix(msg, now = Date.now()) {
|
|
59
|
+
const { rmc, gga } = msg;
|
|
60
|
+
if (!rmc?.valid || rmc.lat === undefined || rmc.lon === undefined)
|
|
61
|
+
return undefined;
|
|
62
|
+
return {
|
|
63
|
+
lat: rmc.lat,
|
|
64
|
+
lon: rmc.lon,
|
|
65
|
+
...(rmc.speed !== undefined && { speed: rmc.speed }),
|
|
66
|
+
...(rmc.course !== undefined && { heading: rmc.course }),
|
|
67
|
+
...(gga?.altitude !== undefined && gga.quality > 0 && { altitude: gga.altitude }),
|
|
68
|
+
...(gga?.satellites !== undefined && { satellites: gga.satellites }),
|
|
69
|
+
...(gga?.hdop !== undefined && { hdop: gga.hdop }),
|
|
70
|
+
...(gga && gga.quality > 0 && { quality: gga.quality }),
|
|
71
|
+
...(gga?.geoidSeparation !== undefined && gga.quality > 0 && { geoidSeparation: gga.geoidSeparation }),
|
|
72
|
+
...(rmc.mode !== undefined && { mode: rmc.mode }),
|
|
73
|
+
timestamp: rmc.timestamp ?? now,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=messages.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AnyDriver } from '../core/driver.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Drivers shipped with the server. A new device type is one module exporting a `defineDriver(...)`
|
|
4
|
+
* plus one line here. See CONTRIBUTING.md → "Adding a driver".
|
|
5
|
+
*/
|
|
6
|
+
export declare const BUILTIN_DRIVERS: readonly AnyDriver[];
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { ddpaiDriver } from './ddpai/index.js';
|
|
2
|
+
import { simulatorDriver } from './simulator.js';
|
|
3
|
+
/**
|
|
4
|
+
* Drivers shipped with the server. A new device type is one module exporting a `defineDriver(...)`
|
|
5
|
+
* plus one line here. See CONTRIBUTING.md → "Adding a driver".
|
|
6
|
+
*/
|
|
7
|
+
export const BUILTIN_DRIVERS = [ddpaiDriver, simulatorDriver];
|
|
8
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface SimulatorOptions {
|
|
2
|
+
lat: number;
|
|
3
|
+
lon: number;
|
|
4
|
+
radiusM: number;
|
|
5
|
+
speedKmh: number;
|
|
6
|
+
intervalMs: number;
|
|
7
|
+
altitude: number;
|
|
8
|
+
/** Report "no fix" for this many seconds first, like a receiver searching for satellites. */
|
|
9
|
+
noFixSeconds: number;
|
|
10
|
+
motion: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** Drives in a circle. For overlay development and for checking a setup without a camera. */
|
|
13
|
+
export declare const simulatorDriver: import("../core/driver.ts").Driver<SimulatorOptions>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { defineDriver } from '../core/driver.js';
|
|
2
|
+
const EARTH_M_PER_DEG = 111_320;
|
|
3
|
+
/** Drives in a circle. For overlay development and for checking a setup without a camera. */
|
|
4
|
+
export const simulatorDriver = defineDriver({
|
|
5
|
+
id: 'simulator',
|
|
6
|
+
name: 'Simulator',
|
|
7
|
+
description: 'Fake GPS driving in a circle (no hardware needed).',
|
|
8
|
+
capabilities: ['gps', 'motion'],
|
|
9
|
+
parseOptions: (o) => ({
|
|
10
|
+
// Kızılay square, Ankara.
|
|
11
|
+
lat: o.number('lat', 39.92077, { min: -90, max: 90 }),
|
|
12
|
+
lon: o.number('lon', 32.85411, { min: -180, max: 180 }),
|
|
13
|
+
radiusM: o.number('radiusM', 300, { min: 10 }),
|
|
14
|
+
speedKmh: o.number('speedKmh', 40, { min: 0, max: 400 }),
|
|
15
|
+
intervalMs: o.number('intervalMs', 1000, { min: 50, integer: true }),
|
|
16
|
+
altitude: o.number('altitude', 890),
|
|
17
|
+
noFixSeconds: o.number('noFixSeconds', 0, { min: 0 }),
|
|
18
|
+
motion: o.boolean('motion', false),
|
|
19
|
+
}),
|
|
20
|
+
create(ctx, o) {
|
|
21
|
+
let timer;
|
|
22
|
+
let angle = 0; // bearing of the car as seen from the center, radians
|
|
23
|
+
let startedAt = 0;
|
|
24
|
+
const tick = () => {
|
|
25
|
+
const now = Date.now();
|
|
26
|
+
if (now - startedAt < o.noFixSeconds * 1000) {
|
|
27
|
+
ctx.publishNoFix({ satellites: 3 });
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const speed = o.speedKmh / 3.6;
|
|
31
|
+
angle = (angle + (speed * o.intervalMs) / 1000 / o.radiusM) % (2 * Math.PI);
|
|
32
|
+
const lat = o.lat + (o.radiusM * Math.cos(angle)) / EARTH_M_PER_DEG;
|
|
33
|
+
const lon = o.lon + (o.radiusM * Math.sin(angle)) / (EARTH_M_PER_DEG * Math.cos((o.lat * Math.PI) / 180));
|
|
34
|
+
// Clockwise around the center: heading is the bearing plus 90°.
|
|
35
|
+
const heading = ((angle * 180) / Math.PI + 90) % 360;
|
|
36
|
+
ctx.publishFix({
|
|
37
|
+
lat,
|
|
38
|
+
lon,
|
|
39
|
+
heading,
|
|
40
|
+
speed,
|
|
41
|
+
altitude: o.altitude + 10 * Math.sin(angle),
|
|
42
|
+
satellites: 18,
|
|
43
|
+
hdop: 0.7,
|
|
44
|
+
timestamp: now,
|
|
45
|
+
});
|
|
46
|
+
if (o.motion) {
|
|
47
|
+
// Centripetal acceleration while cornering, in g.
|
|
48
|
+
ctx.publishMotion({ x: speed ** 2 / o.radiusM / 9.81, y: 0, z: 1, timestamp: now });
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
start() {
|
|
53
|
+
startedAt = Date.now();
|
|
54
|
+
ctx.setLink('online');
|
|
55
|
+
tick();
|
|
56
|
+
timer = setInterval(tick, o.intervalMs);
|
|
57
|
+
},
|
|
58
|
+
stop() {
|
|
59
|
+
clearInterval(timer);
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
//# sourceMappingURL=simulator.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Programmatic API. `npx overlays-server` covers normal use; import this to embed the server
|
|
3
|
+
* or to run it with your own drivers:
|
|
4
|
+
*
|
|
5
|
+
* import { startServer, parseConfig, BUILTIN_DRIVERS, defineDriver } from 'overlays-server';
|
|
6
|
+
* const myDriver = defineDriver({ id: 'my-gps', ... });
|
|
7
|
+
* await startServer({ config: parseConfig({ sources: [{ driver: 'my-gps' }] }), drivers: [...BUILTIN_DRIVERS, myDriver] });
|
|
8
|
+
*/
|
|
9
|
+
export { startServer, type RunningServer, type StartOptions } from './app.ts';
|
|
10
|
+
export { DEFAULT_ALLOWED_ORIGINS, DEFAULT_PORT, findConfigFile, parseConfig, readConfigFile, userConfigPath, type AppConfig, type SourceConfig, } from './config.ts';
|
|
11
|
+
export { defineDriver, type AnyDriver, type Driver, type Source, type SourceContext } from './core/driver.ts';
|
|
12
|
+
export { Hub, normalizeFix, type HubEvent, type SourceInfo, type SourceSnapshot } from './core/hub.ts';
|
|
13
|
+
export * from './core/protocol.ts';
|
|
14
|
+
export { DriverRegistry } from './core/registry.ts';
|
|
15
|
+
export type * from './core/types.ts';
|
|
16
|
+
export { BUILTIN_DRIVERS } from './drivers/index.ts';
|
|
17
|
+
export { ddpaiDriver, type DdpaiOptions } from './drivers/ddpai/index.ts';
|
|
18
|
+
export { simulatorDriver, type SimulatorOptions } from './drivers/simulator.ts';
|
|
19
|
+
export { DelimitedDecoder } from './lib/delimited.ts';
|
|
20
|
+
export { createLogger, type Logger, type LogLevel } from './lib/log.ts';
|
|
21
|
+
export * as nmea from './lib/nmea.ts';
|
|
22
|
+
export { ConfigError, OptionReader } from './lib/options.ts';
|
|
23
|
+
export { redact } from './lib/redact.ts';
|
|
24
|
+
export { DEFAULT_PROBE_PORTS, formatProbeReport, probeDevice, type ProbeReport } from './tools/probe.ts';
|
|
25
|
+
export { ReconnectingTcpClient, type ReconnectingTcpOptions } from './lib/reconnecting-tcp.ts';
|
|
26
|
+
export { REPO_URL, VERSION } from './version.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Programmatic API. `npx overlays-server` covers normal use; import this to embed the server
|
|
3
|
+
* or to run it with your own drivers:
|
|
4
|
+
*
|
|
5
|
+
* import { startServer, parseConfig, BUILTIN_DRIVERS, defineDriver } from 'overlays-server';
|
|
6
|
+
* const myDriver = defineDriver({ id: 'my-gps', ... });
|
|
7
|
+
* await startServer({ config: parseConfig({ sources: [{ driver: 'my-gps' }] }), drivers: [...BUILTIN_DRIVERS, myDriver] });
|
|
8
|
+
*/
|
|
9
|
+
export { startServer } from './app.js';
|
|
10
|
+
export { DEFAULT_ALLOWED_ORIGINS, DEFAULT_PORT, findConfigFile, parseConfig, readConfigFile, userConfigPath, } from './config.js';
|
|
11
|
+
export { defineDriver } from './core/driver.js';
|
|
12
|
+
export { Hub, normalizeFix } from './core/hub.js';
|
|
13
|
+
export * from './core/protocol.js';
|
|
14
|
+
export { DriverRegistry } from './core/registry.js';
|
|
15
|
+
export { BUILTIN_DRIVERS } from './drivers/index.js';
|
|
16
|
+
export { ddpaiDriver } from './drivers/ddpai/index.js';
|
|
17
|
+
export { simulatorDriver } from './drivers/simulator.js';
|
|
18
|
+
export { DelimitedDecoder } from './lib/delimited.js';
|
|
19
|
+
export { createLogger } from './lib/log.js';
|
|
20
|
+
export * as nmea from './lib/nmea.js';
|
|
21
|
+
export { ConfigError, OptionReader } from './lib/options.js';
|
|
22
|
+
export { redact } from './lib/redact.js';
|
|
23
|
+
export { DEFAULT_PROBE_PORTS, formatProbeReport, probeDevice } from './tools/probe.js';
|
|
24
|
+
export { ReconnectingTcpClient } from './lib/reconnecting-tcp.js';
|
|
25
|
+
export { REPO_URL, VERSION } from './version.js';
|
|
26
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a byte stream into frames separated by a single delimiter byte (DDPAI uses NUL).
|
|
3
|
+
* Works on bytes, so a multi-byte UTF-8 character split across two TCP chunks stays intact.
|
|
4
|
+
*/
|
|
5
|
+
export declare class DelimitedDecoder {
|
|
6
|
+
private pending;
|
|
7
|
+
private pendingLength;
|
|
8
|
+
readonly delimiter: number;
|
|
9
|
+
readonly maxFrameBytes: number;
|
|
10
|
+
constructor(options?: {
|
|
11
|
+
delimiter?: number;
|
|
12
|
+
maxFrameBytes?: number;
|
|
13
|
+
});
|
|
14
|
+
/**
|
|
15
|
+
* Feeds a chunk and returns every frame it completed (decoded as UTF-8, empty frames skipped).
|
|
16
|
+
* A frame that grows past `maxFrameBytes` without a delimiter is dropped, and `onOverflow` is called.
|
|
17
|
+
*/
|
|
18
|
+
push(chunk: Buffer, onOverflow?: (bytes: number) => void): string[];
|
|
19
|
+
/** Drops any partial frame (call on reconnect). */
|
|
20
|
+
reset(): void;
|
|
21
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a byte stream into frames separated by a single delimiter byte (DDPAI uses NUL).
|
|
3
|
+
* Works on bytes, so a multi-byte UTF-8 character split across two TCP chunks stays intact.
|
|
4
|
+
*/
|
|
5
|
+
export class DelimitedDecoder {
|
|
6
|
+
pending = [];
|
|
7
|
+
pendingLength = 0;
|
|
8
|
+
delimiter;
|
|
9
|
+
maxFrameBytes;
|
|
10
|
+
constructor(options = {}) {
|
|
11
|
+
this.delimiter = options.delimiter ?? 0x00;
|
|
12
|
+
this.maxFrameBytes = options.maxFrameBytes ?? 64 * 1024;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Feeds a chunk and returns every frame it completed (decoded as UTF-8, empty frames skipped).
|
|
16
|
+
* A frame that grows past `maxFrameBytes` without a delimiter is dropped, and `onOverflow` is called.
|
|
17
|
+
*/
|
|
18
|
+
push(chunk, onOverflow) {
|
|
19
|
+
const frames = [];
|
|
20
|
+
let start = 0;
|
|
21
|
+
let index = chunk.indexOf(this.delimiter, start);
|
|
22
|
+
while (index !== -1) {
|
|
23
|
+
const part = chunk.subarray(start, index);
|
|
24
|
+
const frame = this.pendingLength > 0 ? Buffer.concat([...this.pending, part]) : part;
|
|
25
|
+
this.reset();
|
|
26
|
+
if (frame.length > 0)
|
|
27
|
+
frames.push(frame.toString('utf8'));
|
|
28
|
+
start = index + 1;
|
|
29
|
+
index = chunk.indexOf(this.delimiter, start);
|
|
30
|
+
}
|
|
31
|
+
if (start < chunk.length) {
|
|
32
|
+
const rest = chunk.subarray(start);
|
|
33
|
+
if (this.pendingLength + rest.length > this.maxFrameBytes) {
|
|
34
|
+
onOverflow?.(this.pendingLength + rest.length);
|
|
35
|
+
this.reset();
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
// Copy: the caller may reuse the chunk's memory.
|
|
39
|
+
this.pending.push(Buffer.from(rest));
|
|
40
|
+
this.pendingLength += rest.length;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return frames;
|
|
44
|
+
}
|
|
45
|
+
/** Drops any partial frame (call on reconnect). */
|
|
46
|
+
reset() {
|
|
47
|
+
this.pending = [];
|
|
48
|
+
this.pendingLength = 0;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=delimited.js.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export declare const LOG_LEVELS: readonly ['debug', 'info', 'warn', 'error', 'silent'];
|
|
2
|
+
export type LogLevel = (typeof LOG_LEVELS)[number];
|
|
3
|
+
export interface Logger {
|
|
4
|
+
debug(message: string, ...details: unknown[]): void;
|
|
5
|
+
info(message: string, ...details: unknown[]): void;
|
|
6
|
+
warn(message: string, ...details: unknown[]): void;
|
|
7
|
+
error(message: string, ...details: unknown[]): void;
|
|
8
|
+
/** Same level and output, with an extra `[scope]` prefix. */
|
|
9
|
+
child(scope: string): Logger;
|
|
10
|
+
}
|
|
11
|
+
export type LogSink = (level: Exclude<LogLevel, 'silent'>, line: string, details: unknown[]) => void;
|
|
12
|
+
export declare function createLogger(level?: LogLevel, sink?: LogSink, scope?: string): Logger;
|
|
13
|
+
export declare const silentLogger: Logger;
|
|
14
|
+
/** The last N log lines in memory, for the diagnostics download. */
|
|
15
|
+
export declare class LogBuffer {
|
|
16
|
+
private readonly lines;
|
|
17
|
+
readonly capacity: number;
|
|
18
|
+
constructor(capacity?: number);
|
|
19
|
+
push(level: string, message: string): void;
|
|
20
|
+
snapshot(): string[];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Wraps a logger so every line it prints (same level filter) is also kept in `buffer`.
|
|
24
|
+
* Lines below the base logger's level are recorded too at `debug`, so a diagnostics file has more than the console.
|
|
25
|
+
*/
|
|
26
|
+
export declare function recordingLogger(base: Logger, buffer: LogBuffer, scope?: string): Logger;
|
|
27
|
+
export declare function errorMessage(err: unknown): string;
|
package/dist/lib/log.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
export const LOG_LEVELS = ['debug', 'info', 'warn', 'error', 'silent'];
|
|
2
|
+
const RANK = { debug: 10, info: 20, warn: 30, error: 40, silent: 100 };
|
|
3
|
+
const consoleSink = (level, line, details) => {
|
|
4
|
+
const out = level === 'error' || level === 'warn' ? console.error : console.log;
|
|
5
|
+
out(line, ...details);
|
|
6
|
+
};
|
|
7
|
+
function time() {
|
|
8
|
+
const d = new Date();
|
|
9
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
10
|
+
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
11
|
+
}
|
|
12
|
+
export function createLogger(level = 'info', sink = consoleSink, scope) {
|
|
13
|
+
const min = RANK[level];
|
|
14
|
+
const prefix = scope ? `[${scope}] ` : '';
|
|
15
|
+
const emit = (lvl) => (message, ...details) => {
|
|
16
|
+
if (RANK[lvl] < min)
|
|
17
|
+
return;
|
|
18
|
+
sink(lvl, `${time()} ${lvl.toUpperCase().padEnd(5)} ${prefix}${message}`, details);
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
debug: emit('debug'),
|
|
22
|
+
info: emit('info'),
|
|
23
|
+
warn: emit('warn'),
|
|
24
|
+
error: emit('error'),
|
|
25
|
+
child: (child) => createLogger(level, sink, scope ? `${scope}:${child}` : child),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export const silentLogger = createLogger('silent');
|
|
29
|
+
/** The last N log lines in memory, for the diagnostics download. */
|
|
30
|
+
export class LogBuffer {
|
|
31
|
+
lines = [];
|
|
32
|
+
capacity;
|
|
33
|
+
constructor(capacity = 500) {
|
|
34
|
+
this.capacity = capacity;
|
|
35
|
+
}
|
|
36
|
+
push(level, message) {
|
|
37
|
+
const d = new Date();
|
|
38
|
+
this.lines.push(`${d.toISOString()} ${level.toUpperCase().padEnd(5)} ${message}`);
|
|
39
|
+
if (this.lines.length > this.capacity)
|
|
40
|
+
this.lines.splice(0, this.lines.length - this.capacity);
|
|
41
|
+
}
|
|
42
|
+
snapshot() {
|
|
43
|
+
return [...this.lines];
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Wraps a logger so every line it prints (same level filter) is also kept in `buffer`.
|
|
48
|
+
* Lines below the base logger's level are recorded too at `debug`, so a diagnostics file has more than the console.
|
|
49
|
+
*/
|
|
50
|
+
export function recordingLogger(base, buffer, scope) {
|
|
51
|
+
const prefix = scope ? `[${scope}] ` : '';
|
|
52
|
+
const wrap = (level) => (message, ...details) => {
|
|
53
|
+
const extra = details.length ? ` ${details.map((d) => (d instanceof Error ? d.message : safeJson(d))).join(' ')}` : '';
|
|
54
|
+
buffer.push(level, `${prefix}${message}${extra}`);
|
|
55
|
+
base[level](message, ...details);
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
debug: wrap('debug'),
|
|
59
|
+
info: wrap('info'),
|
|
60
|
+
warn: wrap('warn'),
|
|
61
|
+
error: wrap('error'),
|
|
62
|
+
child: (child) => recordingLogger(base.child(child), buffer, scope ? `${scope}:${child}` : child),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function safeJson(value) {
|
|
66
|
+
try {
|
|
67
|
+
return typeof value === 'string' ? value : JSON.stringify(value);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return String(value);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function errorMessage(err) {
|
|
74
|
+
if (err instanceof Error) {
|
|
75
|
+
const code = err.code;
|
|
76
|
+
return code && !err.message.includes(code) ? `${code} ${err.message}` : err.message;
|
|
77
|
+
}
|
|
78
|
+
return String(err);
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=log.js.map
|