dbus service: renaming parameters
[contrib/cloudeebus.git] / cloudeebus / cloudeebus.js
1 /******************************************************************************
2  * Copyright 2012 Intel Corporation.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  * http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *****************************************************************************/
16
17
18
19 /*****************************************************************************/
20
21 var dbus = { // hook object for dbus types not translated by python-json
22                 Double: function(value, level) {
23                         return value;
24                 }
25 };
26
27
28
29 /*****************************************************************************/
30
31 var cloudeebus = window.cloudeebus = {version: "0.2.1"};
32
33 cloudeebus.reset = function() {
34         cloudeebus.sessionBus = null;
35         cloudeebus.systemBus = null;
36         cloudeebus.wampSession = null;
37         cloudeebus.uri = null;
38 };
39
40
41 cloudeebus.log = function(msg) { 
42 };
43
44
45 cloudeebus.connect = function(uri, manifest, successCB, errorCB) {
46         cloudeebus.reset();
47         cloudeebus.uri = uri;
48         
49         function onCloudeebusVersionCheckCB(version) {
50                 if (cloudeebus.version == version) {
51                         cloudeebus.log("Connected to " + cloudeebus.uri);
52                         if (successCB)
53                                 successCB();
54                 } else {
55                         var errorMsg = "Cloudeebus server version " + version + " and client version " + cloudeebus.version + " mismatch";
56                         cloudeebus.log(errorMsg);
57                         if (errorCB)
58                                 errorCB(errorMsg);
59                 }
60         }
61         
62         function onWAMPSessionAuthErrorCB(error) {
63                 cloudeebus.log("Authentication error: " + error.desc);
64                 if (errorCB)
65                         errorCB(error.desc);
66         }
67         
68         function onWAMPSessionAuthenticatedCB(permissions) {
69                 cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
70                 cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
71                 cloudeebus.wampSession.call("getVersion").then(onCloudeebusVersionCheckCB, errorCB);
72         }
73         
74         function onWAMPSessionChallengedCB(challenge) {
75                 var signature = cloudeebus.wampSession.authsign(challenge, manifest.key);
76                 cloudeebus.wampSession.auth(signature).then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
77         }
78         
79         function onWAMPSessionConnectedCB(session) {
80                 cloudeebus.wampSession = session;
81                 if (manifest)
82                         cloudeebus.wampSession.authreq(
83                                         manifest.name, 
84                                         {permissions: JSON.stringify(manifest.permissions)}
85                                 ).then(onWAMPSessionChallengedCB, onWAMPSessionAuthErrorCB);
86                 else
87                         cloudeebus.wampSession.authreq().then(function() {
88                                 cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
89                                 }, onWAMPSessionAuthErrorCB);
90         }
91
92         function onWAMPSessionErrorCB(code, reason) {
93                 if (code == ab.CONNECTION_UNSUPPORTED) {
94                         cloudeebus.log("Browser is not supported");
95                 }
96                 else {
97                         cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
98                 }
99                 if (errorCB)
100                         errorCB(reason);
101         }
102
103         return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
104 };
105
106
107 cloudeebus.SessionBus = function() {
108         return cloudeebus.sessionBus;
109 };
110
111
112 cloudeebus.SystemBus = function() {
113         return cloudeebus.systemBus;
114 };
115
116
117
118 /*****************************************************************************/
119
120 cloudeebus.BusConnection = function(name, session) {
121         this.name = name;
122         this.wampSession = session;
123         this.service = null;
124         return this;
125 };
126
127
128 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
129         var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
130         if (introspectCB)
131                 proxy._introspect(introspectCB, errorCB);
132         return proxy;
133 };
134
135
136 cloudeebus.BusConnection.prototype.addService = function(serviceName, successCB, errorCB) {
137         var self = this;
138         
139         cloudeebusService = new cloudeebus.Service(this.wampSession, this, serviceName);
140         
141         function busServiceAddedSuccessCB(service) {
142                 self.service = service;
143                 if (successCB)
144                         successCB(cloudeebusService);
145         }
146         
147         function busServiceAddedErrorCB(error) {
148                 if (errorCB)
149                         errorCB();
150         }
151         
152         cloudeebusService.add(busServiceAddedSuccessCB, busServiceAddedErrorCB);
153 };
154
155
156 /*****************************************************************************/
157
158 cloudeebus.Service = function(session, busConnection, name) {
159         this.wampSession = session;
160         this.busConnection = busConnection; 
161         this.name = name;
162         this.isCreated = false;
163         return this;
164 };
165
166 cloudeebus.Service.prototype.add = function(successCB, errorCB) {
167         function ServiceAddSuccessCB(dbusService) {
168                 if (successCB) {
169                         try { // calling dbus hook object function for un-translated types
170                                 successCB(dbusService);
171                         }
172                         catch (e) {
173                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
174                         }
175                 }
176         }
177         
178         var arglist = [
179             this.busConnection,
180             this.name
181             ];
182
183         // call dbusSend with bus type, destination, object, message and arguments
184         this.wampSession.call("serviceAdd", arglist).then(ServiceAddSuccessCB, errorCB);
185 };
186
187 cloudeebus.Service.prototype.addAgent = function(objectPath, xmlTemplate, successCB, errorCB) {
188         function ServiceAddAgentSuccessCB(objPath) {
189                 if (successCB) {
190                         try { // calling dbus hook object function for un-translated types
191                                 successCB(objPath);
192                         }
193                         catch (e) {
194                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
195                         }
196                 }
197         }
198         
199         var arglist = [
200             objectPath,
201             xmlTemplate
202             ];
203
204         // call dbusSend with bus type, destination, object, message and arguments
205         this.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, errorCB);
206 };
207
208 cloudeebus.Service.prototype.delAgent = function(objectPath, successCB, errorCB) {
209         function ServiceDelAgentSuccessCB(agent) {
210                 if (successCB) {
211                         try { // calling dbus hook object function for un-translated types
212                                 successCB(agent);
213                         }
214                         catch (e) {
215                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
216                         }
217                 }
218         }
219         
220         var arglist = [
221             objectPath
222             ];
223
224         // call dbusSend with bus type, destination, object, message and arguments
225         this.wampSession.call("serviceDelAgent", arglist).then(ServiceDelAgentSuccessCB, errorCB);
226 };
227
228 cloudeebus.Service.prototype.registerMethod = function(methodId, methodHandler) {
229         this.wampSession.subscribe(methodId, methodHandler);
230 };
231
232 cloudeebus.Service.prototype.returnMethod = function(methodId, success, result, successCB, errorCB) {
233         var arglist = [
234             methodId,
235             success,
236             result
237             ];
238
239         this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
240 };
241
242
243 /*****************************************************************************/
244
245 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
246         this.wampSession = session; 
247         this.busConnection = busConnection; 
248         this.busName = busName; 
249         this.objectPath = objectPath; 
250         return this;
251 };
252
253
254 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
255         
256         var self = this; 
257
258         function getAllPropertiesSuccessCB(props) {
259                 for (var prop in props)
260                         self[prop] = props[prop];
261                 getAllPropertiesNextInterfaceCB();
262         }
263         
264         function getAllPropertiesNextInterfaceCB() {
265                 if (self.propInterfaces.length > 0) 
266                         self.callMethod("org.freedesktop.DBus.Properties", 
267                                 "GetAll", 
268                                 [self.propInterfaces.pop()], 
269                                 getAllPropertiesSuccessCB, 
270                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
271                 else {
272                         self.propInterfaces = null;
273                         if (successCB)
274                                 successCB(self);
275                 }
276         }
277         
278         function introspectSuccessCB(str) {
279                 var parser = new DOMParser();
280                 var xmlDoc = parser.parseFromString(str, "text/xml");
281                 var interfaces = xmlDoc.getElementsByTagName("interface");
282                 self.propInterfaces = [];
283                 var supportDBusProperties = false;
284                 for (var i=0; i < interfaces.length; i++) {
285                         var ifName = interfaces[i].attributes.getNamedItem("name").value;
286                         if (ifName == "org.freedesktop.DBus.Properties")
287                                 supportDBusProperties = true;
288                         var hasProperties = false;
289                         var ifChild = interfaces[i].firstChild;
290                         while (ifChild) {
291                                 if (ifChild.nodeName == "method") {
292                                         var nArgs = 0;
293                                         var metChild = ifChild.firstChild;
294                                         while (metChild) {
295                                                 if (metChild.nodeName == "arg" &&
296                                                         metChild.attributes.getNamedItem("direction").value == "in")
297                                                                 nArgs++;
298                                                 metChild = metChild.nextSibling;
299                                         }
300                                         self._addMethod(ifName, 
301                                                         ifChild.attributes.getNamedItem("name").value, 
302                                                         nArgs);
303                                 }
304                                 else if (ifChild.nodeName == "property") {
305                                         if (!hasProperties)
306                                                 self.propInterfaces.push(ifName);
307                                         hasProperties = true;
308                                 }
309                                 ifChild = ifChild.nextSibling;
310                         }
311                 }
312                 if (supportDBusProperties && self.propInterfaces.length > 0) {
313                         self.callMethod("org.freedesktop.DBus.Properties", 
314                                 "GetAll", 
315                                 [self.propInterfaces.pop()], 
316                                 getAllPropertiesSuccessCB, 
317                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
318                 }
319                 else {
320                         self.propInterfaces = null;
321                         if (successCB)
322                                 successCB(self);
323                 }
324         }
325
326         // call Introspect on self
327         self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", [], introspectSuccessCB, errorCB);
328 };
329
330
331 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs) {
332
333         var self = this;
334         
335         self[method] = function() {
336                 if (arguments.length < nArgs || arguments.length > nArgs + 2)
337                         throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
338                 var args = [];
339                 var successCB = null;
340                 var errorCB = null;
341                 for (var i=0; i < nArgs; i++ )
342                         args.push(arguments[i]);
343                 if (arguments.length > nArgs)
344                         successCB = arguments[nArgs];
345                 if (arguments.length > nArgs + 1)
346                         errorCB = arguments[nArgs + 1];
347                 self.callMethod(ifName, method, args, successCB, errorCB);
348         };
349         
350 };
351
352
353 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, successCB, errorCB) {
354         
355         var self = this; 
356
357         function callMethodSuccessCB(str) {
358                 if (successCB) {
359                         try { // calling dbus hook object function for un-translated types
360                                 successCB.apply(self, eval(str));
361                         }
362                         catch (e) {
363                                 cloudeebus.log("Method callback exception: " + e);
364                                 if (errorCB)
365                                         errorCB(e);
366                         }
367                 }
368         }
369
370         function callMethodErrorCB(error) {
371                 cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
372                 if (errorCB)
373                         errorCB(error.desc);
374         }
375
376         var arglist = [
377                 self.busConnection.name,
378                 self.busName,
379                 self.objectPath,
380                 ifName,
381                 method,
382                 JSON.stringify(args)
383         ];
384
385         // call dbusSend with bus type, destination, object, message and arguments
386         self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
387 };
388
389
390 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {
391         
392         var self = this; 
393
394         function signalHandler(id, data) {
395                 if (successCB) {
396                         try { // calling dbus hook object function for un-translated types
397                                 successCB.apply(self, eval(data));
398                         }
399                         catch (e) {
400                                 cloudeebus.log("Signal handler exception: " + e);
401                                 if (errorCB)
402                                         errorCB(e);
403                         }
404                 }
405         }
406         
407         function connectToSignalSuccessCB(str) {
408                 try {
409                         self.wampSession.subscribe(str, signalHandler);
410                 }
411                 catch (e) {
412                         cloudeebus.log("Subscribe error: " + e);
413                 }
414         }
415
416         function connectToSignalErrorCB(error) {
417                 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
418                 if (errorCB)
419                         errorCB(error.desc);
420         }
421
422         var arglist = [
423                 self.busConnection.name,
424                 self.busName,
425                 self.objectPath,
426                 ifName,
427                 signal
428         ];
429
430         // call dbusSend with bus type, destination, object, message and arguments
431         self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
432 };
433
434
435 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
436         try {
437                 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
438         }
439         catch (e) {
440                 cloudeebus.log("Unsubscribe error: " + e);
441         }
442 };