forked from LCAS/rosbridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ros.js
107 lines (90 loc) · 2.39 KB
/
ros.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
var ros = ros || {};
var Connection = function(url) {
this.handlers = new Array();
this.marshall = function(data) {
return data
};
if (typeof JSON.stringify != 'undefined') {
this.marshall = function(data) {
if (typeof data == 'string')
return data;
return JSON.stringify(data);
}
}
var parse = function(data) {
var call = '';
eval('call = ' + data);
return call;
}
if (typeof JSON.parse != 'undefined')
parse = JSON.parse;
if (typeof WebSocket == 'undefined') {
WebSocket = MozWebSocket;
}
this.socket = new WebSocket(url);
this.onmessage = null;
var ths = this;
this.socket.onmessage = function(e) {
if (ths.onmessage) {
try {
ths.onmessage(e);
} catch (err) {
ros_debug(err);
}
}
var call = '';
try {
call = parse(e.data);
} catch (err) {
return;
}
for ( var i in ths.handlers[call.receiver]) {
var handler = ths.handlers[call.receiver][i]
handler(call.msg);
}
}
this.magicServices = new Array('/rosbridge/topics', '/rosbridge/services',
'/rosbridge/typeStringFromTopic',
'/rosbridge/typeStringFromService',
'/rosbridge/msgClassFromTypeString',
'/rosbridge/reqClassFromTypeString',
'/rosbridge/rspClassFromTypeString', '/rosbridge/classFromTopic',
'/rosbridge/classesFromService');
}
Connection.prototype.callService = function(service, payload, callback) {
this.handlers[service] = new Array(callback);
var call = '{"receiver":"' + service + '"';
call += ',"msg":' + this.marshall(payload) + '}';
this.socket.send(call);
}
Connection.prototype.publish = function(topic, typeStr, payload) {
typeStr.replace(/^\//, '');
var call = '{"receiver":"' + topic + '"';
call += ',"msg":' + this.marshall(payload);
call += ',"type":"' + typeStr + '"}';
this.socket.send(call);
}
Connection.prototype.addHandler = function(topic, func) {
if (!(topic in this.handlers)) {
this.handlers[topic] = new Array();
}
this.handlers[topic].push(func);
}
Connection.prototype.removeHandler = function(topic) {
if (topic in this.handlers) {
this.handlers[topic] = [];
}
}
Connection.prototype.setOnError = function(func) {
this.socket.onerror = func;
}
Connection.prototype.setOnClose = function(func) {
this.socket.onclose = func;
}
Connection.prototype.setOnOpen = function(func) {
this.socket.onopen = func;
}
Connection.prototype.setOnMessage = function(func) {
this.onmessage = func;
}
ros.Connection = Connection;