This repository has been archived by the owner on May 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwebrelais.js
112 lines (80 loc) · 2.46 KB
/
webrelais.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
var util = require('util')
,https = require('https')
,http = require('http')
,url = require('url');
var RESET = 'DELETE'
,GET = 'GET'
,SET = 'POST';
var Client = function( baseurl ) {
this.baseurl = baseurl;
this.username = false;
this.password = false;
};
Client.prototype.authenticate = function( username, password ) {
this.username = username;
this.password = password;
};
Client.prototype.needs_auth = function() {
return (this.username && this.password);
};
Client.prototype.send_command = function( path, type, callback ) {
var options = url.parse(this.baseurl + path);
options.method = type;
options.headers = {'Content-length': 0};
if( this.needs_auth() ) {
options['auth'] = this.username + ":" + this.password;
}
var http_s = options.protocol=='https:' ? https : http;
// Set up the request
var client = this;
var req = http_s.request(options, function(res) {
res.setEncoding('utf8');
var resString = '';
res.on('data', function( data ){
resString += data;
});
res.on('end', function () {
var reply = []
,error = true;
try {
reply = JSON.parse(resString);
error = false;
} catch( e ) {
console.log( 'json parsing error: ' + e.message );
}
if( typeof(callback) == 'function' ) {
callback(error, reply);
}
});
});
req.end();
};
Client.prototype.set_port = function( port, value, callback ) {
if( value == 0 ) {
this.reset_port( port, callback );
return;
}
this.send_command( '/relais/' + port, SET, callback );
};
Client.prototype.set_ports = function( value, callback ) {
if( value == 0 ) {
this.reset_ports( callback );
return;
}
this.send_command( '/relais', SET, callback );
};
Client.prototype.reset_port = function( port, callback ) {
this.send_command( '/relais/' + port, RESET, callback );
};
Client.prototype.reset_ports = function( port, callback ) {
this.send_command( '/relais', RESET, callback );
};
Client.prototype.get_port = function( port, callback ) {
this.send_command( '/relais/' + port, GET, callback );
};
Client.prototype.get_ports = function( callback ) {
this.send_command( '/relais', GET, callback );
};
module.exports = {
Client: Client
};