def build_model(self, configs): timer = Timer() timer.start() for layer in configs['model']['layers']: neurons = layer['neurons'] if 'neurons' in layer else None dropout_rate = layer['rate'] if 'rate' in layer else None activation = layer['activation'] if 'activation' in layer else None return_seq = layer['return_seq'] if 'return_seq' in layer else None input_timesteps = layer[ 'input_timesteps'] if 'input_timesteps' in layer else None input_dim = layer['input_dim'] if 'input_dim' in layer else None if layer['type'] == 'dense': self.model.add(Dense(neurons, activation=activation)) if layer['type'] == 'lstm': self.model.add( LSTM(neurons, input_shape=(input_timesteps, input_dim), return_sequences=return_seq)) if layer['type'] == 'dropout': self.model.add(Dropout(dropout_rate)) self.model.compile(loss=configs['model']['loss'], optimizer=configs['model']['optimizer']) print('[Model] Model Compiled') timer.stop()
def batteryChargingMonitor1(event): #log.debug("Battery charging monitor: {}: start".format(event.itemState)) global chargerTimer1 if items["Outlet9"] == OnOffType.ON and event.itemState <= DecimalType(8) and event.oldItemState <= DecimalType(8): if chargerTimer1 is None or str(chargerTimerAttached.getState()) == "TERMINATED": chargerTimer1 = Timer(600, lambda: events.sendCommand("Outlet9","OFF")) chargerTimer1.start() log.info("Battery charging monitor: Started battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState,event.oldItemState)) elif chargerTimer1 is not None and str(chargerTimer1.getState()) == "TIMED_WAITING": chargerTimer1.stop() log.info("Battery charging monitor: Cancelled battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState,event.oldItemState))
def battery_charging_monitor(event): battery_charging_monitor.log.debug("Battery charging monitor: {}: start".format(event.itemState)) global charger_timer if items["Outlet9"] == ON and event.itemState <= DecimalType(8) and event.oldItemState <= DecimalType(8): if charger_timer is None or not charger_timer.isAlive(): charger_timer = Timer(600, lambda: events.sendCommand("Outlet9","OFF"))# 600 seconds = 5 minutes charger_timer.start() battery_charging_monitor.log.info("Battery charging monitor: Started battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState, event.oldItemState)) elif charger_timer is not None and charger_timer.isAlive(): charger_timer.stop() battery_charging_monitor.log.info("Battery charging monitor: Canceled battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState, event.oldItemState))
class PeriodicCallback(object): """ A wrapper that uses either `tornado.ioloop.PeriodicCallback` or `threading.Timer` to call functions at a specified interval depending on whether or not there's a running instance of `tornado.ioloop.IOLoop`. .. note:: The purpose of this class is primarily for debugging things in an interactive Python interpreter. It is expected that in production you will be using a running `~tornado.ioloop.IOLoop`. """ def __init__(self, callback, callback_time, io_loop=None): self.callback = callback self.callback_time = callback_time self.io_loop = io_loop or IOLoop.current() if self.io_loop._running: # Use a regular PeriodicCallback self._pc = PC(callback, callback_time, io_loop) else: from threading import Timer # NOTE: PeriodicCallback uses ms while Timer uses seconds def callback_wrapper(): "Runs the callback and restarts the Timer so it will run again" self.callback() if self._running: self._pc = Timer(callback_time / 1000, callback_wrapper) self._pc.start() self._pc = Timer(callback_time / 1000, callback_wrapper) self._running = False def start(self): """Starts the timer.""" self._running = True self._pc.start() # Timer() and PeriodicCallback() both use start() def stop(self): """Stops the timer.""" self._running = False if isinstance(self._pc, PC): # PeriodicCallback() self._pc.stop() else: # Timer() self._pc.cancel()
class PeriodicExpiration: """Periodically clean up stale sessions.""" def __init__(self, pool, period=60): super().__init__() self.pool = pool self._stop = False self.period = period self.timer = None self.lock = Lock() def start(self): self.schedule() def _run(self): with self.lock: self.timer = None cull = set() # The set of session IDs to remove. now = datetime.utcnow() for sid in self.pool: if '_expires' not in self.pool[sid]: continue if self.pool[sid]['_expires'] <= now: cull.add(sid) for sid in cull: # Can't remove while iterating above... del self.pool[sid] self.schedule() def schedule(self): if self._stop: return with self.lock: self.timer = Timer(self.period, self._run) self.timer.name = "memory-session-expunge" self.timer.start() def stop(self): self._stop = True if self.timer: self.timer.stop()
class PeriodicCallback(object): """ A wrapper that uses either `tornado.ioloop.PeriodicCallback` or `threading.Timer` to call functions at a specified interval depending on whether or not there's a running instance of `tornado.ioloop.IOLoop`. .. note:: The purpose of this class is primarily for debugging things in an interactive Python interpreter. It is expected that in production you will be using a running `~tornado.ioloop.IOLoop`. """ def __init__(self, callback, callback_time, io_loop=None): self.callback = callback self.callback_time = callback_time self.io_loop = io_loop or IOLoop.current() if self.io_loop._running: # Use a regular PeriodicCallback self._pc = PC(callback, callback_time, io_loop) else: from threading import Timer # NOTE: PeriodicCallback uses ms while Timer uses seconds def callback_wrapper(): "Runs the callback and restarts the Timer so it will run again" self.callback() self._pc = Timer(callback_time / 1000, callback_wrapper) if self._running: self._pc.start() self._pc = Timer(callback_time / 1000, callback_wrapper) self._running = False def start(self): """Starts the timer.""" self._running = True self._pc.start() # Timer() and PeriodicCallback() both use start() def stop(self): """Stops the timer.""" self._running = False if isinstance(self._pc, PC): # PeriodicCallback() self._pc.stop() else: # Timer() self._pc.cancel()
class TimerExtension(Extension): SOUND_FILE = "/usr/share/sounds/freedesktop/stereo/complete.oga" ICON_FILE = 'images/timer.png' timer = None timer_start_time = None def __init__(self): super(TimerExtension, self).__init__() self.icon_path = os.path.join( os.path.dirname(os.path.dirname(__file__)), self.ICON_FILE) self.subscribe( KeywordQueryEvent, ExtensionKeywordListener(self.ICON_FILE, lambda: self.get_time_left())) self.subscribe(ItemEnterEvent, ItemEnterEventListener()) def set_timer(self, delay, text): self.timer = Timer(delay, self.show_notification, args=[text]) self.timer.setDaemon(True) self.timer_start_time = datetime.now() self.timer.start() def stop_timer(self): if self.timer: self.timer.stop() self.timer_start_time = None self.timer = None def get_time_left(self): if self.timer_start_time and self.timer: interval = timedelta(seconds=self.timer.interval) end = self.timer_start_time + interval return end - datetime.now() else: return None def show_notification(self, text, make_sound=True): logger.debug('Show notification: %s' % text) Notify.init("TimerExtension") Notify.Notification.new("Timer", text, self.icon_path).show() if make_sound: subprocess.call(("paplay", self.SOUND_FILE))
class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs def _run(self): self.function(*self.args, **self.kwargs) self.start() def start(self): self._timer = Timer(self.interval, self._run) self._timer.start() # self.is_running = True def stop(self): self._timer.cancel() self._timer.stop()
class RepeatedTimer(object): def __init__(self,interval,function): self.timer = None self.interval = interval self.function = function self.is_running = False self.start() def start(self): if not self.is_running: self.is_running = True self.timer = Timer(self.interval,self.run) self.timer.start() def run(self): self.is_running = False self.function() self.start() def stop(self): self.timer.stop() self.is_running = False
def train(self, x, y, epochs, batch_size, save_dir): timer = Timer() timer.start() print('[Model] Training Started') print('[Model] %s epochs, %s batch size' % (epochs, batch_size)) save_fname = os.path.join( save_dir, '%s-e%s.h5' % (dt.datetime.now().strftime('%d%m%Y-%H%M%S'), str(epochs))) callbacks = [ EarlyStopping(monitor='val_loss', patience=2), ModelCheckpoint(filepath=save_fname, monitor='val_loss', save_best_only=True) ] self.model.fit(x, y, epochs=epochs, batch_size=batch_size, callbacks=callbacks) self.model.save(save_fname) print('[Model] Training Completed. Model saved as %s' % save_fname) timer.stop()
def train_generator(self, data_gen, epochs, batch_size, steps_per_epoch, save_dir): timer = Timer() timer.start() print('[Model] Training Started') print('[Model] %s epochs, %s batch size, %s batches per epoch' % (epochs, batch_size, steps_per_epoch)) save_fname = os.path.join( save_dir, '%s-e%s.h5' % (dt.datetime.now().strftime('%d%m%Y-%H%M%S'), str(epochs))) callbacks = [ ModelCheckpoint(filepath=save_fname, monitor='loss', save_best_only=True) ] self.model.fit_generator(data_gen, steps_per_epoch=steps_per_epoch, epochs=epochs, callbacks=callbacks, workers=1) print('[Model] Training Completed. Model saved as %s' % save_fname) timer.stop()
class idlemove(MumoModule): default_config = { 'idlemove': ( ('interval', float, 0.1), ('servers', commaSeperatedIntegers, []), ), lambda x: re.match('(all)|(server_\d+)', x): (('threshold', commaSeperatedIntegers, [3600]), ('mute', commaSeperatedBool, [True]), ('deafen', commaSeperatedBool, [False]), ('channel', commaSeperatedIntegers, [1]), ('source_channel', commaSeperatedIntegers, [-1]), ('whitelist', commaSeperatedStrings, []), ('channel_whitelist', commaSeperatedIntegers, [])), } def __init__(self, name, manager, configuration=None): MumoModule.__init__(self, name, manager, configuration) self.murmur = manager.getMurmurModule() self.watchdog = None def connected(self): self.affectedusers = {} # {serverid:set(sessionids,...)} manager = self.manager() log = self.log() log.debug("Register for Meta & Server callbacks") cfg = self.cfg() servers = cfg.idlemove.servers if not servers: servers = manager.SERVERS_ALL manager.subscribeServerCallbacks(self, servers) manager.subscribeMetaCallbacks(self, servers) if not self.watchdog: self.watchdog = Timer(cfg.idlemove.interval, self.handleIdleMove) self.watchdog.start() def disconnected(self): self.affectedusers = {} if self.watchdog: self.watchdog.stop() self.watchdog = None def handleIdleMove(self): cfg = self.cfg() try: meta = self.manager().getMeta() if not cfg.idlemove.servers: servers = meta.getBootedServers() else: servers = [ meta.getServer(server) for server in cfg.idlemove.servers ] for server in servers: if not server: continue if server: for user in server.getUsers().itervalues(): self.UpdateUserAutoAway(server, user) finally: # Renew the timer self.watchdog = Timer(cfg.idlemove.interval, self.handleIdleMove) self.watchdog.start() def UpdateUserAutoAway(self, server, user): log = self.log() sid = server.id() try: scfg = getattr(self.cfg(), 'server_%d' % sid) except AttributeError: scfg = self.cfg().all try: index = self.affectedusers[sid] except KeyError: self.affectedusers[sid] = set() index = self.affectedusers[sid] # Check if the user is whitelisted if user.name in scfg.whitelist: return # Remember values so we can see changes later threshold = None mute = user.mute deafen = user.deaf channel = user.channel update = False over_threshold = False # Search all our stages top down for a violated treshold and pick the first for i in range(len(scfg.threshold) - 1, -1, -1): try: source_channel = scfg.source_channel[i] except IndexError: source_channel = -1 try: threshold = scfg.threshold[i] mute = scfg.mute[i] deafen = scfg.deafen[i] channel = scfg.channel[i] except IndexError: log.warning( "Incomplete configuration for stage %d of server %i, ignored", i, server.id()) continue if user.idlesecs > threshold and\ user.channel not in scfg.channel_whitelist and\ (source_channel == -1 or\ user.channel == source_channel or\ user.channel == channel): over_threshold = True # Update if state changes needed if user.deaf != deafen: update = True if user.mute != mute: update = True if channel >= 0 and user.channel != channel: update = True if update: index.add(user.session) self.affectedusers['origchan' + str(user.userid) + str(user.name) + str(user.session)] = user.channel log.info( '%ds > %ds: State transition for user %s (%d/%d) from mute %s -> %s / deaf %s -> %s | channel %d -> %d on server %d', user.idlesecs, threshold, user.name, user.session, user.userid, user.mute, mute, user.deaf, deafen, user.channel, channel, server.id()) break if not over_threshold and user.session in self.affectedusers[sid]: deafen = False mute = False try: channel = self.affectedusers['origchan' + str(user.userid) + str(user.name) + str(user.session)] del self.affectedusers['origchan' + str(user.userid) + str(user.name) + str(user.session)] except KeyError: channel = user.channel log.warning("User's original channel never stored") pass index.remove(user.session) log.info("Restore user %s (%d/%d) on server %d", user.name, user.session, user.userid, server.id()) update = True if update: user.deaf = deafen user.mute = mute user.channel = channel server.setState(user) # #--- Server callback functions # def userDisconnected(self, server, state, context=None): try: index = self.affectedusers[server.id()] if state.session in index: index.remove(state.session) except KeyError: pass def userStateChanged(self, server, state, context=None): self.UpdateUserAutoAway(server, state) def userConnected(self, server, state, context=None): pass # Unused callbacks def userTextMessage(self, server, user, message, current=None): pass def channelCreated(self, server, state, context=None): pass def channelRemoved(self, server, state, context=None): pass def channelStateChanged(self, server, state, context=None): pass # #--- Meta callback functions # def started(self, server, context=None): sid = server.id() self.affectedusers[sid] = set() self.log().debug('Handling server %d', sid) def stopped(self, server, context=None): sid = server.id() self.affectedusers[sid] = set() self.log().debug('Server %d gone', sid)
class ControlCenter( object ) : def __init__( self , root , connStr , directConnection = False) : # connect to the robot server self.__directConnection = directConnection self.__connStr = connStr self.connect() # create main window self.root = root self.rootFrame = Tk.Frame( root , padx = 5 , pady = 5 ) self.rootFrame.pack() # -------------------------------------------------- # input group frame # -------------------------------------------------- # input frame self.inputFrame = Tk.LabelFrame( self.rootFrame , text = "Input Device" , padx = 5 , pady = 5 , borderwidth = 2 ) self.inputFrame.pack( fill="both" , expand="yes" , side = Tk.TOP ) # joystick check button self.joystickActive = False self.joystickPrevButtonDown = False self.joystickTimerPeriod = 0.2 # updated is kind-of slow to prevent jitter/jumping around of the motors self.joystickTimer = None self.joystick = Joystick.Joystick() var = Tk.IntVar() self.joystickCheckButton = Tk.Checkbutton( self.inputFrame , text="Joystick", command = self.joystickCheckButtonEvent , variable = var ) self.joystickCheckButton.getValue = var.get if not self.joystick.init() : self.joystickCheckButton[ "state" ] = Tk.DISABLED self.joystickCheckButton.pack( side = Tk.TOP ) # mouse check box var = Tk.IntVar() self.mouseCheckButton = Tk.Checkbutton( self.inputFrame , text="Mouse" , variable = var ) self.mouseCheckButton.getValue = var.get self.mouseCheckButton.pack( side = Tk.TOP ) # movement canvas self.movementLastValue = (0,0,0,0) self.movementCanvasWidth = 200 self.movementCanvasHeight = 200 self.movementCanvas = Tk.Canvas( self.inputFrame , width = self.movementCanvasWidth , height = self.movementCanvasHeight , bg = 'white' ) self.movementCanvas.pack( side = Tk.RIGHT ) # mouse on movementCanvas self.movementCanvas.bind( "<Button-1>" , self.movementCanvasMouseButtonDown ) self.movementCanvas.bind( "<ButtonRelease-1>" , self.movementCanvasMouseButtonUp ) self.movementCanvas.bind( "<B1-Motion>" , self.movementCanvasMouseMotion ) self.movementCanvaslineId = self.movementCanvas.create_line( self.movementCanvasWidth/2 , self.movementCanvasHeight/2 , self.movementCanvasWidth/2 , self.movementCanvasWidth/2 , width=3 , fill="blue", arrowshape = (10, 10, 3), arrow = "last") # -------------------------------------------------- # hardware frame # -------------------------------------------------- # hardware frame self.hardwareFrame = Tk.LabelFrame( self.rootFrame , text = "Hardware Settings" , padx = 5 , pady = 5 , borderwidth = 2 ) self.hardwareFrame.pack( fill="both" , expand="yes" , side = Tk.TOP ) # enable/disable motors button self.motorsEnabled = False self.motorsButton = Tk.Button( self.hardwareFrame , text="Enable Motors", command = self.motorsButtonPressed ) self.motorsButton.pack( side = Tk.LEFT ) # trim -- FIXME: use Tk.scale #self.turnATrimScrollbar = Tk.Scrollbar( root ) #self.turnATrimScrollbar.pack( side = Tk.LEFT ) #self.turnATrimScrollbar["command"] = self.turnAScroll #self.turnATrimScrollbar.set(0.5,0.6) # -------------------------------------------------- # output device frame # -------------------------------------------------- # output frame self.outputFrame = Tk.LabelFrame( self.rootFrame , text = "Output Device" , padx = 5 , pady = 5 , borderwidth = 2 ) self.outputFrame.pack( fill="both" , expand="yes" , side = Tk.TOP ) # output button setup self.outputButtonValue = Tk.StringVar() self.outputButton = [] # MOTECOM output button self.moteComFrame = Tk.Frame( self.outputFrame ) self.moteComFrame.pack() button = Tk.Radiobutton( self.moteComFrame , text = "MOTECOM" , variable = self.outputButtonValue , value = "motecom" , command = self.outputButtonEvent ) button.pack( side = Tk.LEFT ) self.outputButton.append( button ) self.moteComEntry = Tk.Entry( self.moteComFrame , state = Tk.DISABLED ) self.moteComEntry.pack( side = Tk.LEFT ) # RoboServ output button button = Tk.Radiobutton( self.outputFrame , text = "RoboServ@" , variable = self.outputButtonValue , value = "roboserv" , command = self.outputButtonEvent ) button.pack( side = Tk.TOP ) self.outputButton.append( button ) # connect to output button self.outputConnected = False self.outputConnectButton = Tk.Button( self.outputFrame , text = "Connect to Output" , command = self.outputConnectButtonPressed ) self.outputConnectButton.pack() # -------------------------------------------------- # general events # -------------------------------------------------- # keep alive timer self.keepAliveTimerPeriod = 1 self.enableKeepAliveTimer() # event handler for closing window self.root.protocol( "WM_DELETE_WINDOW" , self.exit ) def exit( self ) : self.disableKeepAliveTimer() self.disableJoystick() self.root.destroy() try : self.__roboMote.stopMovement() self.__roboMote.disableMotors() except : pass #-------------------------------------------------- # Connect to mote or server #-------------------------------------------------- def connect( self ) : success = False while not success : try : print "Trying to connect..." if self.__directConnection : from Robot import RoboMote self.__roboMote = RoboMote.RoboMote( self.__connStr ) success = True else : from Robot import Client c = Client.makeClient( host = self.__connStr , ignoreLostPackets = True ) self.__roboMote = c.roboMote success = True except : time.sleep( 10 ) print "Connected" #-------------------------------------------------- # Keep Alive Timer #-------------------------------------------------- def enableKeepAliveTimer( self ) : self.keepAliveTimerActive = True self.keepAliveTimer = Timer( self.keepAliveTimerPeriod , self.keepAliveTimerEvent ).start() def disableKeepAliveTimer( self ) : self.keepAliveTimerActive = False time.sleep( self.keepAliveTimerPeriod * 2 ) # make sure any timers have time to finish firing def keepAliveTimerEvent( self ) : if self.__directConnection : if not jpype.isThreadAttachedToJVM() : jpype.attachThreadToJVM() if self.keepAliveTimerActive : success = False while not success : try : self.__roboMote.sendKeepAlive() success = True except : self.connect() self.keepAliveTimer = Timer( self.keepAliveTimerPeriod , self.keepAliveTimerEvent ).start() else : #keepAliveTimer is not active if self.keepAliveTimer : self.keepAliveTimer.stop() self.keepAliveTimer = None #-------------------------------------------------- # Output button #-------------------------------------------------- def outputButtonEvent( self ) : if self.outputButtonValue.get() == "motecom" : self.moteComEntry[ "state" ] = Tk.NORMAL else: self.moteComEntry[ "state" ] = Tk.DISABLED def outputConnectButtonPressed( self ) : #try : # pass #except : self.outputConnectButton[ "text" ] = "Failed to connect" self.outputConnectButton[ "background" ] = "red" #self.outputConnectButton[ "text" ] = "connect" #-------------------------------------------------- # Movement canvas: # x,y are assumed to be in terms of normal x,y # coords; (0,0) at the center of the canvas; # x,y each range from -1 to 1 #-------------------------------------------------- def updateMovementCanvas( self , x , y ) : # clip x,y range to [-1,1] x = min( max(x,-1) , 1) y = min( max(y,-1) , 1) # change x and y range to [0,1] arrowX = ( x + 1 ) / 2 arrowY = ( y + 1 ) / 2 # draw the arrow arrowX = arrowX * self.movementCanvasWidth arrowY = (1-arrowY) * self.movementCanvasHeight self.movementCanvas.coords( self.movementCanvaslineId , self.movementCanvasWidth/2 , self.movementCanvasHeight/2 , arrowX , arrowY ) # actuate the motors # round the values to prevent jitter turnA = round(-x,1) speedA = round(y,1) turnB = turnA speedB = speedA newMovement = (turnA,turnB,speedA,speedB) if not (newMovement == self.movementLastValue) : self.movementLastValue = newMovement success = False while not success : try : self.__roboMote.setMovement( *newMovement ) success = True except : self.connect() #-------------------------------------------------- # Mouse #-------------------------------------------------- def updateMovementCanvasMouse( self , xMouse , yMouse ) : self.updateMovementCanvas( xMouse * 2.0 / self.movementCanvasWidth - 1 , 1 - yMouse * 2.0 / self.movementCanvasWidth ) def movementCanvasMouseButtonDown( self , event ) : if self.mouseCheckButton.getValue() : self.updateMovementCanvasMouse( event.x , event.y ) def movementCanvasMouseButtonUp( self , event ) : if self.mouseCheckButton.getValue() : self.updateMovementCanvas( 0.0 , 0.0 ) def movementCanvasMouseMotion( self , event ) : if self.mouseCheckButton.getValue() : self.updateMovementCanvasMouse( event.x , event.y ) #-------------------------------------------------- # Joystick #-------------------------------------------------- def enableJoystick( self ) : self.joystickActive = True self.joystickTimer = Timer( self.joystickTimerPeriod , self.joystickTimerEvent ).start() def disableJoystick( self ) : self.joystickActive = False time.sleep( self.joystickTimerPeriod * 2 ) # make sure any timers have time to finish firing def joystickTimerEvent( self ) : if self.__directConnection : if not jpype.isThreadAttachedToJVM() : jpype.attachThreadToJVM() if self.joystickActive : self.joystick.update() if not self.joystick.getButton(0) : if self.joystickPrevButtonDown : # if button was just recently let up self.joystickPrevButtonDown = False self.updateMovementCanvas( 0.0 , 0.0 ) else : self.joystickPrevButtonDown = True if self.joystick.getButton(1) : self.updateMovementCanvas( self.joystick.getAxis(0) , -self.joystick.getAxis(1) ) elif self.joystick.getButton(3) : self.updateMovementCanvas( self.joystick.getAxis(0) , -self.joystick.getAxis(1) / 2.0 ) elif self.joystick.getButton(2) : self.updateMovementCanvas( self.joystick.getAxis(0) , -self.joystick.getAxis(1) / 4.0 ) else : self.updateMovementCanvas( self.joystick.getAxis(0) , -self.joystick.getAxis(1) / 6.0 ) self.joystickTimer = Timer( self.joystickTimerPeriod , self.joystickTimerEvent ).start() else : #joystick is not active if self.joystickTimer : self.joystickTimer.stop() self.joystickTimer = None self.joystickPrevButtonDown = False self.updateMovementCanvas( 0.0 , 0.0 ) def joystickCheckButtonEvent( self ) : if self.joystickCheckButton.getValue() : self.enableJoystick() else : self.disableJoystick() #-------------------------------------------------- # Motors #-------------------------------------------------- def enableMotors( self ) : self.motorsEnabled = True self.motorsButton["text"] = "Disable Motors" success = False while not success : try : self.__roboMote.enableMotors() success = True except : self.connect() def disableMotors( self ) : self.motorsEnabled = False self.motorsButton["text"] = "Enable Motors" success = False while not success : try : self.__roboMote.disableMotors() success = True except : self.connect() def motorsButtonPressed( self ): if self.motorsEnabled : self.disableMotors() else : self.enableMotors()
# if drowsiness detected # do something if EYE_COUNTER >= EYE_AR_CONSEC_FRAMES: # draw an alarm on the frame cv2.putText(frame, "Drowsiness detected.", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (100, 220, 100), 2) # otherwise, the eye aspect ratio is not below the blink # threshold, so reset the counter and alarm else: EYE_COUNTER = 0 ALARM_ON = False # draw the computed eye aspect ratio on the frame to help # with debugging and setting the correct eye aspect ratio # thresholds and frame counters cv2.putText(frame, "E.A.R.: {:.2f}".format(ear), (300, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (100, 220, 100), 2) # show the frame cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break timer.stop() # do a bit of cleanup cv2.destroyAllWindows() vs.stop()
class Reader(): tcs = False # The current matched color reading current = False # The last color reading last = False # Callback for when a new video is found onNewMedia = False player = None timer = None def __init__(self, onNewMedia=False): print('Reader: Reader started') self.onNewMedia = onNewMedia self.tcs = TCS34725(integrationTime=0xEB, gain=0x01) self.tcs.setInterrupt(False) self.player = LoopPlayer( Reader.playlist[0][1] ) self.timer = Timer(1, self._monitor) self.timer.start() def _normalize(raw): denominator = 200 return ( int(raw['r'] / denominator), int(raw['g'] / denominator), int(raw['b'] / denominator) ) def _lookupPlaylistByTuple(t): for video in Reader.playlist: if video[0] == t: return video[1] return False def _monitor(self): # print tcs.getRawData() norm = self._normalize( self.tcs.getRawData() ) print "Reader: norm = " + str(norm) if( norm != self.last ): print "Reader: norm = " + str(norm) self.last = norm video = self._lookupPlaylistByTuple(norm) if( video and norm != self.current and video != self.player.filename ): print "Reader: video = " + str(video) print(self.onNewMedia) self.current = norm # if self.onNewMedia: self.onNewMedia(video) self.player.stop(exit=False) self.player = LoopPlayer( video ) self.timer.stop() self.timer = Timer(0.5, self._monitor) self.timer.start() def stop(self): if(self.timer): self.timer.stop() self.player.stop self.tcs.disable()
class EventEngine(object): """ 事件驱动引擎 事件驱动引擎中所有的变量都设置为了私有,这是为了防止不小心 从外部修改了这些变量的值或状态,导致bug。 变量说明 __queue:私有变量,事件队列 __active:私有变量,事件引擎开关 __thread:私有变量,事件处理线程 __timer:私有变量,计时器 __handlers:私有变量,事件处理函数字典 方法说明 __run: 私有方法,事件处理线程连续运行用 __process: 私有方法,处理事件,调用注册在引擎中的监听函数 __onTimer:私有方法,计时器固定事件间隔触发后,向事件队列中存入计时器事件 start: 公共方法,启动引擎 stop:公共方法,停止引擎 register:公共方法,向引擎中注册监听函数 unregister:公共方法,向引擎中注销监听函数 put:公共方法,向事件队列中存入新的事件 事件监听函数必须定义为输入参数仅为一个event对象,即: 函数 def func(event) ... 对象方法 def method(self, event) ... """ #---------------------------------------------------------------------- def __init__(self): """初始化事件引擎""" # 事件队列 self.__queue = Queue.Queue() # 事件引擎开关 self.__active = False # 事件处理线程 self.__thread = Thread(target = self.__run) # 计时器,用于触发计时器事件 self.__timer = Timer() self.__timer.timeout.connect(self.__onTimer) # 这里的__handlers是一个字典,用来保存对应的事件调用关系 # 其中每个键对应的值是一个列表,列表中保存了对该事件进行监听的函数功能 self.__handlers = {} #---------------------------------------------------------------------- def __run(self): """引擎运行""" while self.__active == True: try: event = self.__queue.get(block = True, timeout = 1) # 获取事件的阻塞时间设为1秒 self.__process(event) except : pass #---------------------------------------------------------------------- def __process(self, event): """处理事件""" # 检查是否存在对该事件进行监听的处理函数 if event.type_ in self.__handlers: # 若存在,则按顺序将事件传递给处理函数执行 [handler(event) for handler in self.__handlers[event.type_]] # 以上语句为Python列表解析方式的写法,对应的常规循环写法为: #for handler in self.__handlers[event.type_]: #handler(event) #---------------------------------------------------------------------- def __onTimer(self): """向事件队列中存入计时器事件""" # 创建计时器事件 event = Event(type_=EVENT_TIMER) # 向队列中存入计时器事件 self.put(event) #---------------------------------------------------------------------- def start(self): """引擎启动""" # 将引擎设为启动 self.__active = True # 启动事件处理线程 self.__thread.start() # 启动计时器,计时器事件间隔默认设定为1秒 self.__timer.start(1000) #---------------------------------------------------------------------- def stop(self): """停止引擎""" # 将引擎设为停止 self.__active = False # 停止计时器 self.__timer.stop() # 等待事件处理线程退出 self.__thread.join() #---------------------------------------------------------------------- def register(self, type_, handler): """注册事件处理函数监听""" # 尝试获取该事件类型对应的处理函数列表,若无则创建 try: handlerList = self.__handlers[type_] except KeyError: handlerList = [] self.__handlers[type_] = handlerList # 若要注册的处理器不在该事件的处理器列表中,则注册该事件 if handler not in handlerList: handlerList.append(handler) #---------------------------------------------------------------------- def unregister(self, type_, handler): """注销事件处理函数监听""" # 尝试获取该事件类型对应的处理函数列表,若无则忽略该次注销请求 try: handlerList = self.__handlers[type_] # 如果该函数存在于列表中,则移除 if handler in handlerList: handlerList.remove(handler) # 如果函数列表为空,则从引擎中移除该事件类型 if not handlerList: del self.__handlers[type_] except KeyError: pass #---------------------------------------------------------------------- def put(self, event): """向事件队列中存入事件""" self.__queue.put(event)
class EventListener(object): def __init__(self, l_id, e_type, e_matcher, expire=0, timeout=None): ''' params: l_id: event listener id e_type: listened event type e_matcher: event matcher matching the listened event expire: 0: current listener stays through the whole life cycle of the component 1: the listener will be removed once it is matched timeout: the max life time of the listener when expire eqs 1 ''' self.listener_id = l_id self.event_type = e_type self.matcher = e_matcher self.expire = expire self.timeout = timeout def get_listener_id(self): return self.listener_id def match(self, event): ''' match the input event return: true: the input event match the current event listener false: else ''' result = self.matcher.match(event.get_event_data(), event.get_event_meta()) if result: self.event = event print '#### EventListener: get a event with data: %s and meta: %s' % ( event.get_event_data(), event.get_event_meta()) return result def process_event(self): ''' process the event with match handler ''' self._on_match(self.event) def get_listener_id(self): return self.listener_id def start_timer(self): ''' start the timer according to the timeout value ''' if expire == 0: return if not timeout: return self.timer = Timer(timeout, self._on_timeout, [self]) self.timer.start() def stop_timer(self): self.timer.stop() def set_timeout_handler(self, callback, **params): ''' set the handler to handle the listener timeout params: callback: the callback function called when the listener timeout params: the params used when call the callback function ''' self.timeout_handler = [callback, params] def _on_timeout(self): ''' handler to handle the listener timeout ''' try: if timeout_handler[0]: self.timeout_handler[0](listener=self, **self.timeout_handler[1]) except Exception, e: print Exception, ':', e, \ ' in %s:%s' % get_class_func_name(self)
class grouptag(MumoModule): default_config = { 'grouptag': ( ('interval', int, 10), ('servers', commaSeperatedIntegers, []), ), lambda x: re.match('(all)|(server_\d+)', x): (('groupmap', commaSeperatedStrings, ['admin:admin']), ), } def __init__(self, name, manager, configuration=None): MumoModule.__init__(self, name, manager, configuration) self.murmur = manager.getMurmurModule() self.watchdog = None def connected(self): self.affectedusers = {} # {serverid:set(sessionids,...)} manager = self.manager() log = self.log() log.debug("Register for Meta & Server callbacks") cfg = self.cfg() servers = cfg.grouptag.servers if not servers: servers = manager.SERVERS_ALL manager.subscribeServerCallbacks(self, servers) manager.subscribeMetaCallbacks(self, servers) if not self.watchdog: self.watchdog = Timer(cfg.grouptag.interval, self.setTag) self.watchdog.start() def disconnected(self): self.affectedusers = {} if self.watchdog: self.watchdog.stop() self.watchdog = None def isuseringroup(self, server, user, group_to_check): '''Checks if userid is member of the excluded_for_afk group in the root channel''' try: scfg = getattr(self.cfg(), 'server_%d' % int(server.id())) except AttributeError: scfg = self.cfg().all ACL = server.getACL(0) userid = user.userid for group in ACL[1]: if userid in group.members and group.name == group_to_check: return True return False def setTag(self): cfg = self.cfg() try: meta = self.manager().getMeta() if not cfg.grouptag.servers: servers = meta.getBootedServers() else: servers = [ meta.getServer(server) for server in cfg.grouptag.servers ] for server in servers: if not server: continue if server: for user in server.getUsers().itervalues(): self.updateTags(server, user) finally: # Renew the timer self.watchdog.cancel() self.watchdog = Timer(cfg.grouptag.interval, self.setTag) self.watchdog.start() def updateTags(self, server, user): log = self.log() sid = server.id() try: scfg = getattr(self.cfg(), 'server_%d' % sid) except AttributeError: scfg = self.cfg().all try: index = self.affectedusers[sid] except KeyError: self.affectedusers[sid] = set() index = self.affectedusers[sid] # Remember values so we can see changes later tags = [] # grab all the appropriate tags for the user and update the tagset. for i in range(len(scfg.groupmap) - 1, -1, -1): try: map = scfg.groupmap[i] except IndexError: log.warning( "Incomplete configuration for stage %d of server %i, ignored", i, server.id()) continue group = map.split(':')[0] tag = map.split(':')[1] if self.isuseringroup(server, user, group) and tag not in tags: log.info('Adding tag %s to user %s on serverid %i', tag, user.name, server.id()) tags.append(tag) userstate = server.getState(int(user.session)) if any(x.split(':')[1] in user.name for x in scfg.groupmap): prefix = [ x for x in scfg.groupmap if x.split(':')[1] in user.name ][0].split(':')[1] prefix = user.name.find(prefix) + len(prefix) original_username = user.name[prefix:] else: original_username = user.name if len(tags) > 0: userstate.name = '%s%s' % (''.join(tags), original_username) else: userstate.name = '%s' % (original_username) server.setState(userstate) log.info('Setting tags %s to user %s on server %d', tags, original_username, server.id()) # #--- Server callback functions # def userDisconnected(self, server, state, context=None): try: index = self.affectedusers[server.id()] if state.session in index: index.remove(state.session) except KeyError: pass def userConnected(self, server, state, context=None): self.setTag() def userStateChanged(self, server, state, context=None): pass def userTextMessage(self, server, user, message, current=None): pass def channelCreated(self, server, state, context=None): pass def channelRemoved(self, server, state, context=None): pass def channelStateChanged(self, server, state, context=None): pass # #--- Meta callback functions # def started(self, server, context=None): sid = server.id() self.affectedusers[sid] = set() self.log().debug('Handling server %d', sid) def stopped(self, server, context=None): sid = server.id() self.affectedusers[sid] = set() self.log().debug('Server %d gone', sid)
class idlemove(MumoModule): default_config = {'idlemove':( ('interval', float, 0.1), ('servers', commaSeperatedIntegers, []), ), lambda x: re.match('(all)|(server_\d+)', x):( ('threshold', commaSeperatedIntegers, [3600]), ('mute', commaSeperatedBool, [True]), ('deafen', commaSeperatedBool, [False]), ('channel', commaSeperatedIntegers, [1]), ('source_channel', commaSeperatedIntegers, [-1]), ('whitelist', commaSeperatedStrings, []) ), } def __init__(self, name, manager, configuration=None): MumoModule.__init__(self, name, manager, configuration) self.murmur = manager.getMurmurModule() self.watchdog = None def connected(self): self.affectedusers = {} # {serverid:set(sessionids,...)} manager = self.manager() log = self.log() log.debug("Register for Meta & Server callbacks") cfg = self.cfg() servers = cfg.idlemove.servers if not servers: servers = manager.SERVERS_ALL manager.subscribeServerCallbacks(self, servers) manager.subscribeMetaCallbacks(self, servers) if not self.watchdog: self.watchdog = Timer(cfg.idlemove.interval, self.handleIdleMove) self.watchdog.start() def disconnected(self): self.affectedusers = {} if self.watchdog: self.watchdog.stop() self.watchdog = None def handleIdleMove(self): cfg = self.cfg() try: meta = self.manager().getMeta() if not cfg.idlemove.servers: servers = meta.getBootedServers() else: servers = [meta.getServer(server) for server in cfg.idlemove.servers] for server in servers: if not server: continue if server: for user in server.getUsers().itervalues(): self.UpdateUserAutoAway(server, user) finally: # Renew the timer self.watchdog = Timer(cfg.idlemove.interval, self.handleIdleMove) self.watchdog.start() def UpdateUserAutoAway(self, server, user): log = self.log() sid = server.id() try: scfg = getattr(self.cfg(), 'server_%d' % sid) except AttributeError: scfg = self.cfg().all try: index = self.affectedusers[sid] except KeyError: self.affectedusers[sid] = set() index = self.affectedusers[sid] # Check if the user is whitelisted if user.name in scfg.whitelist: return # Remember values so we can see changes later threshold = None mute = user.mute deafen = user.deaf channel = user.channel update = False over_threshold = False # Search all our stages top down for a violated treshold and pick the first for i in range(len(scfg.threshold) - 1, -1, -1): try: source_channel = scfg.source_channel[i] except IndexError: source_channel = -1 try: threshold = scfg.threshold[i] mute = scfg.mute[i] deafen = scfg.deafen[i] channel = scfg.channel[i] except IndexError: log.warning("Incomplete configuration for stage %d of server %i, ignored", i, server.id()) continue if user.idlesecs > threshold and\ (source_channel == -1 or\ user.channel == source_channel or\ user.channel == channel): over_threshold = True # Update if state changes needed if user.deaf != deafen: update = True if user.mute != mute: update = True if channel >= 0 and user.channel != channel: update = True if update: index.add(user.session) log.info('%ds > %ds: State transition for user %s (%d/%d) from mute %s -> %s / deaf %s -> %s | channel %d -> %d on server %d', user.idlesecs, threshold, user.name, user.session, user.userid, user.mute, mute, user.deaf, deafen, user.channel, channel, server.id()) break if not over_threshold and user.session in self.affectedusers[sid]: deafen = False mute = False channel = user.channel index.remove(user.session) log.info("Restore user %s (%d/%d) on server %d", user.name, user.session, user.userid, server.id()) update = True if update: user.deaf = deafen user.mute = mute user.channel = channel server.setState(user) # #--- Server callback functions # def userDisconnected(self, server, state, context=None): try: index = self.affectedusers[server.id()] if state.session in index: index.remove(state.session) except KeyError: pass def userStateChanged(self, server, state, context=None): self.UpdateUserAutoAway(server, state) def userConnected(self, server, state, context=None): pass # Unused callbacks def userTextMessage(self, server, user, message, current=None): pass def channelCreated(self, server, state, context=None): pass def channelRemoved(self, server, state, context=None): pass def channelStateChanged(self, server, state, context=None): pass # #--- Meta callback functions # def started(self, server, context = None): sid = server.id() self.affectedusers[sid] = set() self.log().debug('Handling server %d', sid) def stopped(self, server, context = None): sid = server.id() self.affectedusers[sid] = set() self.log().debug('Server %d gone', sid)
class password(MumoModule): default_config = { 'password': (('servers', commaSeperatedIntegers, []), ), lambda x: re.match('(all)|(server_\d+)', x): ( ('welcometext', str, 'Welcome to Mumble'), ('genpassword', str, '!pass'), ('delpassword', str, '!clearpass'), ('interval', int, 1800), ) } def __init__(self, name, manager, configuration=None): MumoModule.__init__(self, name, manager, configuration) self.murmur = manager.getMurmurModule() self.watchdog = None def sendMessage(self, server, user, message, msg): server.sendMessage(user.session, msg) def cleartoken(self): cfg = self.cfg() log = self.log() try: meta = self.manager().getMeta() if not cfg.password.servers: servers = meta.getBootedServers() else: servers = [ meta.getServer(server) for server in cfg.password.servers ] for server in servers: if not server: continue if server: try: scfg = getattr(self.cfg(), 'server_%d' % int(server.id())) except AttributeError: scfg = self.cfg().all server.setConf("password", uuid.uuid4().hex[:24]) server.setConf("welcometext", cfg.all.welcometext) log.debug("Serverpassword cleared after 30minutes.") except: pass def connected(self): manager = self.manager() log = self.log() cfg = self.cfg() log.debug("Register for Server callbacks") servers = self.cfg().password.servers if not servers: servers = manager.SERVERS_ALL manager.subscribeServerCallbacks(self, servers) if not self.watchdog: self.watchdog = Timer(cfg.all.interval, self.cleartoken) self.watchdog.start() def disconnected(self): if self.watchdog: self.watchdog.stop() self.watchdog = None # --- Server callback functions # def userTextMessage(self, server, user, message, current=None): log = self.log() cfg = self.cfg() try: scfg = getattr(self.cfg(), 'server_%d' % server.id()) except AttributeError: scfg = self.cfg().all # Only allow registered Users to use command if user.userid > 0: if message.text.startswith(scfg.delpassword): msg = "Password cleared" self.sendMessage(server, user, message, msg) self.cleartoken() if message.text.startswith(scfg.genpassword): token = uuid.uuid4().hex[:12] server.setConf("password", token) server.setConf( "welcometext", cfg.all.welcometext + ", the current server password is: \"%s\" , it will expire in 30 minutes.\n Generated by %s" % (token, user.name)) log.debug("A new serverpassword got generated by %s" % user.name) # refresh timer self.watchdog = Timer(scfg.interval, self.cleartoken) self.watchdog.start() def userConnected(self, server, state, context=None): pass def userDisconnected(self, server, state, context=None): pass def userStateChanged(self, server, state, context=None): pass def channelCreated(self, server, state, context=None): pass def channelRemoved(self, server, state, context=None): pass def channelStateChanged(self, server, state, context=None): pass