-
Notifications
You must be signed in to change notification settings - Fork 0
/
JMRIService.js
78 lines (57 loc) · 1.78 KB
/
JMRIService.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
'use strict'
var WebSocketClient = require('websocket').client;
var Promise = require("bluebird");
function JMRIService(ip, commandBuilder) {
var self = this;
self.serveIP = ip;
self.commandBuilder = commandBuilder;
var server = new WebSocketClient();
server.on('connect', connectHandler.bind(self));
server.on('connectFailed', function (error) {
console.log('Connect Error: ' + error.toString());
}
);
server.connect('ws://' + ip + ':12080/json/');
this.server = server;
}
var connectHandler = function(connection) {
var self = this;
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function() {
console.log('echo-protocol Connection Closed');
});
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received: '" + message.utf8Data + "'");
}
});
self.connection = connection;
self.init();
};
JMRIService.prototype.send = function (message) {
var self = this;
console.log('Sent: ' + message);
return new Promise(function (resolve, reject) {
if (self.connection.connected) {
self.connection.sendUTF(message);
resolve();
}
}).delay(1000);
};
JMRIService.prototype.init = function () {
var self = this;
self.send(self.commandBuilder.fillTemplate('set_address'));
self.send(self.commandBuilder.fillTemplate('power'));
setInterval(self.beat.bind(self), 1000);
};
JMRIService.prototype.stop = function () {
var self = this;
self.send(self.commandBuilder.fillTemplate('emergency_stop'));
};
JMRIService.prototype.beat = function () {
var self = this;
self.send(self.commandBuilder.fillTemplate('ping'))
}
module.exports = JMRIService;