remove debug trace in generated code
[contrib/cloudeebus.git] / cloudeebus / cloudeebus.py
index 35789c2..69e499f 100755 (executable)
@@ -48,9 +48,10 @@ from twisted.python import log
 # XML parser module
 from xml.etree.ElementTree import XMLParser
 
+
 ###############################################################################
 
-VERSION = "0.2.1"
+VERSION = "0.3.0"
 OPENDOOR = False
 CREDENTIALS = {}
 WHITELIST = []
@@ -146,41 +147,30 @@ class DbusCallHandler:
         '''
         return dbus error message
         '''
-        self.request.errback(error.get_dbus_message())
+        self.request.errback(Exception(error.get_dbus_message()))
         self.pending = False
 
 
 
 ################################################################################       
 class exec_code:
-    def __init__(self) :
+    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
-
-    # __str__ : Return a string representation of the object, for
-    # nice printing.
-    def __str__(self) :
-        return self.exec_string
-
-    def p(self) :
-        print str(self)
+        self.localCtx = localCtx
+        self.globalCtx = globalCtx
+        
 
     def append_stmt(self, stmt) :
         self.exec_code_valid = 0
         self.line += 1
-        if (stmt != "\n"):
-            for x in range(0,self.indent_level):
-                self.exec_string = self.exec_string + ' '            
-            self.exec_string = self.exec_string + stmt + "\t\t# l:" + str(self.line) + '\n'
-        else:
-            if (stmt == "\n"):
-                self.exec_string = self.exec_string + "# l:" + str(self.line) + '\n'
-            else:
-                self.exec_string = self.exec_string + stmt + "\t\t# l:" + str(self.line) + '\n'
+        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
@@ -193,12 +183,12 @@ class exec_code:
     def compile(self) :
         if not self.exec_code_valid :
             self.exec_code = compile(self.exec_string, "<string>", "exec")
-        self.exec_code_valid = 1
+        self.exec_code_valid = True
 
     def execute(self) :
         if not self.exec_code_valid :
             self.compile()
-        exec self.exec_code
+        exec(self.exec_code, self.globalCtx, self.localCtx)
 
 
 
@@ -229,6 +219,8 @@ class XmlCb_Parser: # The target object of the parser
         # 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'])
@@ -259,14 +251,11 @@ class dynDBusClass():
     def __init__(self, className, globalCtx, localCtx):
         self.className = className
         self.xmlCB = XmlCb_Parser(self)
-        self.localCtx = localCtx
-        self.globalCtx = globalCtx        
         self.signature = {}
-        self.class_code = exec_code()  
+        self.class_code = exec_code(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("\n")
         self.class_code.append_stmt("class " + self.className + "(dbus.service.Object):")
         self.class_code.indent()
         
@@ -276,7 +265,19 @@ class dynDBusClass():
         self.add_stmt("self.bus = bus")
         self.add_stmt("self.objName = objName")
         self.add_stmt("self.callback = callback")        
-        self.add_stmt("dbus.service.Object.__init__(self, conn=bus, object_path=objName, bus_name=busName)")
+        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.objName)")
+        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.objName)")
         self.end_method()
                
     def createDBusServiceFromXML(self, xml):
@@ -314,31 +315,35 @@ class dynDBusClass():
         if (direction == 'out'):
             self.signature['out'] = signature                        
         
-    def add_method(self, args = None, async_cb = None, async_err_cb = None):
+    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_cb != None):
-            if (self.args_str != str()):
-                self.args_str += ", "
-            self.args_str += async_cb
+        if (async_success_cb != None):
+            async_cb_str = async_success_cb
         if (async_err_cb != None):
-            if (self.args_str != str()):
-                self.args_str += ", "
-            self.args_str += async_err_cb
+            if (async_cb_str != str()):
+                async_cb_str += ", "
+            async_cb_str += async_err_cb
                         
-        if (self.args_str != str()):
-            self.class_code.append_stmt("def " + name + "(self, %s):" % self.args_str)
+        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.append_stmt("\n")        
         self.class_code.dedent()
         
     def add_dbus_method(self):
@@ -351,9 +356,9 @@ class dynDBusClass():
         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_cb='dbus_async_cb', async_err_cb='dbus_async_err_cb')
+            self.add_method(self.signature['name'], async_success_cb='dbus_async_cb', async_err_cb='dbus_async_err_cb')
         else:
-            self.add_method(async_cb='dbus_async_cb', async_err_cb='dbus_async_err_cb')
+            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 + '"'
@@ -368,11 +373,10 @@ class dynDBusClass():
 
     def add_body_method(self):
         if (self.methodToAdd != None):
-            self.class_code.append_stmt("print 'In " + self.methodToAdd + "()'")
             if (self.args_str != str()):
                 self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', dbus_async_cb, dbus_async_err_cb, %s)" % self.args_str)
             else:        
