Remove traces when decoding JSON arguments for dbus patterns
[contrib/cloudeebus.git] / cloudeebus / cloudeebus.py
index 232b862..7f1517e 100755 (executable)
@@ -51,7 +51,7 @@ from xml.etree.ElementTree import XMLParser
 
 ###############################################################################
 
-VERSION = "0.5.99"
+VERSION = "0.6.0"
 OPENDOOR = False
 CREDENTIALS = {}
 WHITELIST = []
@@ -297,11 +297,12 @@ class DynDBusClass():
         
         ## Overload of __init__ method 
         self.def_method("__init__")
-        self.add_method("bus, callback=None, objPath='/sample', busName='org.cloudeebus'")
+        self.add_method("bus, callback=None, objPath='/sample', srvName='org.cloudeebus'")
         self.add_stmt("self.bus = bus")
         self.add_stmt("self.objPath = objPath")
+        self.add_stmt("self.srvName = srvName")        
         self.add_stmt("self.callback = callback")        
-        self.add_stmt("dbus.service.Object.__init__(self, conn=bus, bus_name=busName)")
+        self.add_stmt("dbus.service.Object.__init__(self, conn=bus, bus_name=srvName)")
         self.end_method()
                
         ## Create 'add_to_connection' method 
@@ -410,9 +411,9 @@ class DynDBusClass():
     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)
