Author: remi
Date: 2009-03-27 13:43:14 +0100 (Fri, 27 Mar 2009)
New Revision: 4219
Added:
software_suite_v2/tuxware/tuxdroidserver/trunk/resources/01_robot_system/resourceAttituneManager.py
Log:
* started the resource "Attitune Manager"
Added:
software_suite_v2/tuxware/tuxdroidserver/trunk/resources/01_robot_system/resourceAttituneManager.py
===================================================================
---
software_suite_v2/tuxware/tuxdroidserver/trunk/resources/01_robot_system/resourceAttituneManager.py
(rev 0)
+++
software_suite_v2/tuxware/tuxdroidserver/trunk/resources/01_robot_system/resourceAttituneManager.py
2009-03-27 12:43:14 UTC (rev 4219)
@@ -0,0 +1,266 @@
+#
==============================================================================
+# Attitune manager resource.
+#
==============================================================================
+
+from util.attitunes.AttitunesContainer import AttitunesContainer
+from util.misc.tuxPaths import USER_BASE_PATH
+from util.logger.SimpleLogger import *
+
+# Attitune manager events/statuses
+ST_NAME_AM_RUN = "attitune_manager_run"
+ST_NAME_AM_CONTAINER_DEPLOYED = "attitune_manager_container_deployed"
+ST_NAME_AM_CONTAINER_ERROR = "attitune_manager_container_error"
+ST_NAME_AM_ATTITUNE_LOADED = "attitune_manager_attitune_loaded"
+ST_NAME_AM_ATTITUNE_UNLOADED = "attitune_manager_attitune_unloaded"
+ST_NAME_AM_ATTITUNE_STARTING = "attitune_manager_attitune_starting"
+ST_NAME_AM_ATTITUNE_STOPPED = "attitune_manager_attitune_stopped"
+
+# Attitune manager events/statuses list
+SW_NAME_ATTITUNE_MANAGER = [
+ ST_NAME_AM_RUN, # Is sent to clients
+ ST_NAME_AM_CONTAINER_DEPLOYED, # Is sent to clients
+ ST_NAME_AM_CONTAINER_ERROR, # Is not sent to clients
+ ST_NAME_AM_ATTITUNE_LOADED, # Is not sent to clients
+ ST_NAME_AM_ATTITUNE_UNLOADED, # Is not sent to clients
+ ST_NAME_AM_ATTITUNE_STARTING, # Is sent to clients
+ ST_NAME_AM_ATTITUNE_STOPPED, # Is sent to clients
+]
+
+#
------------------------------------------------------------------------------
+# Declaration of the resource "attitune_manager".
+#
------------------------------------------------------------------------------
+class TDSResourceAttituneManager(TDSResource):
+
+ #
--------------------------------------------------------------------------
+ # Inherited methods from TDSResource
+ #
--------------------------------------------------------------------------
+
+ def configure(self):
+ self.name = "attitune_manager"
+ self.comment = "Resource to manage the attitunes container."
+ self.fileName = RESOURCE_FILENAME
+ # Create a gadgets container
+ self.__attitunesContainer = AttitunesContainer()
+
self.__attitunesContainer.setOnDirectoryDeployedCallback(self.__onDirectoryDeployed)
+
self.__attitunesContainer.setOnDirectoryUndeployedCallback(self.__onDirectoryUndeployed)
+
self.__attitunesContainer.setOnAttituneDeployedCallback(self.__onAttituneDeployed)
+
self.__attitunesContainer.setOnAttituneUndeployedCallback(self.__onAttituneUndeployed)
+
self.__attitunesContainer.setOnAttituneDeploymentErrorCallback(self.__onAttituneDeploymentError)
+ # Registering the attitune manager statuses and add it in the excluded
list.
+ # Clients have to syndicate to receive.
+ for statusName in SW_NAME_ATTITUNE_MANAGER:
+ eventsHandler.insert(statusName)
+ clientsManager.addDefaultExcludedEvent(statusName)
+ eventsHandler.getEventHandler(ST_NAME_AM_RUN).updateState("False")
+ # Default configuration
+ attitunesPath = os.path.join(USER_BASE_PATH, "MyTux", "MyTuxAttitunes")
+ self.defaultConfiguration = {
+ 'auto-start' : True,
+ 'attitunes_path' : attitunesPath,
+ }
+ # Create a logger
+ self.logger = SimpleLogger("attitune_manager")
+ self.logger.resetLog()
+ self.logger.setLevel(LOG_LEVEL_DEBUG)
+ self.logger.setTarget(LOG_TARGET_BOTH)
+ self.logger.logInfo("-----------------------------------------------")
+ self.logger.logInfo("Tux Droid Attitune Manager")
+ self.logger.logInfo("Licence : GPL")
+ self.logger.logInfo("-----------------------------------------------")
+
+ def stop(self):
+ self.getConfigurator().store()
+ self.logger.logInfo("Undeploy the attitunes container")
+ self.__attitunesContainer.undeploy()
+ self.__publishEvents(True, ST_NAME_AM_RUN, ["False",])
+
+ #
--------------------------------------------------------------------------
+ # Attitunes container events
+ #
--------------------------------------------------------------------------
+
+ def __onDirectoryDeployed(self, observerName):
+ self.logger.logInfo("Directory deployed [%s]" % observerName)
+ self.__publishEvents(True, ST_NAME_AM_CONTAINER_DEPLOYED, ["True",])
+
+ def __onDirectoryUndeployed(self, observerName):
+ self.logger.logInfo("Directory undeployed [%s]" % observerName)
+ self.__publishEvents(True, ST_NAME_AM_CONTAINER_DEPLOYED, ["False",])
+
+ def __onAttituneDeployed(self, attitune, attituneWorkingPath):
+ self.logger.logDebug("Attitune deployed [%s] to [%s]" % (
+ attitune.getDescription().getName(), attituneWorkingPath))
+ self.__publishEvents(False, ST_NAME_AM_ATTITUNE_LOADED,
+ [attitune.getDescription().getName(),])
+
+ def __onAttituneDeploymentError(self, observerName, attituneFileName,
message):
+ messagesList = [
+ observerName,
+ attituneFileName,
+ message,
+ ]
+ self.logger.logWarning("Attitune deployment error [%s, %s] to (%s)" % (
+ observerName, attituneFileName, message))
+ self.__publishEvents(False, ST_NAME_AM_CONTAINER_ERROR, messagesList)
+
+ def __onAttituneUndeployed(self, gadget, attituneWorkingPath):
+ self.logger.logDebug("Attitune undeployed [%s] to [%s]" % (
+ attitune.getDescription().getName(), attituneWorkingPath))
+ self.__publishEvents(False, ST_NAME_AM_ATTITUNE_UNLOADED,
+ [attitune.getDescription().getName(),])
+
+ #
--------------------------------------------------------------------------
+ # Private methods
+ #
--------------------------------------------------------------------------
+
+ def __publishEvents(self, sendToClients, eventName, eventValues = []):
+ def async():
+ values = ""
+ for value in eventValues:
+ values += value + ":"
+ if len(values) > 0:
+ values = values[:-1]
+ eventStruct = {
+ 'name' : eventName,
+ 'value' : values,
+ 'delay' : "0.0",
+ 'type' : "string"
+ }
+ if sendToClients:
+ clientsManager.pushEvents([eventStruct,])
+ eventsHandler.emit(eventName, (values, 0.0))
+ t = threading.Thread(target = async)
+ t.start()
+
+ #
--------------------------------------------------------------------------
+ # Shared methods
+ #
--------------------------------------------------------------------------
+
+ def publishEvents(self, sendToClients, eventName, eventValues = []):
+ """
+ """
+ self.__publishEvents(sendToClients, eventName, eventValues)
+
+ def getAttitunesContainer(self):
+ """Get the attitunes container.
+ @return: The attitunes container.
+ """
+ return self.__attitunesContainer
+
+ def insertAttituneInContainer(self, attFilename):
+ """Insert an attitune in the container.
+ @param attFilename: ATT attitune file name.
+ @return: The success.
+ - attFilename can be a local file or an external file (URL)
+ """
+ # Check that the attitune manager is started
+ if not self.__attitunesContainer.isDeployed():
+ return False
+ # Check that the container directory is selected
+ directories = self.__attitunesContainer.getDirectories()
+ if len(directories) == 0:
+ return False
+ directory = directories[-1]
+ # Check the file extension
+ if attFilename.lower().rfind(".att") == -1:
+ return False
+ # Create a cached file with the attitune file
+ cFile = filesCacheManager.createFileCache(attFilename)
+ # If the attitune can't be cached then FAIL
+ if cFile == None:
+ return False
+ # Copy the attitune in the container directory
+ result = True
+ import shutil
+ try:
+ attName = os.path.split(attFilename)[-1]
+ attName = os.path.join(directory, attName)
+ shutil.copy(cFile.getOutputFilePath(), attName)
+ except:
+ result = False
+ filesCacheManager.destroyFileCache(cFile)
+ return result
+
+ def removeAttituneFromContainer(self, attituneName):
+ """Remove an attitune from the attitunes container.
+ @param attituneName: Attitune name.
+ @return: The success.
+ """
+ # Check that the attitune manager is started
+ if not self.__attitunesContainer.isDeployed():
+ return False
+ for attitune in self.__attitunesContainer.getAttitunes():
+ if attitune.getDescription().getName() == attituneName:
+ attFile = attitune.getAttFile()
+ # Remove the att file
+ DirectoriesAndFilesTools.RMFile(attFile)
+ return True
+ return False
+
+# Create an instance of the resource
+resourceAttituneManager = TDSResourceAttituneManager("resourceAttituneManager")
+# Register the resource into the resources manager
+resourcesManager.addResource(resourceAttituneManager)
+
+#
------------------------------------------------------------------------------
+# Declaration of the service "start".
+#
------------------------------------------------------------------------------
+class TDSServiceAttituneManagerStart(TDSService):
+
+ def configure(self):
+ self.parametersDict = {
+ 'attitunes_path' : 'string',
+ }
+ self.minimalUserLevel = TDS_CLIENT_LEVEL_ANONYMOUS
+ self.exclusiveExecution = False
+ self.name = "start"
+ self.comment = "Start the attitune manager."
+
+ def start(self):
+ # Auto start of this service with the resource configuration.
+ config = resourceAttituneManager.getConfigurator().load(
+ "resourceAttituneManager.conf",
+ resourceAttituneManager.defaultConfiguration)
+ if config['auto-start']:
+ attitunesContainer =
resourceAttituneManager.getAttitunesContainer()
+ resourceAttituneManager.logger.logInfo("Add directory in the
container [%s]." %\
+ config['attitunes_path'])
+ attitunesContainer.addDirectory(config['attitunes_path'])
+ resourceAttituneManager.logger.logInfo("Deploy the attitunes
container.")
+ attitunesContainer.deploy()
+ resourceAttituneManager.logger.logInfo("Attitunes container is
deployed.")
+ resourceAttituneManager.publishEvents(True, ST_NAME_AM_RUN,
["True",])
+
+ def execute(self, id, parameters):
+ headersStruct = self.getDefaultHeadersStruct()
+ contentStruct = self.getDefaultContentStruct()
+ contentStruct['root']['result'] = getStrError(E_TDREST_SUCCESS)
+ # Check the directory
+ if not os.path.isdir(parameters['attitunes_path']):
+ contentStruct['root']['result'] = getStrError(E_TDREST_FAILED)
+ else:
+ # Store the configuration
+ configurator = resourceAttituneManager.getConfigurator()
+ config = configurator.getConfiguration()
+ config['attitunes_path'] = parameters['attitunes_path']
+ configurator.store()
+ # Start the attitune manager
+ attitunesContainer =
resourceAttituneManager.getAttitunesContainer()
+ resourceAttituneManager.publishEvents(True, ST_NAME_AM_RUN,
["False",])
+ resourceAttituneManager.logger.logInfo("Undeploy the attitunes
container.")
+ attitunesContainer.undeploy()
+ resourceAttituneManager.logger.logInfo("Attitunes container is
undeployed.")
+ for directory in attitunesContainer.getDirectories():
+ resourceAttituneManager.logger.logInfo("Remove directory from
the container [%s]." %\
+ directory)
+ attitunesContainer.removeDirectory(directory)
+ resourceAttituneManager.logger.logInfo("Add directory in the
container [%s]." %\
+ config['attitunes_path'])
+ attitunesContainer.addDirectory(config['attitunes_path'])
+ resourceAttituneManager.logger.logInfo("Deploy the attitunes
container.")
+ attitunesContainer.deploy()
+ resourceAttituneManager.logger.logInfo("Attitunes container is
deployed.")
+ resourceAttituneManager.publishEvents(True, ST_NAME_AM_RUN,
["True",])
+ return headersStruct, contentStruct
+
+# Register the service into the resource
+resourceAttituneManager.addService(TDSServiceAttituneManagerStart)
Property changes on:
software_suite_v2/tuxware/tuxdroidserver/trunk/resources/01_robot_system/resourceAttituneManager.py
___________________________________________________________________
Name: svn:keywords
+ Id
------------------------------------------------------------------------------
_______________________________________________
Tux-droid-svn mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/tux-droid-svn