def run(self): ''' return False if Quit event received, True is Start event received ''' log.debug('PongWaitStart.run() START') while not self.terminate: time.sleep(0.5) log.debug('PongWaitStart.run() END') return self.start
def run(self): log.debug('PongVictory.run() START') # Wait for a swipe (indicated by setting self.delay to not None) ScoreBoard().display('P%d Swipe!' % self.player) log.info('Waiting for player %d swipe...' % self.player) while self.terminate is False and self.delay is None: time.sleep(0.1) if self.terminate: return False while self.idx < len(self.puffers): if self.terminate: return 'Quit' log.info("%s idx=%02d id=%08X" % (self.puff_type, self.idx, self.puffers[self.idx])) e = FpEvent(self.puffers[self.idx], self.puff_type, struct.pack('<H', self.puff_duration)) log.info(str(e)) Visualizer().info(e) FpSerial().write(e.serialize()) time.sleep(self.delay) self.idx += 1 log.info('LARGE PUFFER id=%08X duration (ms)=%d' % (self.large_puffer, self.large_puff_duration_ms)) e = FpEvent(self.large_puffer, 'FP_EVENT_PUFF', struct.pack('<H', self.large_puff_duration_ms)) Visualizer().info(e) FpSerial().write(e.serialize())
def push_mode(self, mode): log.debug('ModeManager.push_mode(%s)' % mode) self.event_handler = mode.event self.mode.append(mode) ret = self.mode[-1].run() self.pop_mode() return ret
def run(self): ''' Return None if Quit was pressed, else return the winner of the game, i.e. 1 or 2 ''' log.debug('PongGame.run()') while self.win is None: if self.terminate: return if self.idx < 0: self.win = 2 break elif self.idx >= len(self.puffers): self.win = 1 break elif self.idx >= 0 and self.idx < len(self.puffers): log.info("%s idx=%02d id=%08X" % (self.puff_type, self.idx, self.puffers[self.idx])) e = FpEvent(self.puffers[self.idx], self.puff_type, struct.pack('<H', self.puff_duration)) log.info(str(e)) Visualizer().info(e) FpSerial().write(e.serialize()) time.sleep(self.delay) self.idx += self.inc if self.quit: return None else: death_puffer = self.large_puffers[1 if self.win == 1 else 0] e = FpEvent(death_puffer, 'FP_EVENT_PUFF', struct.pack('<H', self.large_puff_duration)) log.info(str(e)) Visualizer().info(e) FpSerial().write(e.serialize()) return self.win
def run(self): last_second = time.time() try: log.debug('InputManager[%s]: start' % tid()) while not self.terminate: #log.debug('InputManager[%s]: tick' % tid()) t = time.time() if self.wm1: self.wm1.tick() if self.wm2: self.wm2.tick() # polling for keypresses... ugly. TODO: change to callback if self.keyboard: for action in self.keyboard.get_actions(): if self.keyboard.get_pressed(action): if action == 'quit': self.emit(EventQuit()) elif action == 'swipe1': self.emit(EventSwipe('1UP', randint(20, 300))) elif action == 'swipe2': self.emit(EventSwipe('2UP', randint(20, 300))) else: self.emit(EventButton(action)) time.sleep(config['InputManager']['tick']) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() log.exception('InputManager[%s]: uncaught exception: %s, SHUTTING DOWN\n%s' % (tid(), e, repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))) log.debug('InputManager[%s]: end' % tid())
def __init__(self): defaults = { 'baudrate': 115200, 'parity': 'none', 'stopbits': 2, 'bytesize': 8 } c = fire_pong.util.config['serial'] for k, v in defaults.items(): if k not in c: c[k] = v # translate text to serial param names c['parity'] = { 'none': pyserial.PARITY_NONE, 'odd': pyserial.PARITY_ODD, 'even': pyserial.PARITY_EVEN }[c['parity']] c['stopbits'] = { 1: pyserial.STOPBITS_ONE, 2: pyserial.STOPBITS_TWO }[c['stopbits']] c['bytesize'] = { 8: pyserial.EIGHTBITS, 7: pyserial.SEVENBITS }[c['bytesize']] log.debug('FpSerial serial config: %s' % c) self.serial = pyserial.Serial(port=c['port'], baudrate=c['baudrate'], parity=c['parity'], stopbits=c['stopbits'], bytesize=c['bytesize']) self.serial.isOpen()
def init_display(self): disp_no = os.getenv("DISPLAY") if disp_no: log.info('Using X with DISPLAY: %s' % disp_no) self.screen = pygame.display.set_mode((800,600)) pygame.init() pygame.font.init() pygame.display.set_caption('Fire Pong Keyboard Input') else: found = False drivers = ['fbcon', 'directfb', 'svgalib'] for driver in drivers: if not os.getenv('SDL_VIDEODRIVER'): os.putenv('SDL_VIDEODRIVER', driver) try: pygame.display.init() except pygame.error as e: log.debug('Framebuffer driver %s failed: %s' % (driver, e)) continue found = True log.info('Using framebuffer driver: %s' % driver) break if not found: raise Exception('No working video driver found') size = (pygame.display.Info().current_w, pygame.display.Info().current_h) log.info('Display size: %d x %d' % (size[0], size[1])) self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN) self.screen.fill(Keyboard.COLBG) pygame.font.init() self.font = pygame.font.Font(None, Keyboard.FONTSIZE) pygame.display.update()
def run(self): log.debug('ContinuousModePuffs.run() START') ScoreBoard().display('CP') while self.terminate is False: # Print a little graphic of the puffers showing which one is active... log.info("%s idx=%02d id=%08X" % (self.puff_type, self.idx, self.puffers[self.idx])) e = FpEvent(self.puffers[self.idx], self.puff_type, struct.pack('<H', self.puff_duration)) log.info(str(e)) Visualizer().info(e) FpSerial().write(e.serialize()) # Move the frixel by inc self.idx += self.inc # Bounce if necessary if self.idx == -1: self.idx = 1 self.inc = 1 elif self.idx == len(self.puffers): self.idx = len(self.puffers) - 2 self.inc = -1 # Wait a little bit... time.sleep(self.delay) log.debug('ContinuousModePuffs.run() END')
def run(self): log.debug('PongMode.run() START') while not self.terminate: self.reset() while max(self.score) < self.winning_score and not self.terminate: self.display_score() if ModeManager().push_mode(PongWaitStart()) is False: return 'PongMode Quit' if ModeManager().push_mode(PongCounterMode(start=3, end=1)) is False: return 'PongMode Quit' self.display_score() win = ModeManager().push_mode(PongGame(self.start_player)) if win is None: self.terminate = True else: self.score[win-1] += 1 if self.start_player == 1: self.start_player = 2 else: self.start_player = 1 if self.score[0] > self.score[1]: log.info("Player 1 wins") ScoreBoard().display("1W") ModeManager().push_mode(PongVictory(win)) elif self.score[1] > self.score[0]: log.info("Player 2 wins") ScoreBoard().display("2W") ModeManager().push_mode(PongVictory(win)) else: log.info("It's a DRAW!") ScoreBoard().display("Dr") log.debug('PongMode.run() END')
def dispatcher(self, event): log.debug('ModeManager.dispatcher received: %s' % event) propagate = True if propagate and self.event_handler: log.debug('ModeManager.dispatcher propagating to %s' % self.event_handler) self.event_handler(event)
def __init__(self, music_file): log.debug('MusicPlayMode.__init__() START') Mode.__init__(self) # Make sure moc is running subprocess.call(["mocp", "-S"]) self.music_file = music_file self.large_puffers = config['LargePuffers']['ids'] self.small_puffers = config['PongGame']['puffers'] self.all_puffers = copy.copy(self.large_puffers) self.all_puffers.extend(self.small_puffers) log.info('MusicPlayMode.__init__() all_puffers: %s' % str([('%x' % x) for x in self.all_puffers])) log.info('MusicPlayMode.__init__() large_puffers: %s' % str([('%x' % x) for x in self.large_puffers])) self.puff_duration = config['MusicMode']['puff_duration'] self.puff_type = 'FP_EVENT_ALTPUFF' if config['PongGame']['use_alt_puff'] else 'FP_EVENT_PUFF' self.means = [] self.meanlen = 10 self.puff_frequency = None self.frequencylen = 30 self.threshold = 2 self.threshold_step = 0.004 self.min_threshold = 0.5 self.max_threshold = 10 self.target_density = config['MusicMode']['target_density'] self.channels = [] self.min_wait = 0.5 self.max_wait = 2.5 self.chunk = (len(self.all_puffers)/2)*80 self.sample_rate = 44100 self.start = time.time() self.inp = None self.out = None self.manual_mask = 0 try: for _ in range(0, len(self.all_puffers)/2): self.means.append(RunningMean(self.meanlen)) self.means[-1].set(0) self.channels.append(False) self.puff_frequency = RunningMean(self.frequencylen) self.inp = alsa.PCM(alsa.PCM_CAPTURE, alsa.PCM_NORMAL, 'hw:Loopback,1,0') self.out = alsa.PCM(alsa.PCM_PLAYBACK, alsa.PCM_NORMAL, 'plughw:0,0') self.inp.setchannels(2) self.inp.setrate(self.sample_rate) self.inp.setformat(alsa.PCM_FORMAT_S16_LE) self.inp.setperiodsize(self.chunk) self.out.setchannels(2) self.out.setrate(self.sample_rate) self.out.setformat(alsa.PCM_FORMAT_S16_LE) self.out.setperiodsize(self.chunk) except Exception as e: log.error('MusicPlayMode.__init__() %s: %s' % (type(e), e)) if self.inp: self.inp.close() if self.out: self.out.close() log.debug('MusicPlayMode.__init__() END')
def __init__(self): log.debug('ScoreBoard display id=%08X' % self.get_id()) self.keyboard = None self.muted = False try: self.keyboard = Keyboard() except Exception as e: log.info('Could not get Keyboard object (for screen display)')
def run(self): log.debug('PongCounterMode.run()') while not self.terminate and self.count != self.end + self.step: ScoreBoard().display(' %d' % self.count) self.count += self.step time.sleep(self.time) log.debug('PongCounterMode.run() END %s' % self.start) return self.start
def write(self, buf): if self.serial: if fire_pong.util.config['serial']['debug']: log.debug('SERIAL WRITE: %3d bytes: %s [%s]' % (len(buf), repr(bytearray(buf)), ' '.join( ['%02x' % ord(x) for x in buf]))) self.serial.write(buf) else: log.warning('FpSerial.write() serial device not configured')
def __init__(self, ids, callback): Mode.__init__(self) log.debug('%s.__init__(ids=%s, callback=%s) START' % (str(ids), str(callback), self.__class__.__name__)) self.ids = ids self.callback = callback self.idx = 0 self.display = True self.activate = False
def run(self): log.debug('ContinuousMode.run() START') self.terminate = False while not self.terminate: if ModeManager().push_mode(ContinuousModeWait()) is False: self.terminate = True break else: ModeManager().push_mode(ContinuousModePuffs()) log.debug('ContinuousMode.run() END')
def __init__(self): Mode.__init__(self) log.debug('ManualMode.__init__()') self.small_puffers = config['PongGame']['puffers'] self.large_puffers = config['LargePuffers']['ids'] self.small_puff_duration = config['ManualMode']['small_puff_duration'] self.large_puff_duration = config['ManualMode']['large_puff_duration'] self.puff_type = 'FP_EVENT_ALTPUFF' if config['PongGame'][ 'use_alt_puff'] else 'FP_EVENT_PUFF' self.puffer_mask = 0 self.duration = 0
def displayname(cls): ''' returns a short (no more than 2 characters) name for use on the display in MenuMode ''' try: # if class.__displayname__ is defined, use that return cls.__displayname__ except Exception as e: log.debug('could not find __displayname__ class variable: %s: %s' % (type(e), e)) # otherwise just use the first character of the mode class name # capitalized. return cls.__name__[0].upper()
def run(self): log.debug('ContinuousModeWait.run() START') log.info("Continuous Mode. WAITING. Press START button to continue") ScoreBoard().display('CW') while not self.terminate: time.sleep(0.5) log.debug('ContinuousModeWait.run() END') if self.quit: return False else: return True
def event(self, event): log.debug('ContinuousModePuffs.event received: %s' % str(event)) if event in [EventButton('start'), EventQuit()]: self.terminate = True if type(event) is EventSwipe: if event.player == '1UP': self.delay += 0.025 else: self.delay -= 0.025 if self.delay < 0.08: self.delay = 0.08 log.info('DELAY set to %s' % self.delay)
def __init__(self): Mode.__init__(self) self.music_path = config['MusicMode']['path'] log.debug('MusicMode.__init__() looking in: %s' % self.music_path) self.music_files = [] for f in sorted(listdir(self.music_path)): m = re.match(r'^.*\.(mp3|wav|ogg)$', f, re.IGNORECASE) if m: f = '%s/%s' % (self.music_path, f) log.debug('MusicMode: adding file %s' % f) self.music_files.append(f) self.display = True self.activate = False self.idx = 0
def event(self, event): log.debug('%s.event(%s)' % (self.__class__.__name__, str(event))) if event == EventQuit(): self.terminate = True if event == EventButton('start'): self.activate = True if type(event) is EventSwipe: if event.player == '2UP': self.idx = (self.idx + 1) % len(self.ids) else: self.idx = (self.idx - 1) % len(self.ids) self.display = True
def event(self, event): log.debug('MusicMode.event(%s)' % str(event)) if event == EventQuit(): self.terminate = True if event == EventButton('start'): self.activate = True if type(event) is EventSwipe: if event.player == '2UP': self.idx = (self.idx + 1) % len(self.music_files) else: self.idx = (self.idx - 1) % len(self.music_files) self.display = True
def run(self): log.debug('ManualMode.run() START') ScoreBoard().display( 'Yellow=random small puff; Green=Large 1; Blue=Large 2') while not self.terminate: if self.puffer_mask != 0: e = FpEvent(self.puffer_mask, self.puff_type, pack('<H', self.duration)) log.info('Event: %s' % str(e)) Visualizer().info(e) FpSerial().write(e.serialize()) self.puffer_mask = 0 time.sleep(0.1) log.debug('ManualMode.run() END')
def run(self): log.debug('MusicMode.run() START') while not self.terminate: if self.display: self.display = False log.info('MusicMode.run() SELECTED idx=%d, song=%s' % (self.idx, self.music_files[self.idx])) ScoreBoard().display(os.path.basename(self.music_files[self.idx])) next if self.activate: self.activate = False log.info('MusicMode.run() PLAY %s' % self.music_files[self.idx]) ModeManager().push_mode(MusicPlayMode(self.music_files[self.idx])) next time.sleep(0.2) log.debug('MusicMode.run() END')
def discover(self): while self.wm is None: try: log.info('Put Wiimote for player %s in discovery mode' % self.name) ScoreBoard().display('D%s' % self.name[0]) self.wm = cwiid.Wiimote() self.wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC self.last_swipe = 0 log.debug('Connected to wiimote for %s' % self.name) except RuntimeError as e: log.error('%s - run "sudo hciconfig hci0 up"?' % e) except Exception as e: log.error('While discovering WiiMote %s / %s' % (type(e), e)) ScoreBoard().display('ER%s' % self.name) time.sleep(1.5)
def run(self): log.debug('%s.run() START' % self.__class__.__name__) while not self.terminate: if self.activate: self.activate = False self.callback(self.ids[self.idx]) if self.display: log.info( '%s.run() select puffer idx=%d; id=0x%08X; press START to activate' % (self.__class__.__name__, self.idx, self.ids[self.idx])) ScoreBoard().display('%02d' % self.idx) self.display = False time.sleep(0.2) log.debug('%s.run() END' % self.__class__.__name__) return None
def event(self, event): if event == EventQuit(): self.quit = True self.terminate = True if type(event) is EventSwipe: log.debug('Swipe by %s' % event.player) if self.idx in self.hit_idx[event.player]: log.info("Player %s HITS!" % event.player) if event.player == '1UP': self.inc = 1 else: self.inc = -1 self.delay = strength2delay(event.strength) else: log.info('Player %s MISS!' % event.player)
def run(self): log.debug('%s.run() START' % self.__class__.__name__) while not self.terminate: if self.activate: self.activate = False try: ModeManager().push_mode(self.modes[self.idx]()) except Exception as e: log.exception('in mode %s : %s : %s' % (self.modes[self.idx].__name__, type(e), e)) if self.display: log.info('%s selection: %s; press START to activate' % (self.__class__.__name__, self.modes[self.idx].__name__)) ScoreBoard().display(self.modes[self.idx].displayname()) self.display = False time.sleep(0.2) log.debug('%s.run() END' % self.__class__.__name__) return 'END'
def event(self, event): log.debug('ManualMode.event(%s)' % str(event)) if event == EventQuit(): self.terminate = True if event == EventButton('start'): self.duration = self.small_puff_duration self.puffer_mask = self.puffer_mask | self.small_puffers[ random.randint(0, len(self.small_puffers) - 1)] if type(event) is EventSwipe: self.duration = self.large_puff_duration if event.player == '2UP': self.puffer_mask = self.puffer_mask | self.large_puffers[0] else: self.puffer_mask = self.puffer_mask | self.large_puffers[-1]
def event(self, event): log.debug('%s.event(%s) START' % (self.__class__.__name__, str(event))) if event == EventQuit(): self.terminate = True if event == EventButton('start'): log.info('%s.event() activating mode %s' % (self.__class__.__name__, self.modes[self.idx].__name__)) self.display = True # we can't actually push a mode in an event handler, so we set the flag to do it in the main loop instead self.activate = True if type(event) is EventSwipe: if event.player == '2UP': self.idx = (self.idx + 1) % len(self.modes) else: self.idx = (self.idx - 1) % len(self.modes) self.display = True
def __init__(self, callback): log.debug('GpioButtons.__init__') wiringpi.wiringPiSetupGpio() self.debounce = dict() self.debounce_time = fire_pong.util.config['InputManager']['gpio']['debounce_time'] self.callback = callback for action in ['quit', 'start', 'swipe1', 'swipe2']: try: pin = fire_pong.util.config['InputManager']['gpio'][action] wiringpi.pinMode(pin, wiringpi.GPIO.INPUT) wiringpi.pullUpDnControl(pin, wiringpi.GPIO.PUD_UP) wiringpi.wiringPiISR(pin, wiringpi.GPIO.INT_EDGE_FALLING, getattr(self, action)) self.debounce[action] = 0 log.debug('GpioButtons.__init__() %s => pin %s' % (action, pin)) except KeyError as e: log.warning('GpioButtons.__init__(): %s' % e) pass
def __init__(self): log.debug('InputManager.__init__: START') self.thread = threading.Thread(target=self.run) self.terminate = False # Config wiimotes self.wm1 = None self.wm2 = None try: if config['InputManager']['wiimotes']['enabled']: SwipeMote.IDLE = config['InputManager']['wiimotes'][ 'swipe_idle'] SwipeMote.SWIPE_MIN = config['InputManager']['wiimotes'][ 'swipe_min'] self.wm1 = SwipeMote('1UP', self.wiiswipe) self.wm2 = SwipeMote('2UP', self.wiiswipe) self.discover() except KeyError as e: log.exception('InputManager.__init__(): %s' % e) # Configure keyboard input self.keyboard = None try: if config['InputManager']['keyboard']['enabled']: self.keyboard = Keyboard() self.keyboard.thread.start() except Exception as e: log.exception('InputManager.__init__(): %s' % e) # Configure GPIO buttons self.gpiobuttons = None try: if config['InputManager']['gpio']['enabled']: import fire_pong.gpiobuttons from fire_pong.gpiobuttons import GpioButtons fire_pong.gpiobuttons.log = log self.gpiobuttons = GpioButtons(self.gpiocallback) log.debug( 'InputManager.__init__: configured GpioButtons successfully' ) except Exception as e: log.error('InputManager.__init__: %s : %s' % (type(e), e)) self.event_handler = None
def run(self): log.debug('MusicMode.run() START') while not self.terminate: if self.display: self.display = False log.info('MusicMode.run() SELECTED idx=%d, song=%s' % (self.idx, self.music_files[self.idx])) ScoreBoard().display( os.path.basename(self.music_files[self.idx])) next if self.activate: self.activate = False log.info('MusicMode.run() PLAY %s' % self.music_files[self.idx]) ModeManager().push_mode( MusicPlayMode(self.music_files[self.idx])) next time.sleep(0.2) log.debug('MusicMode.run() END')
def run(self): log.debug('%s.run() START' % self.__class__.__name__) while not self.terminate: if self.activate: self.activate = False try: ModeManager().push_mode(self.modes[self.idx]()) except Exception as e: log.exception('in mode %s : %s : %s' % (self.modes[self.idx].__name__, type(e), e)) if self.display: log.info( '%s selection: %s; press START to activate' % (self.__class__.__name__, self.modes[self.idx].__name__)) ScoreBoard().display(self.modes[self.idx].displayname()) self.display = False time.sleep(0.2) log.debug('%s.run() END' % self.__class__.__name__) return 'END'
def __init__(self, callback): log.debug('GpioButtons.__init__') wiringpi.wiringPiSetupGpio() self.debounce = dict() self.debounce_time = fire_pong.util.config['InputManager']['gpio'][ 'debounce_time'] self.callback = callback for action in ['quit', 'start', 'swipe1', 'swipe2']: try: pin = fire_pong.util.config['InputManager']['gpio'][action] wiringpi.pinMode(pin, wiringpi.GPIO.INPUT) wiringpi.pullUpDnControl(pin, wiringpi.GPIO.PUD_UP) wiringpi.wiringPiISR(pin, wiringpi.GPIO.INT_EDGE_FALLING, getattr(self, action)) self.debounce[action] = 0 log.debug('GpioButtons.__init__() %s => pin %s' % (action, pin)) except KeyError as e: log.warning('GpioButtons.__init__(): %s' % e) pass
def __init__(self): log.debug('InputManager.__init__: START') self.thread = threading.Thread(target=self.run) self.terminate = False # Config wiimotes self.wm1 = None self.wm2 = None try: if config['InputManager']['wiimotes']['enabled']: SwipeMote.IDLE = config['InputManager']['wiimotes']['swipe_idle'] SwipeMote.SWIPE_MIN = config['InputManager']['wiimotes']['swipe_min'] self.wm1 = SwipeMote('1UP', self.wiiswipe) self.wm2 = SwipeMote('2UP', self.wiiswipe) self.discover() except KeyError as e: log.exception('InputManager.__init__(): %s' % e) # Configure keyboard input self.keyboard = None try: if config['InputManager']['keyboard']['enabled']: self.keyboard = Keyboard() self.keyboard.thread.start() except Exception as e: log.exception('InputManager.__init__(): %s' % e) # Configure GPIO buttons self.gpiobuttons = None try: if config['InputManager']['gpio']['enabled']: import fire_pong.gpiobuttons from fire_pong.gpiobuttons import GpioButtons fire_pong.gpiobuttons.log = log self.gpiobuttons = GpioButtons(self.gpiocallback) log.debug('InputManager.__init__: configured GpioButtons successfully') except Exception as e: log.error('InputManager.__init__: %s : %s' % (type(e), e)) self.event_handler = None
def run(self): log.debug('MusicPlayMode.run() START') time.sleep(0.5) try: self.start_playback() while not self.terminate: l, data = self.inp.read() self.inp.pause(1) if l: try: matrix = self.calculate_levels(data) puffer_state = (len(self.channels)*2) * [' '] puffcount = 0 puffmask = 0x00000000 for i in range(0, len(self.channels)): diff = matrix[i] - self.means[i].mean() if diff > 0: self.means[i].set(matrix[i]) if diff > self.threshold: puffer_idx = i*2 if self.channels[i]: puffer_idx += 1 self.channels[i] = not(self.channels[i]) puffer_state[puffer_idx] = 'PUFF' puffmask = puffmask | self.all_puffers[puffer_idx] puffcount += 1 else: self.means[i].push(matrix[i]) self.puff_frequency.push(puffcount) puff_density = self.puff_frequency.mean() if self.target_density > puff_density and self.threshold > self.min_threshold: self.threshold -= self.threshold_step elif self.threshold < self.max_threshold: self.threshold += self.threshold_step log.debug('Music t=%5.2f d=%5.3f t=%5.3f' % ( time.time() - self.start, puff_density, self.threshold)) if self.manual_mask > 0: puffmask = puffmask | self.manual_mask self.manual_mask = 0 if puffmask != 0: e = FpEvent(puffmask, self.puff_type, pack('<H', self.puff_duration)) log.info('Event: %s' % str(e)) Visualizer().info(e) FpSerial().write(e.serialize()) self.out.write(data) except Exception as e: log.exception("END: %s: %s" % (type(e), e)) break self.inp.pause(0) self.stop_playback() finally: try: self.inp.close() self.out.close() except Exception as e: log.error('while closing ALSA devices %s: %s' % (type(e), e)) log.debug('MusicPlayMode.run() END')
def __init__(self): self.thread = threading.Thread(target=self.run) self.terminate = False self.buttons = dict() self.pressed = dict() self.gain_action = None self.screen = None for action in ['quit', 'start', 'emstop', 'back', 'swipe1', 'swipe2', 'btstart', 'btemstop']: try: key = fire_pong.util.config['InputManager']['keyboard'][action] if action[0:2] == 'bt': action = action[2:] if key == '_gain': self.gain_action = action log.debug('Keyboard() for _gain input, action is: %s' % action) else: pygame_id = 'K_' + key self.buttons[getattr(pygame, pygame_id)] = action log.debug('Keyboard() for %s input set to key %s' % (action, pygame_id)) self.pressed[action] = False except KeyError as e: log.warning('Keyboard.__init__(): %s' % e) pass
def run(self): self.init_display() while not self.terminate: for event in pygame.event.get(): if event.type == pygame.QUIT: self.terminate = True if event.type == pygame.KEYUP: log.debug('Keyboard KEYUP event: %s' % event) if event.key in self.buttons: log.debug('Keyboard: key %s pressed, triggering action %s' % (event.key, self.buttons[event.key])) self.pressed[self.buttons[event.key]] = True if event.scancode == 115: log.debug('Keyboard: btbutton 115 scancode, triggering action %s' % self.gain_action) self.pressed[self.gain_action] = True elif self.gain_action is not None and event.type == pygame.ACTIVEEVENT and event.state == 2 and event.gain == 1: log.debug('Keyboard: _gain pressed, triggering action %s' % self.gain_action) self.pressed[self.gain_action] = True time.sleep(fire_pong.util.config['InputManager']['keyboard']['tick']) pygame.quit()
def run(self): log.debug('%s.run() START' % self.__class__.__name__) ScoreBoard().display('GO') try: while not self.terminate: if self.idx: log.debug('%s.run() calling sequence' % self.__class__.__name__) self.sequence(self.puffers[self.idx]) self.idx = None time.sleep(0.1) log.debug('%s.run() END' % self.__class__.__name__) finally: # When leaving mode make sure all relays are OFF! for i in range(0, len(self.puffers)): self.spark(self.puffers[i], on=False) self.solenoid(self.puffers[i], on=False)
def run(self): log.debug('ModeManager.run() START mode: %s' % self.start_mode) r = self.push_mode(self.start_mode) log.debug('ModeManager.run() END, (top level mode returned: %s)' % r)
def shutdown(self): log.debug('ModeManager.shutdown()')
fire_pong.util.config = { "InputManager": { "tick": 0.02, "keyboard": { "tick": 0.02, "enabled": True, "quit": "ESCAPE", "start": "s", "emstop": "h", "back": "b", "swipe1": "z", "swipe2": "COMMA", "btstart": "RETURN", "btemstop": "_gain" } } } log.basicConfig(level=logging.DEBUG) k = Keyboard() log.debug('supported actions: %s' % k.get_actions()) k.thread.start() for _ in range(0, 60): if k.get_pressed('quit'): break else: time.sleep(0.1) k.shutdown() k.thread.join()
def shutdown(self): log.debug('InputManager[%s]: shutdown() requested' % tid()) if self.keyboard: self.keyboard.shutdown() self.keyboard.thread.join() self.terminate = True
def __init__(self): log.debug('Visualizer.__init__()') self.text = ''