-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-http.js
More file actions
293 lines (248 loc) · 9.77 KB
/
example-http.js
File metadata and controls
293 lines (248 loc) · 9.77 KB
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
#!/usr/bin/env node
/**
* PTZOptics HTTP-CGI API Controller Example
*
* This example demonstrates how to control PTZOptics cameras using HTTP-CGI commands.
* Implements HTTP Digest Authentication (SHA-256) natively using Node.js built-in modules.
*
* Usage:
* node using-HTTP.js
*/
const http = require('http');
const crypto = require('crypto');
// Configuration Constants
const CAMERA_HOST = "192.168.1.100";
const CAMERA_USERNAME = "admin";
const CAMERA_PASSWORD = "admin";
class PTZOpticsHTTPController {
constructor(host = "ptzoptics.local", username = "admin", password = "admin") {
this.host = host;
this.username = username;
this.password = password;
this.running = false;
this.commandIndex = 0;
this.timerInterval = null;
// HTTP-CGI Command List
this.cgiCommands = [
"/cgi-bin/ptzctrl.cgi?ptzcmd&left&12&10",
"/cgi-bin/ptzctrl.cgi?ptzcmd&ptzstop&0&0",
"/cgi-bin/ptzctrl.cgi?ptzcmd&right&12&10",
];
// Command descriptions
this.commandDescriptions = [
"Pan Left (Speed 12/10)",
"Stop Pan/Tilt",
"Pan Right (Speed 12/10)",
];
}
makeRequest(path) {
return new Promise((resolve, reject) => {
const options = {
hostname: this.host,
port: 80,
path: path,
method: 'GET',
headers: {
'Accept': '*/*'
}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 401 && res.headers['www-authenticate']) {
// Need to handle digest auth
const authHeader = res.headers['www-authenticate'];
const digestResponse = this.createDigestResponse(authHeader, path);
// Make authenticated request
const authOptions = {
...options,
headers: {
...options.headers,
'Authorization': digestResponse
}
};
const authReq = http.request(authOptions, (authRes) => {
let authData = '';
authRes.on('data', chunk => {
authData += chunk;
});
authRes.on('end', () => {
resolve({
statusCode: authRes.statusCode,
data: authData,
headers: authRes.headers
});
});
});
authReq.on('error', reject);
authReq.end();
} else {
resolve({
statusCode: res.statusCode,
data: data,
headers: res.headers
});
}
});
});
req.on('error', reject);
req.end();
});
}
createDigestResponse(authHeader, uri) {
// Parse WWW-Authenticate header
const params = {};
authHeader.replace('Digest ', '').split(',').forEach(param => {
const [key, value] = param.trim().split('=');
params[key] = value ? value.replace(/"/g, '') : '';
});
const realm = params.realm || '';
const nonce = params.nonce || '';
const qop = params.qop || '';
const algorithm = params.algorithm || 'MD5';
// Generate client nonce
const cnonce = crypto.randomBytes(8).toString('hex');
const nc = '00000001';
// Calculate digest
let ha1, ha2, response;
if (algorithm === 'SHA-256') {
const hash = crypto.createHash('sha256');
hash.update(`${this.username}:${realm}:${this.password}`);
ha1 = hash.digest('hex');
const hash2 = crypto.createHash('sha256');
hash2.update(`GET:${uri}`);
ha2 = hash2.digest('hex');
const hash3 = crypto.createHash('sha256');
if (qop === 'auth') {
hash3.update(`${ha1}:${nonce}:${nc}:${cnonce}:${qop}:${ha2}`);
} else {
hash3.update(`${ha1}:${nonce}:${ha2}`);
}
response = hash3.digest('hex');
} else {
// MD5
const hash = crypto.createHash('md5');
hash.update(`${this.username}:${realm}:${this.password}`);
ha1 = hash.digest('hex');
const hash2 = crypto.createHash('md5');
hash2.update(`GET:${uri}`);
ha2 = hash2.digest('hex');
const hash3 = crypto.createHash('md5');
if (qop === 'auth') {
hash3.update(`${ha1}:${nonce}:${nc}:${cnonce}:${qop}:${ha2}`);
} else {
hash3.update(`${ha1}:${nonce}:${ha2}`);
}
response = hash3.digest('hex');
}
// Build Authorization header
let authStr = `Digest username="${this.username}", realm="${realm}", nonce="${nonce}", uri="${uri}"`;
if (qop) {
authStr += `, cnonce="${cnonce}", nc=${nc}, qop=${qop}`;
}
authStr += `, response="${response}", algorithm=${algorithm}`;
return authStr;
}
async testConnection() {
try {
console.log(`Testing connection to: http://${this.host}/cgi-bin/ptzctrl.cgi?ptzcmd&ptzstop&0&0`);
const result = await this.makeRequest('/cgi-bin/ptzctrl.cgi?ptzcmd&ptzstop&0&0');
console.log(`Response status: ${result.statusCode}`);
if (result.statusCode === 200) {
console.log(`✓ Connected to PTZ camera at ${this.host}`);
return true;
} else {
console.log(`❌ Connection failed - HTTP ${result.statusCode}`);
console.log(`Response: ${result.data.substring(0, 200)}`);
return false;
}
} catch (error) {
console.log(`❌ Connection error: ${error.message}`);
return false;
}
}
async sendCommand(path) {
try {
console.log(` URL: ${path}`);
const result = await this.makeRequest(path);
if (result.statusCode === 200) {
console.log(` ✅ Command successful (HTTP ${result.statusCode})`);
if (result.data.trim()) {
const firstLine = result.data.trim().split('\n')[0].substring(0, 100);
console.log(` Response: ${firstLine}`);
}
return true;
} else {
console.log(` ❌ Command failed (HTTP ${result.statusCode})`);
return false;
}
} catch (error) {
console.log(` ❌ Request error: ${error.message}`);
return false;
}
}
async sendNextCommand() {
if (!this.cgiCommands || this.cgiCommands.length === 0) {
console.log("⚠️ No commands in command list");
return;
}
const command = this.cgiCommands[this.commandIndex];
const description = this.commandDescriptions[this.commandIndex] || `Command ${this.commandIndex + 1}`;
console.log(`\n📤 Sending: ${description}`);
await this.sendCommand(command);
this.commandIndex = (this.commandIndex + 1) % this.cgiCommands.length;
}
async start() {
if (await this.testConnection()) {
this.running = true;
await this.sendNextCommand();
this.timerInterval = setInterval(() => {
if (this.running) {
this.sendNextCommand();
}
}, 5000);
console.log("🕒 Started command timer (5 second intervals)");
return true;
}
return false;
}
stop() {
this.running = false;
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
console.log("⏹️ Controller stopped");
}
}
let controller;
function signalHandler() {
console.log("\n\n🛑 Stopping PTZ Controller...");
if (controller) {
controller.stop();
}
process.exit(0);
}
async function main() {
controller = new PTZOpticsHTTPController(CAMERA_HOST, CAMERA_USERNAME, CAMERA_PASSWORD);
process.on('SIGINT', signalHandler);
process.on('SIGTERM', signalHandler);
console.log("PTZOptics HTTP-CGI Controller Example");
console.log("=".repeat(40));
console.log(`Connecting to camera at: ${controller.host}`);
console.log("Commands will be sent every 5 seconds");
console.log("Press Ctrl+C to stop\n");
if (await controller.start()) {
// Keep running
} else {
console.log("Failed to start controller");
process.exit(1);
}
}
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});