def fromURItoPath(self, dbName): LOG("Create database " + repr(dbName)) idx = dbName.find('://') if idx != -1: # User database dbType = dbName[0:idx] dbName = dbName[idx + 3:] dbPath = self.__ctxConfig.getLocationPath( dbType.upper()) + os.sep + dbName LOG("User path: " + repr(dbPath)) else: # Preconfigured database location, filename = self.__ctxConfig.getDatabaseInfo(dbName) if location is None: raise DriverException("Unknown database location") if filename is None: raise DriverException("No database file") dbType = location lpath = self.__ctxConfig.getLocationPath(location) dbPath = lpath + os.sep + filename # Translate path tags idx = dbPath.find("$SATNAME$") if idx != -1: dbPath = dbPath[0:idx] + self.__ctxConfig.getSatName( ) + dbPath[idx + 9:] idx = dbPath.find("$SATID$") if idx != -1: dbPath = dbPath[0:idx] + self.__ctxConfig.getSC() + dbPath[idx + 7:] LOG("Database path: " + repr(dbPath)) return dbType, dbPath
def load(self): LOG("Load DB from file: " + repr(self._filename)) # If the file exists go on directly. Otherwise try to find it # no matter the case of the name if not os.path.exists(self._filename): basepath = os.path.dirname(self._filename) filename = os.path.basename(self._filename) found = False for root, dirs, files in os.walk(basepath, topdown=False): for f in files: if f.upper() == filename.upper(): path = basepath + os.sep + f found = True if not found: raise DriverException("Database file not found: " + repr(self._filename)) self._filename = path if not os.path.exists(self._filename): raise DriverException("Cannot load: no such file: " + self._filename) # Read the data from the file self._readData()
def delete(self): if not self.exists(): raise DriverException("Cannot delete " + repr(self), "File not found") if not self.canWrite(): raise DriverException("Cannot delete " + repr(self), "Not enough permissions") try: if self.isDir(): os.rmdir(self.__filename) else: os.remove(self.__filename) except OSError,ex: raise DriverException("Cannot delete " + repr(self), repr(ex))
def truncate(self): if not self.isOpen(): raise DriverException("Cannot truncate file", "File is not open") if self.isDir(): raise DriverException("Cannot truncate file", "It is a directory") if not self.canWrite(): raise DriverException("Cannot truncate file", "Permission denied") if self.__mode != WRITE and self.__mode != READ_WRITE and self.__mode != APPEND: raise DriverException("Cannot truncate file", "Incorrect file mode") try: self.__file.truncate() except Exception,ex: raise DriverException("Cannot truncate file", str(ex))
def flush(self): try: if not self.isOpen(): raise DriverException("Cannot flush file", "File is not open") if self.isDir(): raise DriverException("Cannot flush file", "It is a directory") if not self.canWrite(): raise DriverException("Cannot flush file", "Permission denied") if self.__mode != WRITE and self.__mode != READ_WRITE and self.__mode != APPEND: raise DriverException("Cannot flush file", "Incorrect file mode") self.__file.flush() except DriverException,ex: raise ex
def __init__(self, name, path, defaultExt=None): super(DatabaseFile, self).__init__() self._name = name self._defaultExt = defaultExt dataHome = os.getenv( "SPELL_DATA", (os.getenv("SPELL_HOME") + os.sep + "data")).replace('/', os.sep) if dataHome is None: raise DriverException( "SPELL_DATA environment variable not defined") # Append the data home to the path thePath = dataHome + os.sep + path.replace('/', os.sep) # First check if there is an extension in the file. If there is no # extension, append the default extension (if there is one). filename = os.path.basename(thePath) if (not len(filename.split(".")) > 1) and (defaultExt is not None): thePath += "." + defaultExt self._filename = thePath LOG("Instanciated: " + name)
def _setLimits(self, param, limits, config ): """ Modify an Out Of Limits definition for a given telemetry parameter param: the telemetry parameter name limits: dictionary containing the limit parameters config: configuration dictionary with modifiers Relevant modifiers are: - Select=ACTIVE/ALL/<STR>: indicates which definitions should be affected (all, only the active ones, or the one indicated by the string) Limit parameters dictionary may contain the following: LoRed,LoYel,HiRed,HiYel: indicate the hard and soft limit values Midpoint,Tolerance: indicate a middle limit point and a tolerance that is used to calculate the upper and lower limits (M+T, M-T) Hard and soft limits are considered equal. Nominal,Earning,Error,Ignore: the values are lists containing the values assigned to each category, e.g. Nominal:['ValueA','ValueB'] Delta: set a step or spike limit """ raise DriverException("Service not available in this driver")
def _setLimit(self, param, limit, value, config ): """ Modify an Out Of Limits definition for a given telemetry parameter param: the telemetry parameter name limit: the limit to be modified value: the limit value config: configuration dictionary with modifiers Relevant modifiers are: - Select=ACTIVE/ALL/<STR>: indicates which definitions should be affected (all, only the active ones, or the one indicated by the string) The limit to be modified may be one of the following: LoRed,LoYel,HiRed,HiYel: indicate the hard and soft limit values Nominal,Earning,Error,Ignore: the values are lists containing the values assigned to each category, e.g. Nominal:['ValueA','ValueB'] Delta: set a step or spike limit """ raise DriverException("Service not available in this driver")
def _refreshItem(self, tmItem, config = {} ): """ Acquire the value for a TM parameter. tmItem : instance of TmItemClass with the parameter information config : configuration dictionary with modifiers. Relevant modifiers are - Wait=True/False: when True, the system shall block the caller until a new sample of the required parameter arrives to the GCS. If False, the last recorded value of the parameter shall be returned immediately. - ValueFormat=RAW/ENG: if RAW is given, the raw or uncalibrated value of the parameter shall be given. If ENG is used, the engineering or calibrated value shall be returned. - Timeout=(TIME): maximum amount of time to wait for new samples, before the parameter is declared as impossible to acquire. It only makes sense when Wait=True. Returned value: a list with the value and True/False indicating the validity of the parameter """ raise DriverException("Service not available in this driver")
def __init__(self, timestamp): ttime = ttime_class() self._val = None if isinstance(timestamp, TIME): if isinstance(timestamp._val, str): self._val = ttime.cnv(timestamp._val) self.__fmt = ttime.fmt() else: self._val = timestamp._val elif isinstance(timestamp, datetime.datetime) or isinstance(timestamp, datetime.timedelta): self._val = timestamp elif isinstance(timestamp, str): if timestamp in (NOW_STR, TODAY_STR, YESTERDAY_STR, TOMORROW_STR): self._val = timestamp else: self._val = ttime.cnv(timestamp) self.__fmt = ttime.fmt() else: self._val = ttime.cnv(timestamp) #Setting time format self.__fmt = ttime.fmt() if self._val is None: raise DriverException("Invalid input for date/time: " + repr(timestamp))
def __getDatabaseInstance(self, dbName): dbType, dbPath, dbExt = self.__fromURItoPath(dbName) dbType = dbType.lower() LOG("Database type: " + repr(dbType)) db = None #from libSPELL_SDB import DatabaseFile #from libSPELL_SDB import DatabaseFileSPB if dbType == DB_TYPE_FILE: db = DatabaseFile(dbName, dbPath, dbExt) elif dbType == DB_TYPE_SPB: db = DatabaseFileSPB(dbName, dbPath, dbExt) elif dbType == DB_TYPE_EPH_A2100: db = DatabaseFileEphA2100(dbName, dbPath, dbExt) elif dbType == DB_TYPE_EPH_OSCS2: db = DatabaseFileEphOscS2(dbName, dbPath, dbExt) elif dbType == DB_TYPE_EPH_SB4000: db = DatabaseFileEphSB4000(dbName, dbPath, dbExt) elif dbType == DB_TYPE_SVN: db = DatabaseSubversion(dbName, dbPath, dbExt) elif dbType == DB_TYPE_SPB_SVN: db = DatabaseSubversionSPB(dbName, dbPath, dbExt) elif dbType == DB_TYPE_ASRUN: db = DatabaseAsRun(dbName, dbPath, dbExt) else: raise DriverException("Unknown database type: " + repr(dbType)) self.__databases[dbName] = db return db
def append(self,other): if self.isOpen(): raise DriverException("Cannot append path", "File object is open") if self.isFile(): raise DriverException("Cannot append path", "Cannot append to a file") if type(other)==str: self.__filename += os.sep + other elif isinstance(other,File): self.__filename += os.sep + other.filename() else: raise DriverException("Cannot append to path", "Expected file object or string") return self
def setup(self, ctxConfig, drvConfig): superClass.setup(self, ctxConfig, drvConfig) SIM = SimulatorModel() REGISTRY['SIM'] = SIM LOG("Setup standalone CFG interface") dataPath = Config.getRuntimeDir() driverConfig = self.getDriverConfig() simulationPath = driverConfig['SimPath'] simulationFile = self.getContextConfig().getDriverParameter('Simulation') home = Config.getHome() if home is None: raise DriverException("SPELL home is not defined") LOG("Loading simulation: " + simulationFile) simulationFile = dataPath + os.sep + simulationPath + \ os.sep + simulationFile SIM.tmClass = REGISTRY['TM'] SIM.tcClass = REGISTRY['TC'] SIM.setup( simulationFile ) self.__ready = True
def setup(self, contextName): # Get the context information self.contextName = contextName self.context = Config.instance().getContextConfig(contextName) # Obtain the corresponding driver self.driver = self.context.getDriver() REGISTRY['CTX'] = self.context if self.loaded is not None: # Do not load the same driver twice if self.loaded == self.driver: return True success = self.cleanup() if not success: raise DriverException( "Unable to load driver", "Could not cleanup previously loaded driver " + str(self.loaded)) driverInfo = Config.instance().getDriverConfig(self.driver) self.interfaces = [] self.libraries = [] for iif in INTERNAL_INTERFACES: self.interfaces.append(iif) driverInterfaces = driverInfo.getInterfaces() if len(driverInterfaces) > 0: driverInterfaces = driverInterfaces.split(",") for iif in driverInterfaces: self.interfaces.append(iif) libraries = driverInfo.getLibraries() if len(libraries) > 0: self.libraries = libraries.split(",") LOG("Using driver:" + self.driver) LOG("Using interfaces: " + repr(self.interfaces)) LOG("Using libraries: " + repr(self.libraries)) try: # Configure the factory Factory.instance().setup(self.driver) # Preload libraries for lib in self.libraries: lib = lib.strip(" \n\r") lib = Config.instance().resolvePath(lib) LOG("Appending to path: " + lib) sys.path.append(lib) # Create driver interfaces self.createInterfaces() # Initialize driver interfaces self.initInterfaces() # Set the driver as loaded self.loaded = self.driver except DriverException, e: traceback.print_exc(file=sys.stderr) raise e
def read(self): if not self.isOpen(): raise DriverException("Cannot read file lines", "File is not open") if not self.canRead(): raise DriverException("Cannot read file lines", "Permission denied") if self.isdir(): return self.__list() else: if self.__mode != READ and self.__mode != READ_WRITE: raise DriverException("Cannot read file lines", "Incorrect file mode") lines = [] try: lines = self.__file.readlines() except Exception,ex: raise DriverException("Cannot read file lines", str(ex)) return lines
def _checkLink(self, name): """ Check if a GCS link (TM, TC or others) is enabled or disabled name: link identifier config: configuration modifiers """ raise DriverException("Service not available in this driver")
def _sendList(self, tcItemList, config={}): """ Inject a group of TC items into the GCS. tcItemList : list of TcItemClass instance with the command information. config : configuration dictionary """ raise DriverException("Service not available in this driver")
def _sendCommand(self, tcItem, config={}): """ Inject a TC item into the GCS. tcItem : TcItemClass instance with the command information. config : configuration dictionary """ raise DriverException("Service not available in this driver")
def _getResource(self, name, config={}): """ Acquire the value of one resource or configuration parameter in the GCS name: resource identifier config: configuration modifiers """ raise DriverException("Service not available in this driver")
def _stopTask(self, name, config={}): """ Invoked by the system in order to stop a GCS task. name: string containing the task name config: configuration dictionary with modifiers. """ raise DriverException("Service not available in this driver")
def write(self, data): try: if not self.isOpen(): raise DriverException("Cannot write to file", "File is not open") if self.isDir(): raise DriverException("Cannot write to file", "It is a directory") if not self.canWrite(): raise DriverException("Cannot write to file", "Permission denied") if self.__mode != WRITE and self.__mode != READ_WRITE and self.__mode != APPEND: raise DriverException("Cannot write to file", "Incorrect file mode") if type(data)!=str: raise DriverException("Cannot write to file", "Expected a string as input, received " + repr(type(data))) self.__file.write(data) except DriverException,ex: raise ex
def _logout(self, username, config={}): """ Logout the given user from the GCS system. username: user name config: configuration dictionary with modifiers. """ raise DriverException("Service not available in this driver")
def _injectItem(self, tmItem, value, config = {} ): """ Inject a ground value for a TM parameter. tmItem : instance of TmItemClass with the parameter information value : contains the required value config : configuration dictionary with modifiers. """ raise DriverException("Service not available in this driver")
def close(self): try: if self.isOpen(): if self.isfile(): self.__file.close() else: os.close(self.__fd) except Exception,ex: raise DriverException("Cannot close " + repr(self.__filename), str(ex))
def _sendBlock(self, tcItemList, config={}): """ Inject a block of TC items into the GCS. Blocked items are injected and transmitted as a single TC frame. tcItemList : list of TcItemClass instance with the command information. config : configuration dictionary """ raise DriverException("Service not available in this driver")
def _createTcItem(self, mnenonic, description=""): """ Instantiate a telecommand (usually taking the information from GCS) The item shall be derived from TcItemClass class. If not overriden, the adapter class provides a generic TC item structure. """ raise DriverException("Service not available in this driver")
def _isLoggedIn(self, username, config={}): """ Check if the given user is logged in the GCS system. username: user name config: configuration dictionary with modifiers. """ raise DriverException("Service not available in this driver")
def _isResourceOK(self, name, config={}): """ Check if the current value of one resource or configuration parameter in the GCS is correct or incorrect name: resource identifier config: configuration modifiers """ raise DriverException("Service not available in this driver")
def _setLink(self, name, enable, config={}): """ Enable or disable a GCS link (TM, TC or others) name: link identifier enable: True/False, indicates if the link needs to be enabled or disabled config: configuration modifiers """ raise DriverException("Service not available in this driver")
def _raiseEvent(self, message, config): """ Invoked by the system in order to inject an event into the GCS. message: string containing the event message config: dictionary containing the event parameters: - Severity modifier (INFORMATION/WARNING/ERROR/FATAL) - Scope (SCOPE_PROC,SCOPE_SYS,SCOPE_CFG) """ raise DriverException("Service not available in this driver")