Repository navigation
Expand file tree
/
Copy pathcamera.js
More file actions
351 lines (326 loc) · 11.7 KB
/
Copy pathcamera.js
File metadata and controls
351 lines (326 loc) · 11.7 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Kamera-Proxy: Der Server holt die Bilder vom Drucker und reicht sie als
// JPEG (Einzelbild) bzw. MJPEG (Livebild) an den Browser weiter.
// Vorteil: Zugangsdaten bleiben auf dem Server, Bambu-Kameras (die kein
// Browser direkt anzeigen kann) funktionieren, und Benachrichtigungen können
// ein Foto anhängen.
//
// Quellen (vom Treiber über cameraSource() geliefert):
// { type: 'http-snapshot', url, headers?, intervalMs? } Moonraker, OctoPrint
// { type: 'ffmpeg', input, inputArgs? } RTSP(S), z. B. Bambu X1/H2
// { type: 'bambu-tcp', host, accessCode } Bambu P1/A1 (Port 6000)
const { EventEmitter } = require('events');
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
/**
* ffmpeg finden: FFMPEG_PATH, sonst übliche Installationsorte (Windows: winget, Chocolatey,
* C:\ffmpeg; macOS: Homebrew), sonst "ffmpeg" aus dem Suchpfad.
*/
let ffmpegCache;
function ffmpegPath() {
if (ffmpegCache !== undefined) return ffmpegCache;
if (process.env.FFMPEG_PATH) return (ffmpegCache = process.env.FFMPEG_PATH);
const cands = [];
if (process.platform === 'win32') {
const la = process.env.LOCALAPPDATA || '';
cands.push(path.join(la, 'Microsoft', 'WinGet', 'Links', 'ffmpeg.exe'));
try {
const pk = path.join(la, 'Microsoft', 'WinGet', 'Packages');
for (const d of fs.readdirSync(pk).filter((x) => /ffmpeg/i.test(x))) {
for (const sub of fs.readdirSync(path.join(pk, d))) cands.push(path.join(pk, d, sub, 'bin', 'ffmpeg.exe'));
}
} catch { /* kein winget */ }
cands.push(path.join(process.env.ProgramData || 'C:\\ProgramData', 'chocolatey', 'bin', 'ffmpeg.exe'));
cands.push('C:\\ffmpeg\\bin\\ffmpeg.exe', path.join(process.env.ProgramFiles || 'C:\\Program Files', 'ffmpeg', 'bin', 'ffmpeg.exe'));
} else {
cands.push('/opt/homebrew/bin/ffmpeg', '/usr/local/bin/ffmpeg', '/usr/bin/ffmpeg');
}
ffmpegCache = cands.find((c) => { try { return fs.statSync(c).isFile(); } catch { return false; } }) || 'ffmpeg';
return ffmpegCache;
}
/** Ist ffmpeg aufrufbar? (für Hinweise in der Oberfläche) */
function ffmpegAvailable() {
return new Promise((resolve) => {
try {
const p = spawn(ffmpegPath(), ['-version'], { stdio: 'ignore' });
p.on('error', () => resolve(false));
p.on('exit', (code) => resolve(code === 0));
} catch {
resolve(false);
}
});
}
const tls = require('tls');
const IDLE_STOP_MS = 30_000; // Quelle stoppen, wenn so lange niemand zuschaut
const SOI = Buffer.from([0xff, 0xd8]);
const EOI = Buffer.from([0xff, 0xd9]);
// ------------------------------------------------------------------ Quellen
class HttpSnapshotSource extends EventEmitter {
constructor({ url, headers = {}, intervalMs = 1000 }) {
super();
Object.assign(this, { url, headers, intervalMs });
}
start() {
this.running = true;
this.loop();
}
stop() {
this.running = false;
clearTimeout(this.timer);
}
async loop() {
if (!this.running) return;
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 6000);
try {
const res = await fetch(this.url, { headers: this.headers, signal: ctrl.signal });
if (!res.ok) throw new Error(`Kamera antwortet mit HTTP ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
if (buf.subarray(0, 2).equals(SOI)) this.emit('frame', buf);
else throw new Error('Kamera liefert kein JPEG');
} catch (err) {
this.emit('error', err.name === 'AbortError' ? new Error('Kamera antwortet nicht') : err);
} finally {
clearTimeout(t);
}
this.timer = setTimeout(() => this.loop(), this.intervalMs);
}
}
class FfmpegSource extends EventEmitter {
constructor({ input, inputArgs = [], fps = 2, width = 1280 }) {
super();
Object.assign(this, { input, inputArgs, fps, width });
}
start() {
this.running = true;
this.spawn();
}
stop() {
this.running = false;
clearTimeout(this.restartTimer);
if (this.proc) this.proc.kill('SIGKILL');
}
spawn() {
if (!this.running) return;
const args = [
'-hide_banner', '-loglevel', 'error',
...this.inputArgs,
'-i', this.input,
'-an',
'-vf', `fps=${this.fps},scale='min(${this.width},iw)':-2`,
'-q:v', '6',
'-f', 'mjpeg', 'pipe:1',
];
let proc;
try {
proc = spawn(ffmpegPath(), args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
} catch (err) {
this.emit('error', err);
return;
}
this.proc = proc;
let buf = Buffer.alloc(0);
let stderr = '';
proc.stdout.on('data', (chunk) => {
buf = Buffer.concat([buf, chunk]);
buf = extractJpegs(buf, (jpg) => this.emit('frame', jpg));
});
proc.stderr.on('data', (d) => (stderr = (stderr + d).slice(-500)));
proc.on('error', (err) => {
this.emit('error', err.code === 'ENOENT' ? new Error('ffmpeg nicht gefunden – nötig für diese Kamera. Windows: „winget install Gyan.FFmpeg“, dann PrintDock neu starten.') : err);
});
proc.on('exit', () => {
if (this.proc === proc) this.proc = null;
if (!this.running) return;
const msg = stderr.trim().split('\n').pop();
this.emit('error', new Error(msg ? `Kamerastream: ${msg}` : 'Kamerastream beendet'));
this.restartTimer = setTimeout(() => this.spawn(), 5000);
});
}
}
/** Bambu P1/A1: proprietärer JPEG-Stream über TLS auf Port 6000. */
class BambuTcpSource extends EventEmitter {
constructor({ host, accessCode }) {
super();
Object.assign(this, { host, accessCode });
}
start() {
this.running = true;
this.connect();
}
stop() {
this.running = false;
clearTimeout(this.restartTimer);
if (this.sock) this.sock.destroy();
}
connect() {
if (!this.running) return;
const sock = tls.connect({ host: this.host, port: 6000, rejectUnauthorized: false, timeout: 10000 });
this.sock = sock;
let buf = Buffer.alloc(0);
sock.on('secureConnect', () => {
// 80-Byte-Anmeldung: 0x40, 0x3000, 0, 0, Benutzer (32 Byte), Access Code (32 Byte)
const auth = Buffer.alloc(80);
auth.writeUInt32LE(0x40, 0);
auth.writeUInt32LE(0x3000, 4);
auth.write('bblp', 16, 'ascii');
auth.write(String(this.accessCode || ''), 48, 'ascii');
sock.write(auth);
});
sock.on('data', (chunk) => {
buf = Buffer.concat([buf, chunk]);
// Jeder Frame: 16 Byte Kopf (Länge in den ersten 3 Byte, little endian) + JPEG
while (buf.length >= 16) {
const size = buf[0] | (buf[1] << 8) | (buf[2] << 16);
if (size === 0 || size > 5_000_000) {
buf = Buffer.alloc(0); // Synchronisation verloren
break;
}
if (buf.length < 16 + size) break;
const jpg = buf.subarray(16, 16 + size);
if (jpg.subarray(0, 2).equals(SOI)) this.emit('frame', Buffer.from(jpg));
buf = buf.subarray(16 + size);
}
});
sock.on('timeout', () => sock.destroy(new Error('Kamera antwortet nicht')));
sock.on('error', (err) => this.emit('error', err));
sock.on('close', () => {
if (!this.running) return;
this.restartTimer = setTimeout(() => this.connect(), 5000);
});
}
}
/** Schneidet vollständige JPEGs aus einem Bytestrom; gibt den Rest zurück. */
function extractJpegs(buf, onFrame) {
for (;;) {
const start = buf.indexOf(SOI);
if (start < 0) return Buffer.alloc(0);
const end = buf.indexOf(EOI, start + 2);
if (end < 0) return start > 0 ? buf.subarray(start) : buf;
onFrame(Buffer.from(buf.subarray(start, end + 2)));
buf = buf.subarray(end + 2);
}
}
const SOURCES = { 'http-snapshot': HttpSnapshotSource, ffmpeg: FfmpegSource, 'bambu-tcp': BambuTcpSource };
// ------------------------------------------------------------------ Sitzung
class CameraSession extends EventEmitter {
constructor(sourceConfig) {
super();
this.setMaxListeners(100);
this.sourceConfig = sourceConfig;
this.frame = null;
this.frameAt = 0;
this.error = null;
this.viewers = 0;
}
ensureRunning() {
clearTimeout(this.idleTimer);
if (!this.source) {
const Source = SOURCES[this.sourceConfig.type];
this.source = new Source(this.sourceConfig);
this.source.on('frame', (f) => {
this.frame = f;
this.frameAt = Date.now();
this.error = null;
this.emit('frame', f);
});
this.source.on('error', (err) => {
this.error = err.message;
});
this.source.start();
}
if (this.viewers === 0) this.idleTimer = setTimeout(() => this.halt(), IDLE_STOP_MS);
}
halt() {
if (this.source) this.source.stop();
this.source = null;
}
addViewer() {
this.viewers++;
this.ensureRunning();
}
removeViewer() {
this.viewers = Math.max(0, this.viewers - 1);
if (this.viewers === 0) this.ensureRunning(); // startet den Leerlauf-Timer
}
/** Aktuelles Bild (max. maxAgeMs alt) oder auf das nächste warten. */
snapshot({ maxAgeMs = 3000, timeoutMs = 12000 } = {}) {
this.ensureRunning();
if (this.frame && Date.now() - this.frameAt < maxAgeMs) return Promise.resolve(this.frame);
return new Promise((resolve, reject) => {
const t = setTimeout(() => {
this.off('frame', onFrame);
reject(new Error(this.error || 'Kein Kamerabild erhalten'));
}, timeoutMs);
const onFrame = (f) => {
clearTimeout(t);
resolve(f);
};
this.once('frame', onFrame);
});
}
}
// ------------------------------------------------------------------ Verwaltung
class CameraManager {
constructor() {
this.sessions = new Map(); // printerId -> { key, session }
}
/** Sitzung für einen Drucker holen (oder null, falls er keine Kamera hat). */
async get(printerId, driver) {
const cfg = await driver.cameraSource();
if (!cfg || !SOURCES[cfg.type]) return null;
const key = JSON.stringify(cfg);
const existing = this.sessions.get(printerId);
if (existing && existing.key === key) return existing.session;
if (existing) existing.session.halt();
const session = new CameraSession(cfg);
this.sessions.set(printerId, { key, session });
return session;
}
drop(printerId) {
const s = this.sessions.get(printerId);
if (s) s.session.halt();
this.sessions.delete(printerId);
}
/** Einzelbild für Benachrichtigungen – Fehler werden still geschluckt. */
async trySnapshot(printerId, driver) {
try {
const s = await this.get(printerId, driver);
return s ? await s.snapshot({ maxAgeMs: 5000, timeoutMs: 10000 }) : null;
} catch {
return null;
}
}
}
/** Express-freie HTTP-Handler. */
async function serveSnapshot(res, session) {
try {
const jpg = await session.snapshot();
res.writeHead(200, { 'Content-Type': 'image/jpeg', 'Cache-Control': 'no-store', 'Content-Length': jpg.length });
res.end(jpg);
} catch (err) {
res.writeHead(504, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ error: err.message }));
}
}
function serveMjpeg(req, res, session) {
const boundary = 'printdockframe';
res.writeHead(200, {
'Content-Type': `multipart/x-mixed-replace; boundary=${boundary}`,
'Cache-Control': 'no-store',
Connection: 'close',
});
const send = (jpg) => {
res.write(`--${boundary}\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpg.length}\r\n\r\n`);
res.write(jpg);
res.write('\r\n');
};
session.addViewer();
if (session.frame && Date.now() - session.frameAt < 10000) send(session.frame);
session.on('frame', send);
req.on('close', () => {
session.off('frame', send);
session.removeViewer();
});
}
module.exports = { CameraManager, serveSnapshot, serveMjpeg, extractJpegs, ffmpegPath, ffmpegAvailable };