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) {
47 cloudeebus.getError = function(error) {
48 if (error.desc && error.uri)
49 return error.desc + " : " + error.uri; // Python exception (cloudeebus.py)
54 if (error.name && error.message)
55 return error.name + " : " + error.message; // Javascript exception
60 return error; // Autobahn error
63 cloudeebus.versionCheck = function(version) {
64 var ver = version.split(".");
65 var min = cloudeebus.minVersion.split(".");
66 for (var i=0; i<ver.length; i++) {
67 if (Number(ver[i]) > Number(min[i]))
69 if (Number(ver[i]) < Number(min[i]))
76 cloudeebus.connect = function(uri, manifest, successCB, errorCB) {
80 function onCloudeebusVersionCheckCB(version) {
81 if (cloudeebus.versionCheck(version)) {
82 cloudeebus.log("Connected to " + cloudeebus.uri);
86 var errorMsg = "Cloudeebus server version " + version + " unsupported, need version " + cloudeebus.minVersion + " or superior";
87 cloudeebus.log(errorMsg);
93 function onWAMPSessionAuthErrorCB(error) {
94 var errorStr = cloudeebus.getError(error);
95 cloudeebus.log("Authentication error: " + errorStr);
100 function onWAMPSessionAuthenticatedCB(permissions) {
101 cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
102 cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
103 cloudeebus.wampSession.call("getVersion").then(onCloudeebusVersionCheckCB, errorCB);
106 function onWAMPSessionChallengedCB(challenge) {
107 var signature = cloudeebus.wampSession.authsign(challenge, manifest.key);
108 cloudeebus.wampSession.auth(signature).then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
111 function onWAMPSessionConnectedCB(session) {
112 cloudeebus.wampSession = session;
114 cloudeebus.wampSession.authreq(
116 {permissions: manifest.permissions,
117 services: manifest.services}
118 ).then(onWAMPSessionChallengedCB, onWAMPSessionAuthErrorCB);
121 cloudeebus.wampSession.authreq().then(function() {
122 cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
123 }, onWAMPSessionAuthErrorCB);
126 function onWAMPSessionErrorCB(code, reason) {
127 if (code == ab.CONNECTION_UNSUPPORTED) {
128 cloudeebus.log("Browser is not supported");
131 cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
137 return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
141 cloudeebus.SessionBus = function() {
142 return cloudeebus.sessionBus;
146 cloudeebus.SystemBus = function() {
147 return cloudeebus.systemBus;
152 /*****************************************************************************/
154 cloudeebus.BusConnection = function(name, session) {
156 this.wampSession = session;
161 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
162 var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
164 proxy._introspect(introspectCB, errorCB);
169 cloudeebus.BusConnection.prototype.addService = function(serviceName) {
175 var promise = new cloudeebus.Promise(function (resolver) {
176 var cloudeebusService = new cloudeebus.Service(self.wampSession, self, serviceName);
178 function ServiceAddedSuccessCB(serviceName) {
180 cloudeebusService.isCreated = true;
181 resolver.fulfill(cloudeebusService, true);
184 var errorStr = cloudeebus.getError(e);
185 cloudeebus.log("Method callback exception: " + errorStr);
186 resolver.reject(errorStr, true);
190 function ServiceAddedErrorCB(error) {
191 var errorStr = cloudeebus.getError(error);
192 cloudeebus.log("Error adding service method: " + self.name + ", error: " + errorStr);
193 resolver.reject(errorStr, true);
201 // call dbusSend with bus type, destination, object, message and arguments
202 self.wampSession.call("serviceAdd", arglist).then(ServiceAddedSuccessCB, ServiceAddedErrorCB);
210 /*****************************************************************************/
211 //Generic definition for an agent. An agent needs :
212 //srvDbusName : the DBus parent service
213 //objPath : a DBus path to access it
214 //jsHdl : a Javascript handler to process methods,
215 //xml : the xml which describe interface/methods/signals...
216 cloudeebus.Agent = function(srvDbusName, objPath, jsHdl, xml) {
217 this.srvName = srvDbusName;
218 this.registered = false;
220 this.objectPath = objPath;
226 cloudeebus.Service = function(session, busConnection, name) {
227 this.wampSession = session;
228 this.busConnection = busConnection;
231 this.isCreated = false;
236 cloudeebus.Service.prototype.remove = function() {
239 var promise = new cloudeebus.Promise(function (resolver) {
240 function ServiceRemovedSuccessCB(serviceName) {
242 resolver.fulfill(serviceName, true);
245 var errorStr = cloudeebus.getError(e);
246 cloudeebus.log("Method callback exception: " + errorStr);
247 resolver.reject(errorStr, true);
251 function ServiceRemovedErrorCB(error) {
252 var errorStr = cloudeebus.getError(error);
253 cloudeebus.log("Error removing service : " + self.name + ", error: " + errorStr);
254 self.promise.resolver.reject(errorStr, true);
257 for (var idx in self.agents) {
258 if (self.agents[idx]) {
259 self.removeAgent(self.agents[idx]);
267 // call dbusSend with bus type, destination, object, message and arguments
268 self.wampSession.call("serviceRelease", arglist).then(ServiceRemovedSuccessCB, ServiceRemovedErrorCB);
275 cloudeebus.Service.prototype._searchMethod = function(ifName, method, objectJS) {
277 var funcToCall = null;
279 // Check if 'objectJS' has a member 'interfaceProxies' with an interface named 'ifName'
280 // and a method named 'method'
281 if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName] &&
282 objectJS.interfaceProxies[ifName][method]) {
283 funcToCall = objectJS.interfaceProxies[ifName][method];
285 // retrieve the method directly from 'root' of objectJs
286 funcToCall = objectJS[method];
293 cloudeebus.Service.prototype._addMethod = function(ifName, method, agent) {
296 var methodId = this.name + "#" + agent.objectPath + "#" + ifName + "#" + method;
297 var funcToCall = this._searchMethod(ifName, method, agent.jsHdl);
299 if (funcToCall == null)
300 cloudeebus.log("Method " + method + " doesn't exist in Javascript object");
302 agent.jsHdl.wrapperFunc[method] = function() {
304 var methodId = arguments[0];
306 // affectation of callDict in eval, otherwise dictionary(='{}') interpreted as block of code by eval
307 eval("callDict = " + arguments[1]);
309 result = funcToCall.apply(agent.jsHdl, callDict.args);
310 service._returnMethod(methodId, callDict.callIndex, true, result);
313 var errorStr = cloudeebus.getError(e);
314 cloudeebus.log("Method " + ifName + "." + method + " call on " + agent.objectPath + " exception: " + errorStr);
315 service._returnMethod(methodId, callDict.callIndex, false, errorStr);
318 agent.jsHdl.methodId[agent.objectPath].push(methodId);
319 this.wampSession.subscribe(methodId, agent.jsHdl.wrapperFunc[method]);
324 cloudeebus.Service.prototype._addSignal = function(ifName, signal, agent) {
326 var methodExist = false;
328 if (agent.jsHdl.interfaceProxies && agent.jsHdl.interfaceProxies[ifName])
329 if (agent.jsHdl.interfaceProxies[ifName][signal]) {
332 agent.jsHdl.interfaceProxies[ifName][signal] = function() {
333 service._emitSignal(agent.objectPath, signal, arguments[0]);
338 if ((agent.jsHdl[signal] == undefined || agent.jsHdl[signal] == null) && !methodExist)
339 agent.jsHdl[signal] = function() {
340 service._emitSignal(agent.objectPath, signal, arguments[0]);
343 cloudeebus.log("Can not create new method to emit signal '" + signal + "' in object JS this method already exist!");
347 cloudeebus.Service.prototype._createWrapper = function(agent) {
349 var parser = new DOMParser();
350 var xmlDoc = parser.parseFromString(agent.xml, "text/xml");
351 var ifXml = xmlDoc.getElementsByTagName("interface");
352 agent.jsHdl.wrapperFunc = [];
353 agent.jsHdl.methodId = [];
354 agent.jsHdl.methodId[agent.objectPath] = [];
355 for (var i=0; i < ifXml.length; i++) {
356 var ifName = ifXml[i].attributes.getNamedItem("name").value;
357 var ifChild = ifXml[i].firstChild;
359 if (ifChild.nodeName == "method") {
360 var metName = ifChild.attributes.getNamedItem("name").value;
361 self._addMethod(ifName, metName, agent);
363 if (ifChild.nodeName == "signal") {
364 var metName = ifChild.attributes.getNamedItem("name").value;
365 self._addSignal(ifName, metName, agent);
367 ifChild = ifChild.nextSibling;
373 cloudeebus.Service.prototype.addAgent = function(agent) {
376 var promise = new cloudeebus.Promise(function (resolver) {
377 function ServiceAddAgentSuccessCB(objPath) {
378 try { // calling dbus hook object function for un-translated types
379 self.agents.push(agent);
380 agent.registered = true;
381 resolver.fulfill(objPath, true);
384 var errorStr = cloudeebus.getError(e);
385 cloudeebus.log("Method callback exception: " + errorStr);
386 resolver.reject(errorStr, true);
390 function ServiceAddAgenterrorCB(error) {
391 var errorStr = cloudeebus.getError(error);
392 cloudeebus.log("Error adding agent : " + agent.objectPath + ", error: " + errorStr);
393 self.promise.resolver.reject(errorStr, true);
397 self._createWrapper(agent);
400 var errorStr = cloudeebus.getError(e);
401 cloudeebus.log("Exception creating agent wrapper " + agent.objectPath + " : " + errorStr);
402 resolver.reject(errorStr, true);
411 // call dbusSend with bus type, destination, object, message and arguments
412 self.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, ServiceAddAgenterrorCB);
419 cloudeebus.Service.prototype._deleteWrapper = function(agent) {
420 var objJs = agent.jsHdl;
421 if (objJs.methodId[agent.objectPath]) {
422 for (var idx in objJs.methodId[agent.objectPath]) {
424 cloudeebus.log("unsubscribe " + objJs.methodId[agent.objectPath][idx]);
425 this.wampSession.unsubscribe(objJs.methodId[agent.objectPath][idx]);
426 objJs.methodId[agent.objectPath][idx] = null;
429 cloudeebus.log("Unsubscribe error: " + cloudeebus.getError(e));
432 delete objJs.methodId[agent.objectPath];
437 cloudeebus.Service.prototype.removeAgent = function(rmAgent) {
440 var promise = new cloudeebus.Promise(function (resolver) {
441 function ServiceRemoveAgentSuccessCB(objectPath) {
442 // Searching agent in list
444 for (idx in self.agents)
445 if (self.agents[idx].objectPath == objectPath) {
446 agent = self.agents[idx];
450 try { // calling dbus hook object function for un-translated types
451 self.agents.splice(idx, 1);
452 self._deleteWrapper(agent);
453 resolver.fulfill(agent, true);
456 var errorStr = cloudeebus.getError(e);
457 cloudeebus.log("Method callback exception: " + errorStr);
458 resolver.reject(errorStr, true);
462 function ServiceRemoveAgentErrorCB(error) {
463 var errorStr = cloudeebus.getError(error);
464 cloudeebus.log("Error removing agent : " + rmAgent.objectPath + ", error: " + errorStr);
465 self.promise.resolver.reject(errorStr, true);
472 // call dbusSend with bus type, destination, object, message and arguments
473 self.wampSession.call("serviceDelAgent", arglist).then(ServiceRemoveAgentSuccessCB, ServiceRemoveAgentErrorCB);
480 cloudeebus.Service.prototype._returnMethod = function(methodId, callIndex, success, result, successCB, errorCB) {
488 this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
492 cloudeebus.Service.prototype._emitSignal = function(objectPath, signalName, result, successCB, errorCB) {
499 this.wampSession.call("emitSignal", arglist).then(successCB, errorCB);
504 /*****************************************************************************/
506 function _processWrappers(wrappers, value) {
507 for (var i=0; i<wrappers.length; i++)
512 function _processWrappersAsync(wrappers, value) {
514 function processAsyncOnce() {
515 _processWrappers(wrappers, value);
516 clearInterval(taskid);
518 taskid = setInterval(processAsyncOnce, 200);
523 /*****************************************************************************/
525 cloudeebus.PromiseResolver = function(promise) {
526 this.promise = promise;
527 this.resolved = null;
532 cloudeebus.PromiseResolver.prototype.resolve = function(value, sync) {
536 var then = (value && value.then && value.then.apply) ? value.then : null;
539 var fulfillCallback = function(arg) {
540 self.resolve(arg, true);
542 var rejectCallback = function(arg) {
543 self.reject(arg, true);
546 then.apply(value, [fulfillCallback, rejectCallback]);
549 this.reject(cloudeebus.getError(e), true);
553 this.fulfill(value, sync);
557 cloudeebus.PromiseResolver.prototype.fulfill = function(value, sync) {
561 var promise = this.promise;
562 promise.state = "fulfilled";
563 promise.result = value;
565 this.resolved = true;
567 _processWrappers(promise._fulfillWrappers, value);
569 _processWrappersAsync(promise._fulfillWrappers, value);
573 cloudeebus.PromiseResolver.prototype.reject = function(value, sync) {
577 var promise = this.promise;
578 promise.state = "rejected";
579 promise.result = value;
581 this.resolved = true;
583 _processWrappers(promise._rejectWrappers, value);
585 _processWrappersAsync(promise._rejectWrappers, value);
590 /*****************************************************************************/
592 cloudeebus.Promise = function(init) {
593 this.state = "pending";
595 this._fulfillWrappers = [];
596 this._rejectWrappers = [];
597 this.resolver = new cloudeebus.PromiseResolver(this);
600 init.apply(this, [this.resolver]);
603 this.resolver.reject(cloudeebus.getError(e), true);
610 cloudeebus.Promise.prototype.appendWrappers = function(fulfillWrapper, rejectWrapper) {
612 this._fulfillWrappers.push(fulfillWrapper);
614 this._rejectWrappers.push(rejectWrapper);
615 if (this.state == "fulfilled")
616 _processWrappersAsync(this._fulfillWrappers, this.result);
617 if (this.state == "rejected")
618 _processWrappersAsync(this._rejectWrappers, this.result);
622 cloudeebus.Promise.prototype.then = function(fulfillCB, rejectCB) {
623 var promise = new cloudeebus.Promise();
624 var resolver = promise.resolver;
625 var fulfillWrapper, rejectWrapper;
628 fulfillWrapper = function(arg) {
630 var value = fulfillCB.apply(promise, [arg]);
631 resolver.resolve(value, true);
634 resolver.reject(cloudeebus.getError(e), true);
638 fulfillWrapper = function(arg) {
639 resolver.fulfill(arg, true);
643 rejectWrapper = function(arg) {
645 var value = rejectCB.apply(promise, [arg]);
646 resolver.resolve(value, true);
649 resolver.reject(cloudeebus.getError(e), true);
653 rejectWrapper = function(arg) {
654 resolver.reject(arg, true);
657 this.appendWrappers(fulfillWrapper,rejectWrapper);
662 cloudeebus.Promise.prototype["catch"] = function(rejectCB) {
663 return this.then(undefined,rejectCB);
667 cloudeebus.Promise.prototype.done = function(fulfillCB, rejectCB) {
668 this.appendWrappers(fulfillCB,rejectCB);
672 cloudeebus.Promise.resolve = function(value) {
673 var promise = new cloudeebus.Promise();
674 promise.resolver.resolve(value);
679 cloudeebus.Promise.fulfill = function(value) {
680 var promise = new cloudeebus.Promise();
681 promise.resolver.fulfill(value);
686 cloudeebus.Promise.reject = function(value) {
687 var promise = new cloudeebus.Promise();
688 promise.resolver.reject(value);
693 cloudeebus.Promise.any = function() {
694 var promise = new cloudeebus.Promise();
695 var resolver = promise.resolver;
696 var fulfillCallback = function(arg) {
697 resolver.resolve(arg, true);
699 var rejectCallback = function(arg) {
700 resolver.reject(arg, true);
702 if (arguments.length == 0)
703 resolver.resolve(undefined, true);
706 Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
711 cloudeebus.Promise.every = function() {
712 var promise = new cloudeebus.Promise();
713 var resolver = promise.resolver;
715 var countdown = arguments.length;
716 var args = new Array(countdown);
717 var rejectCallback = function(arg) {
718 resolver.reject(arg, true);
720 if (arguments.length == 0)
721 resolver.resolve(undefined, true);
723 for (i in arguments) {
724 var fulfillCallback = function(arg) {
728 resolver.resolve(args, true);
731 Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
738 cloudeebus.Promise.some = function() {
739 var promise = new cloudeebus.Promise();
740 var resolver = promise.resolver;
742 var countdown = arguments.length;
743 var args = new Array(countdown);
744 var fulfillCallback = function(arg) {
745 resolver.resolve(arg, true);
747 if (arguments.length == 0)
748 resolver.resolve(undefined, true);
750 for (i in arguments) {
751 var rejectCallback = function(arg) {
755 resolver.reject(args, true);
758 Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
766 /*****************************************************************************/
768 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
769 this.wampSession = session;
770 this.busConnection = busConnection;
771 this.busName = busName;
772 this.objectPath = objectPath;
773 this.interfaceProxies = {};
778 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
779 return this.interfaceProxies[ifName];
783 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
787 function getAllPropertiesSuccessCB(props) {
788 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
789 for (var prop in props)
790 ifProxy[prop] = self[prop] = props[prop];
791 getAllPropertiesNextInterfaceCB();
794 function getAllPropertiesNextInterfaceCB() {
795 self.propInterfaces.pop();
796 if (self.propInterfaces.length > 0)
797 self.callMethod("org.freedesktop.DBus.Properties",
799 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB,
800 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
802 self.propInterfaces = null;
808 function introspectSuccessCB(str) {
809 var parser = new DOMParser();
810 var xmlDoc = parser.parseFromString(str, "text/xml");
811 var interfaces = xmlDoc.getElementsByTagName("interface");
812 self.propInterfaces = [];
813 var supportDBusProperties = false;
814 for (var i=0; i < interfaces.length; i++) {
815 var ifName = interfaces[i].attributes.getNamedItem("name").value;
816 self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
817 if (ifName == "org.freedesktop.DBus.Properties")
818 supportDBusProperties = true;
819 var hasProperties = false;
820 var ifChild = interfaces[i].firstChild;
822 if (ifChild.nodeName == "method") {
825 var metChild = ifChild.firstChild;
827 if (metChild.nodeName == "arg" &&
828 metChild.attributes.getNamedItem("direction").value == "in") {
829 signature += metChild.attributes.getNamedItem("type").value;
832 metChild = metChild.nextSibling;
834 var metName = ifChild.attributes.getNamedItem("name").value;
836 self._addMethod(ifName, metName, nArgs, signature);
837 self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs, signature);
839 else if (ifChild.nodeName == "property") {
841 self.propInterfaces.push(ifName);
842 hasProperties = true;
844 ifChild = ifChild.nextSibling;
847 if (supportDBusProperties && self.propInterfaces.length > 0) {
848 self.callMethod("org.freedesktop.DBus.Properties",
850 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB,
851 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
854 self.propInterfaces = null;
860 // call Introspect on self
861 self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", []).then(introspectSuccessCB, errorCB);
865 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs, signature) {
869 self[method] = function() {
871 for (var i=0; i < nArgs; i++ )
872 args.push(arguments[i]);
873 return self.callMethod(ifName, method, args, signature);
878 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, signature) {
882 var promise = new cloudeebus.Promise(function (resolver) {
883 function callMethodSuccessCB(str) {
884 try { // calling dbus hook object function for un-translated types
885 var result = eval(str);
886 resolver.fulfill(result[0], true);
889 var errorStr = cloudeebus.getError(e);
890 cloudeebus.log("Method callback exception: " + errorStr);
891 resolver.reject(errorStr, true);
895 function callMethodErrorCB(error) {
896 var errorStr = cloudeebus.getError(error);
897 cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + errorStr);
898 resolver.reject(errorStr, true);
902 self.busConnection.name,
910 // call dbusSend with bus type, destination, object, message and arguments
911 self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
918 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, handlerCB, errorCB) {
922 function signalHandler(id, data) {
924 try { // calling dbus hook object function for un-translated types
925 handlerCB.apply(self, eval(data));
928 var errorStr = cloudeebus.getError(e);
929 cloudeebus.log("Signal handler exception: " + errorStr);
936 function connectToSignalSuccessCB(str) {
938 self.wampSession.subscribe(str, signalHandler);
941 cloudeebus.log("Subscribe error: " + cloudeebus.getError(e));
945 function connectToSignalErrorCB(error) {
946 var errorStr = cloudeebus.getError(error);
947 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + errorStr);
953 self.busConnection.name,
960 // call dbusSend with bus type, destination, object, message and arguments
961 self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
965 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
967 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
970 cloudeebus.log("Unsubscribe error: " + cloudeebus.getError(e));