-
Notifications
You must be signed in to change notification settings - Fork 65
/
dahua.js
executable file
·702 lines (555 loc) · 22 KB
/
dahua.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
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
// #!/usr/bin/nodejs
// Dahua HTTP API Module
var events = require('events');
var util = require('util');
var request = require('request');
var progress = require('request-progress');
var NetKeepAlive = require('net-keepalive')
var setKeypath = require('keypather/set');
var fs = require('fs');
var path = require('path');
var moment = require('moment');
var RECONNECT_TIMEOUT_SECONDS = 10;
var dahua = function(options) {
events.EventEmitter.call(this);
this.TRACE = options.log;
this.BASEURI = 'http://'+ options.host + ':' + options.port;
this.USER = options.user;
this.PASS = options.pass;
this.HOST = options.host;
if( options.cameraAlarms === undefined ) {
options.cameraAlarms = true;
}
if( options.cameraAlarms ) { this.client = this.connect(options) }
this.on('error',function(err){
console.log("Error: " + err);
});
};
util.inherits(dahua, events.EventEmitter);
// set up persistent connection to recieve alarm events from camera
dahua.prototype.connect = function(options) {
var self = this;
var connected = false;
var eventNames = [
'All'
];
var opts = {
'url' : self.BASEURI + '/cgi-bin/eventManager.cgi?action=attach&codes=[' + eventNames.join(',') + ']',
'forever' : true,
'headers': {'Accept':'multipart/x-mixed-replace'}
};
console.log("Connecting...");
var client = request(opts).auth(self.USER, self.PASS, false);
client.on('socket', function(socket) {
// Set keep-alive probes - throws ESOCKETTIMEDOUT error after ~16min if connection broken
socket.setKeepAlive(true, 1000);
NetKeepAlive.setKeepAliveInterval(socket, 1000);
if (self.TRACE) console.log('TCP_KEEPINTVL:',NetKeepAlive.getKeepAliveInterval(socket));
NetKeepAlive.setKeepAliveProbes(socket, 1);
if (self.TRACE) console.log('TCP_KEEPCNT:',NetKeepAlive.getKeepAliveProbes(socket));
});
client.on('response', function() {
connected = true;
handleDahuaEventConnection(self,options);
});
client.on('error', function(err) {
if (!connected) {
console.error("Connection closed- reconnecting in " + RECONNECT_TIMEOUT_SECONDS + " seconds...");
setTimeout(function() { self.connect(options); }, RECONNECT_TIMEOUT_SECONDS * 1000 );
}
handleDahuaEventError(self, err);
});
client.on('data', function(data) {
handleDahuaEventData(self, data);
});
client.on('close', function() { // Try to reconnect after 30s
connected = false;
console.error("Connection closed- reconnecting in " + RECONNECT_TIMEOUT_SECONDS + " seconds...");
setTimeout(function() { self.connect(options); }, RECONNECT_TIMEOUT_SECONDS * 1000 );
handleDahuaEventEnd(self);
});
client.on('error', function(err) {
handleDahuaEventError(self, err);
});
};
function handleDahuaEventData(self, data) {
if (self.TRACE) console.log('Data: ' + data.toString());
data = data.toString().split('\r\n');
var i = Object.keys(data);
i.forEach(function(id){
if (data[id].startsWith('Code=')) {
var alarm = data[id].split(';');
if (alarm.length >= 3) {
var code = alarm[0].substr(5);
var action = alarm[1].substr(7);
var index = alarm[2].substr(6);
// an alarm can have also a data object
// which is multiline in the body
var metadata = {};
if (alarm.length >= 4 && alarm[3].startsWith('data={')) {
var metadataArray = alarm[3].split('\n');
metadataArray[0] = '{'; // we don't want "data={"
metadata = metadataArray.join('');
try {
metadata = JSON.parse(metadata);
if (self.TRACE) console.dir(metadata, 'Got JSON parsed metadata');
}
catch (e) {
self.emit("error", "Error during JSON.parse of alarm extra data");
console.error(e, 'Error during JSON.parse of alarm extra data');
}
}
self.emit("alarm", code,action,index, metadata);
}
}
});
}
function handleDahuaEventConnection(self,options) {
if (self.TRACE) console.log('Connected to ' + options.host + ':' + options.port);
//self.socket = socket;
self.emit("connect", options);
}
function handleDahuaEventEnd(self) {
if (self.TRACE) console.log("Connection closed!");
self.emit("end");
}
function handleDahuaEventError(self, err) {
if (self.TRACE) console.log("Connection error: " + err);
self.emit("error", err);
}
dahua.prototype.ptzCommand = function (cmd,arg1,arg2,arg3,arg4) {
var self = this;
if ((!cmd) || (isNaN(arg1)) || (isNaN(arg2)) || (isNaN(arg3)) || (isNaN(arg4))) {
self.emit("error",'INVALID PTZ COMMAND');
return 0;
}
request(self.BASEURI + '/cgi-bin/ptz.cgi?action=start&channel=0&code=' + ptzcommand + '&arg1=' + arg1 + '&arg2=' + arg2 + '&arg3=' + arg3 + '&arg4=' + arg4, function (error, response, body) {
if ((error) || (response.statusCode !== 200) || (body.trim() !== "OK")) {
self.emit("error", 'FAILED TO ISSUE PTZ COMMAND');
}
}).auth(self.USER,self.PASS,false);
};
dahua.prototype.ptzPreset = function (preset) {
var self = this;
if (isNaN(preset)) self.emit("error",'INVALID PTZ PRESET');
request(self.BASEURI + '/cgi-bin/ptz.cgi?action=start&channel=0&code=GotoPreset&arg1=0&arg2=' + preset + '&arg3=0', function (error, response, body) {
if ((error) || (response.statusCode !== 200) || (body.trim() !== "OK")) {
self.emit("error", 'FAILED TO ISSUE PTZ PRESET');
}
}).auth(self.USER,self.PASS,false);
};
dahua.prototype.ptzZoom = function (multiple) {
var self = this;
if (isNaN(multiple)) self.emit("error",'INVALID PTZ ZOOM');
if (multiple > 0) cmd = 'ZoomTele';
if (multiple < 0) cmd = 'ZoomWide';
if (multiple === 0) return 0;
request(self.BASEURI + '/cgi-bin/ptz.cgi?action=start&channel=0&code=' + cmd + '&arg1=0&arg2=' + multiple + '&arg3=0', function (error, response, body) {
if ((error) || (response.statusCode !== 200) || (body.trim() !== "OK")) {
self.emit("error", 'FAILED TO ISSUE PTZ ZOOM');
}
}).auth(self.USER,self.PASS,false);
};
dahua.prototype.ptzMove = function (direction,action,speed) {
var self = this;
if (isNaN(speed)) self.emit("error",'INVALID PTZ SPEED');
if ((action !== 'start') || (action !== 'stop')) {
self.emit("error",'INVALID PTZ COMMAND');
return 0;
}
if ((direction !== 'Up') || (direction !== 'Down') || (direction !== 'Left') || (direction !== 'Right') ||
(direction !== 'LeftUp') || (direction !== 'RightUp') || (direction !== 'LeftDown') || (direction !== 'RightDown')) {
self.emit("error",'INVALID PTZ DIRECTION');
return 0;
}
request(self.BASEURI + '/cgi-bin/ptz.cgi?action=' + action + '&channel=0&code=' + direction + '&arg1=' + speed +'&arg2=' + speed + '&arg3=0', function (error, response, body) {
if ((error) || (response.statusCode !== 200) || (body.trim() !== "OK")) {
self.emit("error", 'FAILED TO ISSUE PTZ UP COMMAND');
}
}).auth(self.USER,self.PASS,false);
};
dahua.prototype.ptzStatus = function () {
var self = this;
request(self.BASEURI + '/cgi-bin/ptz.cgi?action=getStatus', function (error, response, body) {
if ((!error) && (response.statusCode === 200)) {
body = body.toString().split('\r\n');
self.emit("ptzStatus", body);
} else {
self.emit("error", 'FAILED TO QUERY STATUS');
}
}).auth(self.USER,self.PASS,false);
};
dahua.prototype.dayProfile = function () {
var self = this;
request(self.BASEURI + '/cgi-bin/configManager.cgi?action=setConfig&VideoInMode[0].Config[0]=1', function (error, response, body) {
if ((!error) && (response.statusCode === 200)) {
if (body === 'Error') { // Didnt work, lets try another method for older cameras
request(self.BASEURI + '/cgi-bin/configManager.cgi?action=setConfig&VideoInOptions[0].NightOptions.SwitchMode=0', function (error, response, body) {
if ((error) || (response.statusCode !== 200)) {
self.emit("error", 'FAILED TO CHANGE TO DAY PROFILE');
}
}).auth(self.USER,self.PASS,false);
}
} else {
self.emit("error", 'FAILED TO CHANGE TO DAY PROFILE');
}
}).auth(self.USER,self.PASS,false);
};
dahua.prototype.nightProfile = function () {
var self = this;
request(self.BASEURI + '/cgi-bin/configManager.cgi?action=setConfig&VideoInMode[0].Config[0]=2', function (error, response, body) {
if ((!error) && (response.statusCode === 200)) {
if (body === 'Error') { // Didnt work, lets try another method for older cameras
request(self.BASEURI + '/cgi-bin/configManager.cgi?action=setConfig&VideoInOptions[0].NightOptions.SwitchMode=3', function (error, response, body) {
if ((error) || (response.statusCode !== 200)) {
self.emit("error", 'FAILED TO CHANGE TO NIGHT PROFILE');
}
}).auth(self.USER,self.PASS,false);
}
} else {
self.emit("error", 'FAILED TO CHANGE TO NIGHT PROFILE');
}
}).auth(self.USER,self.PASS,false);
};
/*====================================
= File Finding =
====================================*/
dahua.prototype.findFiles = function(query){
var self = this;
if ((!query.channel) || (!query.startTime) || (!query.endTime)) {
self.emit("error",'FILE FIND MISSING ARGUMENTS');
return 0;
}
// create a finder
this.createFileFind();
// start search
this.on('fileFinderCreated',function(objectId){
if (self.TRACE) console.log('fileFinderId:',objectId);
self.startFileFind(objectId,query.channel,query.startTime,query.endTime,query.types);
});
// fetch results
this.on('startFileFindDone',function(objectId,body){
if (self.TRACE) console.log('startFileFindDone:',objectId,body);
self.nextFileFind(objectId,query.count);
});
// handle the results
this.on('nextFileFindDone',function(objectId,items){
if (self.TRACE) console.log('nextFileFindDone:',objectId);
items.query = query;
self.emit('filesFound',items);
self.closeFileFind(objectId);
});
// close and destroy the finder
this.on('closeFileFindDone',function(objectId,body){
if (self.TRACE) console.log('closeFileFindDone:',objectId,body);
self.destroyFileFind(objectId);
});
this.on('destroyFileFindDone',function(objectId,body){
if (self.TRACE) console.log('destroyFileFindDone:',objectId,body);
});
};
// 10.1.1 Create
// URL Syntax
// http://<ip>/cgi-bin/mediaFileFind.cgi?action=factory.create
// Comment
// Create a media file finder
// Response
// result=08137
dahua.prototype.createFileFind = function () {
var self = this;
request(self.BASEURI + '/cgi-bin/mediaFileFind.cgi?action=factory.create', function (error, response, body) {
if ((error)) {
self.emit("error", 'ERROR ON CREATE FILE FIND COMMAND');
}
// stripping 'result=' and returning the object ID
var oid = body.trim().substr(7);
self.emit("fileFinderCreated",oid);
}).auth(self.USER,self.PASS,false);
};
// 10.1.2 StartFind
// URL Syntax
// http://<ip>/cgi-bin/mediaFileFind.cgi?action=findFile&object=<objectId>&condition.Channel=<channel>&condition.StartTime= <start>&condition.EndT ime=<end>&condition.Dirs[0]=<dir>&condition.Types[0]=<type>&condition.Flag[0]=<flag>&condition.E vents[0]=<event>
// Comment
// Start to find file wth the above condition. If start successfully, return true, else return false.
// object : The object Id is got from interface in 10.1.1 Create
// condition.Channel: in which channel you want to find the file .
// condition.StartTime/condition.EndTime: the start/end time when recording.
// condition.Dirs: in which directories you want to find the file. It is an array. The index starts from 0. The range of dir is {“/mnt/dvr/sda0”, “/mnt/dvr/sda1”}. This condition can be omitted. If omitted, find files in all the directories.
// condition.Types: which types of the file you want to find. It is an array. The index starts from 0. The range of type is {“dav”,
// “jpg”, “mp4”}. If omitted, find files with all the types.
// condition.Flags: which flags of the file you want to find. It is an array. The index starts from 0. The range of flag is {“Timing”, “Manual”, “Marker”, “Event”, “Mosaic”, “Cutout”}. If omitted, find files with all the flags.
// condition.Event: by which event the record file is triggered. It is an array. The index starts from 0. The range of event is {“AlarmLocal”, “VideoMotion”, “VideoLoss”, “VideoBlind”, “Traffic*”}. This condition can be omitted. If omitted, find files of all the events.
// Example:
// Find file in channel 1, in directory “/mnt/dvr/sda0",event type is "AlarmLocal" or "VideoMotion", file type is “dav”, and time between 2011-1-1 12:00:00 and 2011-1-10 12:00:00 , URL is: http://<ip>/cgi-bin/mediaFileFind.cgi?action=findFile&object=08137&condition.Channel=1&conditon.Dir[0]=”/mnt/dvr/sda0”& conditon.Event[0]=AlarmLocal&conditon.Event[1]=V ideoMotion&condition.StartT ime=2011-1-1%2012:00:00&condition.EndT i me=2011-1-10%2012:00:00
// Response
// OK or Error
//
// To be Done: Implement Dirs, Types, Flags, Event Args
dahua.prototype.startFileFind = function (objectId,channel,startTime,endTime,types) { // Dirs,Types,Flags,Event) {
var self = this;
if ((!objectId) || (!channel) || (!startTime) || (!endTime) ) {
self.emit("error",'INVALID FINDFILE COMMAND - MISSING ARGS');
return 0;
}
types = types || [];
var typesQueryString = "";
types.forEach(function(el,idx){
typesQueryString += '&condition.Types[' + idx + ']=' + el;
});
var url = self.BASEURI + '/cgi-bin/mediaFileFind.cgi?action=findFile&object=' + objectId + '&condition.Channel=' + channel + '&condition.StartTime=' + startTime + '&condition.EndTime=' + endTime + typesQueryString;
// console.log(url);
request(url, function (error, response, body) {
if ((error)) {
if (self.TRACE) console.log('startFileFind Error:',error);
self.emit("error", 'FAILED TO ISSUE FIND FILE COMMAND');
} else {
if (self.TRACE) console.log('startFileFind Response:',body.trim());
// no results = http code 400 ?
//if(response.statusCode == 400 ) {
// self.emit("error", 'FAILED TO ISSUE FIND FILE COMMAND - NO RESULTS ?');
//} else {
//
self.emit('startFileFindDone',objectId,body.trim());
//}
}
}).auth(self.USER,self.PASS,false);
};
// 10.1.3 FindNextFile
// URL Syntax
// http://<ip>/cgi-bin/mediaFileFind.cgi?action=findNextFile&object=<objectId>&count=<fileCount>
// Comment
// Find the next fileCount files.
// The maximum value of fileCount is 100.
// Response
// found=1
// items[0]. Channel =1
// items[0]. StartTime =2011-1-1 12:00:00
// items[0]. EndTime =2011-1-1 13:00:00
// items[0]. Type =dav
// items[0]. Events[0]=AlarmLocal
// items[0]. FilePath =/mnt/dvr/sda0/2010/8/11/dav/15:40:50.jpg items[0]. Length =790
// items[0]. Duration = 3600
// items[0].SummaryOffset=2354
// tems[0].Repeat=0
// items[0].WorkDir=”/mnt/dvr/sda0”
// items[0]. Overwrites=5
// items[0]. WorkDirSN=0
// Response
// found - Count of found file, found is 0 if no file is found.
// Channel - Channel
// StartTime - Start Time
// EndTime - End time
// Type - File type
// Events - Event type.
// FilePath - filepath.
// Length - File length
// Duration - Duration time
// SummaryOffset - Summary offset
// Repeat - Repeat file number
// WorkDir - The file’s directory
// Overwrites - Overwrite times of the work directory
// WorkDirSN - Workdir No
//
//
dahua.prototype.nextFileFind = function (objectId,count) {
var self = this;
count = count || 100;
if ((!objectId)) {
self.emit("error",'INVALID NEXT FILE COMMAND');
return 0;
}
request(self.BASEURI + '/cgi-bin/mediaFileFind.cgi?action=findNextFile&object=' + objectId + '&count=' + count, function (error, response, body) {
if ((error) || (response.statusCode !== 200)) {
if (self.TRACE) console.log('nextFileFind Error:',error);
self.emit("error", 'FAILED NEXT FILE COMMAND');
}
// if (self.TRACE) console.log('nextFileFind Response:',body.trim());
var items = {};
var data = body.split('\r\n');
// getting found count
items.found = data[0].split("=")[1];
// parsing items
data.forEach(function(item){
if(item.startsWith('items[')) {
var propertyAndValue = item.split("=");
setKeypath(items, propertyAndValue[0], propertyAndValue[1]);
}
});
self.emit('nextFileFindDone',objectId,items);
}).auth(self.USER,self.PASS,false);
};
// 10.1.4 Close
// URL Syntax
// http://<ip>/cgi-bin/mediaFileFind.cgi?action=close&object=<objectId>
// Comment
// Stop find.
// Response
// OK or ERROR
dahua.prototype.closeFileFind = function (objectId) {
var self = this;
if ((!objectId)) {
self.emit("error",'OBJECT ID MISSING');
return 0;
}
request(self.BASEURI + '/cgi-bin/mediaFileFind.cgi?action=close&object=' + objectId, function (error, response, body) {
if ((error) || (response.statusCode !== 200) || (body.trim() !== "OK")) {
self.emit("error", 'ERROR ON CLOSE FILE FIND COMMAND');
}
self.emit('closeFileFindDone',objectId,body.trim());
}).auth(self.USER,self.PASS,false);
};
// 10.1.5 Destroy
// URL Syntax
// http://<ip>/cgi-bin/mediaFileFind.cgi?action=destroy&object=<objectId>
// Comment
// Close the media file finder.
// Response
// OK or ERROR
dahua.prototype.destroyFileFind = function (objectId) {
var self = this;
if ((!objectId)) {
self.emit("error",'OBJECT ID MISSING');
return 0;
}
request(self.BASEURI + '/cgi-bin/mediaFileFind.cgi?action=destroy&object=' + objectId, function (error, response, body) {
if ((error) || (response.statusCode !== 200) || (body.trim() !== "OK")) {
self.emit("error", 'ERROR ON DESTROY FILE FIND COMMAND');
}
self.emit('destroyFileFindDone',objectId,body.trim());
}).auth(self.USER,self.PASS,false);
};
/*===== End of File Finding ======*/
/*================================
= Load File =
================================*/
// API Description
//
// URL Syntax
// http://<ip>/cgi-bin/RPC_Loadfile/<filename>
// Response
// HTTP Code: 200 OK
// Content-Type: Application/octet-stream
// Content-Length:<fileLength>
// Body:
// <data>
// <data>
// For example: http://10.61.5.117/cgi-bin/RPC_Loadfile/mnt/sd/2012-07-13/001/dav/09/09.30.37-09.30.47[R][0@0][0].dav
dahua.prototype.saveFile = function (file,filename) {
var self = this;
if ((!file)) {
self.emit("error",'FILE OBJECT MISSING');
return 0;
}
if ((!file.FilePath)) {
self.emit("error",'FILEPATH in FILE OBJECT MISSING');
return 0;
}
if(!filename) {
if( !file.Channel || !file.StartTime || !file.EndTime || !file.Type ) {
self.emit("error",'FILE OBJECT ATTRIBUTES MISSING');
return 0;
}
// the fileFind response obejct
// { Channel: '0',
// Cluster: '0',
// Compressed: 'false',
// CutLength: '634359892',
// Disk: '0',
// Duration: '495',
// EndTime: '2018-05-19 10:45:00',
// FilePath: '/mnt/sd/2018-05-19/001/dav/10/10.36.45-10.45.00[R][0@0][0].dav',
// Flags: [Object],
// Length: '634359892',
// Overwrites: '0',
// Partition: '0',
// Redundant: 'false',
// Repeat: '0',
// StartTime: '2018-05-19 10:36:45',
// Summary: [Object],
// SummaryOffset: '0',
// Type: 'dav',
// WorkDir: '/mnt/sd',
// WorkDirSN: '0' };
filename = this.generateFilename(self.HOST,file.Channel,file.StartTime,file.EndTime,file.Type);
}
progress(request(self.BASEURI + '/cgi-bin/RPC_Loadfile/' + file.FilePath))
.auth(self.USER,self.PASS,false)
.on('progress', function (state) {
if(self.TRACE) {
console.log('Downloaded', Math.floor(state.percent * 100) + '%','@ '+Math.floor(state.speed / 1000), 'KByte/s' );
}
})
.on('response',function(response){
if (response.statusCode !== 200) {
self.emit("error", 'ERROR ON LOAD FILE COMMAND');
}
})
.on('error',function (error){
if(error.code == "ECONNRESET") {
self.emit("error", 'ERROR ON LOAD FILE COMMAND - FILE NOT FOUND?');
} else {
self.emit("error", 'ERROR ON LOAD FILE COMMAND');
}
})
.on('end',function() {
self.emit("saveFile", {
'status':'DONE',
});
})
.pipe(fs.createWriteStream(filename));
// TBD: file writing error handling
};
/*===== End of Load File ======*/
/*====================================
= Get Snapshot =
====================================*/
// API Description
//
// URL Syntax
// http://<ip>/cgi-bin/snapshot.cgi? [channel=<channelNo>]
// Response
// A picture encoded by jpg
// Comment
// The channel number is default 0 if the request is not carried the param.
dahua.prototype.getSnapshot = function (options) {
var self = this;
options = options || {};
if ((!options.channel)) {
options.channel = 0;
}
if ((!options.path)) {
options.path = '';
}
if (!options.filename) {
options.filename = this.generateFilename(self.HOST,options.channel,moment(),'','jpg');
}
request(self.BASEURI + '/cgi-bin/snapshot.cgi?' + options.channel , function (error, response, body) {
if ((error) || (response.statusCode !== 200)) {
self.emit("error", 'ERROR ON SNAPSHOT');
}
})
.on('end',function(){
if(self.TRACE) console.log('SNAPSHOT SAVED');
self.emit("getSnapshot", {
'status':'DONE',});
})
.auth(self.USER,self.PASS,false).pipe(fs.createWriteStream(path.join(options.path,options.filename)));
// TBD: file writing error handling
};
/*===== End of Get Snapshot ======*/
dahua.prototype.generateFilename = function( device, channel, start, end, filetype ) {
filename = device + '_ch' + channel + '_';
// to be done: LOCALIZATION ?
startDate = moment(start);
filename += startDate.format('YYYYMMDDhhmmss');
if(end) {
endDate = moment(end);
filename += '_' + endDate.format('YYYYMMDDhhmmss');
}
filename += '.' + filetype;
return filename;
};
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
exports.dahua = dahua;