-                self.class_code.append_stmt("self.callback('" + self.methodToAdd + "')")
+                self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', 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
@@ -382,19 +386,7 @@ class dynDBusClass():
         self.class_code.append_stmt(stmt)
         
     def declare(self) :
-        self.class_code.compile()
-        exec(self.class_code.exec_string, self.globalCtx, self.localCtx)
-     
-    def __str__(self) :
-        return self.class_code.exec_string
-
-    # p : Since it is often useful to be able to look at the code
-    # that is generated interactively, this function provides
-    # a shorthand for "print str(some_exec_code_instance)", which
-    # gives a reasonable nice look at the contents of the
-    # exec_code object.
-    def p(self) :
-        print str(self)
+        self.class_code.execute()
 
 
 
@@ -411,6 +403,9 @@ class CloudeebusService:
         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):
@@ -489,13 +484,97 @@ class CloudeebusService:
         return dbusCallHandler.callMethod()
 
 
+    @exportRpc
+    def returnMethod(self, list):
+        '''
+        arguments: methodId, success (=true, error otherwise), result (to return)
+        '''
+        methodId = list[0]
+        success = list[1]
+        result = list[2]
+        if (self.servicePendingCalls.has_key(methodId)):
+            cb = self.servicePendingCalls[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] = None
+        else:
+            print "No methodID %s  !!" % (methodId)  
+
+    def jsonEncodeTupleKeyDict(self, data):
+        ndict = dict()
+        # creates new dictionary with the original tuple converted to json string
+        dataLen = len(data)
+        string = ""
+        for index in range(dataLen):
+            for key in data[index]:
+                value = data[index][key]
+                print "key=" + key
+                print "value=" + str(value)
+                nkey = str(key)
+                nvalue = ""
+                print "JSON key=" + nkey
+                if (isinstance(value, dbus.Array)):
+                    # Searching dbus byte in array...
+                    ValueLen = len(value)
+                    nvalue = []
+                    for indexValue in range(ValueLen):
+                        a = value[indexValue]
+                        if (isinstance(a, dbus.Byte)):
+                            a = int(value[indexValue])
+                            nvalue.append(a)
+                        else:
+                            nvalue = str(value[indexValue])
+                            
+                print "JSON value=" + str(nvalue)                
+                ndict[nkey] =  nvalue
+
+        return ndict
+
     def srvCB(self, name, async_succes_cb, async_error_cb, *args):
-        seconds = 10
-        print "self.srvCB(name='%s', args=%s')\n\n" % (name, str(args))
-        if (async_error_cb != None):
-            t.start()
-            time.sleep(seconds + 2)
-        
+        methodId = self.srvName + "#" + self.agentObjectPath + "#" + name
+        cb = { 'successCB': async_succes_cb, 
+               'errorCB': async_error_cb}
+        self.servicePendingCalls[methodId] = cb
+
+        if (len(args) > 0):
+            print "Received args=%s" % (str(args))
+        else:                     
+            print "No args received"
+            
+        try:               
+            print "factory.dispatch(methodId=%s, args=%s)" % (methodId, json.dumps(args))                     
+            factory.dispatch(methodId, json.dumps(args))
+            return
+        except Exception, e :
+            print "Error=%s" % (str(e))
+            
+        print "Trying to decode dbus.Dictionnary..."
+        try:
+            params = self.jsonEncodeTupleKeyDict(args)                
+            print "factory.dispatch(methodId=%s, args=%s)" % (methodId, params)                     
+            factory.dispatch(methodId, params)
+            return
+        except Exception, e :
+            print "Error=%s" % (str(e))
+                    
+        print "Trying to pass args as string..."
+        try:               
+            print "factory.dispatch(methodId=%s, args=%s)" % (methodId, str(args))                     
+            factory.dispatch(methodId, str(args))
+            return
+        except Exception, e :
+            print "Error=%s" % (str(e))
+                    
     @exportRpc
     def serviceAdd(self, list):
         '''
@@ -507,24 +586,54 @@ class CloudeebusService:
         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
         '''
-        objectPath = list[0]
+        self.agentObjectPath = list[0]
         xmlTemplate = list[1]
-        className = re.sub('/', '_', objectPath[1:])
-        if (self.dynDBusClasses.has_key(className) == False):
-            self.dynDBusClasses[className] = dynDBusClass(className, globals(), locals())
-            self.dynDBusClasses[className].createDBusServiceFromXML(xmlTemplate)
-            self.dynDBusClasses[className].declare()
-#            self.dynDBusClass[className].p()
-
-            if (self.serviceAgents.has_key(className) == False):            
-                exe_str = "self.serviceAgents[" + className +"] = " + className + "(self.bus, callback=self.srvCB, objName=objectPath, busName=self.srvName)"
-                exec (exe_str, globals(), locals())
+        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, objName=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):