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);
120 cloudeebus.wampSession.authreq().then(function() {
121 cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
122 }, onWAMPSessionAuthErrorCB);
125 function onWAMPSessionErrorCB(code, reason) {
126 if (code == ab.CONNECTION_UNSUPPORTED) {
127 cloudeebus.log("Browser is not supported");
130 cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
136 return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
140 cloudeebus.SessionBus = function() {
141 return cloudeebus.sessionBus;
145 cloudeebus.SystemBus = function() {
146 return cloudeebus.systemBus;
151 /*****************************************************************************/
153 cloudeebus.BusConnection = function(name, session) {
155 this.wampSession = session;
160 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
161 var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
163 proxy._introspect(introspectCB, errorCB);
168 cloudeebus.BusConnection.prototype.addService = function(serviceName) {
174 var promise = new cloudeebus.Promise(function (resolver) {
175 var cloudeebusService = new cloudeebus.Service(self.wampSession, self, serviceName);
177 function ServiceAddedSuccessCB(serviceName) {
178 cloudeebusService.isCreated = true;
179 resolver.fulfill(cloudeebusService, true);
182 function ServiceAddedErrorCB(error) {
183 var errorStr = cloudeebus.getError(error);
184 cloudeebus.log("Error adding service method: " + self.name + ", error: " + errorStr);
185 resolver.reject(errorStr, true);
193 // call dbusSend with bus type, destination, object, message and arguments
194 self.wampSession.call("serviceAdd", arglist).then(ServiceAddedSuccessCB, ServiceAddedErrorCB);
202 /*****************************************************************************/
203 //Generic definition for an agent. An agent needs :
204 //srvDbusName : the DBus parent service
205 //objPath : a DBus path to access it
206 //jsHdl : a Javascript handler to process methods,
207 //xml : the xml which describe interface/methods/signals...
208 cloudeebus.Agent = function(srvName, objPath, jsHdl, xml) {
209 this.srvName = srvName;
211 this.objectPath = objPath;
217 cloudeebus.Service = function(session, busConnection, name) {
218 this.wampSession = session;
219 this.busConnection = busConnection;
222 this.isCreated = false;
227 cloudeebus.Service.prototype.remove = function() {
230 var promise = new cloudeebus.Promise(function (resolver) {
231 function ServiceRemovedSuccessCB(serviceName) {
232 resolver.fulfill(serviceName, true);
235 function ServiceRemovedErrorCB(error) {
236 var errorStr = cloudeebus.getError(error);
237 resolver.reject(errorStr, true);
244 // call dbusSend with bus type, destination, object, message and arguments
245 self.wampSession.call("serviceRelease", arglist).then(ServiceRemovedSuccessCB, ServiceRemovedErrorCB);
252 cloudeebus.Service.prototype._searchMethod = function(ifName, method, objectJS) {
254 var funcToCall = null;
256 // Check if 'objectJS' has a member 'interfaceProxies' with an interface named 'ifName'
257 // and a method named 'method'
258 if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName] &&
259 objectJS.interfaceProxies[ifName][method]) {
260 funcToCall = objectJS.interfaceProxies[ifName][method];
262 // retrieve the method directly from 'root' of objectJs
263 funcToCall = objectJS[method];
270 cloudeebus.Service.prototype._addMethod = function(ifName, method, agent) {
273 var methodId = this.name + "#" + agent.objectPath + "#" + ifName + "#" + method;
274 var funcToCall = this._searchMethod(ifName, method, agent.jsHdl);
276 if (funcToCall == null)
277 cloudeebus.log("Method " + method + " doesn't exist in Javascript object");
279 agent.jsHdl.wrapperFunc[method] = function() {
281 var methodId = arguments[0];
283 // affectation of callDict in eval, otherwise dictionary(='{}') interpreted as block of code by eval
284 eval("callDict = " + arguments[1]);
286 result = funcToCall.apply(agent.jsHdl, callDict.args);
287 service._returnMethod(methodId, callDict.callIndex, true, result);
290 var errorStr = cloudeebus.getError(e);
291 cloudeebus.log("Method " + ifName + "." + method + " call on " + agent.objectPath + " exception: " + errorStr);
292 service._returnMethod(methodId, callDict.callIndex, false, errorStr);
295 agent.jsHdl.methodId[agent.objectPath].push(methodId);
296 this.wampSession.subscribe(methodId, agent.jsHdl.wrapperFunc[method]);
301 cloudeebus.Service.prototype._addSignal = function(ifName, signal, agent) {
303 var methodExist = false;
305 if (agent.jsHdl.interfaceProxies && agent.jsHdl.interfaceProxies[ifName])
306 if (agent.jsHdl.interfaceProxies[ifName][signal]) {
309 agent.jsHdl.interfaceProxies[ifName][signal] = function() {
310 service._emitSignal(agent.objectPath, signal, arguments[0]);
315 if ((agent.jsHdl[signal] == undefined || agent.jsHdl[signal] == null) && !methodExist)
316 agent.jsHdl[signal] = function() {
317 service._emitSignal(agent.objectPath, signal, arguments[0]);
320 cloudeebus.log("Can not create new method to emit signal '" + signal + "' in object JS this method already exist!");
324 cloudeebus.Service.prototype._createWrapper = function(agent) {
326 var parser = new DOMParser();
327 var xmlDoc = parser.parseFromString(agent.xml, "text/xml");
328 var ifXml = xmlDoc.getElementsByTagName("interface");
329 agent.jsHdl.wrapperFunc = {};
330 agent.jsHdl.methodId = {};
331 agent.jsHdl.methodId[agent.objectPath] = [];
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(ifName, metName, agent);
340 if (ifChild.nodeName == "signal") {
341 var metName = ifChild.attributes.getNamedItem("name").value;
342 self._addSignal(ifName, metName, agent);
344 ifChild = ifChild.nextSibling;
350 cloudeebus.Service.prototype.addAgent = function(agent) {
353 var promise = new cloudeebus.Promise(function (resolver) {
354 function ServiceAddAgentSuccessCB(objPath) {
355 self.agents.push(agent);
357 self._createWrapper(agent);
360 var errorStr = cloudeebus.getError(e);
361 cloudeebus.log("Exception creating agent wrapper " + agent.objectPath + " : " + errorStr);
362 resolver.reject(errorStr, true);
365 resolver.fulfill(objPath, true);
368 function ServiceAddAgenterrorCB(error) {
369 var errorStr = cloudeebus.getError(error);
370 cloudeebus.log("Error adding agent : " + agent.objectPath + ", error: " + errorStr);
371 self.promise.resolver.reject(errorStr, true);
380 // call dbusSend with bus type, destination, object, message and arguments
381 self.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, ServiceAddAgenterrorCB);
388 cloudeebus.Service.prototype._deleteWrapper = function(agent) {
389 var objJs = agent.jsHdl;
390 if (objJs.methodId[agent.objectPath]) {
391 while (objJs.methodId[agent.objectPath].length) {
393 this.wampSession.unsubscribe( objJs.methodId[agent.objectPath].pop() );
396 cloudeebus.log("Unsubscribe error: " + cloudeebus.getError(e));
399 objJs.methodId[agent.objectPath] = null;
404 cloudeebus.Service.prototype.removeAgent = function(rmAgent) {
407 var promise = new cloudeebus.Promise(function (resolver) {
408 function ServiceRemoveAgentSuccessCB(objectPath) {
409 // Searching agent in list
410 for (var idx in self.agents)
411 if (self.agents[idx].objectPath == objectPath) {
412 agent = self.agents[idx];
416 self.agents.splice(idx, 1);
417 self._deleteWrapper(agent);
418 resolver.fulfill(agent, true);
421 function ServiceRemoveAgentErrorCB(error) {
422 var errorStr = cloudeebus.getError(error);
423 cloudeebus.log("Error removing agent : " + rmAgent.objectPath + ", error: " + errorStr);
424 resolver.reject(errorStr, true);
431 // call dbusSend with bus type, destination, object, message and arguments
432 self.wampSession.call("serviceDelAgent", arglist).then(ServiceRemoveAgentSuccessCB, ServiceRemoveAgentErrorCB);
439 cloudeebus.Service.prototype._returnMethod = function(methodId, callIndex, success, result, successCB, errorCB) {
447 this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
451 cloudeebus.Service.prototype._emitSignal = function(objectPath, signalName, result, successCB, errorCB) {
458 this.wampSession.call("emitSignal", arglist).then(successCB, errorCB);
463 /*****************************************************************************/
465 function _processWrappers(wrappers, value) {
466 for (var i=0; i<wrappers.length; i++)
471 function _processWrappersAsync(wrappers, value) {
473 function processAsyncOnce() {
474 _processWrappers(wrappers, value);
475 clearInterval(taskid);
477 taskid = setInterval(processAsyncOnce, 200);
482 /*****************************************************************************/
484 cloudeebus.PromiseResolver = function(promise) {
485 this.promise = promise;
486 this.resolved = null;
491 cloudeebus.PromiseResolver.prototype.resolve = function(value, sync) {
495 var then = (value && value.then && value.then.apply) ? value.then : null;
498 var fulfillCallback = function(arg) {
499 self.resolve(arg, true);
501 var rejectCallback = function(arg) {
502 self.reject(arg, true);
505 then.apply(value, [fulfillCallback, rejectCallback]);
508 this.reject(cloudeebus.getError(e), true);
512 this.fulfill(value, sync);
516 cloudeebus.PromiseResolver.prototype.fulfill = function(value, sync) {
520 var promise = this.promise;
521 promise.state = "fulfilled";
522 promise.result = value;
524 this.resolved = true;
526 _processWrappers(promise._fulfillWrappers, value);
528 _processWrappersAsync(promise._fulfillWrappers, value);
532 cloudeebus.PromiseResolver.prototype.reject = function(value, sync) {
536 var promise = this.promise;
537 promise.state = "rejected";
538 promise.result = value;
540 this.resolved = true;
542 _processWrappers(promise._rejectWrappers, value);
544 _processWrappersAsync(promise._rejectWrappers, value);
549 /*****************************************************************************/
551 cloudeebus.Promise = function(init) {
552 this.state = "pending";
554 this._fulfillWrappers = [];
555 this._rejectWrappers = [];
556 this.resolver = new cloudeebus.PromiseResolver(this);
559 init.apply(this, [this.resolver]);
562 this.resolver.reject(cloudeebus.getError(e), true);
569 cloudeebus.Promise.prototype.appendWrappers = function(fulfillWrapper, rejectWrapper) {
571 this._fulfillWrappers.push(fulfillWrapper);
573 this._rejectWrappers.push(rejectWrapper);
574 if (this.state == "fulfilled")
575 _processWrappersAsync(this._fulfillWrappers, this.result);
576 if (this.state == "rejected")
577 _processWrappersAsync(this._rejectWrappers, this.result);
581 cloudeebus.Promise.prototype.then = function(fulfillCB, rejectCB) {
582 var promise = new cloudeebus.Promise();
583 var resolver = promise.resolver;
584 var fulfillWrapper, rejectWrapper;
587 fulfillWrapper = function(arg) {
589 var value = fulfillCB.apply(promise, [arg]);
590 resolver.resolve(value, true);
593 resolver.reject(cloudeebus.getError(e), true);
597 fulfillWrapper = function(arg) {
598 resolver.fulfill(arg, true);
602 rejectWrapper = function(arg) {
604 var value = rejectCB.apply(promise, [arg]);
605 resolver.resolve(value, true);
608 resolver.reject(cloudeebus.getError(e), true);
612 rejectWrapper = function(arg) {
613 resolver.reject(arg, true);
616 this.appendWrappers(fulfillWrapper,rejectWrapper);
621 cloudeebus.Promise.prototype["catch"] = function(rejectCB) {
622 return this.then(undefined,rejectCB);
626 cloudeebus.Promise.prototype.done = function(fulfillCB, rejectCB) {
627 this.appendWrappers(fulfillCB,rejectCB);
631 cloudeebus.Promise.resolve = function(value) {
632 var promise = new cloudeebus.Promise();
633 promise.resolver.resolve(value);
638 cloudeebus.Promise.fulfill = function(value) {
639 var promise = new cloudeebus.Promise();
640 promise.resolver.fulfill(value);
645 cloudeebus.Promise.reject = function(value) {
646 var promise = new cloudeebus.Promise();
647 promise.resolver.reject(value);
652 cloudeebus.Promise.any = function() {
653 var promise = new cloudeebus.Promise();
654 var resolver = promise.resolver;
655 var fulfillCallback = function(arg) {
656 resolver.resolve(arg, true);
658 var rejectCallback = function(arg) {
659 resolver.reject(arg, true);
661 if (arguments.length == 0)
662 resolver.resolve(undefined, true);
665 cloudeebus.Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
670 cloudeebus.Promise.every = function() {
671 var promise = new cloudeebus.Promise();
672 var resolver = promise.resolver;
674 var countdown = arguments.length;
675 var args = new Array(countdown);
676 var rejectCallback = function(arg) {
677 resolver.reject(arg, true);
679 if (arguments.length == 0)
680 resolver.resolve(undefined, true);
682 for (i in arguments) {
683 var fulfillCallback = function(arg) {
687 resolver.resolve(args, true);
690 cloudeebus.Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
697 cloudeebus.Promise.some = function() {
698 var promise = new cloudeebus.Promise();
699 var resolver = promise.resolver;
701 var countdown = arguments.length;
702 var args = new Array(countdown);
703 var fulfillCallback = function(arg) {
704 resolver.resolve(arg, true);
706 if (arguments.length == 0)
707 resolver.resolve(undefined, true);
709 for (i in arguments) {
710 var rejectCallback = function(arg) {
714 resolver.reject(args, true);
717 cloudeebus.Promise.resolve(arguments[i]).appendWrappers(fulfillCallback,rejectCallback);
725 /*****************************************************************************/
727 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
728 this.wampSession = session;
729 this.busConnection = busConnection;
730 this.busName = busName;
731 this.objectPath = objectPath;
732 this.interfaceProxies = {};
737 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
738 return this.interfaceProxies[ifName];
742 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
746 function getAllPropertiesSuccessCB(props) {
747 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
748 for (var prop in props)
749 ifProxy[prop] = self[prop] = props[prop];
750 getAllPropertiesNextInterfaceCB();
753 function getAllPropertiesNextInterfaceCB() {
754 self.propInterfaces.pop();
755 if (self.propInterfaces.length > 0)
756 self.callMethod("org.freedesktop.DBus.Properties",
758 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB,
759 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
761 self.propInterfaces = null;
767 function introspectSuccessCB(str) {
768 var parser = new DOMParser();
769 var xmlDoc = parser.parseFromString(str, "text/xml");
770 var nodes = xmlDoc.getElementsByTagName("node");
771 self.childNodeNames = [];
772 var l = nodes.length;
773 //there will always be 1 node, the parent/head node
775 for(var i = 1; i < l; i++){
776 self.childNodeNames.push(nodes[i].getAttribute("name"));
779 var interfaces = xmlDoc.getElementsByTagName("interface");
780 self.propInterfaces = [];
781 var supportDBusProperties = false;
782 for (var i=0; i < interfaces.length; i++) {
783 var ifName = interfaces[i].attributes.getNamedItem("name").value;
784 self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
785 if (ifName == "org.freedesktop.DBus.Properties")
786 supportDBusProperties = true;
787 var hasProperties = false;
788 var ifChild = interfaces[i].firstChild;
790 if (ifChild.nodeName == "method") {
793 var metChild = ifChild.firstChild;
795 if (metChild.nodeName == "arg" &&
796 metChild.attributes.getNamedItem("direction").value == "in") {
797 signature += metChild.attributes.getNamedItem("type").value;
800 metChild = metChild.nextSibling;
802 var metName = ifChild.attributes.getNamedItem("name").value;
804 self._addMethod(ifName, metName, nArgs, signature);
805 self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs, signature);
807 else if (ifChild.nodeName == "property") {
809 self.propInterfaces.push(ifName);
810 hasProperties = true;
812 ifChild = ifChild.nextSibling;
815 if (supportDBusProperties && self.propInterfaces.length > 0) {
816 self.callMethod("org.freedesktop.DBus.Properties",
818 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB,
819 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
822 self.propInterfaces = null;
828 // call Introspect on self
829 self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", []).then(introspectSuccessCB, errorCB);
833 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs, signature) {
837 self[method] = function() {
839 for (var i=0; i < nArgs; i++ )
840 args.push(arguments[i]);
841 return self.callMethod(ifName, method, args, signature);
846 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, signature) {
850 var promise = new cloudeebus.Promise(function (resolver) {
851 function callMethodSuccessCB(str) {
852 try { // calling dbus hook object function for un-translated types
853 var result = eval(str);
854 resolver.fulfill(result[0], true);
857 var errorStr = cloudeebus.getError(e);
858 cloudeebus.log("Method callback exception: " + errorStr);
859 resolver.reject(errorStr, true);
863 function callMethodErrorCB(error) {
864 var errorStr = cloudeebus.getError(error);
865 cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + errorStr);
866 resolver.reject(errorStr, true);
870 self.busConnection.name,
878 // call dbusSend with bus type, destination, object, message and arguments
879 self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
886 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, handlerCB, errorCB) {
890 function signalHandler(id, data) {
892 try { // calling dbus hook object function for un-translated types
893 handlerCB.apply(self, eval(data));
896 var errorStr = cloudeebus.getError(e);
897 cloudeebus.log("Signal handler exception: " + errorStr);
904 function connectToSignalSuccessCB(str) {
906 self.wampSession.subscribe(str, signalHandler);
909 cloudeebus.log("Subscribe error: " + cloudeebus.getError(e));
913 function connectToSignalErrorCB(error) {
914 var errorStr = cloudeebus.getError(error);
915 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + errorStr);
921 self.busConnection.name,
928 // call dbusSend with bus type, destination, object, message and arguments
929 self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
933 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
935 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
938 cloudeebus.log("Unsubscribe error: " + cloudeebus.getError(e));