This repository was archived by the owner on Jun 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdevice.js
More file actions
107 lines (93 loc) · 2.75 KB
/
device.js
File metadata and controls
107 lines (93 loc) · 2.75 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
var util = require( 'util' );
var events = require('events');
var http = require('http');
var Device = function(options){
events.EventEmitter.call(this);
var self = this;
self.config = options;
this.init();
};
var jsonRpcQuery = function(host, port, method, callback) {
var params = method;
var paramsString = JSON.stringify(params);
var headers = {
'Content-Type': 'application/json',
'Content-Length': paramsString.length
};
var options = {
host: host,
port: port,
path: '/jsonrpc',
method: 'POST',
headers: headers
};
var req = http.request(options, function(res) {
res.setEncoding('utf-8');
var response = '';
res.on('data', function(data) {
response += data;
});
res.on('end', function() {
var result;
try {
result = JSON.parse(response);
} catch (err) {
callback({status: 'error'});
}
if( !('result' in result) && result.result !== 'ok' ) {
callback({status: 'error'});
}
else {
callback({status: 'success'});
}
});
});
req.on('error', function(e) {
callback({status: 'error'});
});
req.write(paramsString);
req.end();
};
exports.Device = Device;
util.inherits( Device, events.EventEmitter );
Device.prototype.init = function(){
var self = this;
self.host = self.config.addresses[0];
self.port = self.config.port;
self.name = self.config.name;
self.playing = false;
};
Device.prototype.play = function(resource, callback){
var self = this;
var method = {"jsonrpc": "2.0","id": "1","method": "Player.Open","params": {"item": {"file": resource}}};
jsonRpcQuery(self.host, self.port, method, function(result) {
if( result.status !== 'error' ) {
self.playing = true;
if(callback){
callback(result.status);
}
}
});
};
Device.prototype.input = function(resource, callback){
var self = this;
var method = {"jsonrpc": "2.0","id": "1","method": resource};
jsonRpcQuery(self.host, self.port, method, function(result) {
if( result.status !== 'error' ) {
if(callback){
callback(result.status);
}
}
});
};
Device.prototype.player = function(resource, callback){
var self = this;
var method = {"jsonrpc": "2.0", "method": resource, "params": { "playerid": 0 }, "id": 1};
jsonRpcQuery(self.host, self.port, method, function(result) {
if( result.status !== 'error' ) {
if(callback){
callback(result.status);
}
}
});
};