1 /******************************************************************************
2 * Copyright 2012 Intel Corporation.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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 *****************************************************************************/
19 /*****************************************************************************/
21 var dbus = { // hook object for dbus types not translated by python-json
22 Double: function(value, level) {
29 /*****************************************************************************/
31 var cloudeebus = window.cloudeebus = {
36 cloudeebus.reset = function() {
37 cloudeebus.sessionBus = null;
38 cloudeebus.systemBus = null;
39 cloudeebus.wampSession = null;
40 cloudeebus.uri = null;
44 cloudeebus.log = function(msg) {
48 cloudeebus.versionCheck = function(version) {
49 var ver = version.split(".");
50 var min = cloudeebus.minVersion.split(".");
51 for (var i=0; i<ver.length; i++) {
52 if (Number(ver[i]) > Number(min[i]))
54 if (Number(ver[i]) < Number(min[i]))
61 cloudeebus.connect = function(uri, manifest, successCB, errorCB) {
65 function onCloudeebusVersionCheckCB(version) {
66 if (cloudeebus.versionCheck(version)) {
67 cloudeebus.log("Connected to " + cloudeebus.uri);
71 var errorMsg = "Cloudeebus server version " + version + " unsupported, need version " + cloudeebus.minVersion + " or superior";
72 cloudeebus.log(errorMsg);
78 function onWAMPSessionAuthErrorCB(error) {
79 cloudeebus.log("Authentication error: " + error.desc);
84 function onWAMPSessionAuthenticatedCB(permissions) {
85 cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
86 cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
87 cloudeebus.wampSession.call("getVersion").then(onCloudeebusVersionCheckCB, errorCB);
90 function onWAMPSessionChallengedCB(challenge) {
91 var signature = cloudeebus.wampSession.authsign(challenge, manifest.key);
92 cloudeebus.wampSession.auth(signature).then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
95 function onWAMPSessionConnectedCB(session) {
96 cloudeebus.wampSession = session;
98 cloudeebus.wampSession.authreq(
100 {permissions: manifest.permissions}
101 ).then(onWAMPSessionChallengedCB, onWAMPSessionAuthErrorCB);
103 cloudeebus.wampSession.authreq().then(function() {
104 cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
105 }, onWAMPSessionAuthErrorCB);
108 function onWAMPSessionErrorCB(code, reason) {
109 if (code == ab.CONNECTION_UNSUPPORTED) {
110 cloudeebus.log("Browser is not supported");
113 cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
119 return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
123 cloudeebus.SessionBus = function() {
124 return cloudeebus.sessionBus;
128 cloudeebus.SystemBus = function() {
129 return cloudeebus.systemBus;
134 /*****************************************************************************/
136 cloudeebus.BusConnection = function(name, session) {
138 this.wampSession = session;
144 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
145 var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
147 proxy._introspect(introspectCB, errorCB);
152 cloudeebus.BusConnection.prototype.addService = function(serviceName) {
156 var future = new cloudeebus.Future(function (resolver) {
157 cloudeebusService = new cloudeebus.Service(self.wampSession, self, serviceName);
159 function busServiceAddedSuccessCB(service) {
160 self.service = cloudeebusService;
162 var result = [cloudeebusService];
163 resolver.accept(result[0], true);
166 cloudeebus.log("Method callback exception: " + e);
167 resolver.reject(e, true);
171 function busServiceErrorSuccessCB(error) {
173 resolver.reject(error, true);
176 cloudeebusService.add(this).then(busServiceAddedSuccessCB, busServiceErrorSuccessCB);
182 cloudeebus.BusConnection.prototype.removeService = function(serviceName, successCB, errorCB) {
185 function busServiceRemovedSuccessCB(serviceName) {
186 // Be sure we are removing the service requested...
187 if (serviceName == self.service.name) {
190 successCB(serviceName);
194 cloudeebusService.remove(busServiceRemovedSuccessCB, errorCB);
198 /*****************************************************************************/
200 cloudeebus.Service = function(session, busConnection, name) {
201 this.wampSession = session;
202 this.busConnection = busConnection;
204 this.isCreated = false;
208 cloudeebus.Service.prototype.add = function(future) {
210 self.future = future;
212 function ServiceAddedSuccessCB(serviceName) {
213 try { // calling dbus hook object function for un-translated types
214 var resolver = self.future.resolver;
216 resolver.accept(result[0], true);
219 cloudeebus.log("Method callback exception: " + e);
220 resolver.reject(e, true);
224 function ServiceAddedErrorCB(error) {
225 cloudeebus.log("Error adding service method: " + self.name + ", error: " + error.desc);
226 self.future.resolver.reject(error.desc, true);
234 // call dbusSend with bus type, destination, object, message and arguments
235 this.wampSession.call("serviceAdd", arglist).then(ServiceAddedSuccessCB, ServiceAddedErrorCB);
239 cloudeebus.Service.prototype.remove = function(successCB, errorCB) {
240 function ServiceRemovedSuccessCB(serviceName) {
243 successCB(serviceName);
246 alert("Exception removing service " + serviceName + " : " + e);
255 // call dbusSend with bus type, destination, object, message and arguments
256 this.wampSession.call("serviceRelease", arglist).then(ServiceRemovedSuccessCB, errorCB);
259 cloudeebus.Service.prototype._searchMethod = function(ifName, method, objectJS) {
261 var funcToCall = null;
263 // Check if 'objectJS' has a member 'interfaceProxies' with an interface named 'ifName'
264 // and a method named 'method'
265 if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName] &&
266 objectJS.interfaceProxies[ifName][method]) {
267 funcToCall = objectJS.interfaceProxies[ifName][method];
269 // retrieve the method directly from 'root' of objectJs
270 funcToCall = objectJS[method];
276 cloudeebus.Service.prototype._addMethod = function(objectPath, ifName, method, objectJS) {
279 var methodId = this.name + "#" + objectPath + "#" + ifName + "#" + method;
280 var funcToCall = this._searchMethod(ifName, method, objectJS);
282 if (funcToCall == null)
283 cloudeebus.log("Method " + method + " doesn't exist in Javascript object");
285 objectJS.wrapperFunc[method] = function() {
287 var methodId = arguments[0];
289 // affectation of callDict in eval, otherwise dictionary(='{}') interpreted as block of code by eval
290 eval("callDict = " + arguments[1]);
292 result = funcToCall.apply(objectJS, callDict.args);
293 service._returnMethod(methodId, callDict.callIndex, true, result);
296 cloudeebus.log("Method " + ifName + "." + method + " call on " + objectPath + " exception: " + e);
297 service._returnMethod(methodId, callDict.callIndex, false, e.message);
300 this._registerMethod(methodId, objectJS.wrapperFunc[method]);
304 cloudeebus.Service.prototype._addSignal = function(objectPath, ifName, signal, objectJS) {
306 var methodExist = false;
308 if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName])
309 if (objectJS.interfaceProxies[ifName][signal]) {
312 objectJS.interfaceProxies[ifName][signal] = function() {
313 service.emitSignal(objectPath, signal, arguments[0]);
318 if ((objectJS[signal] == undefined || objectJS[signal] == null) && !methodExist)
319 objectJS[signal] = function() {
320 service.emitSignal(objectPath, signal, arguments[0]);
323 cloudeebus.log("Can not create new method to emit signal '" + signal + "' in object JS this method already exist!");
326 cloudeebus.Service.prototype._createWrapper = function(xmlTemplate, objectPath, objectJS) {
328 var parser = new DOMParser();
329 var xmlDoc = parser.parseFromString(xmlTemplate, "text/xml");
330 var ifXml = xmlDoc.getElementsByTagName("interface");
331 objectJS.wrapperFunc = [];
332 for (var i=0; i < ifXml.length; i++) {
333 var ifName = ifXml[i].attributes.getNamedItem("name").value;
334 var ifChild = ifXml[i].firstChild;
336 if (ifChild.nodeName == "method") {
337 var metName = ifChild.attributes.getNamedItem("name").value;
338 self._addMethod(objectPath, ifName, metName, objectJS);
340 if (ifChild.nodeName == "signal") {
341 var metName = ifChild.attributes.getNamedItem("name").value;
342 self._addSignal(objectPath, ifName, metName, objectJS);
344 ifChild = ifChild.nextSibling;
349 cloudeebus.Service.prototype.addAgent = function(objectPath, xmlTemplate, objectJS, successCB, errorCB) {
350 function ServiceAddAgentSuccessCB(objPath) {
356 alert("Exception adding agent " + objectPath + " : " + e);
362 this._createWrapper(xmlTemplate, objectPath, objectJS);
365 alert("Exception creating agent wrapper " + objectPath + " : " + e);
375 // call dbusSend with bus type, destination, object, message and arguments
376 this.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, errorCB);
379 cloudeebus.Service.prototype.delAgent = function(objectPath, successCB, errorCB) {
380 function ServiceDelAgentSuccessCB(agent) {
386 alert("Exception deleting agent " + objectPath + " : " + e);
395 // call dbusSend with bus type, destination, object, message and arguments
396 this.wampSession.call("serviceDelAgent", arglist).then(ServiceDelAgentSuccessCB, errorCB);
399 cloudeebus.Service.prototype._registerMethod = function(methodId, methodHandler) {
400 this.wampSession.subscribe(methodId, methodHandler);
403 cloudeebus.Service.prototype._returnMethod = function(methodId, callIndex, success, result, successCB, errorCB) {
411 this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
414 cloudeebus.Service.prototype.emitSignal = function(objectPath, signalName, result, successCB, errorCB) {
421 this.wampSession.call("emitSignal", arglist).then(successCB, errorCB);
425 /*****************************************************************************/
427 function _processWrappers(wrappers, value) {
428 for (var i=0; i<wrappers.length; i++)
433 function _processWrappersAsync(wrappers, value) {
435 function processAsyncOnce() {
436 _processWrappers(wrappers, value);
437 clearInterval(taskid);
439 taskid = setInterval(processAsyncOnce, 200);
444 /*****************************************************************************/
446 cloudeebus.FutureResolver = function(future) {
447 this.future = future;
448 this.resolved = null;
453 cloudeebus.FutureResolver.prototype.resolve = function(value, sync) {
457 var then = (value && value.then && value.then.apply) ? value.then : null;
460 var acceptCallback = function(arg) {
461 self.resolve(arg, true);
463 var rejectCallback = function(arg) {
464 self.reject(arg, true);
467 then.apply(value, [acceptCallback, rejectCallback]);
470 this.reject(e, true);
474 this.accept(value, sync);
478 cloudeebus.FutureResolver.prototype.accept = function(value, sync) {
482 var future = this.future;
483 future.state = "accepted";
484 future.result = value;
486 this.resolved = true;
488 _processWrappers(future._acceptWrappers, value);
490 _processWrappersAsync(future._acceptWrappers, value);
494 cloudeebus.FutureResolver.prototype.reject = function(value, sync) {
498 var future = this.future;
499 future.state = "rejected";
500 future.result = value;
502 this.resolved = true;
504 _processWrappers(future._rejectWrappers, value);
506 _processWrappersAsync(future._rejectWrappers, value);
511 /*****************************************************************************/
513 cloudeebus.Future = function(init) {
514 this.state = "pending";
516 this._acceptWrappers = [];
517 this._rejectWrappers = [];
518 this.resolver = new cloudeebus.FutureResolver(this);
521 init.apply(this, [this.resolver]);
524 this.resolver.reject(e, true);
531 cloudeebus.Future.prototype.appendWrappers = function(acceptWrapper, rejectWrapper) {
532 this._acceptWrappers.push(acceptWrapper);
533 this._rejectWrappers.push(rejectWrapper);
534 if (this.state == "accepted")
535 _processWrappersAsync(this._acceptWrappers, this.result);
536 if (this.state == "rejected")
537 _processWrappersAsync(this._rejectWrappers, this.result);
541 cloudeebus.Future.prototype.then = function(acceptCB, rejectCB) {
542 var future = new cloudeebus.Future();
543 var resolver = future.resolver;
544 var acceptWrapper, rejectWrapper;
547 acceptWrapper = function(arg) {
549 var value = acceptCB.apply(future, [arg]);
550 resolver.resolve(value, true);
553 resolver.reject(e, true);
557 acceptWrapper = function(arg) {
558 resolver.accept(arg, true);
562 rejectWrapper = function(arg) {
564 var value = rejectCB.apply(future, [arg]);
565 resolver.resolve(value, true);
568 resolver.reject(e, true);
572 rejectWrapper = function(arg) {
573 resolver.reject(arg, true);
576 this.appendWrappers(acceptWrapper,rejectWrapper);
582 /*****************************************************************************/
584 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
585 this.wampSession = session;
586 this.busConnection = busConnection;
587 this.busName = busName;
588 this.objectPath = objectPath;
589 this.interfaceProxies = {};
594 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
595 return this.interfaceProxies[ifName];
599 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
603 function getAllPropertiesSuccessCB(props) {
604 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
605 for (var prop in props)
606 ifProxy[prop] = self[prop] = props[prop];
607 getAllPropertiesNextInterfaceCB();
610 function getAllPropertiesNextInterfaceCB() {
611 self.propInterfaces.pop();
612 if (self.propInterfaces.length > 0)
613 self.callMethod("org.freedesktop.DBus.Properties",
615 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB,
616 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
618 self.propInterfaces = null;
624 function introspectSuccessCB(str) {
625 var parser = new DOMParser();
626 var xmlDoc = parser.parseFromString(str, "text/xml");
627 var interfaces = xmlDoc.getElementsByTagName("interface");
628 self.propInterfaces = [];
629 var supportDBusProperties = false;
630 for (var i=0; i < interfaces.length; i++) {
631 var ifName = interfaces[i].attributes.getNamedItem("name").value;
632 self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
633 if (ifName == "org.freedesktop.DBus.Properties")
634 supportDBusProperties = true;
635 var hasProperties = false;
636 var ifChild = interfaces[i].firstChild;
638 if (ifChild.nodeName == "method") {
641 var metChild = ifChild.firstChild;
643 if (metChild.nodeName == "arg" &&
644 metChild.attributes.getNamedItem("direction").value == "in") {
645 signature += metChild.attributes.getNamedItem("type").value;
648 metChild = metChild.nextSibling;
650 var metName = ifChild.attributes.getNamedItem("name").value;
652 self._addMethod(ifName, metName, nArgs, signature);
653 self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs, signature);
655 else if (ifChild.nodeName == "property") {
657 self.propInterfaces.push(ifName);
658 hasProperties = true;
660 ifChild = ifChild.nextSibling;
663 if (supportDBusProperties && self.propInterfaces.length > 0) {
664 self.callMethod("org.freedesktop.DBus.Properties",
666 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB,
667 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
670 self.propInterfaces = null;
676 // call Introspect on self
677 self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", []).then(introspectSuccessCB, errorCB);
681 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs, signature) {
685 self[method] = function() {
687 for (var i=0; i < nArgs; i++ )
688 args.push(arguments[i]);
689 return self.callMethod(ifName, method, args, signature);
694 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, signature) {
698 var future = new cloudeebus.Future(function (resolver) {
699 function callMethodSuccessCB(str) {
700 try { // calling dbus hook object function for un-translated types
701 var result = eval(str);
702 resolver.accept(result[0], true);
705 cloudeebus.log("Method callback exception: " + e);
706 resolver.reject(e, true);
710 function callMethodErrorCB(error) {
711 cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
712 resolver.reject(error.desc, true);
716 self.busConnection.name,
724 // call dbusSend with bus type, destination, object, message and arguments
725 self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
732 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {
736 function signalHandler(id, data) {
738 try { // calling dbus hook object function for un-translated types
739 successCB.apply(self, eval(data));
742 cloudeebus.log("Signal handler exception: " + e);
749 function connectToSignalSuccessCB(str) {
751 self.wampSession.subscribe(str, signalHandler);
754 cloudeebus.log("Subscribe error: " + e);
758 function connectToSignalErrorCB(error) {
759 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
765 self.busConnection.name,
772 // call dbusSend with bus type, destination, object, message and arguments
773 self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
777 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
779 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
782 cloudeebus.log("Unsubscribe error: " + e);