cloudeebus.egg-info
.project
.pydevproject
+*.pyc
DBus service support:
---------------------
-- support publishing a DBus service
- support sending signals
/*****************************************************************************/
var cloudeebus = window.cloudeebus = {
- version: "0.5.1",
+ version: "0.5.0",
minVersion: "0.3.2"
};
};
+cloudeebus.BusConnection.prototype.addService = function(serviceName) {
+ var self = this;
+
+ var future = new cloudeebus.Future(function (resolver) {
+ cloudeebusService = new cloudeebus.Service(self.wampSession, self, serviceName);
+
+ function busServiceAddedSuccessCB(service) {
+ try {
+ service.isCreated = true;
+ var result = [cloudeebusService];
+ resolver.accept(result[0], true);
+ }
+ catch (e) {
+ cloudeebus.log("Method callback exception: " + e);
+ resolver.reject(e, true);
+ }
+ }
+
+ function busServiceErrorSuccessCB(error) {
+ resolver.reject(error, true);
+ }
+
+ cloudeebusService.add(this).then(busServiceAddedSuccessCB, busServiceErrorSuccessCB);
+ });
+
+ return future;
+};
+
+cloudeebus.BusConnection.prototype.removeService = function(serviceName, successCB, errorCB) {
+ var self = this;
+
+ function busServiceRemovedSuccessCB(serviceName) {
+ // Be sure we are removing the service requested...
+ if (serviceName == self.service.name) {
+ self.service = null;
+ if (successCB)
+ successCB(serviceName);
+ }
+ }
+
+ cloudeebusService.remove(busServiceRemovedSuccessCB, errorCB);
+};
+
+
+/*****************************************************************************/
+//Generic definition for an agent. An agent need :
+//srvDbusName : the DBus parent service
+//objPath : a DBus path to access it
+//jsHdl : a Javascript handler to process methods,
+//xml : the xml which describe interface/methods/signals...
+Agent = function(srvDbusName, objPath, jsHdl, xml) {
+ this.srvName = srvDbusName;
+ this.registered = false;
+ this.xml = xml;
+ this.objectPath = objPath;
+ this.jsHdl = jsHdl;
+ return this;
+};
+
+
+cloudeebus.Service = function(session, busConnection, name) {
+ this.wampSession = session;
+ this.busConnection = busConnection;
+ this.name = name;
+ this.isCreated = false;
+ return this;
+};
+
+cloudeebus.Service.prototype.add = function(future) {
+ var self = this;
+ self.future = future;
+ var resolver = self.future.resolver;
+
+ function ServiceAddedSuccessCB(serviceName) {
+ try { // calling dbus hook object function for un-translated types
+ var result = [self];
+ resolver.accept(result[0], true);
+ }
+ catch (e) {
+ cloudeebus.log("Method callback exception: " + e);
+ resolver.reject(e, true);
+ }
+ }
+
+ function ServiceAddedErrorCB(error) {
+ cloudeebus.log("Error adding service method: " + self.name + ", error: " + error.desc);
+ self.future.resolver.reject(error.desc, true);
+ }
+
+ var arglist = [
+ this.busConnection,
+ this.name
+ ];
+
+ // call dbusSend with bus type, destination, object, message and arguments
+ this.wampSession.call("serviceAdd", arglist).then(ServiceAddedSuccessCB, ServiceAddedErrorCB);
+ return future;
+};
+
+cloudeebus.Service.prototype.remove = function(successCB, errorCB) {
+ function ServiceRemovedSuccessCB(serviceName) {
+ if (successCB) {
+ try {
+ successCB(serviceName);
+ }
+ catch (e) {
+ alert("Exception removing service " + serviceName + " : " + e);
+ }
+ }
+ }
+
+ var arglist = [
+ this.name
+ ];
+
+ // call dbusSend with bus type, destination, object, message and arguments
+ this.wampSession.call("serviceRelease", arglist).then(ServiceRemovedSuccessCB, errorCB);
+};
+
+cloudeebus.Service.prototype._searchMethod = function(ifName, method, objectJS) {
+
+ var funcToCall = null;
+
+ // Check if 'objectJS' has a member 'interfaceProxies' with an interface named 'ifName'
+ // and a method named 'method'
+ if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName] &&
+ objectJS.interfaceProxies[ifName][method]) {
+ funcToCall = objectJS.interfaceProxies[ifName][method];
+ } else {
+ // retrieve the method directly from 'root' of objectJs
+ funcToCall = objectJS[method];
+ }
+
+ return funcToCall;
+};
+
+cloudeebus.Service.prototype._addMethod = function(ifName, method, agent) {
+
+ var service = this;
+ var methodId = this.name + "#" + agent.objectPath + "#" + ifName + "#" + method;
+ var funcToCall = this._searchMethod(ifName, method, agent.jsHdl);
+
+ if (funcToCall == null)
+ cloudeebus.log("Method " + method + " doesn't exist in Javascript object");
+ else {
+ agent.jsHdl.wrapperFunc[method] = function() {
+ var result;
+ var methodId = arguments[0];
+ var callDict = {};
+ // affectation of callDict in eval, otherwise dictionary(='{}') interpreted as block of code by eval
+ eval("callDict = " + arguments[1]);
+ try {
+ result = funcToCall.apply(agent.jsHdl, callDict.args);
+ service._returnMethod(methodId, callDict.callIndex, true, result);
+ }
+ catch (e) {
+ cloudeebus.log("Method " + ifName + "." + method + " call on " + agent.objectPath + " exception: " + e);
+ service._returnMethod(methodId, callDict.callIndex, false, e.message);
+ }
+ };
+ agent.jsHdl.methodId[agent.objectPath].push(methodId);
+ cloudeebus.log("subscribe " + methodId);
+ this.wampSession.subscribe(methodId, agent.jsHdl.wrapperFunc[method]);
+ }
+};
+
+cloudeebus.Service.prototype._addSignal = function(ifName, signal, agent) {
+ var service = this;
+ var methodExist = false;
+
+ if (agent.jsHdl.interfaceProxies && agent.jsHdl.interfaceProxies[ifName])
+ if (agent.jsHdl.interfaceProxies[ifName][signal]) {
+ methodExist = true;
+ } else {
+ agent.jsHdl.interfaceProxies[ifName][signal] = function() {
+ service._emitSignal(agent.objectPath, signal, arguments[0]);
+ };
+ return;
+ }
+
+ if ((agent.jsHdl[signal] == undefined || agent.jsHdl[signal] == null) && !methodExist)
+ agent.jsHdl[signal] = function() {
+ service.emitSignal(agent.objectPath, signal, arguments[0]);
+ };
+ else
+ cloudeebus.log("Can not create new method to emit signal '" + signal + "' in object JS this method already exist!");
+};
+
+cloudeebus.Service.prototype._createWrapper = function(agent) {
+ var self = this;
+ var parser = new DOMParser();
+ var xmlDoc = parser.parseFromString(agent.xml, "text/xml");
+ var ifXml = xmlDoc.getElementsByTagName("interface");
+ agent.jsHdl.wrapperFunc = [];
+ agent.jsHdl.methodId = [];
+ agent.jsHdl.methodId[agent.objectPath] = [];
+ for (var i=0; i < ifXml.length; i++) {
+ var ifName = ifXml[i].attributes.getNamedItem("name").value;
+ var ifChild = ifXml[i].firstChild;
+ while (ifChild) {
+ if (ifChild.nodeName == "method") {
+ var metName = ifChild.attributes.getNamedItem("name").value;
+ self._addMethod(ifName, metName, agent);
+ }
+ if (ifChild.nodeName == "signal") {
+ var metName = ifChild.attributes.getNamedItem("name").value;
+ self._addSignal(objectPath, ifName, metName, objectJS);
+ }
+ ifChild = ifChild.nextSibling;
+ }
+ }
+};
+
+cloudeebus.Service.prototype.addAgent = function(agent, successCB, errorCB) {
+ function ServiceAddAgentSuccessCB(objPath) {
+ if (successCB) {
+ try {
+ successCB(objPath);
+ }
+ catch (e) {
+ alert("Exception adding agent " + agent.objectPath + " : " + e);
+ }
+ }
+ }
+
+ try {
+ this._createWrapper(agent);
+ }
+ catch (e) {
+ alert("Exception creating agent wrapper " + agent.objectPath + " : " + e);
+ errorCB(e);
+ return;
+ }
+
+ var arglist = [
+ agent.objectPath,
+ agent.xml
+ ];
+
+ // call dbusSend with bus type, destination, object, message and arguments
+ this.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, errorCB);
+};
+
+cloudeebus.Service.prototype._deleteWrapper = function(agent) {
+ var self = this;
+ var objJs = agent.jsHdl;
+ if (objJs.methodId[agent.objectPath]) {
+ for (var idx in objJs.methodId[agent.objectPath]) {
+ try {
+ cloudeebus.log("unsubscribe " + objJs.methodId[agent.objectPath][idx]);
+ this.wampSession.unsubscribe(objJs.methodId[agent.objectPath][idx]);
+ objJs.methodId[agent.objectPath][idx] = null;
+ }
+ catch (e) {
+ cloudeebus.log("Unsubscribe error: " + e);
+ }
+ }
+ delete objJs.methodId[agent.objectPath];
+ }
+};
+
+cloudeebus.Service.prototype.delAgent = function(rmAgent, successCB, errorCB) {
+ function ServiceDelAgentSuccessCB(agent) {
+ if (successCB) {
+ try {
+ successCB(agent);
+ }
+ catch (e) {
+ alert("Exception deleting agent " + rmAgent.objectPath + " : " + e);
+ errorCB(e);
+ }
+ }
+ }
+
+ try {
+ this._deleteWrapper(rmAgent);
+ }
+ catch (e) {
+ alert("Exception deleting agent wrapper " + rmAgent.objectPath + " : " + e);
+ errorCB(e);
+ }
+
+ var arglist = [
+ rmAgent.objectPath
+ ];
+
+ // call dbusSend with bus type, destination, object, message and arguments
+ this.wampSession.call("serviceDelAgent", arglist).then(ServiceDelAgentSuccessCB, errorCB);
+};
+
+cloudeebus.Service.prototype._returnMethod = function(methodId, callIndex, success, result, successCB, errorCB) {
+ var arglist = [
+ methodId,
+ callIndex,
+ success,
+ result
+ ];
+
+ this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
+};
+
+cloudeebus.Service.prototype._emitSignal = function(objectPath, signalName, result, successCB, errorCB) {
+ var arglist = [
+ objectPath,
+ signalName,
+ result
+ ];
+
+ this.wampSession.call("emitSignal", arglist).then(successCB, errorCB);
+};
+
+
+/*****************************************************************************/
+
+function _processWrappers(wrappers, value) {
+ for (var i=0; i<wrappers.length; i++)
+ wrappers[i](value);
+}
+
+
+function _processWrappersAsync(wrappers, value) {
+ var taskid = -1;
+ function processAsyncOnce() {
+ _processWrappers(wrappers, value);
+ clearInterval(taskid);
+ }
+ taskid = setInterval(processAsyncOnce, 200);
+}
+
+
+
+/*****************************************************************************/
+
+cloudeebus.FutureResolver = function(future) {
+ this.future = future;
+ this.resolved = null;
+ return this;
+};
+
+
+cloudeebus.FutureResolver.prototype.resolve = function(value, sync) {
+ if (this.resolved)
+ return;
+
+ var then = (value && value.then && value.then.apply) ? value.then : null;
+ if (then) {
+ var self = this;
+ var acceptCallback = function(arg) {
+ self.resolve(arg, true);
+ };
+ var rejectCallback = function(arg) {
+ self.reject(arg, true);
+ };
+ try {
+ then.apply(value, [acceptCallback, rejectCallback]);
+ }
+ catch (e) {
+ this.reject(e, true);
+ }
+ }
+
+ this.accept(value, sync);
+};
+
+
+cloudeebus.FutureResolver.prototype.accept = function(value, sync) {
+ if (this.resolved)
+ return;
+
+ var future = this.future;
+ future.state = "accepted";
+ future.result = value;
+
+ this.resolved = true;
+ if (sync)
+ _processWrappers(future._acceptWrappers, value);
+ else
+ _processWrappersAsync(future._acceptWrappers, value);
+};
+
+
+cloudeebus.FutureResolver.prototype.reject = function(value, sync) {
+ if (this.resolved)
+ return;
+
+ var future = this.future;
+ future.state = "rejected";
+ future.result = value;
+
+ this.resolved = true;
+ if (sync)
+ _processWrappers(future._rejectWrappers, value);
+ else
+ _processWrappersAsync(future._rejectWrappers, value);
+};
+
+
+
+/*****************************************************************************/
+
+cloudeebus.Future = function(init) {
+ this.state = "pending";
+ this.result = null;
+ this._acceptWrappers = [];
+ this._rejectWrappers = [];
+ this.resolver = new cloudeebus.FutureResolver(this);
+ if (init) {
+ try {
+ init.apply(this, [this.resolver]);
+ }
+ catch (e) {
+ this.resolver.reject(e, true);
+ }
+ }
+ return this;
+};
+
+
+cloudeebus.Future.prototype.appendWrappers = function(acceptWrapper, rejectWrapper) {
+ this._acceptWrappers.push(acceptWrapper);
+ this._rejectWrappers.push(rejectWrapper);
+ if (this.state == "accepted")
+ _processWrappersAsync(this._acceptWrappers, this.result);
+ if (this.state == "rejected")
+ _processWrappersAsync(this._rejectWrappers, this.result);
+};
+
+
+cloudeebus.Future.prototype.then = function(acceptCB, rejectCB) {
+ var future = new cloudeebus.Future();
+ var resolver = future.resolver;
+ var acceptWrapper, rejectWrapper;
+
+ if (acceptCB)
+ acceptWrapper = function(arg) {
+ try {
+ var value = acceptCB.apply(future, [arg]);
+ resolver.resolve(value, true);
+ }
+ catch (e) {
+ resolver.reject(e, true);
+ }
+ };
+ else
+ acceptWrapper = function(arg) {
+ resolver.accept(arg, true);
+ };
+
+ if (rejectCB)
+ rejectWrapper = function(arg) {
+ try {
+ var value = rejectCB.apply(future, [arg]);
+ resolver.resolve(value, true);
+ }
+ catch (e) {
+ resolver.reject(e, true);
+ }
+ };
+ else
+ rejectWrapper = function(arg) {
+ resolver.reject(arg, true);
+ };
+
+ this.appendWrappers(acceptWrapper,rejectWrapper);
+ return future;
+};
+
+
/*****************************************************************************/
from dbus.mainloop.glib import DBusGMainLoop
import gobject
+import re
+import dbus.service
gobject.threads_init()
from dbus import glib
# enable debug log
from twisted.python import log
-
+# XML parser module
+from xml.etree.ElementTree import XMLParser
###############################################################################
-VERSION = "0.5.1"
+VERSION = "0.5.0"
OPENDOOR = False
CREDENTIALS = {}
WHITELIST = []
+################################################################################
+class ExecCode:
+ '''
+ Execute DynDBusClass generated code
+ '''
+ def __init__(self, globalCtx, localCtx) :
+ self.exec_string = ""
+ self.exec_code = None
+ self.exec_code_valid = 1
+ self.indent_level = 0
+ self.indent_increment = 1
+ self.line = 0
+ self.localCtx = localCtx
+ self.globalCtx = globalCtx
+
+
+ def append_stmt(self, stmt) :
+ self.exec_code_valid = 0
+ self.line += 1
+ for x in range(0,self.indent_level):
+ self.exec_string = self.exec_string + ' '
+ self.exec_string = self.exec_string + stmt + '\n'
+
+ def indent(self) :
+ self.indent_level = self.indent_level + self.indent_increment
+
+ def dedent(self) :
+ self.indent_level = self.indent_level - self.indent_increment
+
+ # compile : Compile exec_string into exec_code using the builtin
+ # compile function. Skip if already in sync.
+ def compile(self) :
+ if not self.exec_code_valid :
+ self.exec_code = compile(self.exec_string, "<string>", "exec")
+ self.exec_code_valid = True
+
+ def execute(self) :
+ if not self.exec_code_valid :
+ self.compile()
+ exec(self.exec_code, self.globalCtx, self.localCtx)
+
+
+
+################################################################################
+class XmlCbParser: # The target object of the parser
+ maxDepth = 0
+ depth = 0
+ def __init__(self, dynDBusClass):
+ self.dynDBusClass = dynDBusClass
+
+ def start(self, tag, attrib): # Called for each opening tag.
+ if (tag == 'node'):
+ return
+ # Set interface name
+ if (tag == 'interface'):
+ self.dynDBusClass.set_interface(attrib['name'])
+ return
+ # Set method name
+ if (tag == 'method'):
+ self.current = tag
+ self.dynDBusClass.def_method(attrib['name'])
+ return
+ if (tag == 'signal'):
+ self.current = tag
+ self.dynDBusClass.def_signal(attrib['name'])
+ return
+
+ # Set signature (in/out & name) for method
+ if (tag == 'arg'):
+ if (self.current == 'method'):
+ if (attrib.has_key('direction') == False):
+ attrib['direction'] = "in"
+ self.dynDBusClass.add_signature(attrib['name'],
+ attrib['direction'],
+ attrib['type'])
+ return
+ if (self.current == 'signal'):
+ if (attrib.has_key('name') == False):
+ attrib['name'] = 'value'
+ self.dynDBusClass.add_signature(attrib['name'], 'in',
+ attrib['type'])
+ return
+ def end(self, tag): # Called for each closing tag.
+ if (tag == 'method'):
+ self.dynDBusClass.add_dbus_method()
+ self.dynDBusClass.add_body_method()
+ self.dynDBusClass.end_method()
+ if (tag == 'signal'):
+ self.dynDBusClass.add_dbus_signal()
+ self.dynDBusClass.add_body_signal()
+ self.dynDBusClass.end_method()
+
+ def data(self, data):
+ pass # We do not need to do anything with data.
+ def close(self): # Called when all data has been parsed.
+ return self.maxDepth
+
+
+
+################################################################################
+class DynDBusClass():
+ def __init__(self, className, globalCtx, localCtx):
+ self.className = className
+ self.xmlCB = XmlCbParser(self)
+ self.signature = {}
+ self.class_code = ExecCode(globalCtx, localCtx)
+ self.class_code.indent_increment = 4
+ self.class_code.append_stmt("import dbus")
+ self.class_code.append_stmt("\n")
+ self.class_code.append_stmt("class " + self.className + "(dbus.service.Object):")
+ self.class_code.indent()
+
+ ## Overload of __init__ method
+ self.def_method("__init__")
+ self.add_method("bus, callback=None, objPath='/sample', busName='org.cloudeebus'")
+ self.add_stmt("self.bus = bus")
+ self.add_stmt("self.objPath = objPath")
+ self.add_stmt("self.callback = callback")
+ self.add_stmt("dbus.service.Object.__init__(self, conn=bus, bus_name=busName)")
+ self.end_method()
+
+ ## Create 'add_to_connection' method
+ self.def_method("add_to_connection")
+ self.add_method("connection=None, path=None")
+ self.add_stmt("dbus.service.Object.add_to_connection(self, connection=self.bus, path=self.objPath)")
+ self.end_method()
+
+ ## Create 'remove_from_connection' method
+ self.def_method("remove_from_connection")
+ self.add_method("connection=None, path=None")
+ self.add_stmt("dbus.service.Object.remove_from_connection(self, connection=None, path=self.objPath)")
+ self.end_method()
+
+ def createDBusServiceFromXML(self, xml):
+ self.parser = XMLParser(target=self.xmlCB)
+ self.parser.feed(xml)
+ self.parser.close()
+
+ def set_interface(self, ifName):
+ self.ifName = ifName
+
+ def def_method(self, methodName):
+ self.methodToAdd = methodName
+ self.signalToAdd = None
+ self.args_str = str()
+ self.signature = {}
+ self.signature['name'] = str()
+ self.signature['in'] = str()
+ self.signature['out'] = str()
+
+ def def_signal(self, signalName):
+ self.methodToAdd = None
+ self.signalToAdd = signalName
+ self.args_str = str()
+ self.signature = {}
+ self.signature['name'] = str()
+ self.signature['in'] = str()
+ self.signature['out'] = str()
+
+ def add_signature(self, name, direction, signature):
+ if (direction == 'in'):
+ self.signature['in'] += signature
+ if (self.signature['name'] != str()):
+ self.signature['name'] += ", "
+ self.signature['name'] += name
+ if (direction == 'out'):
+ self.signature['out'] = signature
+
+ def add_method(self, args = None, async_success_cb = None, async_err_cb = None):
+ async_cb_str = str()
+ if (self.methodToAdd != None):
+ name = self.methodToAdd
+ else:
+ name = self.signalToAdd
+ if (args != None):
+ self.args_str = args
+ if (async_success_cb != None):
+ async_cb_str = async_success_cb
+ if (async_err_cb != None):
+ if (async_cb_str != str()):
+ async_cb_str += ", "
+ async_cb_str += async_err_cb
+
+ parameters = self.args_str
+ if (async_cb_str != str()):
+ if (parameters != str()):
+ parameters += ", "
+ parameters +=async_cb_str
+
+ if (parameters != str()):
+ self.class_code.append_stmt("def " + name + "(self, %s):" % parameters)
+ else:
+ self.class_code.append_stmt("def " + name + "(self):")
+ self.class_code.indent()
+
+ def end_method(self):
+ self.class_code.append_stmt("\n")
+ self.class_code.dedent()
+
+ def add_dbus_method(self):
+ decorator = '@dbus.service.method("' + self.ifName + '"'
+ if (self.signature.has_key('in') and self.signature['in'] != str()):
+ decorator += ", in_signature='" + self.signature['in'] + "'"
+ if (self.signature.has_key('out') and self.signature['out'] != str()):
+ decorator += ", out_signature='" + self.signature['out'] + "'"
+ decorator += ", async_callbacks=('dbus_async_cb', 'dbus_async_err_cb')"
+ decorator += ")"
+ self.class_code.append_stmt(decorator)
+ if (self.signature.has_key('name') and self.signature['name'] != str()):
+ self.add_method(self.signature['name'], async_success_cb='dbus_async_cb', async_err_cb='dbus_async_err_cb')
+ else:
+ self.add_method(async_success_cb='dbus_async_cb', async_err_cb='dbus_async_err_cb')
+
+ def add_dbus_signal(self):
+ decorator = '@dbus.service.signal("' + self.ifName + '"'
+ if (self.signature.has_key('in') and self.signature['in'] != str()):
+ decorator += ", signature='" + self.signature['in'] + "'"
+ decorator += ")"
+ self.class_code.append_stmt(decorator)
+ if (self.signature.has_key('name') and self.signature['name'] != str()):
+ self.add_method(self.signature['name'])
+ else:
+ self.add_method()
+
+ def add_body_method(self):
+ if (self.methodToAdd != None):
+ if (self.args_str != str()):
+ self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', self.objPath, '" + self.ifName + "', " + "dbus_async_cb, dbus_async_err_cb, %s)" % self.args_str)
+ else:
+ self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', self.objPath, '" + self.ifName + "', " + "dbus_async_cb, dbus_async_err_cb)")
+
+ def add_body_signal(self):
+ self.class_code.append_stmt("return") ## TODO: Remove and fix with code ad hoc
+ self.class_code.append_stmt("\n")
+
+ def add_stmt(self, stmt) :
+ self.class_code.append_stmt(stmt)
+
+ def declare(self) :
+ self.class_code.execute()
+
+
+
###############################################################################
class CloudeebusService:
'''
self.proxyObjects = {}
self.proxyMethods = {}
self.pendingCalls = []
+ self.dynDBusClasses = {} # DBus class source code generated dynamically (a list because one by classname)
+ self.services = {} # DBus service created
+ self.serviceAgents = {} # Instantiated DBus class previously generated dynamically, for now, one by classname
+ self.servicePendingCalls = {} # JS methods called (and waiting for a Success/error response), containing 'methodId', (successCB, errorCB)
+ self.localCtx = locals()
+ self.globalCtx = globals()
def proxyObject(self, busName, serviceName, objectName):
@exportRpc
+ def emitSignal(self, list):
+ '''
+ arguments: agentObjectPath, signalName, result (to emit)
+ '''
+ objectPath = list[0]
+ className = re.sub('/', '_', objectPath[1:])
+ signalName = list[1]
+ result = list[2]
+ if (self.serviceAgents.has_key(className) == True):
+ exe_str = "self.serviceAgents['"+ className +"']."+ signalName + "(" + str(result) + ")"
+ eval(exe_str, self.globalCtx, self.localCtx)
+ else:
+ raise Exception("No object path " + objectPath)
+
+ @exportRpc
+ def returnMethod(self, list):
+ '''
+ arguments: methodId, callIndex, success (=true, error otherwise), result (to return)
+ '''
+ methodId = list[0]
+ callIndex = list[1]
+ success = list[2]
+ result = list[3]
+ if (self.servicePendingCalls.has_key(methodId)):
+ cb = self.servicePendingCalls[methodId]['calls'][callIndex]
+ if cb is None:
+ raise Exception("No pending call " + str(callIndex) + " for methodID " + methodId)
+ if (success):
+ successCB = cb["successCB"]
+ if (result != None):
+ successCB(result)
+ else:
+ successCB()
+ else:
+ errorCB = cb["errorCB"]
+ if (result != None):
+ errorCB(result)
+ else:
+ errorCB()
+ self.servicePendingCalls[methodId]['calls'][callIndex] = None
+ self.servicePendingCalls[methodId]['count'] = self.servicePendingCalls[methodId]['count'] - 1
+ if self.servicePendingCalls[methodId]['count'] == 0:
+ del self.servicePendingCalls[methodId]
+ else:
+ raise Exception("No methodID " + methodId)
+
+ def srvCB(self, name, objPath, ifName, async_succes_cb, async_error_cb, *args):
+ methodId = self.srvName + "#" + objPath + "#" + ifName + "#" + name
+ cb = { 'successCB': async_succes_cb,
+ 'errorCB': async_error_cb}
+ if methodId not in self.servicePendingCalls:
+ self.servicePendingCalls[methodId] = {'count': 0, 'calls': []}
+
+ try:
+ pendingCallStr = json.dumps({'callIndex': len(self.servicePendingCalls[methodId]['calls']), 'args': args})
+ except Exception, e:
+ args = eval( str(args).replace("dbus.Byte", "dbus.Int16") )
+ pendingCallStr = json.dumps({'callIndex': len(self.servicePendingCalls[methodId]['calls']), 'args': args})
+
+ self.servicePendingCalls[methodId]['calls'].append(cb)
+ self.servicePendingCalls[methodId]['count'] = self.servicePendingCalls[methodId]['count'] + 1
+ factory.dispatch(methodId, pendingCallStr)
+
+ @exportRpc
+ def serviceAdd(self, list):
+ '''
+ arguments: busName, srvName
+ '''
+ busName = list[0]
+ self.bus = cache.dbusConnexion( busName['name'] )
+ self.srvName = list[1]
+ if (self.services.has_key(self.srvName) == False):
+ self.services[self.srvName] = dbus.service.BusName(name = self.srvName, bus = self.bus)
+ return self.srvName
+
+ @exportRpc
+ def serviceRelease(self, list):
+ '''
+ arguments: busName, srvName
+ '''
+ self.srvName = list[0]
+ if (self.services.has_key(self.srvName) == True):
+ self.services.pop(self.srvName)
+ return self.srvName
+ else:
+ raise Exception(self.srvName + " do not exist")
+
+ @exportRpc
+ def serviceAddAgent(self, list):
+ '''
+ arguments: objectPath, xmlTemplate
+ '''
+ self.agentObjectPath = list[0]
+ xmlTemplate = list[1]
+ self.className = re.sub('/', '_', self.agentObjectPath[1:])
+ if (self.dynDBusClasses.has_key(self.className) == False):
+ self.dynDBusClasses[self.className] = DynDBusClass(self.className, self.globalCtx, self.localCtx)
+ self.dynDBusClasses[self.className].createDBusServiceFromXML(xmlTemplate)
+ self.dynDBusClasses[self.className].declare()
+
+ ## Class already exist, instanciate it if not already instanciated
+ if (self.serviceAgents.has_key(self.className) == False):
+ self.serviceAgents[self.className] = eval(self.className + "(self.bus, callback=self.srvCB, objPath=self.agentObjectPath, busName=self.srvName)", self.globalCtx, self.localCtx)
+
+ self.serviceAgents[self.className].add_to_connection()
+ return (self.agentObjectPath)
+
+ @exportRpc
+ def serviceDelAgent(self, list):
+ '''
+ arguments: objectPath, xmlTemplate
+ '''
+ agentObjectPath = list[0]
+ className = re.sub('/', '_', agentObjectPath[1:])
+
+ if (self.serviceAgents.has_key(className)):
+ self.serviceAgents[self.className].remove_from_connection()
+ self.serviceAgents.pop(self.className)
+ else:
+ raise Exception(agentObjectPath + " doesn't exist!")
+
+ return (agentObjectPath)
+
+ @exportRpc
def getVersion(self):
'''
return current version string
--- /dev/null
+{
+ "cloudeebus": "secret"
+}
--- /dev/null
+[
+ "org.cloudeebus.Sample"
+]
--- /dev/null
+<!DOCTYPE html>
+<html>
+ <head>
+ <script src="../../lib/autobahn.min.js"></script>
+ <script src="../../cloudeebus/cloudeebus.js"></script>
+ <script type="text/javascript">
+ function evalScript() {
+ eval(
+ "var lambda = function() {" +
+ document.getElementById('script').value +
+ "};" +
+ "lambda();"
+ );
+ }
+ </script>
+ </head>
+ <body>
+ <center><h1>cloudeebus</h1></center>
+ <br>
+ <textarea style="width:80%" rows="32" id="script">
+var manifest = {
+ name: "cloudeebus",
+ key: "secret",
+ permissions: [
+ "org.cloudeebus.Sample"
+ ]
+};
+
+
+var sampleProxy = null;
+
+cloudeebus.log = function(msg) {
+ document.getElementById("log").innerHTML += msg + "\n";
+}
+
+function logCB(result) {
+ cloudeebus.log(JSON.stringify(result));
+}
+
+function errorCB(error) {
+ cloudeebus.log(error.desc ? error.desc : error);
+}
+
+function gotDictResult(result) {
+ cloudeebus.log("gotDictResult: " + JSON.stringify(result));
+ cloudeebus.log("Name: " + result.Name);
+}
+
+function gotDivResult(result) {
+ cloudeebus.log("gotDivResult: " + result);
+ var dictionary = {Name: "Mickey",
+ Sisters: [""],
+ Married: true,
+ Divorced: 0,
+ Friends: ["Donald", "Dingo"],
+ Others: [""]};
+ sampleProxy.Variant(dictionary).then(gotDictResult,errorCB);
+// sampleProxy.Release();
+}
+
+function gotAddResult(result) {
+ cloudeebus.log("gotAddResult: " + result);
+ logCB('Divide by 3.33');
+ sampleProxy.Div(result,3.33).then(gotDivResult,errorCB);
+}
+
+function signalHandler(result) {
+ cloudeebus.log("signal 'ResultChanged': " + result);
+}
+
+function gotProxy(proxy) {
+ sampleProxy = proxy;
+ logCB(sampleProxy);
+ if (0) {
+ proxy.Release();
+ return;
+ } else {
+ proxy.connectToSignal("org.cloudeebus.Sample1", "ResultChanged", signalHandler);
+ logCB('Addition');
+
+ for (var i=-10; i<10; i++)
+ proxy.Add(i,i*2).then(gotAddResult,errorCB);
+ }
+
+}
+
+function connectSuccess() {
+ cloudeebus.SessionBus().getObject("org.cloudeebus.Sample", "/org/cloudeebus/Sample", gotProxy, errorCB);
+}
+
+cloudeebus.connect("ws://localhost:9002", manifest, connectSuccess, errorCB);
+</textarea>
+ <br>
+ <input type="button" value="run script" onclick="evalScript()"/>
+ <input type="button" value="clear log" onclick="document.getElementById('log').innerHTML='';"/>
+ <br>
+ <pre id="log" style="height: 20em; overflow-x: auto; overflow-y: auto; background-color: #faa;"></pre>
+ </body>
+</html>
--- /dev/null
+#!/bin/sh
+
+cloudeebus.py -d -c ./CREDENTIALS -w ./WHITELIST -p 9002
--- /dev/null
+<!DOCTYPE html>
+<html>
+ <head>
+ <script src="../../lib/autobahn.min.js"></script>
+ <script src="../../cloudeebus/cloudeebus.js"></script>
+ <script type="text/javascript">
+ function evalScript() {
+ eval(
+ "var lambda = function() {" +
+ document.getElementById('script').value +
+ "};" +
+ "lambda();"
+ );
+ }
+ </script>
+ </head>
+ <body>
+ <center><h1>cloudeebus</h1></center>
+ <br>
+ <textarea style="width:80%" rows="32" id="script">var sampleXml= '<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"\n"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">\n<node><interface name="org.cloudeebus.Sample1"><method name="Release"></method><method name="Add"><arg type="i" name="arg1"/><arg type="i" name="arg2"/><arg type="i" name="result" direction="out"/></method><method name="Variant"><arg type="a{sv}" name="arg1"/><arg type="a{sv}" name="result" direction="out"/></method><signal name="ResultChanged"><arg type="v" name="result"/></signal></interface><interface name="org.cloudeebus.Sample2"><method name="Div"><arg type="d" name="arg1"/><arg type="d" name="arg2"/><arg type="d" name="result" direction="out"/></method></interface></node>';
+var sampleXml= '<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"\n"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">\n<node><interface name="org.cloudeebus.Sample1"><method name="Release"></method><method name="Add"><arg type="i" name="arg1"/><arg type="i" name="arg2"/><arg type="i" name="result" direction="out"/></method><method name="Variant"><arg type="a{sv}" name="arg1"/><arg type="a{sv}" name="result" direction="out"/></method><signal name="ResultChanged"><arg type="v" name="result"/></signal></interface><interface name="org.cloudeebus.Sample2"><method name="Div"><arg type="d" name="arg1"/><arg type="d" name="arg2"/><arg type="d" name="result" direction="out"/></method></interface></node>';
+cloudeebus.log = function(msg) {
+ document.getElementById("log").innerHTML += msg + "\n";
+}
+
+function logCB(result) {
+ cloudeebus.log(JSON.stringify(result));
+}
+
+function errorCB(error) {
+ cloudeebus.log(error.desc ? error.desc : error);
+}
+
+sampleObjectHandler = {
+ Add: function(a,b) {
+ cloudeebus.log("Add " + a + " + " + b);
+ this.ResultChanged(a+b);
+ return a+b;
+ },
+ Variant: function(a) {
+ cloudeebus.log("Get and return :" + JSON.stringify(a));
+ return a;
+ },
+ Release: function() {
+ cloudeebus.SessionBus().service.delAgent("/org/cloudeebus/Sample", logCB, errorCB);
+ cloudeebus.SessionBus().service.remove(logCB, errorCB);
+ },
+ interfaceProxies : {
+ "org.cloudeebus.Sample2" : {
+ Div: function(a,b) {
+ cloudeebus.log("Div " + a + " / " + b);
+ this.ResultChanged(a/b);
+ return a/b;
+ }
+ }
+ }
+};
+
+sampleObjectHandler2 = {
+ interfaceProxies : {
+ "org.cloudeebus.Sample1" : {
+ Add: function(a,b) {
+ this.interfaceProxies["org.cloudeebus.Sample1"].ResultChanged(a+b);
+ return a+b;
+ },
+ Variant: function(a) {
+ cloudeebus.log("Get and return :" + JSON.stringify(a));
+ return a;
+ },
+ Release: function() {
+ cloudeebus.SessionBus().service.delAgent("/org/cloudeebus/Sample", logCB, errorCB);
+ cloudeebus.SessionBus().service.remove(logCB, errorCB);
+ },
+ },
+ "org.cloudeebus.Sample2" : {
+ Div: function(a,b) {
+ return a/b;
+ }
+ }
+ }
+};
+
+function addAgents(service) {
+ var agentName = "/org/cloudeebus/Sample"; // = DBUS object name
+ cloudeebus.log("Adding agent " + agentName + " on " + service.name + "and mapped on Javascript object: 'sampleObjectHandler");
+ cloudeebus.SessionBus().service.addAgent(agentName, sampleXml, sampleObjectHandler, logCB, errorCB);
+
+ // adding another agent using parameter 'service'
+ agentName = agentName +"2";
+ cloudeebus.log("Adding agent " + agentName + " on " + service.name + "and mapped on Javascript object: 'sampleObjectHandler2'");
+ service.addAgent(agentName, sampleXml, sampleObjectHandler2, logCB, errorCB);
+}
+
+function connectSuccess() {
+ cloudeebus.SessionBus().addService("org.cloudeebus.Sample").then(addAgents, errorCB);
+}
+
+cloudeebus.connect("ws://localhost:9003", null, connectSuccess, errorCB);
+</textarea>
+ <br>
+- <input type="button" value="run script" onclick="evalScript()"/>
+ <input type="button" value="clear log" onclick="document.getElementById('log').innerHTML='';"/>
+ <br>
+ <pre id="log" style="height: 20em; overflow-x: auto; overflow-y: auto; background-color: #faa;"></pre>
+ </body>
+</html>
--- /dev/null
+#!/bin/sh
+
+cloudeebus.py -d -o -p 9003
--- /dev/null
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<busconfig>
+ <policy user="root">
+ <allow own="org.cloudeebus"/>
+ <allow send_destination="org.cloudeebus"/>
+ </policy>
+ <policy at_console="true">
+ <allow send_destination="org.cloudeebus"/>
+ </policy>
+ <policy context="default">
+ <deny send_destination="org.cloudeebus"/>
+ </policy>
+ </busconfig>
from setuptools import setup
setup(name = "cloudeebus",
- version = "0.5.1",
+ version = "0.5.0",
description = "Javascript-DBus bridge",
author = "Luc Yriarte, Christophe Guiraud, Frederic Paut",
author_email = "luc.yriarte@intel.com, christophe.guiraud@intel.com, frederic.paut@intel.com",
license = "http://www.apache.org/licenses/LICENSE-2.0",
scripts = ["cloudeebus/cloudeebus.py"],
packages = ["cloudeebus"],
- data_files = [("cloudeebus" ,["AUTHORS", "README.md", "LICENSE"])],
+ data_files = [("cloudeebus" ,["AUTHORS", "README.md", "LICENSE"]),
+ ('/etc/dbus-1/system.d/', ['org.cloudeebus.conf'])],
platforms = ("Any"),
install_requires = ["setuptools", "autobahn>=0.5.8"],
classifiers = ["License :: OSI Approved :: Apache Software License",