iobroker.agent-dvr 0.4.2 → 0.5.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/build/main.js CHANGED
@@ -287,6 +287,7 @@ window.ADVscan=scan;scan();
287
287
  class AgentDvr extends utils.Adapter {
288
288
  pollTimer = void 0;
289
289
  pollBusy = false;
290
+ _pollStopped = false;
290
291
  refreshTimer = void 0;
291
292
  authHeader = null;
292
293
  baseUrl = "";
@@ -294,6 +295,7 @@ class AgentDvr extends utils.Adapter {
294
295
  ensuredFolders = /* @__PURE__ */ new Set();
295
296
  registry = /* @__PURE__ */ new Map();
296
297
  ptzActive = /* @__PURE__ */ new Map();
298
+ ptzPresetNames = /* @__PURE__ */ new Map();
297
299
  widgetSig = {};
298
300
  profileSig = "";
299
301
  lastCamNames = [];
@@ -336,17 +338,15 @@ class AgentDvr extends utils.Adapter {
336
338
  } catch (e) {
337
339
  this.log.warn(`First poll error: ${e.message}`);
338
340
  }
339
- this.pollTimer = this.setInterval(
340
- () => this.poll().catch((e) => this.log.warn(`Poll error: ${e.message}`)),
341
- pollSeconds * 1e3
342
- );
341
+ this.schedulePoll(pollSeconds * 1e3);
343
342
  this.subscribeStates("*");
344
343
  this.log.info(`Agent DVR adapter ready. Polling ${this.baseUrl} every ${pollSeconds}s.`);
345
344
  }
346
345
  onUnload(callback) {
347
346
  try {
347
+ this._pollStopped = true;
348
348
  if (this.pollTimer !== void 0) {
349
- this.clearInterval(this.pollTimer);
349
+ this.clearTimeout(this.pollTimer);
350
350
  this.pollTimer = void 0;
351
351
  }
352
352
  if (this.refreshTimer !== void 0) {
@@ -395,6 +395,9 @@ class AgentDvr extends utils.Adapter {
395
395
  return { result: rows };
396
396
  }
397
397
  fetchGo2rtcStreams(overrideUrl) {
398
+ if (!overrideUrl && !this.config.go2rtcEnabled) {
399
+ return Promise.resolve({ streams: [], error: "go2rtc disabled" });
400
+ }
398
401
  const url = (overrideUrl || this.config.go2rtcUrl || "").replace(/^https:\/\//i, "http://");
399
402
  if (!url) {
400
403
  return Promise.resolve({ streams: [], error: "go2rtcUrl not configured" });
@@ -458,7 +461,12 @@ class AgentDvr extends utils.Adapter {
458
461
  }
459
462
  apiGet(path) {
460
463
  return new Promise((resolve) => {
461
- const timeout = Math.max(1e3, Math.min(3e4, this.config.httpTimeoutMs || 8e3));
464
+ var _a;
465
+ const rawTimeout = (_a = this.config.httpTimeoutMs) != null ? _a : 8e3;
466
+ const timeout = Math.max(1e3, Math.min(3e4, rawTimeout));
467
+ if (timeout !== rawTimeout) {
468
+ this.log.debug(`httpTimeoutMs ${rawTimeout} clamped to ${timeout} ms`);
469
+ }
462
470
  const opts = {
463
471
  hostname: this.config.serverIp,
464
472
  port: this.config.port || 8090,
@@ -497,7 +505,12 @@ class AgentDvr extends utils.Adapter {
497
505
  }
498
506
  apiGetBuffer(path) {
499
507
  return new Promise((resolve) => {
500
- const timeout = Math.max(1e3, Math.min(3e4, this.config.httpTimeoutMs || 8e3));
508
+ var _a;
509
+ const rawTimeout = (_a = this.config.httpTimeoutMs) != null ? _a : 8e3;
510
+ const timeout = Math.max(1e3, Math.min(3e4, rawTimeout));
511
+ if (timeout !== rawTimeout) {
512
+ this.log.debug(`httpTimeoutMs ${rawTimeout} clamped to ${timeout} ms`);
513
+ }
501
514
  const opts = {
502
515
  hostname: this.config.serverIp,
503
516
  port: this.config.port || 8090,
@@ -550,13 +563,16 @@ class AgentDvr extends utils.Adapter {
550
563
  }
551
564
  }
552
565
  }
553
- async writeLeaf(id, val) {
566
+ async writeLeaf(id, val, unit) {
554
567
  const t = typeof val;
555
568
  let common;
556
569
  if (t === "boolean") {
557
570
  common = { name: id.split(".").pop() || id, type: "boolean", role: "indicator", read: true, write: false };
558
571
  } else if (t === "number") {
559
572
  common = { name: id.split(".").pop() || id, type: "number", role: "value", read: true, write: false };
573
+ if (unit) {
574
+ common.unit = unit;
575
+ }
560
576
  } else {
561
577
  const role = typeof val === "string" && /^https?:\/\//i.test(val) ? "text.url" : "text";
562
578
  common = { name: id.split(".").pop() || id, type: "string", role, read: true, write: false };
@@ -798,6 +814,7 @@ class AgentDvr extends utils.Adapter {
798
814
  await this.ensureButton(cid, `PTZ ${p.id}`, { kind: "ptz", oid: d.oid, dir: p.dir });
799
815
  }
800
816
  }
817
+ await this.buildPtzPresets(d, fid);
801
818
  }
802
819
  if (d.ot === 2) {
803
820
  const sfx = { kind: "levelCmd", path: "/command/setSensitivity", oid: d.oid, ot: d.ot };
@@ -864,6 +881,35 @@ class AgentDvr extends utils.Adapter {
864
881
  }
865
882
  await this.updateCameraEvents(d, fid);
866
883
  }
884
+ // ---- PTZ presets ----
885
+ async buildPtzPresets(d, fid) {
886
+ var _a;
887
+ const selectorId = `${fid}.control.ptz.preset`;
888
+ if (!this.ptzPresetNames.has(d.oid)) {
889
+ const res = await this.apiGet(`/command/ptzpresets?oid=${d.oid}&ot=2`);
890
+ const json = asJson(res.data);
891
+ const raw = json && Array.isArray(json.presets) ? json.presets : [];
892
+ const names2 = raw.map((p) => {
893
+ var _a2, _b;
894
+ return toStr((_b = (_a2 = p.name) != null ? _a2 : p.token) != null ? _b : "");
895
+ }).filter(Boolean);
896
+ this.ptzPresetNames.set(d.oid, names2);
897
+ }
898
+ const names = (_a = this.ptzPresetNames.get(d.oid)) != null ? _a : [];
899
+ if (!names.length) {
900
+ return;
901
+ }
902
+ const states = {};
903
+ names.forEach((n, i) => {
904
+ states[i] = n;
905
+ });
906
+ await this.ensureSelector(
907
+ selectorId,
908
+ "Preset",
909
+ { kind: "ptzPreset", oid: d.oid, ot: d.ot, presetNames: names },
910
+ states
911
+ );
912
+ }
867
913
  // ---- event formatting ----
868
914
  fmtEvent(ev, oid) {
869
915
  var _a, _b, _c;
@@ -875,13 +921,14 @@ class AgentDvr extends utils.Adapter {
875
921
  const dur = e.d != null ? String(e.d) : "";
876
922
  const tag = (_b = e.tg) != null ? _b : "";
877
923
  const ms = (parseFloat(String((_c = e.c) != null ? _c : 0)) - 621355968e9) / 1e4;
924
+ const ts = Number.isFinite(ms) ? Math.round(ms) : 0;
878
925
  const dt = new Date(ms);
879
926
  const two = (n) => String(n).padStart(2, "0");
880
927
  const date = `${two(dt.getDate())}.${two(dt.getMonth() + 1)}.`;
881
928
  const time = `${two(dt.getHours())}:${two(dt.getMinutes())}`;
882
929
  const thumb = `${this.baseUrl}/fileThumb.jpg?oid=${oid}&fn=${encodeURIComponent(jpg)}`;
883
930
  const video = `${this.baseUrl}/streamFile.cgi?oid=${oid}&ot=2&fn=${encodeURIComponent(fn)}`;
884
- return { fn, sizeMB, dur, tag, date, time, thumb, video };
931
+ return { fn, sizeMB, dur, tag, date, time, thumb, video, ts };
885
932
  }
886
933
  // ---- gallery HTML builders ----
887
934
  effectiveMinCol() {
@@ -1019,7 +1066,7 @@ class AgentDvr extends utils.Adapter {
1019
1066
  }
1020
1067
  // ---- event data points ----
1021
1068
  async writeEventDps(d, fid, events) {
1022
- var _a, _b, _c, _d;
1069
+ var _a, _b, _c, _d, _e;
1023
1070
  const oid = d.oid;
1024
1071
  await this.ensureFolder(`${fid}.events`, "Events", "channel");
1025
1072
  await this.ensureFolder(`${fid}.events.last`, "Last event", "channel");
@@ -1052,43 +1099,24 @@ class AgentDvr extends utils.Adapter {
1052
1099
  }
1053
1100
  await this.setStateAsync(jsonId, {
1054
1101
  val: JSON.stringify(
1055
- events.slice(0, Math.max(1, this.config.widgetAnzahl || 50)).map((ev) => {
1102
+ events.slice(0, Math.max(1, (_b = this.config.dashMaxRec) != null ? _b : 200)).map((ev) => {
1056
1103
  const p = this.fmtEvent(ev, oid);
1057
1104
  return {
1105
+ fn: p.fn,
1058
1106
  date: p.date,
1059
1107
  time: p.time,
1060
1108
  dur: p.dur,
1061
1109
  size: p.sizeMB,
1062
1110
  tag: p.tag,
1063
1111
  thumb: p.thumb,
1064
- video: p.video
1112
+ video: p.video,
1113
+ ts: p.ts
1065
1114
  };
1066
1115
  })
1067
1116
  ),
1068
1117
  ack: true
1069
1118
  });
1070
1119
  await this.ensureFlag(`${fid}.events.new`, "New event");
1071
- if (this.config.enablePush) {
1072
- const pid = `${fid}.events.pushTrigger`;
1073
- if (!this.ensuredFolders.has(pid)) {
1074
- await this.ensurePath(pid);
1075
- await this.setObjectNotExistsAsync(pid, {
1076
- type: "state",
1077
- common: {
1078
- name: "Push trigger (AgentDVR action)",
1079
- type: "string",
1080
- role: "text",
1081
- read: true,
1082
- write: true,
1083
- def: ""
1084
- },
1085
- native: {}
1086
- });
1087
- await this.setStateAsync(pid, { val: "", ack: true });
1088
- this.ensuredFolders.add(pid);
1089
- }
1090
- this.registry.set(pid, { kind: "push", oid, fid });
1091
- }
1092
1120
  const ignore = (this.config.eventTagsIgnore || "detected").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
1093
1121
  const tokensOf = (s) => s.toLowerCase().split(/[,\s]+/).filter(Boolean);
1094
1122
  for (const kw of (this.config.eventTags || "").split(",").map((s) => s.trim()).filter(Boolean)) {
@@ -1097,7 +1125,7 @@ class AgentDvr extends utils.Adapter {
1097
1125
  if (this.config.eventTagsDynamic) {
1098
1126
  const seen = /* @__PURE__ */ new Set();
1099
1127
  for (const ev of events) {
1100
- tokensOf((_b = ev.tg) != null ? _b : "").forEach((t) => seen.add(t));
1128
+ tokensOf((_c = ev.tg) != null ? _c : "").forEach((t) => seen.add(t));
1101
1129
  }
1102
1130
  for (const t of seen) {
1103
1131
  if (ignore.includes(t)) {
@@ -1113,13 +1141,13 @@ class AgentDvr extends utils.Adapter {
1113
1141
  const i = events.findIndex((e) => e.fn === prev);
1114
1142
  newCount = i === -1 ? events.length : i;
1115
1143
  }
1116
- this.lastEventFn[oid] = (_c = events[0].fn) != null ? _c : "";
1144
+ this.lastEventFn[oid] = (_d = events[0].fn) != null ? _d : "";
1117
1145
  }
1118
1146
  if (newCount > 0) {
1119
1147
  await this.pulse(`${fid}.events.new`);
1120
1148
  const tags = /* @__PURE__ */ new Set();
1121
1149
  for (let i = 0; i < newCount && i < events.length; i++) {
1122
- tokensOf((_d = events[i].tg) != null ? _d : "").forEach((t) => tags.add(t));
1150
+ tokensOf((_e = events[i].tg) != null ? _e : "").forEach((t) => tags.add(t));
1123
1151
  }
1124
1152
  for (const t of tags) {
1125
1153
  if (ignore.includes(t)) {
@@ -1186,22 +1214,6 @@ class AgentDvr extends utils.Adapter {
1186
1214
  this.eventBusy[d.oid] = false;
1187
1215
  }
1188
1216
  }
1189
- pushRefresh(oid) {
1190
- const d = this.devById.get(oid);
1191
- if (!d) {
1192
- this.log.warn(`Push: camera ${oid} unknown (available after first poll)`);
1193
- return;
1194
- }
1195
- const fid = this.deviceFolder(d);
1196
- for (const ms of [0, 1500, 3500, 6e3]) {
1197
- this.setTimeout(
1198
- () => this.updateCameraEvents(d, fid).catch(
1199
- (e) => this.log.warn(`Push refresh error: ${e.message}`)
1200
- ),
1201
- ms
1202
- );
1203
- }
1204
- }
1205
1217
  // ---- main poll ----
1206
1218
  async poll() {
1207
1219
  var _a, _b;
@@ -1239,10 +1251,94 @@ class AgentDvr extends utils.Adapter {
1239
1251
  await this.pruneStaleDevices(activeFolders);
1240
1252
  const stats = asJson((await this.apiGet("/command/getSystemStats")).data);
1241
1253
  if (stats) {
1242
- await this.flattenWrite(stats, "system.stats", 0);
1254
+ const {
1255
+ disks: _disks,
1256
+ cpup,
1257
+ ramp,
1258
+ ramu,
1259
+ cpu_used,
1260
+ ram_free,
1261
+ disk_free: _disk_free,
1262
+ diskp,
1263
+ ...statsRest
1264
+ } = stats;
1265
+ if (cpup !== void 0) {
1266
+ await this.writeLeaf("system.hardware.cpu.percent", cpup, "%");
1267
+ }
1268
+ await this.delObjectAsync("system.hardware.cpu.used").catch(() => {
1269
+ });
1270
+ if (ramp !== void 0) {
1271
+ await this.writeLeaf("system.hardware.ram.percent", ramp, "%");
1272
+ }
1273
+ if (ramu !== void 0) {
1274
+ await this.writeLeaf("system.hardware.ram.used", toStr(ramu));
1275
+ }
1276
+ if (ram_free !== void 0) {
1277
+ await this.writeLeaf("system.hardware.ram.free", toStr(ram_free));
1278
+ }
1279
+ if (Object.keys(statsRest).length) {
1280
+ await this.flattenWrite(
1281
+ { ...statsRest, ...diskp !== void 0 && { disk_percent: diskp } },
1282
+ "system.stats",
1283
+ 0
1284
+ );
1285
+ }
1286
+ for (const old of [
1287
+ "cpup",
1288
+ "ramp",
1289
+ "ramu",
1290
+ "diskp",
1291
+ "cpu_used",
1292
+ "ram_free",
1293
+ "disk_free",
1294
+ "cpu_percent",
1295
+ "ram_percent",
1296
+ "ram_used",
1297
+ "disk_percent"
1298
+ ]) {
1299
+ await this.delObjectAsync(`system.stats.${old}`).catch(() => {
1300
+ });
1301
+ }
1302
+ for (const old of ["system.cpu", "system.ram", "system.drives", "system.disk_free_gb"]) {
1303
+ await this.delObjectAsync(old, { recursive: true }).catch(() => {
1304
+ });
1305
+ }
1243
1306
  const gb = parseSizeGb(stats.disk_free);
1244
1307
  if (gb !== null) {
1245
- await this.writeLeaf("system.disk_free_gb", gb);
1308
+ await this.writeLeaf("system.hardware.disk_free_gb", gb);
1309
+ }
1310
+ if (Array.isArray(stats.disks)) {
1311
+ const activeKeys = /* @__PURE__ */ new Set();
1312
+ for (const drv of stats.disks) {
1313
+ if (!drv || typeof drv !== "object") {
1314
+ continue;
1315
+ }
1316
+ const key = sanitize(toStr(drv.n).replace(/^\//, "") || "root") || "root";
1317
+ activeKeys.add(key);
1318
+ await this.writeLeaf(
1319
+ `system.hardware.drives.${key}.name`,
1320
+ toStr(drv.n) === "/" ? "/ Root" : toStr(drv.n)
1321
+ );
1322
+ await this.writeLeaf(`system.hardware.drives.${key}.free`, toStr(drv.d));
1323
+ await this.writeLeaf(`system.hardware.drives.${key}.used`, toStr(drv.u));
1324
+ await this.writeLeaf(
1325
+ `system.hardware.drives.${key}.percent`,
1326
+ typeof drv.p === "number" ? drv.p : 0,
1327
+ "%"
1328
+ );
1329
+ const fgb = parseSizeGb(drv.d);
1330
+ if (fgb !== null) {
1331
+ await this.writeLeaf(`system.hardware.drives.${key}.free_gb`, fgb);
1332
+ }
1333
+ }
1334
+ const allObjs = await this.getAdapterObjectsAsync();
1335
+ for (const fullId of Object.keys(allObjs)) {
1336
+ const rel = fullId.slice(this.namespace.length + 1);
1337
+ const m = rel.match(/^system\.hardware\.drives\.([^.]+)$/);
1338
+ if (m && !activeKeys.has(m[1])) {
1339
+ await this.delObjectAsync(rel, { recursive: true });
1340
+ }
1341
+ }
1246
1342
  }
1247
1343
  }
1248
1344
  const status = asJson((await this.apiGet("/command/getStatus")).data);
@@ -1303,6 +1399,14 @@ class AgentDvr extends utils.Adapter {
1303
1399
  this.pollBusy = false;
1304
1400
  }
1305
1401
  }
1402
+ schedulePoll(delayMs) {
1403
+ if (this._pollStopped) {
1404
+ return;
1405
+ }
1406
+ this.pollTimer = this.setTimeout(() => {
1407
+ void this.poll().catch((e) => this.log.warn(`Poll error: ${e.message}`)).finally(() => this.schedulePoll(delayMs));
1408
+ }, delayMs);
1409
+ }
1306
1410
  scheduleRefresh() {
1307
1411
  if (this.refreshTimer !== void 0) {
1308
1412
  this.clearTimeout(this.refreshTimer);
@@ -1349,6 +1453,7 @@ class AgentDvr extends utils.Adapter {
1349
1453
  }
1350
1454
  }
1351
1455
  async runCommand(relId, entry, val) {
1456
+ var _a, _b;
1352
1457
  if (entry.kind === "setProfile") {
1353
1458
  const ind = typeof val === "number" ? val : parseInt(String(val != null ? val : ""), 10);
1354
1459
  if (!isNaN(ind)) {
@@ -1385,10 +1490,20 @@ class AgentDvr extends utils.Adapter {
1385
1490
  await this.setStateAsync(relId, { val: false, ack: true });
1386
1491
  return;
1387
1492
  }
1388
- if (entry.kind === "push") {
1389
- this.log.info(`Push trigger cam ${entry.oid}`);
1390
- await this.setStateAsync(relId, { val: "", ack: true });
1391
- this.pushRefresh(entry.oid);
1493
+ if (entry.kind === "ptzPreset") {
1494
+ const idx = typeof val === "number" ? val : parseInt(String(val != null ? val : ""), 10);
1495
+ const name = isNaN(idx) ? "" : (_b = ((_a = entry.presetNames) != null ? _a : [])[idx]) != null ? _b : "";
1496
+ if (!name) {
1497
+ return;
1498
+ }
1499
+ const url2 = `/command/ptzpreset?oid=${encodeURIComponent(String(entry.oid))}&ot=2&preset=${encodeURIComponent(name)}`;
1500
+ const cmdRes2 = await this.apiGet(url2);
1501
+ if (cmdRes2.ok) {
1502
+ this.log.debug(`PTZ preset \u2192 ${name}`);
1503
+ await this.setStateAsync(relId, { val: idx, ack: true });
1504
+ } else {
1505
+ this.log.warn(`PTZ preset failed (${url2}): ${cmdRes2.error}`);
1506
+ }
1392
1507
  return;
1393
1508
  }
1394
1509
  if (entry.kind === "ptzHold") {