+                self.class_code.append_stmt("self.callback(self.srvName,'" + 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)")
+                self.class_code.append_stmt("self.callback(self.srvName,'" + 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
@@ -446,6 +447,16 @@ class CloudeebusService:
         self.localCtx = locals()
         self.globalCtx = globals()
 
+        self.patternDbus        = re.compile('^dbus\.(\w+)')
+        self.patternDbusBoolean = re.compile('^dbus.Boolean\((\w+)\)$')
+        self.patternDbusByte    = re.compile('^dbus.Byte\((\d+)\)$')
+        self.patternDbusInt16   = re.compile('^dbus.Int16\((\d+)\)$')
+        self.patternDbusInt32   = re.compile('^dbus.Int32\((\d+)\)$')
+        self.patternDbusInt64   = re.compile('^dbus.Int64\((\d+)\)$')
+        self.patternDbusUInt16  = re.compile('^dbus.UInt16\((\d+)\)$')
+        self.patternDbusUInt32  = re.compile('^dbus.UInt32\((\d+)\)$')
+        self.patternDbusUInt64  = re.compile('^dbus.UInt64\((\d+)\)$')
+        self.patternDbusDouble  = re.compile('^dbus.Double\((\d+\.\d+)\)$')
 
     def proxyObject(self, busName, serviceName, objectName):
         '''
@@ -471,6 +482,45 @@ class CloudeebusService:
             self.proxyMethods[id] = obj.get_dbus_method(methodName, interfaceName)
         return self.proxyMethods[id]
 
+    def decodeArgs( self, args ):
+        if isinstance( args, list ):
+            newArgs = []
+            for arg in args:
+                newArgs.append( self.decodeArgs( arg ))
+            return newArgs
+        elif isinstance( args, dict ):
+            newDict = {}
+            for key, value in args.iteritems():
+                key = self.decodeArgs( key )
+                newValue = self.decodeArgs( value )
+                newDict[key] = newValue
+            return newDict
+        elif isinstance( args, basestring ):
+            newArg = self.decodeDbusString( args )
+            return newArg
+        else:
+            return args
+
+    def decodeDbusString( self, dbusString ):
+        matchDbus = self.patternDbus.match( dbusString )
+
+        if not matchDbus:
+            return dbusString
+
+
+        result = {
+           "Boolean" : lambda x : dbus.Boolean(   self.patternDbusBoolean.match( x ).group( 1 ).lower() in ("yes", "true", "t", "1")),
+           "Byte"    : lambda x : dbus.Byte( int( self.patternDbusByte.match(    x ).group( 1 ))),
+           "Int16"   : lambda x : dbus.Int16(     self.patternDbusInt16.match(   x ).group( 1 )),
+           "Int32"   : lambda x : dbus.Int32(     self.patternDbusInt32.match(   x ).group( 1 )),
+           "Int64"   : lambda x : dbus.Int64(     self.patternDbusInt64.match(    x ).group( 1 )),
+           "UInt16"  : lambda x : dbus.UInt16(    self.patternDbusUInt16.match(  x ).group( 1 )),
+           "UInt32"  : lambda x : dbus.UInt32(    self.patternDbusUInt32.match(  x ).group( 1 )),
+           "UInt64"  : lambda x : dbus.UInt64(    self.patternDbusUInt64.match(   x ).group( 1 )),
+           "Double"  : lambda x : dbus.Double(    self.patternDbusDouble.match(  x ).group( 1 ))
+        }[matchDbus.group(1)](dbusString)
+
+        return result
 
     @exportRpc
     def dbusRegister(self, list):
@@ -512,7 +562,9 @@ class CloudeebusService:
         # parse JSON arg list
         args = []
         if len(list) == 6:
-            args = json.loads(list[5])
+            jsonArgs = json.loads(list[5])
+            if jsonArgs:
+                args = self.decodeArgs( jsonArgs )
         
         # get dbus proxy method
         method = self.proxyMethod(*list[0:5])
@@ -526,14 +578,25 @@ class CloudeebusService:
     @exportRpc
     def emitSignal(self, list):
         '''
-        arguments: agentObjectPath, signalName, result (to emit)
+        arguments: agentObjectPath, signalName, args (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) + ")"
+        args = []
+        jsonArgs = json.loads(list[2])
+        print "JSON Arguments:", jsonArgs
+        if jsonArgs:
+            args = self.decodeArgs( jsonArgs )
+            print "Decoded Arguments: ", args
+
+        if (self.serviceAgents.has_key(className) == True):            
+            exe_str = "self.serviceAgents['"+ className +"']."+ signalName + "("
+            if len(args) > 0:
+                exe_str += json.dumps(args[0])
+                for idx in args[1:]:
+                    exe_str += "," + json.dumps(idx)
+            exe_str += ")"               
             eval(exe_str, self.globalCtx, self.localCtx)
         else:
             raise Exception("No object path " + objectPath)
@@ -570,8 +633,8 @@ class CloudeebusService:
         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
+    def srvCB(self, srvName, name, objPath, ifName, async_succes_cb, async_error_cb, *args):
+        methodId = srvName + "#" + objPath + "#" + ifName + "#" + name
         cb = { 'successCB': async_succes_cb, 
                'errorCB': async_error_cb}
         if methodId not in self.servicePendingCalls:
@@ -594,34 +657,35 @@ class CloudeebusService:
         '''
         busName = list[0]
         self.bus =  cache.dbusConnexion( busName )
-        self.srvName = list[1]
+        srvName = list[1]
         if not OPENDOOR and (SERVICELIST == [] or SERVICELIST != [] and self.permissions['services'] == None):
-            SERVICELIST.index(self.srvName)
+            SERVICELIST.index(srvName)
             
-        if (self.services.has_key(self.srvName) == False):
-            self.services[self.srvName] = dbus.service.BusName(name = self.srvName, bus = self.bus)
-        return self.srvName
+        if (self.services.has_key(srvName) == False):
+            self.services[srvName] = dbus.service.BusName(name = srvName, bus = self.bus)
+        return 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
+        srvName = list[0]
+        if (self.services.has_key(srvName) == True):
+            self.services.pop(srvName)
+            return srvName
         else:
-            raise Exception(self.srvName + " does not exist")
+            raise Exception(srvName + " does not exist")
                    
     @exportRpc
     def serviceAddAgent(self, list):
         '''
         arguments: objectPath, xmlTemplate
         '''
-        self.agentObjectPath = list[0]
-        xmlTemplate = list[1]
-        className = createClassName(self.agentObjectPath)
+        srvName = list[0]
+        agentObjectPath = list[1]
+        xmlTemplate = list[2]
+        className = createClassName(agentObjectPath)
         if (self.dynDBusClasses.has_key(className) == False):
             self.dynDBusClasses[className] = DynDBusClass(className, self.globalCtx, self.localCtx)
             self.dynDBusClasses[className].createDBusServiceFromXML(xmlTemplate)
@@ -629,10 +693,10 @@ class CloudeebusService:
 
         ## Class already exist, instanciate it if not already instanciated
         if (self.serviceAgents.has_key(className) == False):
-            self.serviceAgents[className] = eval(className + "(self.bus, callback=self.srvCB, objPath=self.agentObjectPath, busName=self.srvName)", self.globalCtx, self.localCtx)
+            self.serviceAgents[className] = eval(className + "(self.bus, callback=self.srvCB, objPath='" + agentObjectPath + "', srvName='" + srvName + "')", self.globalCtx, self.localCtx)
             
         self.serviceAgents[className].add_to_connection()
-        return (self.agentObjectPath)
+        return (agentObjectPath)
                     
     @exportRpc
     def serviceDelAgent(self, list):
@@ -642,8 +706,6 @@ class CloudeebusService:
         agentObjectPath = list[0]
         className = createClassName(agentObjectPath)
         
-        print 'PY Try to remove ' + className
-
         if (self.serviceAgents.has_key(className)):
             self.serviceAgents[className].remove_from_connection()
             self.serviceAgents.pop(className)
@@ -787,15 +849,7 @@ if __name__ == '__main__':
                 ipAllowed = ip
                 mask = "255.255.255.255" 
             NETMASK.append( {'ipAllowed': ipV4ToHex(ipAllowed), 'mask' : ipV4ToHex(mask)} )
-    
-    if args.debug:
-        print "OPENDOOR='" + str(OPENDOOR) + "'" 
-        print "CREDENTIALS='" + str(args.credentials) + "'" 
-        print "WHITELIST='" + str(args.whitelist) + "'"
-        print "SERVICELIST='" + str(args.servicelist) + "'" 
-        print "NETMASK='" + str(args.netmask) + "'"
-        print 
-        
+
     uri = "ws://localhost:" + args.port
     
     factory = WampServerFactory(uri, debugWamp = args.debug)