forked from pepperhacking/studiotoolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrobotutils.js
290 lines (262 loc) · 10.3 KB
/
robotutils.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
* robotutils.js version 0.3
*
* A utility library for naoqi;
*
* This library is a wrapper over qimessaging.js. Some advantages:
* - debugging and iterating are made easier by support for a
* ?robot=<my-robots-ip> query parameter in the URL, that allows
* you to open a local file and connect it to a remote robot.
* - there is some syntactic sugar over common calls that
* allows you to keep your logic simple without too much nesting
*
* You can of course directly use qimessaging.js instead.
*
* See the method documentations below for sample usage.
*
* Copyright Aldebaran Robotics
* Authors: [email protected], [email protected]
*/
RobotUtils = (function(self) {
/*---------------------------------------------
* Public API
*/
/* RobotUtils.onServices(servicesCallback, errorCallback)
*
* A function for using NAOqi services.
*
* "servicesCallback" should be a function whose arguments are the
* names of NAOqi services; the callback will be called
* with those services as parameters (or the errorCallback
* will be called with a reason).
*
* Sample usage:
*
* RobotUtils.onServices(function(ALLeds, ALTextToSpeech) {
* ALLeds.randomEyes(2.0);
* ALTextToSpeech.say("I can speak");
* });
*
* This is actually syntactic sugar over RobotUtils.connect() and
* some basic QiSession functions, so that the code stays simple.
*/
self.onServices = function(servicesCallback, errorCallback) {
self.connect(function(session) {
var wantedServices = getParamNames(servicesCallback);
var pendingServices = wantedServices.length;
var services = new Array(wantedServices.length);
var i;
wantedServices.forEach(function(serviceName, i) {
getService(session, serviceName, function(service) {
services[i] = service;
pendingServices -= 1;
if (pendingServices == 0) {
servicesCallback.apply(undefined, services);
}
}, function() {
var reason = "Failed getting a NaoQi Service: " +
serviceName;
console.log(reason);
if (errorCallback) {
errorCallback(reason);
}
});
});
}, errorCallback);
}
// alias, so that the code looks natural when there is only one service.
self.onService = self.onServices;
/* Helper to get services, and eventually retry if required.
*
*/
function getService(session, serviceName, onSuccess, onFailure) {
session.service(serviceName).then(
function(service) {
onSuccess(service);
},
function() {
// Failure: the service wasn't there
if ( waitableServices[serviceName] ) {
// It might be normal, try again in 200 ms.
console.log("Waiting for service " + serviceName);
setTimeout(function(){ getService(session,
serviceName, onSuccess, onFailure) }, 200);
}
else {
onFailure();
}
}
);
}
// services we want to wait when onServices is called
var waitableServices = {};
/* RobotUtils.setWaitableServices(serviceA, serviceB, ...)
*
* Flag some services as "to be awaited" - this means that if they
* are missing when RobotUtils.onServices(...) is called, if a
* service is missing then we will wait for it instead of failing.
*
* This is typically useful if you packaged your own service in your
* application and have launched it in parallel to showing a
* webpage, to handle the case where the page is ready before the
* service finished registering.
*/
self.setWaitableServices = function()
{
Array.prototype.slice.call(arguments).forEach(function(serviceName) {
waitableServices[serviceName] = true;
});
}
/* RobotUtils.subscribeToALMemoryEvent(event, eventCallback, subscribeDoneCallback)
*
* connects a callback to an ALMemory event. Returns a MemoryEventSubscription.
*
* This is just syntactic sugar over calls to the ALMemory service, which you can
* do yourself if you want finer control.
*/
self.subscribeToALMemoryEvent = function(event, eventCallback, subscribeDoneCallback) {
var evt = new MemoryEventSubscription(event);
self.onServices(function(ALMemory) {
ALMemory.subscriber(event).then(function (sub) {
evt.setSubscriber(sub)
sub.signal.connect(eventCallback).then(function(id) {
evt.setId(id);
if (subscribeDoneCallback) subscribeDoneCallback(id)
});
},
onALMemoryError);
});
return evt;
}
/* RobotUtils.connect(connectedCallback, failureCallback)
*
* connectedCallback should take a single argument, a NAOqi session object
*
* This function is mostly meant for internal use, for your app you
* should probably use the more specific RobotUtils.onServices or
* RobotUtils.subscribeToALMemoryEvent.
*
* There can be several calls to .connect() in parallel, only one
* session will be created.
*/
self.connect = function(connectedCallback, failureCallback) {
if (self.session) {
// We already have a session, don't create a new one
connectedCallback(self.session);
return;
}
else if (pendingConnectionCallbacks.length > 0) {
// A connection attempt is in progress, just add this callback to the queue
pendingConnectionCallbacks.push(connectedCallback);
return;
}
else {
// Add self to the queue, but create a new connection.
pendingConnectionCallbacks.push(connectedCallback);
}
var qimAddress = null;
var robotlibs = '/libs/';
if (self.robotIp) {
// Special case: we're doing remote debugging on a robot.
robotlibs = "http://" + self.robotIp + "/libs/";
qimAddress = self.robotIp + ":80";
}
function onConnected(session) {
self.session = session;
var numCallbacks = pendingConnectionCallbacks.length;
for (var i = 0; i < numCallbacks; i++) {
pendingConnectionCallbacks[i](session);
}
}
getScript(robotlibs + 'qimessaging/2/qimessaging.js', function() {
QiSession(
onConnected,
failureCallback,
qimAddress
)
}, function() {
if (self.robotIp) {
console.error("Failed to get qimessaging.js from robot: " + self.robotIp);
} else {
console.error("Failed to get qimessaging.js from this domain; host this app on a robot or add a ?robot=MY-ROBOT-IP to the URL.");
}
failureCallback();
});
}
// public variables that can be useful.
self.robotIp = _getRobotIp();
self.session = null;
/*---------------------------------------------
* Internal helper functions
*/
// Replacement for jQuery's getScript function
function getScript(source, successCallback, failureCallback) {
var script = document.createElement('script');
var prior = document.getElementsByTagName('script')[0];
script.async = 1;
prior.parentNode.insertBefore(script, prior);
script.onload = script.onreadystatechange = function( _, isAbort ) {
if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) {
script.onload = script.onreadystatechange = null;
script = undefined;
if(isAbort) {
if (failureCallback) failureCallback();
} else {
// Success!
if (successCallback) successCallback();
}
}
};
script.src = source;
}
function _getRobotIp() {
var regex = new RegExp("[\\?&]robot=([^&#]*)");
var results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ").replace("/", ""));
}
// Helper for getting the parameters from a function.
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function getParamNames(func) {
var fnStr = func.toString().replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(/([^\s,]+)/g);
if(result === null)
result = [];
return result;
};
// ALMemory helpers (event subscription requires a lot of boilerplate)
function MemoryEventSubscription(event) {
this._event = event;
this._internalId = null;
this._sub = null;
this._unsubscribe = false;
}
MemoryEventSubscription.prototype.setId = function(id) {
this._internalId = id;
// as id can be receveid after unsubscribe call, defere
if (this._unsubscribe) this.unsubscribe(this._unsubscribeCallback);
}
MemoryEventSubscription.prototype.setSubscriber = function(sub) {
this._sub = sub;
// as sub can be receveid after unsubscribe call, defere
if (this._unsubscribe) this.unsubscribe(this._unsubscribeCallback);
}
MemoryEventSubscription.prototype.unsubscribe = function(unsubscribeDoneCallback)
{
if (this._internalId != null && this._sub != null) {
evtSubscription = this;
evtSubscription._sub.signal.disconnect(evtSubscription._internalId).then(function() {
if (unsubscribeDoneCallback) unsubscribeDoneCallback();
}).fail(onALMemoryError);
}
else
{
this._unsubscribe = true;
this._unsubscribeCallback = unsubscribeDoneCallback;
}
}
var onALMemoryError = function(errMsg) {
console.log("ALMemory error: " + errMsg);
}
var pendingConnectionCallbacks = [];
return self;
})(window.RobotUtils || {});