@blueharford/scrypted-spatial-awareness 0.1.11 → 0.1.15

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/out/plugin.zip CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blueharford/scrypted-spatial-awareness",
3
- "version": "0.1.11",
3
+ "version": "0.1.15",
4
4
  "description": "Cross-camera object tracking for Scrypted NVR with spatial awareness",
5
5
  "author": "Joshua Seidel <blueharford>",
6
6
  "license": "Apache-2.0",
@@ -3,7 +3,7 @@
3
3
  * Generates and dispatches alerts based on tracking events
4
4
  */
5
5
 
6
- import sdk, { Notifier } from '@scrypted/sdk';
6
+ import sdk, { Notifier, Camera, ScryptedInterface, MediaObject } from '@scrypted/sdk';
7
7
  import {
8
8
  Alert,
9
9
  AlertRule,
@@ -15,7 +15,7 @@ import {
15
15
  } from '../models/alert';
16
16
  import { TrackedObject, GlobalTrackingId } from '../models/tracked-object';
17
17
 
18
- const { systemManager } = sdk;
18
+ const { systemManager, mediaManager } = sdk;
19
19
 
20
20
  export class AlertManager {
21
21
  private rules: AlertRule[] = [];
@@ -109,6 +109,20 @@ export class AlertManager {
109
109
  ? rule.notifiers
110
110
  : this.getDefaultNotifiers();
111
111
 
112
+ // Try to get a thumbnail from the camera
113
+ let mediaObject: MediaObject | undefined;
114
+ const cameraId = alert.details.toCameraId || alert.details.cameraId;
115
+ if (cameraId) {
116
+ try {
117
+ const camera = systemManager.getDeviceById<Camera>(cameraId);
118
+ if (camera && camera.interfaces?.includes(ScryptedInterface.Camera)) {
119
+ mediaObject = await camera.takePicture();
120
+ }
121
+ } catch (e) {
122
+ this.console.warn(`Failed to get thumbnail from camera ${cameraId}:`, e);
123
+ }
124
+ }
125
+
112
126
  for (const notifierId of notifierIds) {
113
127
  try {
114
128
  const notifier = systemManager.getDeviceById<Notifier>(notifierId);
@@ -127,10 +141,11 @@ export class AlertManager {
127
141
  trackedObjectId: alert.trackedObjectId,
128
142
  timestamp: alert.timestamp,
129
143
  },
130
- }
144
+ },
145
+ mediaObject
131
146
  );
132
147
 
133
- this.console.log(`Notification sent to ${notifierId}`);
148
+ this.console.log(`Notification sent to ${notifierId}${mediaObject ? ' with thumbnail' : ''}`);
134
149
  } catch (e) {
135
150
  this.console.error(`Failed to send notification to ${notifierId}:`, e);
136
151
  }
@@ -142,17 +157,19 @@ export class AlertManager {
142
157
  */
143
158
  private getNotificationTitle(alert: Alert): string {
144
159
  const prefix = alert.severity === 'critical' ? '🚨 ' :
145
- alert.severity === 'warning' ? '⚠️ ' : 'ℹ️ ';
160
+ alert.severity === 'warning' ? '⚠️ ' : '';
146
161
 
147
162
  switch (alert.type) {
148
163
  case 'property_entry':
149
- return `${prefix}Entry Detected`;
164
+ return `${prefix}🚶 Entry Detected`;
150
165
  case 'property_exit':
151
- return `${prefix}Exit Detected`;
166
+ return `${prefix}🚶 Exit Detected`;
167
+ case 'movement':
168
+ return `${prefix}🚶 Movement Detected`;
152
169
  case 'unusual_path':
153
170
  return `${prefix}Unusual Path`;
154
171
  case 'dwell_time':
155
- return `${prefix}Extended Presence`;
172
+ return `${prefix}⏱️ Extended Presence`;
156
173
  case 'restricted_zone':
157
174
  return `${prefix}Restricted Zone Alert`;
158
175
  case 'lost_tracking':
@@ -169,6 +186,24 @@ export class AlertManager {
169
186
  */
170
187
  private getDefaultNotifiers(): string[] {
171
188
  try {
189
+ // Try new multiple notifiers setting first
190
+ const notifiers = this.storage.getItem('defaultNotifiers');
191
+ if (notifiers) {
192
+ // Could be JSON array or comma-separated string
193
+ try {
194
+ const parsed = JSON.parse(notifiers);
195
+ if (Array.isArray(parsed)) {
196
+ return parsed;
197
+ }
198
+ } catch {
199
+ // Not JSON, might be comma-separated or single value
200
+ if (notifiers.includes(',')) {
201
+ return notifiers.split(',').map(s => s.trim()).filter(Boolean);
202
+ }
203
+ return [notifiers];
204
+ }
205
+ }
206
+ // Fallback to old single notifier setting
172
207
  const defaultNotifier = this.storage.getItem('defaultNotifier');
173
208
  return defaultNotifier ? [defaultNotifier] : [];
174
209
  } catch {
@@ -192,6 +192,8 @@ export class TrackingEngine {
192
192
  // Check if this is a cross-camera transition
193
193
  const lastSighting = getLastSighting(tracked);
194
194
  if (lastSighting && lastSighting.cameraId !== sighting.cameraId) {
195
+ const transitDuration = sighting.timestamp - lastSighting.timestamp;
196
+
195
197
  // Add journey segment
196
198
  this.state.addJourney(tracked.globalId, {
197
199
  fromCameraId: lastSighting.cameraId,
@@ -200,7 +202,7 @@ export class TrackingEngine {
200
202
  toCameraName: sighting.cameraName,
201
203
  exitTime: lastSighting.timestamp,
202
204
  entryTime: sighting.timestamp,
203
- transitDuration: sighting.timestamp - lastSighting.timestamp,
205
+ transitDuration,
204
206
  correlationConfidence: correlation.confidence,
205
207
  });
206
208
 
@@ -209,6 +211,18 @@ export class TrackingEngine {
209
211
  `${lastSighting.cameraName} → ${sighting.cameraName} ` +
210
212
  `(confidence: ${(correlation.confidence * 100).toFixed(0)}%)`
211
213
  );
214
+
215
+ // Generate movement alert for cross-camera transition
216
+ await this.alertManager.checkAndAlert('movement', tracked, {
217
+ fromCameraId: lastSighting.cameraId,
218
+ fromCameraName: lastSighting.cameraName,
219
+ toCameraId: sighting.cameraId,
220
+ toCameraName: sighting.cameraName,
221
+ transitTime: transitDuration,
222
+ objectClass: sighting.detection.className,
223
+ objectLabel: sighting.detection.label,
224
+ detectionId: sighting.detectionId,
225
+ });
212
226
  }
213
227
 
214
228
  // Add sighting to tracked object
package/src/main.ts CHANGED
@@ -123,10 +123,12 @@ export class SpatialAwarenessPlugin extends ScryptedDeviceBase
123
123
  defaultValue: true,
124
124
  group: 'Alerts',
125
125
  },
126
- defaultNotifier: {
127
- title: 'Default Notifier',
126
+ defaultNotifiers: {
127
+ title: 'Notifiers',
128
128
  type: 'device',
129
+ multiple: true,
129
130
  deviceFilter: `interfaces.includes('${ScryptedInterface.Notifier}')`,
131
+ description: 'Select one or more notifiers to receive alerts',
130
132
  group: 'Alerts',
131
133
  },
132
134
 
@@ -386,14 +388,33 @@ export class SpatialAwarenessPlugin extends ScryptedDeviceBase
386
388
 
387
389
  // Add status display
388
390
  const activeCount = this.trackingState.getActiveCount();
391
+ const topologyJson = this.storage.getItem('topology');
392
+ let statusText = 'Not configured - add cameras and configure topology';
393
+
394
+ if (this.trackingEngine) {
395
+ statusText = `Active: Tracking ${activeCount} object${activeCount !== 1 ? 's' : ''}`;
396
+ } else if (topologyJson) {
397
+ try {
398
+ const topology = JSON.parse(topologyJson) as CameraTopology;
399
+ if (topology.cameras && topology.cameras.length > 0) {
400
+ // Topology exists but engine not running - try to start it
401
+ statusText = `Configured (${topology.cameras.length} cameras) - Starting...`;
402
+ // Restart the tracking engine asynchronously
403
+ this.startTrackingEngine(topology).catch(e => {
404
+ this.console.error('Failed to restart tracking engine:', e);
405
+ });
406
+ }
407
+ } catch (e) {
408
+ statusText = 'Error loading topology';
409
+ }
410
+ }
411
+
389
412
  settings.push({
390
413
  key: 'status',
391
414
  title: 'Tracking Status',
392
415
  type: 'string',
393
416
  readonly: true,
394
- value: this.trackingEngine
395
- ? `Active: Tracking ${activeCount} object${activeCount !== 1 ? 's' : ''}`
396
- : 'Not configured - add cameras and configure topology',
417
+ value: statusText,
397
418
  group: 'Status',
398
419
  });
399
420
 
@@ -410,9 +431,83 @@ export class SpatialAwarenessPlugin extends ScryptedDeviceBase
410
431
  });
411
432
  }
412
433
 
434
+ // Add alert rules configuration UI
435
+ const alertRules = this.alertManager.getRules();
436
+ const rulesHtml = this.generateAlertRulesHtml(alertRules);
437
+ settings.push({
438
+ key: 'alertRulesEditor',
439
+ title: 'Alert Rules',
440
+ type: 'html' as any,
441
+ value: rulesHtml,
442
+ group: 'Alerts',
443
+ });
444
+
413
445
  return settings;
414
446
  }
415
447
 
448
+ private generateAlertRulesHtml(rules: any[]): string {
449
+ const ruleRows = rules.map(rule => `
450
+ <tr data-rule-id="${rule.id}">
451
+ <td style="padding:8px;border-bottom:1px solid #333;">
452
+ <input type="checkbox" ${rule.enabled ? 'checked' : ''}
453
+ onchange="(function(el){var rules=JSON.parse(localStorage.getItem('sa-temp-rules')||'[]');var r=rules.find(x=>x.id==='${rule.id}');if(r)r.enabled=el.checked;localStorage.setItem('sa-temp-rules',JSON.stringify(rules));})(this)" />
454
+ </td>
455
+ <td style="padding:8px;border-bottom:1px solid #333;color:#fff;">${rule.name}</td>
456
+ <td style="padding:8px;border-bottom:1px solid #333;color:#888;">${rule.type}</td>
457
+ <td style="padding:8px;border-bottom:1px solid #333;">
458
+ <span style="padding:2px 8px;border-radius:4px;font-size:12px;background:${
459
+ rule.severity === 'critical' ? '#e94560' :
460
+ rule.severity === 'warning' ? '#f39c12' : '#3498db'
461
+ };color:white;">${rule.severity}</span>
462
+ </td>
463
+ <td style="padding:8px;border-bottom:1px solid #333;color:#888;">${Math.round(rule.cooldown / 1000)}s</td>
464
+ </tr>
465
+ `).join('');
466
+
467
+ const initCode = `localStorage.setItem('sa-temp-rules',JSON.stringify(${JSON.stringify(rules)}))`;
468
+ const saveCode = `(function(){var rules=JSON.parse(localStorage.getItem('sa-temp-rules')||'[]');fetch('/endpoint/@blueharford/scrypted-spatial-awareness/api/alert-rules',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(rules)}).then(r=>r.json()).then(d=>{if(d.success)alert('Alert rules saved!');else alert('Error: '+d.error);}).catch(e=>alert('Error: '+e));})()`;
469
+
470
+ return `
471
+ <style>
472
+ .sa-rules-table { width:100%; border-collapse:collapse; margin-top:10px; }
473
+ .sa-rules-table th { text-align:left; padding:10px 8px; border-bottom:2px solid #e94560; color:#e94560; font-size:13px; }
474
+ .sa-save-rules-btn {
475
+ background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
476
+ color: white;
477
+ border: none;
478
+ padding: 10px 20px;
479
+ border-radius: 6px;
480
+ font-size: 14px;
481
+ font-weight: 600;
482
+ cursor: pointer;
483
+ margin-top: 15px;
484
+ }
485
+ .sa-save-rules-btn:hover { opacity: 0.9; }
486
+ .sa-rules-container { background:#16213e; border-radius:8px; padding:15px; }
487
+ .sa-rules-desc { color:#888; font-size:13px; margin-bottom:10px; }
488
+ </style>
489
+ <div class="sa-rules-container">
490
+ <p class="sa-rules-desc">Enable or disable alert types. Movement alerts notify you when someone moves between cameras.</p>
491
+ <table class="sa-rules-table">
492
+ <thead>
493
+ <tr>
494
+ <th style="width:40px;">On</th>
495
+ <th>Alert Type</th>
496
+ <th>Event</th>
497
+ <th>Severity</th>
498
+ <th>Cooldown</th>
499
+ </tr>
500
+ </thead>
501
+ <tbody>
502
+ ${ruleRows}
503
+ </tbody>
504
+ </table>
505
+ <button class="sa-save-rules-btn" onclick="${saveCode}">Save Alert Rules</button>
506
+ <script>(function(){${initCode}})();</script>
507
+ </div>
508
+ `;
509
+ }
510
+
416
511
  async putSetting(key: string, value: SettingValue): Promise<void> {
417
512
  await this.storageSettings.putSetting(key, value);
418
513
 
@@ -466,13 +561,17 @@ export class SpatialAwarenessPlugin extends ScryptedDeviceBase
466
561
  }
467
562
 
468
563
  if (path.endsWith('/api/topology')) {
469
- return this.handleTopologyRequest(request, response);
564
+ return await this.handleTopologyRequest(request, response);
470
565
  }
471
566
 
472
567
  if (path.endsWith('/api/alerts')) {
473
568
  return this.handleAlertsRequest(request, response);
474
569
  }
475
570
 
571
+ if (path.endsWith('/api/alert-rules')) {
572
+ return this.handleAlertRulesRequest(request, response);
573
+ }
574
+
476
575
  if (path.endsWith('/api/cameras')) {
477
576
  return this.handleCamerasRequest(response);
478
577
  }
@@ -552,7 +651,7 @@ export class SpatialAwarenessPlugin extends ScryptedDeviceBase
552
651
  }
553
652
  }
554
653
 
555
- private handleTopologyRequest(request: HttpRequest, response: HttpResponse): void {
654
+ private async handleTopologyRequest(request: HttpRequest, response: HttpResponse): Promise<void> {
556
655
  if (request.method === 'GET') {
557
656
  const topologyJson = this.storage.getItem('topology');
558
657
  const topology = topologyJson ? JSON.parse(topologyJson) : createEmptyTopology();
@@ -563,7 +662,7 @@ export class SpatialAwarenessPlugin extends ScryptedDeviceBase
563
662
  try {
564
663
  const topology = JSON.parse(request.body!) as CameraTopology;
565
664
  this.storage.setItem('topology', JSON.stringify(topology));
566
- this.startTrackingEngine(topology);
665
+ await this.startTrackingEngine(topology);
567
666
  response.send(JSON.stringify({ success: true }), {
568
667
  headers: { 'Content-Type': 'application/json' },
569
668
  });
@@ -583,6 +682,28 @@ export class SpatialAwarenessPlugin extends ScryptedDeviceBase
583
682
  });
584
683
  }
585
684
 
685
+ private handleAlertRulesRequest(request: HttpRequest, response: HttpResponse): void {
686
+ if (request.method === 'GET') {
687
+ const rules = this.alertManager.getRules();
688
+ response.send(JSON.stringify(rules), {
689
+ headers: { 'Content-Type': 'application/json' },
690
+ });
691
+ } else if (request.method === 'PUT' || request.method === 'POST') {
692
+ try {
693
+ const rules = JSON.parse(request.body!);
694
+ this.alertManager.setRules(rules);
695
+ response.send(JSON.stringify({ success: true }), {
696
+ headers: { 'Content-Type': 'application/json' },
697
+ });
698
+ } catch (e) {
699
+ response.send(JSON.stringify({ error: 'Invalid rules JSON' }), {
700
+ code: 400,
701
+ headers: { 'Content-Type': 'application/json' },
702
+ });
703
+ }
704
+ }
705
+ }
706
+
586
707
  private handleCamerasRequest(response: HttpResponse): void {
587
708
  try {
588
709
  // Get all devices with ObjectDetector interface
@@ -12,6 +12,7 @@ export type AlertSeverity = 'info' | 'warning' | 'critical';
12
12
  export type AlertType =
13
13
  | 'property_entry'
14
14
  | 'property_exit'
15
+ | 'movement'
15
16
  | 'unusual_path'
16
17
  | 'dwell_time'
17
18
  | 'restricted_zone'
@@ -51,10 +52,20 @@ export interface AlertDetails {
51
52
  cameraId?: string;
52
53
  /** Camera display name */
53
54
  cameraName?: string;
55
+ /** Source camera for movement alerts */
56
+ fromCameraId?: string;
57
+ /** Source camera name for movement alerts */
58
+ fromCameraName?: string;
59
+ /** Destination camera for movement alerts */
60
+ toCameraId?: string;
61
+ /** Destination camera name for movement alerts */
62
+ toCameraName?: string;
54
63
  /** Zone name (for zone-related alerts) */
55
64
  zoneName?: string;
56
65
  /** Dwell time in milliseconds (for dwell alerts) */
57
66
  dwellTime?: number;
67
+ /** Transit time in milliseconds (for movement alerts) */
68
+ transitTime?: number;
58
69
  /** Expected path (for unusual path alerts) */
59
70
  expectedPath?: string;
60
71
  /** Actual path taken */
@@ -116,7 +127,7 @@ export function createDefaultRules(): AlertRule[] {
116
127
  conditions: [],
117
128
  severity: 'info',
118
129
  notifiers: [],
119
- cooldown: 300000, // 5 minutes
130
+ cooldown: 60000, // 1 minute
120
131
  },
121
132
  {
122
133
  id: 'property-exit',
@@ -126,7 +137,17 @@ export function createDefaultRules(): AlertRule[] {
126
137
  conditions: [],
127
138
  severity: 'info',
128
139
  notifiers: [],
129
- cooldown: 300000,
140
+ cooldown: 60000,
141
+ },
142
+ {
143
+ id: 'movement',
144
+ name: 'Movement Between Cameras',
145
+ enabled: true,
146
+ type: 'movement',
147
+ conditions: [],
148
+ severity: 'info',
149
+ notifiers: [],
150
+ cooldown: 10000, // 10 seconds - we want frequent movement updates
130
151
  },
131
152
  {
132
153
  id: 'unusual-path',
@@ -178,15 +199,21 @@ export function generateAlertMessage(
178
199
  type: AlertType,
179
200
  details: AlertDetails
180
201
  ): string {
202
+ // Capitalize the object class for display (person -> Person, car -> Car, dog -> Dog)
203
+ const capitalize = (s: string) => s ? s.charAt(0).toUpperCase() + s.slice(1) : 'Object';
181
204
  const objectDesc = details.objectLabel
182
- ? `${details.objectClass} (${details.objectLabel})`
183
- : details.objectClass || 'Object';
205
+ ? `${capitalize(details.objectClass || '')} (${details.objectLabel})`
206
+ : capitalize(details.objectClass || '');
184
207
 
185
208
  switch (type) {
186
209
  case 'property_entry':
187
210
  return `${objectDesc} entered property via ${details.cameraName || 'unknown camera'}`;
188
211
  case 'property_exit':
189
212
  return `${objectDesc} exited property via ${details.cameraName || 'unknown camera'}`;
213
+ case 'movement':
214
+ const transitSecs = details.transitTime ? Math.round(details.transitTime / 1000) : 0;
215
+ const transitStr = transitSecs > 0 ? ` (${transitSecs}s transit)` : '';
216
+ return `${objectDesc} moving from ${details.fromCameraName || 'unknown'} towards ${details.toCameraName || 'unknown'}${transitStr}`;
190
217
  case 'unusual_path':
191
218
  return `${objectDesc} took unusual path: ${details.actualPath || 'unknown'}`;
192
219
  case 'dwell_time':