forked from OpenEVSE/node-openevse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpenEVSEDriverHttp.js
55 lines (47 loc) · 1.43 KB
/
OpenEVSEDriverHttp.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
/* jshint node: true, esversion: 6*/
"use strict";
const OpenEVSEDriver = require("./OpenEVSEDriver");
const OpenEVSEError = require("./OpenEVSEError");
const OpenEVSERequest = require("./OpenEVSERequest");
//const debug = require("debug")("openevse:OpenEVSEDriverHttp");
module.exports = class OpenEVSEDriverHttp extends OpenEVSEDriver
{
constructor(endpoint)
{
super();
this._endpoint = endpoint;
if (endpoint.substring(0, 5) === "https") { this.http = require("https"); }
else { this.http = require("http"); }
}
rapi(command, callback = () => {})
{
var request = new OpenEVSERequest();
var url = this._endpoint + "?json=1&rapi="+encodeURI(command);
this.http.get(url, (res) => {
res.setEncoding("utf8");
var body = "";
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
var data;
try {
data = JSON.parse(body);
callback(data.ret);
request._always();
}
catch (e) {
request._error(new OpenEVSEError("BadBody", body));
request._always();
}
}).on("error", () => {
request._error(new OpenEVSEError("RequestFailed"));
request._always();
}).setTimeout(6000, () => {
request._error(new OpenEVSEError("HTTPTimeout"));
request._always();
});
});
return request;
}
};