-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathhikvision.js
executable file
·287 lines (254 loc) · 10.5 KB
/
hikvision.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
#!/usr/bin/nodejs
// hikvision HTTP API Module
var net = require('net');
var events = require('events');
var util = require('util');
var request = require('request');
var NetKeepAlive = require('net-keepalive');
var xml2js = require('xml2js');
// Define Globals
var TRACE = false;
var BASEURI = false;
var parser = new xml2js.Parser();
// Module Loader
var hikvision = function(options) {
events.EventEmitter.call(this)
this.client = this.connect(options)
if (options.log) TRACE = options.log;
BASEURI = 'http://' + options.host + ':' + options.port
this.activeEvents = { };
this.triggerActive = false
};
util.inherits(hikvision, events.EventEmitter);
// Attach to camera
hikvision.prototype.connect = function(options) {
var self = this
var authHeader = 'Authorization: Basic ' + new Buffer(options.user + ':' + options.pass).toString('base64');
// Connect
var client = net.connect(options, function () {
var header = 'GET /ISAPI/Event/notification/alertStream HTTP/1.1\r\n' +
'Host: ' + options.host + ':' + options.port + '\r\n' +
authHeader + '\r\n' +
'Accept: multipart/x-mixed-replace\r\n\r\n';
client.write(header)
client.setKeepAlive(true,1000)
NetKeepAlive.setKeepAliveInterval(client,5000) // sets TCP_KEEPINTVL to 5s
NetKeepAlive.setKeepAliveProbes(client, 12) // 60s and kill the connection.
handleConnection(self, options);
});
client.on('data', function(data) {
handleData(self, data)
});
client.on('close', function() { // Try to reconnect after 30s
setTimeout(function() { self.connect(options) }, 30000 );
handleEnd(self)
});
client.on('error', function(err) {
handleError(self, err)
});
}
// Raw PTZ Command - command/arg1/arg2/arg3/arg4
hikvision.prototype.ptzCommand = function (cmd,arg1,arg2,arg3,arg4) {
var self = this;
if ((!cmd) || (isNaN(arg1)) || (isNaN(arg2)) || (isNaN(arg3)) || (isNaN(arg4))) {
handleError(self,'INVALID PTZ COMMAND')
return 0
}
request(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');
}
})
}
// PTZ Preset - number
hikvision.prototype.ptzPreset = function (preset) {
var self = this;
if (isNaN(preset)) handleError(self,'INVALID PTZ PRESET');
request(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');
}
})
}
// PTZ Zoom - multiplier
hikvision.prototype.ptzZoom = function (multiple) {
var self = this;
if (isNaN(multiple)) handleError(self,'INVALID PTZ ZOOM');
if (multiple > 0) cmd = 'ZoomTele';
if (multiple < 0) cmd = 'ZoomWide';
if (multiple === 0) return 0;
request(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")) {
if (TRACE) console.log('FAILED TO ISSUE PTZ ZOOM');
self.emit("error", 'FAILED TO ISSUE PTZ ZOOM');
}
})
}
// PTZ Move - direction/action/speed
hikvision.prototype.ptzMove = function (direction,action,speed) {
var self = this;
if (isNaN(speed)) handleError(self,'INVALID PTZ SPEED');
if ((action !== 'start') || (action !== 'stop')) {
handleError(self,'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: ' + direction)
if (TRACE) console.log('INVALID PTZ DIRECTION: ' + direction);
return 0
}
request(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');
if (TRACE) console.log('FAILED TO ISSUE PTZ UP COMMAND');
}
})
}
// Request PTZ Status
hikvision.prototype.ptzStatus = function () {
var self = this;
request(BASEURI + '/cgi-bin/ptz.cgi?action=getStatus', function (error, response, body) {
if ((!error) && (response.statusCode === 200)) {
body = body.toString().split('\r\n').trim()
if (TRACE) console.log('PTZ STATUS: ' + body);
self.emit("ptzStatus", body);
} else {
self.emit("error", 'FAILED TO QUERY STATUS');
if (TRACE) console.log('FAILED TO QUERY STATUS');
}
})
}
// Switch to Day Profile
hikvision.prototype.dayProfile = function () {
var self = this;
request(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(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');
if (TRACE) console.log('FAILED TO CHANGE TO DAY PROFILE');
}
})
}
} else {
self.emit("error", 'FAILED TO CHANGE TO DAY PROFILE');
if (TRACE) console.log('FAILED TO CHANGE TO DAY PROFILE');
}
})
}
// Switch to Night Profile
hikvision.prototype.nightProfile = function () {
var self = this;
request(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(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');
if (TRACE) console.log('FAILED TO CHANGE TO NIGHT PROFILE');
}
})
}
} else {
self.emit("error", 'FAILED TO CHANGE TO NIGHT PROFILE');
if (TRACE) console.log('FAILED TO CHANGE TO NIGHT PROFILE');
}
})
}
// Handle alarms
function handleData(self, data) {
parser.parseString(data, function(err, result) {
if (result) {
var code = result['EventNotificationAlert']['eventType'][0]
var action = result['EventNotificationAlert']['eventState'][0]
var index = parseInt(result['EventNotificationAlert']['channelID'][0])
var count = parseInt(result['EventNotificationAlert']['activePostCount'][0])
// give codes returned by camera prettier and standardized description
if (code === 'IO') code = 'AlarmLocal';
if (code === 'VMD') code = 'VideoMotion';
if (code === 'linedetection') code = 'LineDetection';
if (code === 'videoloss') code = 'VideoLoss';
if (code === 'shelteralarm') code = 'VideoBlind';
if (action === 'active') action = 'Start'
if (action === 'inactive') action = 'Stop'
// create and event identifier for each recieved event
// This allows multiple detection types with multiple indexes for DVR or multihead devices
var eventIdentifier = code + index
// Count 0 seems to indicate everything is fine and nothing is wrong, used as a heartbeat
// if triggerActive is true, lets step through the activeEvents
// If activeEvents has something, lets end those events and clear activeEvents and reset triggerActive
if (count == 0) {
if (self.triggerActive == true) {
for(var i in self.activeEvents) {
if(self.activeEvents.hasOwnProperty(i)){
var eventDetails = self.activeEvents[i]
if (TRACE) console.log('Ending Event: ' + i + ' - ' + eventDetails["code"] + ' - ' + ((Date.now() - eventDetails["lasttimestamp"])/1000));
self.emit("alarm", eventDetails["code"],'Stop', eventDetails["index"]);
}
}
self.activeEvents = {};
self.triggerActive = false
} else {
// should be the most common result
// Nothing interesting happening and we haven't seen any events
if (TRACE) self.emit("alarm", code,action,index);
}
}
// if the first instance of an eventIdentifier, lets emit it,
// add to activeEvents and set triggerActive
else if (typeof self.activeEvents[eventIdentifier] == 'undefined' || self.activeEvents[eventIdentifier] == null){
var eventDetails = { }
eventDetails["code"] = code
eventDetails["index"] = index
eventDetails["lasttimestamp"] = Date.now();
self.activeEvents[eventIdentifier] = eventDetails
self.emit("alarm", code,action,index);
self.triggerActive = true
// known active events
} else {
if (TRACE) console.log(' Skipped Event: ' + code + ' ' + action + ' ' + index + ' ' + count );
// Update lasttimestamp
var eventDetails = { }
eventDetails["code"] = code
eventDetails["index"] = index
eventDetails["lasttimestamp"] = Date.now();
self.activeEvents[eventIdentifier] = eventDetails
// step through activeEvents
// if we haven't seen it in more than 2 seconds, lets end it and remove from activeEvents
for(var i in self.activeEvents) {
if(self.activeEvents.hasOwnProperty(i)){
var eventDetails = self.activeEvents[i]
if (((Date.now() - eventDetails["lasttimestamp"])/1000) > 2) {
if (TRACE) console.log(' Ending Event: ' + i + ' - ' + eventDetails["code"] + ' - ' + ((Date.now() - eventDetails["lasttimestamp"])/1000));
self.emit("alarm", eventDetails["code"],'Stop', eventDetails["index"]);
delete self.activeEvents[i]
}
}
}
}
}
});
}
// Handle connection
function handleConnection(self, options) {
if (TRACE) console.log('Connected to ' + options.host + ':' + options.port)
//self.socket = socket;
self.emit("connect");
}
// Handle connection ended
function handleEnd(self) {
if (TRACE) console.log("Connection closed!");
self.emit("end");
}
// Handle Errors
function handleError(self, err) {
if (TRACE) console.log("Connection error: " + err);
self.emit("error", err);
}
// Prototype to see if string starts with string
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
exports.hikvision = hikvision;