-
Notifications
You must be signed in to change notification settings - Fork 230
/
onvif.js
496 lines (467 loc) · 15.7 KB
/
onvif.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
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
/**
* Created by Andrew D.Laptev<a.d.laptev@gmail.com> on 08.12.14.
*/
'use strict';
var http = require('http')
, async = require('async')
, parseString = require('xml2js').parseString
, crypto = require('crypto')
, util = require('util')
, events = require('events')
, url = require('url')
, _linerase = require('./soapHelpers')._linerase
;
/**
* @name Profile
* @property {object} streamUri
*/
/**
* @typedef Profile
* @type {object}
* @property {object} streamUri
*/
/**
* Camera class
* @param options
* @param callback
* @property presets
* @class
* @constructor
*/
var Cam = function(options, callback) {
this.hostname = options.hostname;
this.username = options.username;
this.password = options.password;
this.port = options.port ? options.port : 80;
this.path = '/onvif/device_service';
/**
* Camera profile information
* @type {Object.<string, Profile>}
*/
this.profiles = {};
this.connect(callback);
};
// events.EventEmitter inheritance
util.inherits(Cam, events.EventEmitter);
/**
* Connect to the camera and fill device information properties
* @param {Function} callback
*/
Cam.prototype.connect = function(callback) {
async.parallel({
getCapabilities: this.getCapabilities.bind(this)
, getVideoSources: this.getVideoSources.bind(this)
, getProfiles: this.getProfiles.bind(this)
}, function(err, results) {
if (!err) {
this.getActiveSources();
}
if (callback) {
callback.call(this, err);
}
}.bind(this));
};
/**
* @callback Cam.requestCallback
* @param {Error} err
* @param {object} responseMessage
*/
/**
* Common camera request
* @param {object} options
* @param {object} options.body SOAP body
* @param {boolean} [options.ptz] make request to PTZ uri or not
* @param {Function} callback response callback
* @param {Cam.requestCallback} callback
* @private
*/
Cam.prototype._request = function(options, callback) {
if (options.ptz && !this.ptzUri) {
return callback(new Error('PTZ uri is absent'));
}
var _this = this;
var req = http.request({
hostname: options.ptz ? this.ptzUri.hostname : this.hostname
, headers: {
'Content-Type': 'application/soap+xml'
, charset: 'utf-8'
}
, port: options.ptz ? this.ptzUri.port : this.port
, path: options.ptz ? this.ptzUri.path : this.path
, method: 'POST'
}, function(res) {
var bufs = [], length = 0;
res.on('data', function(chunk) {
bufs.push(chunk);
length += chunk.length;
});
res.on('end', function() {
var xml = Buffer.concat(bufs, length).toString('utf8');
_this.emit('rawResponse', xml);
parseString(xml, function(err, result) {
if (!result || !result['SOAP-ENV:Envelope'] || !result['SOAP-ENV:Envelope']['SOAP-ENV:Body']) {
callback(new Error('Wrong ONVIF SOAP response'));
} else {
callback(err, result['SOAP-ENV:Envelope']['SOAP-ENV:Body']);
}
});
})
});
req.on('error', function(err) {
callback(err);
});
req.write(options.body);
req.end();
};
/**
* Receive date and time from cam
* @param callback
*/
Cam.prototype.getSystemDateAndTime = function(callback) {
this._request({
body:
'<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">' +
'<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
'<GetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl"/>' +
'</s:Body>' +
'</s:Envelope>'
}, function(err, data) {
var dt = _linerase(data[0]['tds:GetSystemDateAndTimeResponse'][0]['tds:SystemDateAndTime'][0]['tt:UTCDateTime'][0]);
callback(err, err ? null : new Date(dt.date.year, dt.date.month, dt.date.day, dt.time.hour, dt.time.minute, dt.time.second));
});
};
/**
* Receive cam capabilities
* @param [callback]
*/
Cam.prototype.getCapabilities = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetCapabilities xmlns="http://www.onvif.org/ver10/device/wsdl">' +
'<Category>All</Category>' +
'</GetCapabilities>' +
this._envelopeFooter()
}, function(err, data) {
if (!err) {
this.capabilities = _linerase(data[0]['tds:GetCapabilitiesResponse'][0]['tds:Capabilities'][0]);
if (this.capabilities.PTZ.XAddr) {
/**
* PTZ URI object
*/
this.ptzUri = url.parse(this.capabilities.PTZ.XAddr);
}
}
if (callback) {
callback(err, this.capabilities);
}
}.bind(this));
};
/**
* Receive video sources
* @param [callback]
*/
Cam.prototype.getVideoSources = function(callback) {
var req = this._passwordDigest();
this._request({
body: this._envelopeHeader() +
'<GetVideoSources xmlns="http://www.onvif.org/ver10/media/wsdl"/>' +
this._envelopeFooter()
}, function(err, data) {
if (!err) {
this.videoSources = _linerase(data).getVideoSourcesResponse.videoSources;
}
if (callback) {
callback(err, this.videoSources);
}
}.bind(this));
};
/**
* Get active sources
* @private
*/
Cam.prototype.getActiveSources = function() {
if (this.videoSources.$) { // NVT is a camera
if (this.videoSources.$.token === this.defaultProfile.videoSourceConfiguration.sourceToken) {
this.activeSource = {
sourceToken: this.videoSources.$.token
, profileToken: this.defaultProfile.name
, encoding: this.defaultProfile.videoEncoderConfiguration.encoding
, width: this.defaultProfile.videoEncoderConfiguration.resolution.width
, height: this.defaultProfile.videoEncoderConfiguration.resolution.height
, fps: this.defaultProfile.videoEncoderConfiguration.rateControl.frameLimit
, bitrate: this.defaultProfile.videoEncoderConfiguration.rateControl.bitrateLimit
};
if (this.defaultProfile.PTZConfiguration) {
this.activeSource.ptz = {
name: this.defaultProfile.PTZConfiguration.name
, token: this.defaultProfile.PTZConfiguration.$.token
}
}
} else {
throw new Error('Unrecognized configuration');
}
} else {
// TODO NVT is an encoder
throw new Error ('not implemented');
}
};
/**
* Receive profiles
* @param [callback]
*/
Cam.prototype.getProfiles = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetProfiles xmlns="http://www.onvif.org/ver10/media/wsdl"/>' +
this._envelopeFooter()
}, function(err, data) {
if (!err) {
// this.profiles = _linerase(data).getProfilesResponse.profiles;
this.profiles = data[0]['trt:GetProfilesResponse'][0]['trt:Profiles'].map(function(profile) {
return _linerase(profile);
});
if (this.profiles.length) {
this.defaultProfile = this.profiles[0]; // setting up default profile
}
}
if (callback) {
callback(err, this.profiles);
}
}.bind(this));
};
/**
* Receive services
* @param [callback]
*/
Cam.prototype.getServices = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetServices xmlns="http://www.onvif.org/ver10/device/wsdl"><IncludeCapability>false</IncludeCapability></GetServices>' +
this._envelopeFooter()
}, function(err, data) {
if (!err) {
this.services = _linerase(data).getServicesResponse.service;
}
if (callback) {
callback(err, this.services);
}
}.bind(this));
};
/**
* Receive device information
* @param [callback]
*/
Cam.prototype.getDeviceInformation = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetDeviceInformation xmlns="http://www.onvif.org/ver10/device/wsdl"/>' +
this._envelopeFooter()
}, function(err, data) {
if (!err) {
this.deviceInformation = _linerase(data).getDeviceInformationResponse;
}
if (callback) {
callback(err, this.deviceInformation);
}
}.bind(this));
};
/**
* Receive stream URI
* @param {Object} options
* @param {string} [options.stream]
* @param {string} [options.protocol]
* @param [callback]
*/
Cam.prototype.getStreamUri = function(options, callback) {
var profile = options.profileToken || this.activeSource.profileToken;
this._request({
body: this._envelopeHeader() +
'<GetStreamUri xmlns="http://www.onvif.org/ver10/media/wsdl">' +
'<StreamSetup>' +
'<Stream xmlns="http://www.onvif.org/ver10/schema">'+ (options.stream || 'RTP-Unicast') +'</Stream>' +
'<Transport xmlns="http://www.onvif.org/ver10/schema">' +
'<Protocol>'+ (options.protocol || 'RTSP') +'</Protocol>' +
'</Transport>' +
'</StreamSetup>' +
'<ProfileToken>'+ profile +'</ProfileToken>' +
'</GetStreamUri>' +
this._envelopeFooter()
}, function(err, data) {
// TODO save sream uri as a property?
// if (!err) {
// this.profiles[profile].streamUri = _linerase(data);
// }
if (callback) {
callback(err, err ? null : _linerase(data).getStreamUriResponse.mediaUri);
}
}.bind(this));
};
/**
* Receive cam presets
* @param {Object} options
* @param {string} [options.stream]
* @param {string} [options.protocol]
* @param [callback]
*/
Cam.prototype.getPresets = function(options, callback) {
this._request({
body: this._envelopeHeader() +
'<GetPresets xmlns="http://www.onvif.org/ver20/ptz/wsdl">' +
'<ProfileToken>'+ (options.profileToken || this.activeSource.profileToken) +'</ProfileToken>' +
'</GetPresets>' +
this._envelopeFooter()
}, function(err, data) {
if (!err) {
this.presets = {};
_linerase(data).getPresetsResponse.preset.forEach(function(preset) {
this.presets[preset.name] = preset.$.token;
}.bind(this));
}
if (callback) {
callback(err, this.presets);
}
}.bind(this));
};
/**
* Receive cam status
* @param {Object} options
* @param {string} [options.stream]
* @param {string} [options.protocol]
* @param {Function} callback
*/
Cam.prototype.getStatus = function(options, callback) {
this._request({
body: this._envelopeHeader() +
'<GetStatus xmlns="http://www.onvif.org/ver20/ptz/wsdl">' +
'<ProfileToken>'+ (options.profileToken || this.activeSource.profileToken) +'</ProfileToken>' +
'</GetStatus>' +
this._envelopeFooter()
}, function(err, data) {
if (!err) {
var res = _linerase(data).getStatusResponse.PTZStatus;
var status = {
position: {
x: res.position.panTilt.$.x
, y: res.position.panTilt.$.y
, zoom: res.position.zoom.$.x
}
, moveStatus: res.moveStatus
, utcTime: res.utcTime
}
}
callback(err, err ? null : status);
}.bind(this));
};
/**
* Returns the properties of the requested PTZ node, if it exists.
* Use this function to get maximum number of presets, ranges of admitted values for x, y, zoom, iris, focus
*/
Cam.prototype.getNode = function() {
};
/**
* PTZ relative move
* @param {object} options
* @param {string} [options.profileToken]
* @param {string|number} [options.x] Pan, float
* @param {string|number} [options.y] Tilt, float
* @param {string|number} [options.zoom] Zoom, float
* @param {object} [options.speed] If the speed argument is omitted, the default speed set by the PTZConfiguration will be used.
* @param {string|number} [options.speed.x] Pan speed, float
* @param {string|number} [options.speed.y] Tilt speed, float
* @param {string|number} [options.speed.zoom] Zoom speed, float
* @param {Function} [callback]
*/
Cam.prototype.relativeMove = function(options, callback) {
callback = callback ? callback.bind(this) : function() {};
this._request({
body: this._envelopeHeader() +
'<RelativeMove xmlns="http://www.onvif.org/ver20/ptz/wsdl">' +
'<ProfileToken>' + (options.profileToken || this.activeSource.profileToken) + '</ProfileToken>' +
'<Translation>' +
(options.x && options.y ? '<PanTilt x="' + options.x + '" y="' + options.y + '" space="http://www.onvif.org/ver10/tptz/PanTiltSpaces/PositionGenericSpace" xmlns="http://www.onvif.org/ver10/schema"/>' : '') +
(options.zoom ? '<Zoom x="' + options.zoom + '" space="http://www.onvif.org/ver10/tptz/ZoomSpaces/PositionGenericSpace" xmlns="http://www.onvif.org/ver10/schema"/>' : '') +
'</Translation>' +
(options.speed ?
'<Speed>' +
(options.speed.x && options.speed.y ? '<PanTilt x="' + options.speed.x + '" y="' + options.speed.y + '" space="http://www.onvif.org/ver10/tptz/PanTiltSpaces/PositionGenericSpace" xmlns="http://www.onvif.org/ver10/schema"/>' : '') +
(options.zoom ? '<Zoom x="' + options.zoom + '" space="http://www.onvif.org/ver10/tptz/ZoomSpaces/PositionGenericSpace" xmlns="http://www.onvif.org/ver10/schema"/>' : '') +
'</Speed>'
: '') +
'</RelativeMove>' +
this._envelopeFooter()
}, callback);
};
/**
* PTZ absolute move
* @param {object} options
* @param {string} [options.profileToken]
* @param {string|number} [options.x] Pan, float
* @param {string|number} [options.y] Tilt, float
* @param {string|number} [options.zoom] Zoom, float
* @param {object} [options.speed] If the speed argument is omitted, the default speed set by the PTZConfiguration will be used.
* @param {string|number} [options.speed.x] Pan speed, float
* @param {string|number} [options.speed.y] Tilt speed, float
* @param {string|number} [options.speed.zoom] Zoom speed, float
* @param {Function} [callback]
*/
Cam.prototype.absoluteMove = function(options, callback) {
callback = callback ? callback.bind(this) : function() {};
this._request({
body: this._envelopeHeader() +
'<AbsoluteMove xmlns="http://www.onvif.org/ver20/ptz/wsdl">' +
'<ProfileToken>' + (options.profileToken || this.activeSource.profileToken) + '</ProfileToken>' +
'<Position>' +
(options.x && options.y ? '<PanTilt x="' + options.x + '" y="' + options.y + '" space="http://www.onvif.org/ver10/tptz/PanTiltSpaces/PositionGenericSpace" xmlns="http://www.onvif.org/ver10/schema"/>' : '') +
(options.zoom ? '<Zoom x="' + options.zoom + '" space="http://www.onvif.org/ver10/tptz/ZoomSpaces/PositionGenericSpace" xmlns="http://www.onvif.org/ver10/schema"/>' : '') +
'</Position>' +
(options.speed ?
'<Speed>' +
(options.speed.x && options.speed.y ? '<PanTilt x="' + options.speed.x + '" y="' + options.speed.y + '" space="http://www.onvif.org/ver10/tptz/PanTiltSpaces/PositionGenericSpace" xmlns="http://www.onvif.org/ver10/schema"/>' : '') +
(options.zoom ? '<Zoom x="' + options.zoom + '" space="http://www.onvif.org/ver10/tptz/ZoomSpaces/PositionGenericSpace" xmlns="http://www.onvif.org/ver10/schema"/>' : '') +
'</Speed>'
: '') +
'</AbsoluteMove>' +
this._envelopeFooter()
}, callback);
};
/**
* Generate arguments for digest auth
* @return {{passdigest: *, nonce: (*|String), timestamp: string}}
* @private
*/
Cam.prototype._passwordDigest = function() {
if (!timestamp) {
var timestamp = new Date().toISOString(); // TODO timestamp and nonce
}
if (!nonce) {
var nonce = Math.ceil(Math.random()*10000000000).toString()
}
var cryptoDigest = crypto.createHash('sha1');
cryptoDigest.update(nonce + timestamp + this.password);
var passdigest = cryptoDigest.digest('base64');
return {
passdigest: passdigest
, nonce: new Buffer(nonce).toString('base64')
, timestamp: timestamp
}
};
Cam.prototype._envelopeHeader = function() {
var req = this._passwordDigest();
return '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">' +
'<s:Header>' +
'<Security s:mustUnderstand="1" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">' +
'<UsernameToken>' +
'<Username>' + this.username + '</Username>' +
'<Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">' + req.passdigest + '</Password>' +
'<Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">' + req.nonce + '</Nonce>' +
'<Created xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">' + req.timestamp + '</Created>' +
'</UsernameToken>' +
'</Security>' +
'</s:Header>' +
'<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">';
};
Cam.prototype._envelopeFooter = function() {
return '</s:Body>' +
'</s:Envelope>';
};
module.exports.Cam = Cam;