Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
2026 lines (1852 loc) · 80.5 KB
/
Copy pathserver.js
File metadata and controls
2026 lines (1852 loc) · 80.5 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require("dotenv").config();
const express = require("express");
const crypto = require("crypto");
const path = require("path");
const os = require("os");
const fsSync = require("fs");
const Anthropic = require("@anthropic-ai/sdk");
// External data dir — lives outside the git repo so git operations
// (pull/reset/clean) can never delete runtime data.
const DATA_DIR = process.env.DATA_DIR || path.join(os.homedir(), "sensorpush-data");
fsSync.mkdirSync(DATA_DIR, { recursive: true });
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
app.use("/garden", express.static(path.join(__dirname, "garden")));
// ============ SensorPush ============
const SP_BASE = "https://api.sensorpush.com/api/v1";
const SP_EMAIL = process.env.SENSORPUSH_EMAIL;
const SP_PASSWORD = process.env.SENSORPUSH_PASSWORD;
let spToken = null;
let spTokenExpiry = 0;
async function spPost(endpoint, body, token) {
const headers = { "Content-Type": "application/json" };
if (token) headers["Authorization"] = token;
const res = await fetch(`${SP_BASE}${endpoint}`, {
method: "POST",
headers,
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`SP ${endpoint} failed (${res.status})`);
return res.json();
}
async function getSpToken() {
if (spToken && Date.now() < spTokenExpiry) return spToken;
const auth = await spPost("/oauth/authorize", { email: SP_EMAIL, password: SP_PASSWORD });
const tok = await spPost("/oauth/accesstoken", { authorization: auth.authorization });
spToken = tok.accesstoken;
spTokenExpiry = Date.now() + 11 * 3600000;
console.log("SensorPush token refreshed");
return spToken;
}
// ============ Tuya ============
const TUYA_ID = process.env.TUYA_ACCESS_ID;
const TUYA_SECRET = process.env.TUYA_ACCESS_SECRET;
const TUYA_BASE = process.env.TUYA_BASE_URL || "https://openapi.tuyaus.com";
let tuyaToken = null;
let tuyaTokenExpiry = 0;
function tuyaSign(token, t, method, path, body) {
const contentHash = crypto.createHash("sha256").update(body || "").digest("hex");
const stringToSign = [method, contentHash, "", path].join("\n");
const signStr = TUYA_ID + (token || "") + t + stringToSign;
return crypto.createHmac("sha256", TUYA_SECRET).update(signStr).digest("hex").toUpperCase();
}
async function tuyaRequest(method, apiPath, token, body) {
const t = Date.now().toString();
const bodyStr = body ? JSON.stringify(body) : "";
const sign = tuyaSign(token, t, method, apiPath, bodyStr);
const headers = { client_id: TUYA_ID, sign, t, sign_method: "HMAC-SHA256", "Content-Type": "application/json" };
if (token) headers.access_token = token;
const opts = { method, headers };
if (body) opts.body = bodyStr;
const res = await fetch(`${TUYA_BASE}${apiPath}`, opts);
return res.json();
}
async function getTuyaToken() {
if (tuyaToken && Date.now() < tuyaTokenExpiry) return tuyaToken;
const data = await tuyaRequest("GET", "/v1.0/token?grant_type=1");
if (!data.success) throw new Error(`Tuya token failed: ${data.msg}`);
tuyaToken = data.result.access_token;
tuyaTokenExpiry = Date.now() + (data.result.expire_time - 60) * 1000;
console.log("Tuya token refreshed");
return tuyaToken;
}
async function getTuyaDeviceInfo(deviceId) {
const token = await getTuyaToken();
return tuyaRequest("GET", `/v1.0/devices/${deviceId}`, token);
}
async function getTuyaDeviceLogs(deviceId, startTime, endTime, codes) {
const token = await getTuyaToken();
const params = new URLSearchParams({
start_time: startTime.toString(),
end_time: endTime.toString(),
codes,
size: "100",
type: "1,2,3,4,5,6,7,8,9,10",
});
return tuyaRequest("GET", `/v1.0/devices/${deviceId}/logs?${params}`, token);
}
// ============ Weather (NWS) ============
const NWS_LAT = "39.957";
const NWS_LON = "-75.603";
const NWS_UA = "SmartGardenDashboard/1.0 (garden-monitor)";
let weatherCache = null;
let weatherCacheTime = 0;
app.get("/api/weather", async (req, res) => {
try {
if (weatherCache && Date.now() - weatherCacheTime < 30 * 60 * 1000) {
return res.json(weatherCache);
}
const headers = { "User-Agent": NWS_UA };
const pointsRes = await fetch(
`https://api.weather.gov/points/${NWS_LAT},${NWS_LON}`,
{ headers }
);
const points = await pointsRes.json();
const forecastUrl = points.properties.forecast;
const hourlyUrl = points.properties.forecastHourly;
const [forecastRes, hourlyRes, sunRes] = await Promise.all([
fetch(forecastUrl, { headers }),
fetch(hourlyUrl, { headers }),
fetch(`https://api.sunrise-sunset.org/json?lat=${NWS_LAT}&lng=${NWS_LON}&formatted=0&date=today`),
]);
const forecast = await forecastRes.json();
const hourly = await hourlyRes.json();
const sunData = await sunRes.json();
weatherCache = {
location: points.properties.relativeLocation?.properties,
forecast: (forecast.properties.periods || []).slice(0, 14),
hourly: (hourly.properties.periods || []).slice(0, 24),
sun: sunData.results || {},
updated: new Date().toISOString(),
};
weatherCacheTime = Date.now();
res.json(weatherCache);
} catch (err) {
console.error("weather error:", err.message);
if (weatherCache) return res.json(weatherCache);
res.status(500).json({ error: err.message });
}
});
// ============ SensorPush Routes ============
app.get("/api/sensors", async (req, res) => {
try {
const token = await getSpToken();
const sensors = await spPost("/devices/sensors", {}, token);
const sensorIds = Object.keys(sensors);
if (sensorIds.length) {
const samplesData = await spPost("/samples", { sensors: sensorIds, limit: 1 }, token);
const samplesMap = samplesData.sensors || {};
for (const [id, samples] of Object.entries(samplesMap)) {
if (sensors[id] && samples.length > 0) {
const latest = samples[0];
sensors[id].temperature = latest.temperature;
sensors[id].humidity = latest.humidity;
sensors[id].dewpoint = latest.dewpoint;
sensors[id].vpd = latest.vpd;
sensors[id].barometric_pressure = latest.barometric_pressure;
sensors[id].last_update = latest.observed;
}
}
}
res.json(sensors);
} catch (err) {
console.error("sensors error:", err.message);
res.status(500).json({ error: err.message });
}
});
app.get("/api/gateways", async (req, res) => {
try {
const token = await getSpToken();
const gateways = await spPost("/devices/gateways", {}, token);
res.json(gateways);
} catch (err) {
console.error("gateways error:", err.message);
res.status(500).json({ error: err.message });
}
});
app.post("/api/samples", async (req, res) => {
try {
const token = await getSpToken();
const { sensors, startTime, stopTime, limit } = req.body;
const body = { limit: limit || 500 };
if (sensors) body.sensors = sensors;
if (startTime) body.startTime = startTime;
if (stopTime) body.stopTime = stopTime;
const data = await spPost("/samples", body, token);
res.json(data);
} catch (err) {
console.error("samples error:", err.message);
res.status(500).json({ error: err.message });
}
});
// ============ Pond Alarm Log (server-side tracking) ============
const fs = require("fs");
const POND_LOG_FILE = path.join(DATA_DIR, "pond-alarm-log.json");
let pondLog = [];
let lastPondState = {};
// Load saved log on startup
try {
if (fs.existsSync(POND_LOG_FILE)) {
pondLog = JSON.parse(fs.readFileSync(POND_LOG_FILE, "utf8"));
}
} catch (e) { console.error("Failed to load pond log:", e.message); }
function savePondLog() {
// Keep only last 7 days
const cutoff = Date.now() - 7 * 24 * 3600000;
pondLog = pondLog.filter(e => e.time > cutoff);
try { fs.writeFileSync(POND_LOG_FILE, JSON.stringify(pondLog, null, 2)); } catch (e) {}
}
function trackPondState(statusArr) {
const statusMap = {};
(statusArr || []).forEach(s => statusMap[s.code] = s.value);
const rightAlarm = statusMap.watersensor_state === "alarm";
const leftAlarm = statusMap.tamper_alarm === true;
// Detect state changes
if (lastPondState.right !== undefined) {
if (rightAlarm !== lastPondState.right) {
pondLog.push({ time: Date.now(), probe: "black", code: "watersensor_state", alarm: rightAlarm });
console.log(`Pond: black probe ${rightAlarm ? "ALARM" : "normal"}`);
}
if (leftAlarm !== lastPondState.left) {
pondLog.push({ time: Date.now(), probe: "white", code: "tamper_alarm", alarm: leftAlarm });
console.log(`Pond: white probe ${leftAlarm ? "ALARM" : "normal"}`);
}
savePondLog();
}
lastPondState = { right: rightAlarm, left: leftAlarm };
}
// ============ Tuya Routes (water sensor only) ============
app.get("/api/tuya/devices", async (req, res) => {
try {
const devices = [
{ id: "eb4b975ccbbe3fb9dc98n2", type: "water_sensor" },
];
const results = await Promise.all(
devices.map(async (d) => {
const info = await getTuyaDeviceInfo(d.id);
const device = { ...d, ...info.result };
// Track state changes for pond alarm log
if (d.type === "water_sensor" && device.status) {
trackPondState(device.status);
}
return device;
})
);
res.json(results);
} catch (err) {
console.error("tuya devices error:", err.message);
res.status(500).json({ error: err.message });
}
});
app.get("/api/pond/logs", (req, res) => {
const hours = parseInt(req.query.hours) || 24;
const cutoff = Date.now() - hours * 3600000;
const logs = pondLog.filter(e => e.time > cutoff).sort((a, b) => b.time - a.time);
res.json({ logs });
});
app.get("/api/tuya/device/:id/logs", async (req, res) => {
try {
const hours = parseInt(req.query.hours) || 24;
const codes = req.query.codes || "watersensor_state";
const endTime = Date.now();
const startTime = endTime - hours * 3600000;
const data = await getTuyaDeviceLogs(req.params.id, startTime, endTime, codes);
res.json(data.result || { logs: [] });
} catch (err) {
console.error("tuya logs error:", err.message);
res.status(500).json({ error: err.message });
}
});
// ============ Water Timer (Tuya Smart Dual Water Timer) ============
const WATER_TIMER_ID = "eb42c3sv54vcakok";
// Server-side valve state tracking (Tuya device countdown is unreliable)
let valveOnTimes = { 1: null, 2: null };
let valveAutoOff = { 1: null, 2: null }; // setTimeout handles
let valveCountdown = { 1: 0, 2: 0 }; // countdown in minutes set by user
let valveCountdownEnd = { 1: null, 2: null }; // timestamp when countdown expires
async function turnOffValve(valve) {
try {
const token = await getTuyaToken();
await tuyaRequest("POST", `/v1.0/devices/${WATER_TIMER_ID}/commands`, token, {
commands: [{ code: `switch_${valve}`, value: false }],
});
console.log(`Valve ${valve} auto-off by server timer`);
} catch (err) {
console.error(`Valve ${valve} auto-off failed:`, err.message);
}
valveOnTimes[valve] = null;
valveCountdown[valve] = 0;
valveCountdownEnd[valve] = null;
valveAutoOff[valve] = null;
}
function scheduleAutoOff(valve, minutes) {
// Clear any existing timer
if (valveAutoOff[valve]) clearTimeout(valveAutoOff[valve]);
valveCountdown[valve] = minutes;
valveCountdownEnd[valve] = Date.now() + minutes * 60000;
valveAutoOff[valve] = setTimeout(() => turnOffValve(valve), minutes * 60000);
console.log(`Valve ${valve} scheduled auto-off in ${minutes} min`);
}
function clearAutoOff(valve) {
if (valveAutoOff[valve]) clearTimeout(valveAutoOff[valve]);
valveAutoOff[valve] = null;
valveCountdown[valve] = 0;
valveCountdownEnd[valve] = null;
}
app.get("/api/timer/status", async (req, res) => {
try {
const token = await getTuyaToken();
const data = await tuyaRequest("GET", `/v1.0/devices/${WATER_TIMER_ID}`, token);
if (!data.success) return res.status(500).json({ error: data.msg });
const status = {};
(data.result.status || []).forEach(s => status[s.code] = s.value);
// Sync on-times with actual device state
for (const v of [1, 2]) {
if (status[`switch_${v}`] && !valveOnTimes[v]) {
valveOnTimes[v] = Date.now();
} else if (!status[`switch_${v}`]) {
// Device reports off — check if server still has an active countdown
if (valveCountdownEnd[v] && valveCountdownEnd[v] > Date.now()) {
// Server timer still active: Tuya device shut off on its own (unreliable internal timer)
// Re-send switch-on command to keep the valve running
console.log(`Valve ${v} turned off by device while server timer active (${Math.ceil((valveCountdownEnd[v] - Date.now()) / 60000)}m left), re-opening...`);
tuyaRequest("POST", `/v1.0/devices/${WATER_TIMER_ID}/commands`, token, {
commands: [{ code: `switch_${v}`, value: true }],
}).catch(err => console.error(`Valve ${v} re-open failed:`, err.message));
// Keep server state as-is (on + countdown active), report as on
status[`switch_${v}`] = true;
} else {
// No active server timer — valve is genuinely off
valveOnTimes[v] = null;
clearAutoOff(v);
}
}
}
// Compute remaining countdown from server-side timer
const remaining = v => {
if (!valveCountdownEnd[v] || !valveOnTimes[v]) return 0;
return Math.max(0, Math.ceil((valveCountdownEnd[v] - Date.now()) / 60000));
};
res.json({
online: data.result.online,
battery: status.battery_percentage,
valve1: { on: !!status.switch_1, countdown: remaining(1), use_time: status.use_time_1 || 0, on_since: valveOnTimes[1] },
valve2: { on: !!status.switch_2, countdown: remaining(2), use_time: status.use_time_2 || 0, on_since: valveOnTimes[2] },
});
} catch (err) {
console.error("timer status error:", err.message);
res.status(500).json({ error: err.message });
}
});
app.post("/api/timer/valve", async (req, res) => {
try {
const { valve, on, countdown } = req.body;
if (![1, 2].includes(valve)) return res.status(400).json({ error: "valve must be 1 or 2" });
// Build Tuya command (only switch, no Tuya countdown — it's unreliable)
const commands = [];
if (typeof on === "boolean") {
commands.push({ code: `switch_${valve}`, value: on });
}
if (!commands.length) return res.status(400).json({ error: "provide on (bool)" });
const token = await getTuyaToken();
const data = await tuyaRequest("POST", `/v1.0/devices/${WATER_TIMER_ID}/commands`, token, { commands });
if (!data.success) return res.status(500).json({ error: data.msg });
// Server-side timer management
if (on) {
valveOnTimes[valve] = Date.now();
if (typeof countdown === "number" && countdown > 0 && countdown <= 1440) {
scheduleAutoOff(valve, countdown);
}
} else {
valveOnTimes[valve] = null;
clearAutoOff(valve);
}
res.json({ ok: true, valve, on, countdown: countdown || 0 });
} catch (err) {
console.error("timer valve error:", err.message);
res.status(500).json({ error: err.message });
}
});
// ============ Garden Editor API ============
const GARDENS_DIR = path.join(DATA_DIR, "gardens");
if (!fs.existsSync(GARDENS_DIR)) fs.mkdirSync(GARDENS_DIR, { recursive: true });
app.get("/api/gardens", (req, res) => {
const files = fs.readdirSync(GARDENS_DIR).filter(f => f.endsWith(".json"));
const list = files.map(f => {
const data = JSON.parse(fs.readFileSync(path.join(GARDENS_DIR, f), "utf8"));
return { name: f.replace(".json", ""), label: data.label || f.replace(".json", ""), updated: data.updated };
});
res.json(list);
});
app.get("/api/garden/:name", (req, res) => {
const file = path.join(GARDENS_DIR, req.params.name + ".json");
if (!fs.existsSync(file)) return res.status(404).json({ error: "not found" });
res.json(JSON.parse(fs.readFileSync(file, "utf8")));
});
app.post("/api/garden/:name", (req, res) => {
const name = req.params.name.replace(/[^a-zA-Z0-9_-]/g, "");
if (!name) return res.status(400).json({ error: "invalid name" });
const data = { ...req.body, updated: new Date().toISOString() };
fs.writeFileSync(path.join(GARDENS_DIR, name + ".json"), JSON.stringify(data, null, 2));
res.json({ ok: true, name });
});
app.delete("/api/garden/:name", (req, res) => {
const file = path.join(GARDENS_DIR, req.params.name + ".json");
if (fs.existsSync(file)) fs.unlinkSync(file);
res.json({ ok: true });
});
// ============ Reolink Camera (Koi Pond) - RTSP/HLS ============
const { spawn } = require("child_process");
const REOLINK_IP = process.env.REOLINK_IP || "192.168.1.96";
const REOLINK_USER = process.env.REOLINK_USER || "admin";
const REOLINK_PASS = process.env.REOLINK_PASSWORD || "";
const HLS_DIR = path.join(DATA_DIR, "hls-cam");
// Ensure HLS output directory exists
if (!fs.existsSync(HLS_DIR)) fs.mkdirSync(HLS_DIR, { recursive: true });
// Serve HLS segments with proper headers
app.use("/hls", (req, res, next) => {
res.set("Cache-Control", "no-cache, no-store");
res.set("Access-Control-Allow-Origin", "*");
next();
}, express.static(HLS_DIR));
let ffmpegProc = null;
let ffmpegQuality = "stable"; // "stable" (sub, copy, 0% CPU) or "hd" (main, transcode)
let ffmpegStartTime = 0;
let ffmpegRestarts = 0;
// Monotonic generation tag — bumped on every (re)start so a stale exit handler
// from the previous process can't clobber the new process's state. Without
// this, killing+respawning ffmpeg races: the old exit handler runs after the
// new spawn assignment and sets ffmpegProc = null, leaving the watchdog blind
// to a still-running ffmpeg that's gone "headless." Seen as the source of the
// TV-page "stale by days" bug.
let ffmpegGen = 0;
let ffmpegDeadSince = 0; // timestamp when ffmpegProc went null; 0 = healthy
function rtspUrl(stream) {
const profile = stream === "main" ? "h264Preview_01_main" : "h264Preview_01_sub";
return `rtsp://${encodeURIComponent(REOLINK_USER)}:${encodeURIComponent(REOLINK_PASS)}@${REOLINK_IP}:554/${profile}`;
}
function startFFmpeg(quality) {
if (ffmpegProc) {
try { ffmpegProc.kill("SIGTERM"); } catch (e) {}
// Do NOT null ffmpegProc here — the old exit handler will only act if its
// own generation tag still matches the global one. We bump the global gen
// below so the old handler treats itself as stale and bails out.
}
try {
fs.readdirSync(HLS_DIR).forEach(f => fs.unlinkSync(path.join(HLS_DIR, f)));
} catch (e) {}
ffmpegQuality = quality || ffmpegQuality;
ffmpegStartTime = Date.now();
ffmpegDeadSince = 0;
const myGen = ++ffmpegGen;
const useHD = ffmpegQuality === "hd";
const args = [
"-fflags", "+genpts+discardcorrupt+nobuffer",
"-rtsp_transport", "tcp",
"-rtsp_flags", "prefer_tcp",
"-buffer_size", "4194304",
"-analyzeduration", "2000000",
"-probesize", "2000000",
];
if (useHD) {
// Main stream: HEVC 4K → transcode to 720p H.264 (lighter than 1080p)
console.log("Starting ffmpeg: RTSP main → H.264 720p + AAC → HLS (transcode)");
args.push(
"-i", rtspUrl("main"),
"-map", "0:v:0", "-map", "0:a:0",
"-c:v:0", "libx264", "-preset", "ultrafast", "-tune", "zerolatency",
"-b:v:0", "1200k", "-maxrate:v", "1500k", "-bufsize:v", "2000k",
"-filter:v", "scale=1280:-2",
"-r", "15", "-g", "30",
"-c:a:0", "aac", "-ar", "16000", "-ac", "1", "-b:a:0", "64k",
"-sc_threshold", "0",
);
} else {
// Sub stream: H.264 640x360 → copy (0% CPU, rock stable)
console.log("Starting ffmpeg: RTSP sub → H.264 copy → HLS (no transcode)");
args.push(
"-i", rtspUrl("sub"),
"-c:v", "copy",
"-an", // sub has no audio
);
}
args.push(
"-f", "hls",
"-hls_time", "2",
"-hls_list_size", "6",
"-hls_flags", "delete_segments+append_list+independent_segments",
"-hls_segment_type", "mpegts",
"-hls_segment_filename", path.join(HLS_DIR, "seg%05d.ts"),
path.join(HLS_DIR, "stream.m3u8"),
);
ffmpegProc = spawn("ffmpeg", args, { stdio: ["ignore", "pipe", "pipe"] });
let stderrBuf = "";
ffmpegProc.stderr.on("data", (data) => {
stderrBuf += data.toString();
const lines = stderrBuf.split("\n");
stderrBuf = lines.pop();
for (const line of lines) {
if (line.includes("error") || line.includes("Error") || line.includes("Opening") || line.includes("Output #0")) {
console.log("ffmpeg:", line.trim());
}
}
});
ffmpegProc.on("exit", (code, signal) => {
console.log(`ffmpeg exited with code ${code} signal ${signal} (gen ${myGen}, current ${ffmpegGen})`);
// Only this generation's handler should mutate global state. If a newer
// startFFmpeg has run, myGen < ffmpegGen and we silently bail out — the
// newer process is responsible for itself.
if (myGen !== ffmpegGen) return;
ffmpegProc = null;
ffmpegDeadSince = Date.now();
// ALWAYS restart, even on clean (code 0) exit. ffmpeg shouldn't ever
// cleanly exit while we want a live stream — and on the rare occasion it
// does (e.g. RTSP EOF, stream EOF), leaving things dead means the TV
// shows nothing or stale data until someone notices. Past incident: HLS
// dir went stale for days because a clean exit was treated as "fine".
ffmpegRestarts++;
const delay = Math.min(3000 + ffmpegRestarts * 2000, 30000);
console.log(`ffmpeg auto-restart #${ffmpegRestarts} in ${delay/1000}s...`);
setTimeout(() => {
// Only restart if no newer startFFmpeg has fired in the meantime.
if (myGen === ffmpegGen) startFFmpeg(ffmpegQuality);
}, delay);
});
setTimeout(() => { ffmpegRestarts = Math.max(0, ffmpegRestarts - 1); }, 120000);
}
// Watchdog: kill ffmpeg if it stops writing fresh segments. Three failure modes:
// (a) startup never produces segments (no .ts after 20s)
// (b) running process hangs mid-stream — playlist mtime stops advancing (seen Apr 29: 18h stale)
// (c) ffmpeg is dead AND no restart got scheduled (defensive safety net so
// the stream can't stay dark for days even if the exit-handler chain
// above is somehow broken — this was the root TV-stale-stream bug)
setInterval(() => {
// (c) Process is gone. Try to revive it — but give the normal exit-handler
// restart 60s to do its job before we step in.
if (!ffmpegProc) {
if (ffmpegDeadSince && Date.now() - ffmpegDeadSince > 60000) {
console.log("ffmpeg watchdog: process dead >60s with no restart, forcing one");
ffmpegDeadSince = 0;
try { startFFmpeg(ffmpegQuality); } catch (e) { console.error("watchdog restart failed:", e.message); }
}
return;
}
const uptime = Date.now() - ffmpegStartTime;
if (uptime < 20000) return;
let segs = 0, playlistAge = Infinity;
try {
segs = fs.readdirSync(HLS_DIR).filter(f => f.endsWith(".ts")).length;
const m3u8 = path.join(HLS_DIR, "stream.m3u8");
if (fs.existsSync(m3u8)) playlistAge = Date.now() - fs.statSync(m3u8).mtimeMs;
} catch (e) {}
// Healthy stream rewrites m3u8 every ~2s. >20s without an update = hung.
const stalled = segs === 0 || playlistAge > 20000;
if (stalled) {
console.log(`ffmpeg watchdog: stalled (segs=${segs}, playlistAge=${Math.floor(playlistAge/1000)}s, uptime=${Math.floor(uptime/1000)}s), killing for restart`);
try { ffmpegProc.kill("SIGKILL"); } catch (e) {}
}
}, 10000);
// Default: use stable sub stream (no transcode, never drops)
startFFmpeg("stable");
// API: stream status
app.get("/api/camera/status", (req, res) => {
const m3u8Exists = fs.existsSync(path.join(HLS_DIR, "stream.m3u8"));
const segments = fs.readdirSync(HLS_DIR).filter(f => f.endsWith(".ts")).length;
res.json({
running: !!ffmpegProc,
quality: ffmpegQuality,
hlsReady: m3u8Exists && segments > 0,
segments,
uptime: ffmpegProc ? Math.floor((Date.now() - ffmpegStartTime) / 1000) : 0,
restarts: ffmpegRestarts,
});
});
// API: switch output quality (always from main RTSP stream)
app.post("/api/camera/stream", (req, res) => {
const { quality } = req.body;
if (!["stable", "hd"].includes(quality)) return res.status(400).json({ error: "Invalid quality: stable or hd" });
startFFmpeg(quality);
res.json({ ok: true, quality });
});
// API: restart stream
app.post("/api/camera/restart", (req, res) => {
ffmpegRestarts = 0;
startFFmpeg(ffmpegQuality);
res.json({ ok: true });
});
// API: snapshot (grab from RTSP directly)
app.get("/api/camera/snap", async (req, res) => {
try {
const url = `http://${REOLINK_IP}/cgi-bin/api.cgi?cmd=Snap&channel=0&rs=${Date.now()}&user=${encodeURIComponent(REOLINK_USER)}&password=${encodeURIComponent(REOLINK_PASS)}`;
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
if (!response.ok) throw new Error(`Camera returned ${response.status}`);
res.set("Content-Type", response.headers.get("content-type") || "image/jpeg");
res.set("Cache-Control", "no-cache, no-store");
res.send(Buffer.from(await response.arrayBuffer()));
} catch (err) {
console.error("camera snap error:", err.message);
res.status(502).json({ error: err.message });
}
});
// API: PTZ control
app.post("/api/camera/ptz", async (req, res) => {
try {
const { command, speed } = req.body;
const ptzMap = {
left: "Left", right: "Right", up: "Up", down: "Down",
zoomin: "ZoomInc", zoomout: "ZoomDec", stop: "Stop"
};
const op = ptzMap[command];
if (!op) return res.status(400).json({ error: "Invalid PTZ command" });
const body = [{ cmd: "PtzCtrl", action: 0, param: { channel: 0, op, speed: speed || 10 } }];
const url = `http://${REOLINK_IP}/cgi-bin/api.cgi?token=null&user=${encodeURIComponent(REOLINK_USER)}&password=${encodeURIComponent(REOLINK_PASS)}`;
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(3000),
});
res.json(await response.json());
} catch (err) {
console.error("camera ptz error:", err.message);
res.status(502).json({ error: err.message });
}
});
// API: camera device info
app.get("/api/camera/info", async (req, res) => {
try {
const body = [{ cmd: "GetDevInfo", action: 0, param: { channel: 0 } }];
const url = `http://${REOLINK_IP}/cgi-bin/api.cgi?token=null&user=${encodeURIComponent(REOLINK_USER)}&password=${encodeURIComponent(REOLINK_PASS)}`;
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(5000),
});
const data = await response.json();
res.json(data[0]?.value?.DevInfo || {});
} catch (err) {
console.error("camera info error:", err.message);
res.status(502).json({ error: err.message });
}
});
// ============ Blink Cameras (cloud-only, via blinkpy) ============
// Blink cameras have NO RTSP/ONVIF/local stream, so unlike the Reolink koi
// camera (RTSP -> ffmpeg -> HLS) we cannot pull frames directly. Everything
// goes through Amazon's Blink cloud via blink_client.py (the blinkpy library).
// Each call spawns the python helper once; it persists/refreshes the session
// token in DATA_DIR/blink_creds.json (one-time 2FA setup required).
const { execFile: execFileBlink } = require("child_process");
const BLINK_SCRIPT = path.join(__dirname, "blink_client.py");
const BLINK_DIR = path.join(DATA_DIR, "blink");
if (!fs.existsSync(BLINK_DIR)) fs.mkdirSync(BLINK_DIR, { recursive: true });
// Run a blink_client.py command; resolve parsed JSON or reject with stderr.
function blinkCmd(args, { timeout = 30000 } = {}) {
return new Promise((resolve, reject) => {
execFileBlink("python3", [BLINK_SCRIPT, ...args], {
cwd: __dirname,
timeout,
env: { ...process.env, PYTHONUNBUFFERED: "1" },
maxBuffer: 8 * 1024 * 1024,
}, (err, stdout, stderr) => {
if (err) return reject(new Error((stderr || err.message).toString().trim()));
try { resolve(JSON.parse((stdout || "").trim() || "{}")); }
catch (e) { reject(new Error("Bad JSON from blink_client: " + (stdout || "").slice(0, 200))); }
});
});
}
// In-process cache so dashboard polling doesn't hammer Blink's cloud (which
// would also drain the battery cameras). Camera list cached for 60s.
let blinkCamCache = { ts: 0, data: null };
app.get("/api/blink/cameras", async (req, res) => {
try {
const fresh = req.query.fresh === "1";
if (!fresh && blinkCamCache.data && Date.now() - blinkCamCache.ts < 60000) {
return res.json({ ...blinkCamCache.data, cached: true });
}
const data = await blinkCmd(["cameras"]);
blinkCamCache = { ts: Date.now(), data };
res.json(data);
} catch (err) {
console.error("blink cameras error:", err.message);
res.status(502).json({ error: err.message });
}
});
// Thumbnail JPEG for a camera. Downloads to DATA_DIR/blink/<name>.jpg and
// serves it. ?snap=1 first asks the camera to take a fresh photo (slower,
// uses battery); otherwise serves the most recent cloud thumbnail.
app.get("/api/blink/thumbnail/:name", async (req, res) => {
const name = req.params.name;
const safe = name.replace(/[^a-zA-Z0-9_-]/g, "_");
const outfile = path.join(BLINK_DIR, `${safe}.jpg`);
try {
if (req.query.snap === "1") await blinkCmd(["snap", name], { timeout: 45000 });
await blinkCmd(["thumbnail", name, outfile], { timeout: 30000 });
res.set("Cache-Control", "no-cache, no-store");
res.sendFile(outfile);
} catch (err) {
console.error("blink thumbnail error:", err.message);
res.status(502).json({ error: err.message });
}
});
// Trigger a fresh snapshot (returns JSON; image fetched via thumbnail route)
app.post("/api/blink/snap/:name", async (req, res) => {
try {
blinkCamCache.ts = 0;
res.json(await blinkCmd(["snap", req.params.name], { timeout: 45000 }));
} catch (err) {
console.error("blink snap error:", err.message);
res.status(502).json({ error: err.message });
}
});
// Latest motion clip (mp4) for a camera. Can be fed to motion/bird detectors.
app.get("/api/blink/clip/:name", async (req, res) => {
const name = req.params.name;
const safe = name.replace(/[^a-zA-Z0-9_-]/g, "_");
const outfile = path.join(BLINK_DIR, `${safe}.mp4`);
try {
await blinkCmd(["clip", name, outfile], { timeout: 45000 });
res.set("Cache-Control", "no-cache, no-store");
res.sendFile(outfile);
} catch (err) {
console.error("blink clip error:", err.message);
res.status(502).json({ error: err.message });
}
});
// Arm / disarm a sync module (network). body: { network, armed: bool }
app.post("/api/blink/arm", async (req, res) => {
const { network, armed } = req.body;
if (!network) return res.status(400).json({ error: "network required" });
try {
blinkCamCache.ts = 0; // force a fresh poll after state change
res.json(await blinkCmd([armed ? "arm" : "disarm", network]));
} catch (err) {
console.error("blink arm error:", err.message);
res.status(502).json({ error: err.message });
}
});
// ---- On-demand liveview -> HLS --------------------------------------------
// Best-effort only: Blink liveviews are short-lived (~30-90s) and drain the
// battery, so this is NOT a 24/7 stream like the koi camera. One active
// liveview at a time, transcoded into DATA_DIR/blink-hls/stream.m3u8.
const BLINK_HLS_DIR = path.join(DATA_DIR, "blink-hls");
if (!fs.existsSync(BLINK_HLS_DIR)) fs.mkdirSync(BLINK_HLS_DIR, { recursive: true });
app.use("/blink-hls", (req, res, next) => {
res.set("Cache-Control", "no-cache, no-store");
next();
}, express.static(BLINK_HLS_DIR));
let blinkLiveProc = null;
let blinkLiveName = null;
function stopBlinkLive() {
if (blinkLiveProc) { try { blinkLiveProc.kill("SIGKILL"); } catch (e) {} blinkLiveProc = null; }
blinkLiveName = null;
}
app.post("/api/blink/liveview/:name", async (req, res) => {
const name = req.params.name;
try {
const { url } = await blinkCmd(["liveview", name], { timeout: 20000 });
if (!url) throw new Error("No liveview URL returned");
stopBlinkLive();
try { fs.readdirSync(BLINK_HLS_DIR).forEach(f => fs.unlinkSync(path.join(BLINK_HLS_DIR, f))); } catch (e) {}
const args = [
"-rtsp_transport", "tcp",
"-i", url,
"-c:v", "libx264", "-preset", "veryfast", "-tune", "zerolatency", "-pix_fmt", "yuv420p",
"-c:a", "aac",
"-f", "hls", "-hls_time", "1", "-hls_list_size", "4",
"-hls_flags", "delete_segments+append_list+independent_segments",
"-hls_segment_filename", path.join(BLINK_HLS_DIR, "seg%03d.ts"),
path.join(BLINK_HLS_DIR, "stream.m3u8"),
];
blinkLiveProc = spawn("ffmpeg", args, { stdio: ["ignore", "ignore", "pipe"] });
blinkLiveName = name;
const myProc = blinkLiveProc;
blinkLiveProc.stderr.on("data", () => {}); // drain stderr
blinkLiveProc.on("exit", () => { if (blinkLiveProc === myProc) { blinkLiveProc = null; blinkLiveName = null; } });
setTimeout(() => { if (blinkLiveProc === myProc) stopBlinkLive(); }, 90000);
res.json({ ok: true, camera: name, hls: "/blink-hls/stream.m3u8" });
} catch (err) {
// Blink Mini cameras can't do liveview via blinkpy (Blink gates it behind a
// newer app version). Report that distinctly so the UI can disable the button.
const unsupported = /LIVEVIEW_UNSUPPORTED|KeyError|app update/i.test(err.message);
console.error("blink liveview error:", err.message);
res.status(unsupported ? 501 : 502).json({ error: err.message, unsupported });
}
});
app.post("/api/blink/liveview/stop", (req, res) => { stopBlinkLive(); res.json({ ok: true }); });
// ---- Blink motion watcher (auto-capture clips when armed) -----------------
// blink_motion.py polls Blink's cloud and downloads motion clips that Blink
// records whenever an ARMED camera sees motion. Clips land in
// DATA_DIR/blink-motion/clips and the feed is in events.json.
const BLINK_MOTION_DIR = path.join(DATA_DIR, "blink-motion");
const BLINK_MOTION_CLIPS = path.join(BLINK_MOTION_DIR, "clips");
const BLINK_MOTION_EVENTS = path.join(BLINK_MOTION_DIR, "events.json");
if (!fs.existsSync(BLINK_MOTION_CLIPS)) fs.mkdirSync(BLINK_MOTION_CLIPS, { recursive: true });
app.use("/api/blink/motion/clip", express.static(BLINK_MOTION_CLIPS));
let blinkMotionProc = null;
app.get("/api/blink/motion/events", (req, res) => {
const limit = parseInt(req.query.limit) || 50;
try {
if (!fs.existsSync(BLINK_MOTION_EVENTS)) return res.json({ events: [], running: !!blinkMotionProc });
const all = JSON.parse(fs.readFileSync(BLINK_MOTION_EVENTS, "utf8"));
res.json({ events: all.slice(0, limit), running: !!blinkMotionProc });
} catch (e) {
res.json({ events: [], running: !!blinkMotionProc });
}
});
function startBlinkMotion() {
if (blinkMotionProc) return;
const script = path.join(__dirname, "blink_motion.py");
if (!fs.existsSync(script)) return;
// Don't start until Blink is set up — otherwise it just exits immediately.
if (!fs.existsSync(path.join(DATA_DIR, "blink_creds.json"))) {
setTimeout(startBlinkMotion, 300000); // re-check in 5 min
return;
}
console.log("Starting Blink motion watcher...");
blinkMotionProc = spawn("python3", ["-u", script], {
cwd: __dirname,
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, PYTHONUNBUFFERED: "1" },
});
blinkMotionProc.stdout.on("data", d => { const l = d.toString().trim(); if (l) console.log("blink-motion:", l); });
blinkMotionProc.stderr.on("data", d => { const l = d.toString().trim(); if (l && !l.startsWith("INFO:")) console.error("blink-motion-err:", l); });
blinkMotionProc.on("exit", (code) => {
console.log(`Blink motion watcher exited (code ${code})`);
blinkMotionProc = null;
setTimeout(startBlinkMotion, 60000);
});
}
setTimeout(startBlinkMotion, 25000);
app.get("/api/blink/motion/status", (req, res) => {
res.json({ running: !!blinkMotionProc });
});
// ============ Bird Detection API ============
const BIRD_DIR = path.join(DATA_DIR, "bird-detections");
const BIRD_CLIPS = path.join(BIRD_DIR, "clips");
const BIRD_FILE = path.join(BIRD_DIR, "latest.json");
if (!fs.existsSync(BIRD_CLIPS)) fs.mkdirSync(BIRD_CLIPS, { recursive: true });
// Serve bird audio clips
app.use("/api/birds/clip", express.static(BIRD_CLIPS));
// Latest detections
app.get("/api/birds/latest", (req, res) => {
const since = parseInt(req.query.since) || 0;
try {
if (!fs.existsSync(BIRD_FILE)) return res.json({ detections: [] });
const all = JSON.parse(fs.readFileSync(BIRD_FILE, "utf8"));
const filtered = since ? all.filter(d => d.timestamp > since) : all.slice(-20);
res.json({ detections: filtered });
} catch (e) {
res.json({ detections: [] });
}
});
// Helper: local date string (not UTC)
function localDateStr(d) {
const dd = d || new Date();
return dd.getFullYear() + '-' + String(dd.getMonth()+1).padStart(2,'0') + '-' + String(dd.getDate()).padStart(2,'0');
}
// Daily detections by date
// Server's current local date. The frontend uses this for its "today" view instead of
// the browser's clock, so a viewing device whose date is off (e.g. a day ahead) doesn't
// request a future date and see an empty page.
app.get("/api/birds/today", (req, res) => {
res.json({ date: localDateStr() });
});
app.get("/api/birds/daily/:date?", (req, res) => {
try {
const dateStr = req.params.date || localDateStr();
const file = path.join(BIRD_DIR, "daily", `${dateStr}.json`);
if (!fs.existsSync(file)) return res.json({ date: dateStr, detections: [] });
const data = JSON.parse(fs.readFileSync(file, "utf8"));
res.json({ date: dateStr, detections: data });
} catch (e) {
res.json({ date: req.params.date, detections: [] });
}
});
// Available dates that have detections
app.get("/api/birds/dates", (req, res) => {
try {
const dailyDir = path.join(BIRD_DIR, "daily");
if (!fs.existsSync(dailyDir)) return res.json({ dates: [] });
const files = fs.readdirSync(dailyDir).filter(f => f.endsWith(".json")).sort().reverse();
const dates = files.map(f => {
const date = f.replace(".json", "");
const data = JSON.parse(fs.readFileSync(path.join(dailyDir, f), "utf8"));
return { date, count: data.length };
});
res.json({ dates });
} catch (e) {
res.json({ dates: [] });
}
});
// Stats/leaderboard for a date range
app.get("/api/birds/stats", (req, res) => {
try {
const date = req.query.date || localDateStr();
const days = parseInt(req.query.days) || 1;
const allDetections = [];
for (let i = 0; i < days; i++) {
const d = new Date(date);
d.setDate(d.getDate() - i);
const ds = d.toISOString().slice(0, 10);
const file = path.join(BIRD_DIR, "daily", `${ds}.json`);
if (fs.existsSync(file)) {
try {
const data = JSON.parse(fs.readFileSync(file, "utf8"));
allDetections.push(...data);
} catch (e) {}
}
}
// Build species leaderboard
const speciesMap = {};
for (const d of allDetections) {
const key = d.common_name;
if (!speciesMap[key]) {