def run(expo_num, level_name, mode): game_str = "game%s" % expo_num game_settings_str = "Game%sSettings" % expo_num _temp = __import__("pkg.exponates", globals(), locals(), [game_str]) Exhibit = getattr(_temp, game_str).Exhibit _temp = __import__("pkg.settings", globals(), locals(), [game_settings_str]) Settings = getattr(_temp, game_settings_str) invoker = Invoker() settings = Settings(mode) level = None for l in settings.exhibit.levels: if l.name == level_name: level = l if level is None: level = settings.exhibit.levels[0] # inject level-specific settings into settings object for key, val in level.params.items(): setattr(settings, key, val) # set test exhibit to selected level if expo_num == "Test" and level_name != "default": io_settings_str = "Game%sSettings" % level_name _temp = __import__("pkg.settings", globals(), locals(), [io_settings_str]) IOSettings = getattr(_temp, io_settings_str) io_settings = IOSettings(mode) settings.key_map = io_settings.key_map settings.light_map = io_settings.light_map settings.seven_length = io_settings.seven_length logger.info("start_expo.py, before localizing settings") try: from pkg.local_settings import localize_settings except Exception as e: logger.warn("no local settings") if "localize_settings" in locals(): try: localize_settings(settings) logger.info("localizing settings") except Exception as e: logger.error("failed to load local setings") logger.error(e) if mode == "emulator": env = Emulator(invoker, settings) else: from pkg.rpi_env import RpiEnv env = RpiEnv(invoker, settings) exhibit = Exhibit(invoker, env, settings) invoker.start() env.run()
def __exit__(self): """ exits the whole environment; trying to do it properly althought some corner-cases are still not-properly-handled """ if hasattr(self, 'sound_executor'): self.sound_executor.__exit__() self.finishing_list.append(lambda: os.system("pkill zbarcam")) for i in self.finishing_list: try: if hasattr(i, '__call__'): i() except Exception as e: logger.error(e)
def midi_success_accord(self): _akord = [0, 12] akord = [self.st.base + 40 + x for x in _akord] for t in akord: alsaseq.output(noteonevent(1, t, 120)) logger.info("midi_success, 1.faza") time.sleep(2) for t in akord: try: alsaseq.output(noteoffevent(1, t, 120)) except Exception as e: logger.error("midi_success: " + str(e)) logger.info("midi_success, posledna faza")
def _start(): logger.info(self.st.script_command) with Popen(self.env, [self.st.script_command, str(self.st.sound_card_index)], shell=False, stdout=subprocess.PIPE) as child: if not(self.recorder is None): self.recorder.start() while True: out = child.stdout.read(150) if out == '' and child.poll() != None: break reg = r'(\d{1,3})\%' ans = re.findall(reg, out) if len(ans) != 0: try: self.fire_event(int(ans[0])) except Exception as e: logger.error(e)
def _start(): try: logger.info('waiting while sound pipe is created') sleep(4) f = open(self.st.pipe_source, 'rb') buffer = [] sizebuf=0 while True: out = f.read(2000) if len(out)>0: logger.info("chunk length: " + str(len(out))) buffer.append(out) sizebuf+=len(out) if sizebuf > self.st.buffer_size: sizebuf=0 self.fire_event(''.join(buffer)) buffer = [] except Exception as e: logger.error(e)
def __init__(self, invoker, env, settings): BaseExhibit.__init__(self, invoker, env, settings) self.env.game_load.listen_once(self.reset_game) self.env.game_load.listen_once(self.qr_register) try: logger.info(os.system("pgrep timidity")) logger.info(os.system("pkill timidity")) logger.info(os.system("timidity -iA -Os -B5,12 &")) #logger.info(os.system("timidity -iA -Os")) time.sleep(2) #essential for good connection alsaseq.client( 'Simple', 1, 1, True ) alsaseq.connectto( 1, 128, 0 ) alsaseq.start() logger.info("timidity is ok. (i hope)") except Exception as e: logger.error("timidity" + str(e)) self.st.max_tone_amount = 3 self.tones_playing = []
def _start(): try: with Popen(self.env, self.st.script_command, shell=False, stdout=subprocess.PIPE) as child: then = 0 while True: out = child.stdout.readline() m = re.search(r'^(\d+)\t([\d.]+)\t([\d.]+)', out) if m: now = int(m.group(1)) power = float(m.group(2))*float(m.group(3)) energy = power * (now - then) / 1000 then = now if global_idle == True and power <= self.st.threshold: pass else: self.fire_event(energy, power) else: logger.warn('problem parsing ' + str(out)) except Exception as e: logger.error(e)
def upload_game_results(self, exponat_name, user_id, score=None, level=None, additional_data=None, callback=None, timeout=0.5): """Uploads data about game to server. ``additional_data`` can be arbitrary piece of data (in a dict form) that is attached to the result and its pickled form is stored in the database. """ logger.info('upload_game_results') address, port = self.st.server_url() try: conn = httplib.HTTPConnection(address, port, timeout=timeout) conn.request('POST', '/upload-game-results/', json.dumps({ 'exponat_name':exponat_name, 'user_id':user_id, 'score':score, 'level':level, 'additional_data':additional_data})) res = conn.getresponse() if res.status != 200:# vim: set expandtab: logger.error('Server response is not 200 OK: %s'%str(res) + str(res.status) + ' ' + str(res.reason)) conn.close() else: data = json.loads(res.read()) conn.close() if 'error' in data: logger.error(data['error']) else: if callback is not None: callback() except Exception as e: logger.error(str(e))
def get_max_score(self, exponat_name, exponat_level, callback=None, timeout=0.5): """Returns best daily score. If none exists, returns None. """ exponat_name = str(exponat_name) exponat_level = str(exponat_level) address, port = self.st.server_url() try: conn = httplib.HTTPConnection(address, port, timeout=timeout) logger.info(exponat_name + ',' + exponat_level) conn.request('GET', '/get-max-score/%s/%s/' % (exponat_name, exponat_level,)) res = conn.getresponse() if res.status != 200: logger.error('Server response is not 200 OK: %s'%str(res) + str(res.status) + ' ' + str(res.reason)) conn.close() else: text = res.read() logger.info(text) data = json.loads(text) conn.close() if 'error' in data: logger.error(data['error']) else: if callback is not None: callback() return data['max_score'] except Exception as e: logger.error(str(e))
def get_user_info(self, user_id, callback=None, timeout=0.5): """Returns dict with data about user (name, age, gender, location). """ address, port = self.st.server_url() try: conn = httplib.HTTPConnection(address, port, timeout=timeout) conn.request('GET', '/get-user-info/%d/' % (user_id,)) res = conn.getresponse() if res.status != 200: logger.error('Server response is not 200 OK: %s'%str(res) + str(res.status) + ' ' + str(res.reason)) conn.close() else: data = json.loads(res.read()) conn.close() if 'error' in data: logger.error(data['error']) else: if callback is not None: callback() return data except Exception as e: logger.error(str(e)) return {'error':str(e)}
def begin_game(self): try: BaseExhibit.begin_game(self) except Exception as e: logger.error(e) self.idle = False
def __init__(self, invoker, settings=None): """ `invoker` - same as exhibit's invoker `key_map` - maps logical key label to physical adress (i.e. keyboard button or expander pin adress) `light_map` - maps logical light labels to physical adress (similar to key_map) `snd_path` - root path to sound samplse `seven_length` - length of seven-segment display, may not be set if exhibit does not have one """ # clean up - kill all processes that shouldn't be running - maybe they weren't closed # properly during the last run kia = ['barcode', 'zbarcam', 'vol_pipe','arecord', 'play_tone', 'aplay', 'play', 'picocom'] for k in kia: try: os.system("pkill --signal CONT " + k) except: pass try: os.system("pkill --signal KILL "+ k) except: pass self.st=settings self.invoker=invoker self.key_map=settings.key_map self.light_map=settings.light_map self.keyboard = Keyboard(invoker, settings.key_map) self.seven_length=settings.seven_length self.light_labels=list(settings.light_map.keys()) self.lights=OrderedDict((label, 0) for label in self.light_labels) self.snd_path=settings.snd_path self.finishing_list = [] self.qr=self.st.qr_factory(invoker, settings, self) self.qr.start() self.game_load=EventProducer(invoker) try: os.system("./audio_playing/force_analogue_audio.sh") except Exception as e: logger.error("forec_analog" + str(e)) if self.st.enable_soundworker: self.samples={} sample_file_names=[os.path.join(root, filename) for root, dirnames, filenames in os.walk(self.snd_path) if dirnames==[] for filename in filenames] for filename in sample_file_names: with open(filename) as fyle: self.samples[os.path.relpath(filename, self.snd_path)]=fyle.read() logger.info("setting sound devices by pyalsaaudio") try: card = self.st.sound_card card_control = self.st.sound_card_control if not (card in alsaaudio.cards()): logger.error("sound card %s not found "%card) logger.error(str(alsaaudio.cards())) else: self.st.sound_card_index = alsaaudio.cards().index(card) mixer = alsaaudio.Mixer(cardindex=self.st.sound_card_index, control=card_control) mixer.setvolume(self.st.volume) mixer = alsaaudio.Mixer(cardindex=self.st.sound_card_index, control=self.st.sound_card_control_mic) mixer.setvolume(self.st.record_sensitivity, 0, "capture") mixer.setvolume(self.st.record_sensitivity, 1, "capture") except Exception as e: logger.error(e) logger.info("setting sound devices is finished.") if self.st.enable_soundworker: self.sound_executor=SoundExecutor(self.samples, self.st)
def midi_failure(self): try: os.system("timidity " + self.st.midi_failure_file) except Exception as e: logger.error("midi_failure " + str(e))
def midi_success(self): try: os.system("timidity " + self.st.midi_success_file) except Exception as e: logger.error("midi_success " + str(e))