forked from gozoinks/homebridge-camera-ffmpeg-ufv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·333 lines (248 loc) · 11.9 KB
/
index.js
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
'use strict';
var Accessory, hap, UUIDGen, Service, Characteristic;
var http = require('http');
var https = require('https');
var URL = require('url');
var qs = require('qs');
var debug = require('debug')('camera-ffmpeg-ufv');
var UFV = require('./ufv.js').UFV;
var MotionSensorAccessory = require('./lib/motion-sensor-accessory');
var API = require('./lib/util/api');
const apiEndpoint = '/api/2.0';
module.exports = function(homebridge) {
hap = homebridge.hap;
UUIDGen = homebridge.hap.uuid;
Accessory = homebridge.platformAccessory;
Service = hap.Service,
Characteristic = hap.Characteristic,
homebridge.registerPlatform("homebridge-camera-ffmpeg-ufv", "camera-ffmpeg-ufv", ffmpegUfvPlatform, true);
}
function ffmpegUfvPlatform(log, config, api) {
var self = this;
self.log = log;
self.config = config || {};
self._accessories = [];
self.motionCache = {};
if (api) {
self.api = api;
if (api.version < 2.1) {
throw new Error("Unexpected API version.");
}
self.api.on('didFinishLaunching', self.didFinishLaunching.bind(this));
}
}
// Won't do anything
ffmpegUfvPlatform.prototype.didFinishLaunching = function() {
}
ffmpegUfvPlatform.prototype.accessories = function(callback) {
var self = this;
if (self.config.nvrs) {
var configuredAccessories = [];
var nvrs = self.config.nvrs;
nvrs.forEach(function(nvrConfig) {
// From the config we need the host and API key for the NVR.
// - Host will be the NVR's hostname or IP and port, ie "nvr.example.com:7080"
// - API key is created in NVR user settings
var options = {
host: nvrConfig.apiHost,
port: nvrConfig.apiPort,
path: apiEndpoint + '/bootstrap?apiKey=' + nvrConfig.apiKey,
rejectUnauthorized: false // bypass the self-signed certificate error. Bleh
};
// Fetch the "bootstrap" file from the NVR,
// which contains all the config info we need:
(nvrConfig.apiProtocol == 'https' ? https : http ).get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
try {
var parsedResponse = JSON.parse(json);
// At this point we should have the NVR configuration.
var server;
var serverName;
var streamingHost;
var streamingPort;
var channels = [];
// The root of the result is "data"
var discoveredNvrs = parsedResponse.data;
discoveredNvrs.forEach(function(discoveredNvr) {
debug("Discovered NVR " + discoveredNvr.nvrName);
// In the old API, the NVR knows the rtsp port.
// If this is not defined, we'll look for it in the
// channel definition later:
streamingPort = discoveredNvr.systemInfo.rtspPort;
// Within each NVR we should have one or more servers:
var discoveredServers = discoveredNvr.servers;
discoveredServers.forEach(function(discoveredServer) {
debug("Discovered server " + discoveredServer.name);
serverName = discoveredServer.name;
// Override Hostname for the streams:
streamingHost = nvrConfig.apiHost; // discoveredServer.host;
server = discoveredServer;
});
// Hack: there is at this time only one 'server' object.
// We are assuming there will only be one.
// If this changes, things will probably break!
// Within each NVR we should have one or more cameras:
var discoveredCameras = discoveredNvr.cameras;
discoveredCameras.forEach(function(discoveredCamera) {
// Each camera has more than one channel.
// The channel is where the actual streaming params live:
var discoveredChannels = ( discoveredCamera.channels || [] );
// Go through each channel, see if it is rtspEnabled, and if so,
// post it to homebridge and move on to the next camera
for(var channelIndex = 0; channelIndex < discoveredChannels.length; channelIndex++) {
var discoveredChannel = discoveredChannels[channelIndex];
// Let's see if this channel has RSTP enabled:
if(discoveredChannel.isRtspEnabled == true) {
var rtspAlias = discoveredChannel.rtspAlias;
debug('Discovered RTSP enabled camera ' + discoveredCamera.uuid);
// Set the RTSP URI. Let's first try the new way (>=3.9.0), then try the old way.
if ( discoveredChannel.hasOwnProperty('rtspUris') ) {
var rtspUri = discoveredChannel.rtspUris[0];
// Since the Hostname isn't configurable from UFV admin, we can override the hostname here
var url = URL.parse(rtspUri, true);
url.hostname = nvrConfig.apiHost;
delete url.href;
delete url.host;
rtspUri = URL.format(url);
debug("Discovered server " + rtspUri);
} else {
var rtspUri = 'rtsp://' + streamingHost + ':' + streamingPort + '/' + rtspAlias;
}
// We should know have everything we need and can push it to
// UFV:
var videoConfig = {
"source": ('-rtsp_transport http -re -i ' + rtspUri + '?apiKey=' + nvrConfig.apiKey),
"stillImageSource": ((nvrConfig.apiProtocol == 'https' ? 'https' : 'http') + '://' + nvrConfig.apiHost + ':' + nvrConfig.apiPort + apiEndpoint + '/snapshot/camera/' + discoveredCamera._id + '?force=true&apiKey=' + nvrConfig.apiKey),
"maxStreams": 2,
"maxWidth": discoveredChannel.width, // or however we end up getting to this!
"maxHeight": discoveredChannel.height,
"maxFPS": discoveredChannel.fps
};
debug('Config: ' + JSON.stringify(videoConfig));
// Create a new Accessory for this camera:
var cameraAccessory = new Accessory(discoveredCamera.name, discoveredCamera.uuid, hap.Accessory.Categories.CAMERA);
var cameraConfig = {name: discoveredCamera.name, videoConfig: videoConfig};
cameraAccessory
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, "Ubiquiti Networks, Inc.")
.setCharacteristic(Characteristic.Model, discoveredCamera.model)
.setCharacteristic(Characteristic.SerialNumber, discoveredCamera.uuid)
.setCharacteristic(Characteristic.FirmwareRevision, discoveredCamera.firmwareVersion);
debug(JSON.stringify(cameraConfig));
var cameraSource = new UFV(hap, cameraConfig);
cameraAccessory.configureCameraSource(cameraSource);
configuredAccessories.push(cameraAccessory);
// Setup the Motion Sensors for this camera
if (nvrConfig.motionSensors === false) {
self.log('Skipping '+discoveredCamera.name+' Motion Sensor due to NVR config "motionSensors" disabled.');
} else if (discoveredCamera.recordingSettings.motionRecordEnabled) {
debug('Setting up Motion Sensor for: ' + discoveredCamera.name);
self.setupMotionSensor(hap, nvrConfig, discoveredNvr, server, discoveredCamera);
} else {
self.log('Skipping Motion Sensor due to motion recording not enabled for: ' + discoveredCamera.name);
}
// Jump out of the loop once we have one:
channelIndex = discoveredChannels.length;
};
};
});
});
// Publish the cameras we found to homebridge:
self.api.publishCameraAccessories("camera-ffmpeg-ufv", configuredAccessories);
self.log('Published ' + configuredAccessories.length + ' camera accessories.');
} catch (e) {
debug('Error parsing JSON! ' + e);
}
} else {
debug('Status:', res.statusCode);
}
callback(self._accessories);
});
}).on('error', function (err) {
debug('Error:', err);
});
});
}
}
ffmpegUfvPlatform.prototype.setupMotionSensor = function (homebridge, nvrConfig, discoveredNvr, discoveredServer, discoveredCamera) {
var self = this;
// Setup Motion Status Caching
self.setupMotionCache(nvrConfig, discoveredNvr, discoveredServer, discoveredCamera);
var nvrId = UUIDGen.generate(discoveredNvr.nvrName + nvrConfig.apiHost);
// Setup Motion Sensor for this camera.
var accessory = MotionSensorAccessory.createAccessory(hap, nvrConfig, discoveredCamera, self.motionCache[nvrId]);
// Guarantee only one motion sensor for this camera
for (var i in self.accessories) {
var a = self.accessories[i];
if (accessory.username == a.username) {
accessory.destroy();
return;
}
}
debug('Discovered Motion Sensor enabled camera ' + discoveredCamera.uuid);
var properties = new Object({
platform: self,
name: accessory.displayName,
getServices : function(){
return this.services;
}
});
Object.assign(accessory, properties);
this._accessories.push(accessory);
// this.api.registerPlatformAccessories("homebridge-camera-ffmpeg-ufv", "camera-ffmpeg-ufv", [newAccessory])
}
ffmpegUfvPlatform.prototype.setupMotionCache = function (nvrConfig, discoveredNvr, discoveredServer, discoveredCamera) {
var self = this;
var nvrId = UUIDGen.generate(discoveredNvr.nvrName + nvrConfig.apiHost);
if (self.motionCache.hasOwnProperty(nvrId)) {
// This NVR is already caching
debug('Motion Caching already setup for: ' + discoveredNvr.nvrName);
return;
}
debug('Setting up motion cache for: ' + discoveredNvr.nvrName);
// Setup cache object for all recordings on this NVR
self.motionCache[nvrId] = [];
// Within each NVR we should have one or more cameras:
var discoveredCameras = discoveredNvr.cameras;
var allCameras = discoveredCameras.map(function(discoveredCamera) {
// return discoveredCamera.uuid;
return discoveredCamera._id;
})
// Setup timer to cache recordings status
setInterval(function () {
// Setup timer to fetch cache for motion per nvr
var now = Date.now();
// My docker instance experiences time drift when running on a Mac. This helps with that.
var twoHoursInTheFuture = 2 + 60 * 60 * 1000;
// Set the minimum motion limit to 5 minutes in the past
var motionDuration = discoveredServer.alertSettings.motionEmailCoolDownMs; // ms
if (motionDuration < 60 * 1000 * 3) {
motionDuration = 60 * 1000 * 3;
}
var options = {
query: {
// idsOnly: true,
startTime: now - motionDuration,
endTime: now + twoHoursInTheFuture,
sortBy: 'startTime',
sort: 'desc',
cameras: allCameras,
cause:[
'motionRecording'
]
}
}
API.get(apiEndpoint,'/recording', options, nvrConfig).then(function(json) {
// Clear out the object since it's been passed by reference
self.motionCache[nvrId].length = 0;
json.data.map(function(recording) {
self.motionCache[nvrId].push(recording);
});
})
}, 1000);
}