def __init__(self, conf): ''' Configure this object: Get extra attributes for this object. /verify-cert/ True to verify server HTTPS certificate; Defaults to false. /end/ When to end download: A count, a regex, or False for everything in message. ''' FileMonitor.__init__(self, conf) self.options = dict(verify=conf.get('verify-cert') or False) self.url = re.compile(conf.get('url') or "[\"'](http[^\"']+)") end_dl = conf.get('end') or False if isinstance(end_dl, basestring): end_dl = re.compile(end_dl) self.end_dl = end_dl
class Command: def __init__(self): self.exit = False self.fileMonitor = FileMonitor() self.poll_thread = None def start_threads(self): try: command_handler = threading.Thread(target=self.launch) command_handler.start() self.poll_thread = \ threading.Thread(target=self.fileMonitor.poll_changes) except: print('An error occurred starting the threads.') # Starts listening for commands. def launch(self): os.system('color 5f') print("Ladle started.") print("Type help for help, exit to halt.") while not self.exit: prompt_input = input('>_') if prompt_input == 'exit': self.exit_ladle() break elif prompt_input == 'help': print('Commands:') print('* substitute to substitute all flags in directory.') print('* run to keep polling the directory for flags.') print('* printdir to print the directory.') print('* exit to stop.') elif prompt_input == 'substitute': self.fileMonitor.substitute_flags() elif prompt_input == 'run': self.poll_thread.start() print('Now polling files for changes.') print('Type stop to halt polling.') elif prompt_input == 'stop': print('This is not supported yet.') elif prompt_input == 'printdir': self.fileMonitor.print_directory() else: print('Command not found, try again...') def exit_ladle(self): print('Exiting...')
def __init__(self): ''' Constructor ''' Controller.controller = self self.sysStatus = SystemStatus() self.configMgr = ConfigManager() self.statusMgr = StatusManager() self.boardManager = RpiBoardManager() self.eventProcessor = EventProcessor() self.sensorMgr = SensorManager(self, self.eventProcessor) self.scheduleManager = ScheduleManager(self, self.eventProcessor) self.fileMon = FileMonitor(Constants.SYSTEM_CONFIG_FILE, self, self.eventProcessor) self.initializeStatus() self.initializeScheduler() self.controllerService = ControllerService(self)
def __init__(self): Plugin.__init__(self) # Create DB Wrapper and start the thread self._db_wrapper = DBWrapper() self._config = Config() self._file_monitor = FileMonitor(self._db_wrapper, self._config.root_path(), self._config)
def startLesson(fileName, lineList, stringList, tts, editorName): """Create a FileMonitor, open an editor and monitor file. Keyword arguments: fileName -- file to monitor and open lineList -- list of lines to monitor stringList -- list of correct lines tts -- Nao proxy editorName -- Editor to open for the kid """ monitor = FileMonitor() monitor.setData(fileName, lineList, stringList) openEditor(editorName, fileName) monitor.monitor_file(tts)
def __init__(self, path, to_formats, from_formats, option_info, ignore_info, api_key): """ Called upon Watch object creation :param path: the file path for the watch to_formats: the formats that the path converts to from_formats: the formats that the path automatically converts to the to_formats option_info: the toggles for the optional functionality """ # It is possible that a user may not have set the recursive search toggle, in which case we default to False. if option_info["subdirsearch"]: if option_info["subdirsearch"] == 1: recursive_toggle = True else: recursive_toggle = False else: recursive_toggle = False # Make an instance of the FileMonitor class which extends the FileSystemEventHandler class. event_handler = FileMonitor(to_formats, from_formats, option_info, ignore_info, api_key) # Create the observer thread linked to the FileMonitor instance. self.observer = Observer() self.observer.schedule(event_handler, path, recursive=recursive_toggle) self.observer.start()
class Controller(object): ''' classdocs ''' CONTROLLER_STATS_FILE = 'data/controller/status.json' controller = None def __init__(self): ''' Constructor ''' Controller.controller = self self.sysStatus = SystemStatus() self.configMgr = ConfigManager() self.statusMgr = StatusManager() self.boardManager = RpiBoardManager() self.eventProcessor = EventProcessor() self.sensorMgr = SensorManager(self, self.eventProcessor) self.scheduleManager = ScheduleManager(self, self.eventProcessor) self.fileMon = FileMonitor(Constants.SYSTEM_CONFIG_FILE, self, self.eventProcessor) self.initializeStatus() self.initializeScheduler() self.controllerService = ControllerService(self) def startService(self): self.controllerService.start() self.fileMon.start() if self.isRegistered(): self.checkPowerOnResume() def checkPowerOnResume(self): while self.controllerService.status != Constants.SERVICE_STATUS_RUNNING: sleep(1) print ' Controller Service READY' rpiBoards = self.boardManager.getBoards() for boardId in rpiBoards: rpiBoard = rpiBoards[boardId] rpiDevices = rpiBoard.getDevices() for deviceId in rpiDevices: self.powerOnResumeDeviceState(rpiDevices[deviceId]) ''' If manual trigger is enabled and resume-on-power-on is set, then resume the on state ''' def powerOnResumeDeviceState(self, rpiDevice): if self.isResumeOnPowerOnEnabled(rpiDevice) is False: return rpiChannel = rpiDevice.getControlChannel() if rpiChannel is None: return rpiChannel.resumeState() def isResumeOnPowerOnEnabled(self, rpiDevice): deviceAction = rpiDevice.getDeviceAction() if 'manual-trigger' in deviceAction: manualTrigger = deviceAction['manual-trigger'] if manualTrigger != 'enabled': return False if 'resume-on-power-on' in deviceAction: resume = deviceAction['resume-on-power-on'] if resume != 'true': return False else: return False else: return False return True def getController(self): return self.controller def getConfigManager(self): return self.configMgr def getBoardManager(self): return self.boardManager def getStatusManager(self): return self.statusMgr def isRegistered(self): sysStat = self.getSystemStatus() return sysStat.isRegistered() def getSystemStatus(self): return self.sysStatus def initializeStatus(self): boards = self.configMgr.getBoards() self.boardManager.addBoards(boards, self) # Adds RpiBoard for b in boards: board = boards[b] self.statusMgr.createBoardStatus(board) bs = self.statusMgr.getBoards() for b in bs: board = bs[b] devices = self.configMgr.getDevices(b) self.statusMgr.createDevicesStatus(board.getId(), devices) def initializeScheduler(self): boards = self.configMgr.getBoards() for b in boards: devices = self.configMgr.getDevices(b) self.scheduleManager.addDeviceSchedules(devices) def syncService(self): #print 'sync started at ' + Utils.getFormatedTime() if self.isRegistered(): self.checkSensors() self.checkSchedules() return else: #print 'sync service at ' + Utils.getFormatedTime() + ' system Not registered' return def checkSensors(self): self.sensorMgr.checkSensors() def checkSchedules(self): self.scheduleManager.checkSchedules() def configModified(self, config): if self.configMgr.isConfigurationChanged(config): print 'configuration changed' self.reloadChannels(config) self.activate(config) else: print 'configuration not changed' def reloadChannels(self, config): self.boardManager.reloadChannels(config) ''' Supporting methods ''' def getControllerStatus(self): data = None with open(Controller.CONTROLLER_STATS_FILE) as dataFile: try: data = json.load(dataFile) dataFile.close() except ValueError: dataFile.close() return data def activate(self, configuration): if configuration is None: return boards = configuration.getBoards() if boards is None or len(boards) == 0: return for boardId in boards: enabled = True board = boards[boardId] if board.isEnabled() == False: enabled = False self.activateBoard(board, enabled) def activateBoard(self, board, enabled): #if board.isEnabled() == False: # return rbiBoard = self.boardManager.getBoard(board.getId()) rbiBoard.activate(board, enabled) def saveControllerStatus(self): if self.controllerStatus is None: return with open(Controller.CONTROLLER_STATS_FILE) as dataFile: try: json.dump(self.controllerStatus, dataFile) dataFile.close() except: dataFile.close() @staticmethod def getController(): if Controller.controller is None: Controller.controller = Controller() return Controller.controller
from FileMonitor import FileMonitor import os, time #code taken from http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html monitor = FileMonitor() path_to_watch = os.getcwd() #Assumed to be watching the current directory before = dict ([(f, None) for f in os.listdir (path_to_watch)]) timeElapsed = 0; timeBefore = time.clock() while 1: timeAfter = time.clock() timeElapsed = (timeAfter-timeBefore) if timeElapsed >= 1: monitor.printStatistics() timeElapsed = 0; timeBefore += 1; time.sleep(.001) #otherwise the file is accessed too fast after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] before = after; if added: #print "Added: ", ", ".join (added) for file in added: monitor.parseFile(file)
def __init__(self): self.exit = False self.fileMonitor = FileMonitor() self.poll_thread = None
from watchdog.observers import Observer import sys import time from FileMonitor import FileMonitor if __name__ == "__main__": path = sys.argv[1] if len(sys.argv) > 1 else '.' event_handler = FileMonitor() observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
def test_parseFile(self): monitor = FileMonitor() out = StringIO() sys.stdout = out monitor.parseFile("doesNotExist.json") monitor.parseFile("run.py") output = out.getvalue().strip() assert output == "The system could not open the file named: doesNotExist.json\n" \ "The created file was not a valid json file." monitor.parseFile("door.json") monitor.parseFile("img.json") monitor.parseFile("alarm.json") monitor.parseFile("alarm-2.json") assert monitor.doorCount == 1 assert monitor.alarmCount == 2 assert monitor.imageCount == 1 assert monitor.avgProcessingTime > 0
def test_printStatistics(self): monitor = FileMonitor(); monitor.parseFile("door.json") monitor.parseFile("img.json") monitor.parseFile("alarm.json") monitor.parseFile("alarm-2.json") out = StringIO() sys.stdout = out monitor.printStatistics() output = out.getvalue().strip() assert output.startswith("DoorCnt: 1, ImgCnt: 1, AlarmCnt: 2, avgProcessingTime : ") assert output.endswith("ms")
def __init__(self, conf): ''' Configure this object, and open the output file. ''' FileMonitor.__init__(self, conf) self.outf = open(self.routate_filename(self.config('output')), "a")