def __darwin_switch(self, i: int): if self.output_device is not None: logger.debug("Setting audio output device to %s" % self.output_device[i]) wrap_cmd_call( ['SwitchAudioSource', '-s', '%s' % self.output_device[i]]) if self.input_device is not None: logger.debug("Setting audio input device to %s" % self.input_device[i]) wrap_cmd_call([ 'SwitchAudioSource', '-t input', '-s', '%s' % self.input_device[i] ]) if self.output_gain is not None: logger.debug("Setting system volume to configured default %s" % self.output_gain[i]) wrap_cmd_call([ 'osascript', '-e', 'set volume output volume %s' % self.output_gain[i] ]) if self.input_gain is not None: logger.debug("Setting input gain to configured default %s" % self.input_gain[i]) wrap_cmd_call([ 'osascript', '-e', 'set volume input volume %s' % self.input_gain[i] ]) logger.debug("Done configuring audio")
def stop(self) -> None: if not self.is_on: logger.debug("Audio handler is already off. Ignoring.") logger.debug("Stopping audio handler.") self.__wrap('stop') self.is_on = False logger.info("Stopped audio handler.")
def start(self) -> None: if self.is_on: logger.debug("Audio handler is already on. Ignoring.") return self.__wrap('start') logger.debug("Starting audio handler.") self.is_on = True logger.info("Started audio handler.")
def init(self): cap = cv2.VideoCapture(self.config.device_index) cap.set(6, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G')) cap.set(3, self.config.roi.width()) cap.set(4, self.config.roi.height()) cap.set(15, self.config.exposure) for i in range(0, 18): try: logger.debug("Webcam {}={}".format(i, cap.get(i))) except: logger.debug("Failed to read webcam {}".format(i)) self.cap = cap
def exit(self) -> None: logger.info("Setting pins to off and shutting down Arduino") try: self.stop_all_stimuli() self.set_illumination(0) self.reset_all_sensors() self.flash_status(StatusCode.SHUTDOWN) finally: try: asyncio.ensure_future(self._kill()) finally: self._board.core.serial_port.my_serial.close() logger.debug("Finished shutting down Arudino")
def write(self, log_file: str) -> None: logger.debug("Writing stimulus times.") with open(log_file, 'w') as file: file.write('datetime,id,intensity\n') start_stamp = stamp(StimulusTimeRecord.calc_delta(self.start_time)) file.write('{},0,0\n'.format(start_stamp)) for record in self: current_stamp = stamp(record.delta_timestamp()) if record.stimulus is not StimulusType.MARKER: file.write("{},{},{}\n".format(current_stamp, record.stimulus.key.id, record.stimulus.byte_intensity)) end_stamp = stamp(StimulusTimeRecord.calc_delta(self.end_time)) file.write('{},0,0'.format(end_stamp)) logger.debug("Finished writing stimulus times.")
def register_sensor(self, pin: int, callback) -> None: if isinstance(pin, int): pin_number = pin elif pin in self.layout.digital_sensors[pin]: pin_number = self.layout.digital_sensors[pin] elif pin in self.layout.analog_sensors: pin_number = self.layout.digital_sensors else: raise KeyError("No sensor pin for sensor {}".format(pin)) pin_state = self._board.get_pin_state(pin_number) logger.debug("Registered sensor on pin {}".format(pin_number)) self._board.enable_analog_reporting(pin=pin_number) # TODO should be able to use pin_state[1] instead of Constants.ANALOG, but for some reason the setting doesn't stick?? self._board.set_pin_mode(pin_number=pin_number, pin_state=Constants.ANALOG, callback=callback, cb_type=Constants.CB_TYPE_DIRECT)
def plot(self): logger.debug("Plotting microphone data (may take a couple minutes)...") with open(self.output_path, 'rb') as f: self.sampling_rate, data = wavfile.read(f) ms = np.array( [i / self.sampling_rate * 1000 for i in range(0, len(data))]) low_x = self.timestamps[0].strftime('%H:%M:%S') high_x = self.timestamps[-1].strftime('%H:%M:%S') s = HipsterPlotter(num_y_chars=10).plot(data, title=self.name(), low_x_label=low_x, high_x_label=high_x) with open(self.output_path + '.plot.txt', 'w', encoding="utf8") as f: f.write(s) return s
def save(self): try: logger.info("Writing microphone data...") logger.debug("Writing microphone timestamps") with open(self.timestamp_file_path, 'w') as f: for ts in self.timestamps: f.write(stamp(ts) + '\n') logger.debug("Writing microphone WAV data") wf = wave.open(self.log_file, 'wb') try: wf.setnchannels(self.channels) wf.setsampwidth(self._p.get_sample_size(self.audio_format)) wf.setframerate(self.sample_rate) wf.writeframes(b''.join(self.frames)) finally: wf.close() except Exception as e: #warn_user("Microphone failed while writing the .wav file") raise e logger.info("Finished writing microphone data.")
def __windows_switch(self, i: int): def percent_to_real(percent: int) -> int: audio_max = 65535 # This is true of Windows in general, so not necessary to put in config # audio min is 0 return round(audio_max * percent / 100) if self.output_device is not None: logger.debug("Setting audio output device to %s" % self.output_device[i]) wrap_cmd_call([ 'nircmd', 'setdefaultsounddevice', '%s' % self.output_device[i] ], timeout_secs=self.timeout_secs) if self.input_device is not None: logger.debug("Setting audio input device to %s" % self.input_device[i]) wrap_cmd_call([ 'nircmd', 'setdefaultsounddevice', '%s' % self.input_device[i], '2' ], timeout_secs=self.timeout_secs) if self.output_gain is not None: logger.debug("Setting system volume to configured default %s" % self.output_gain[i]) wrap_cmd_call([ 'nircmd', 'setsysvolume', '%s' % percent_to_real(self.output_gain[i]), self.output_device[i] ], timeout_secs=self.timeout_secs) if self.input_gain is not None: logger.debug("Setting input gain to configured default %s" % self.input_gain[i]) wrap_cmd_call([ 'nircmd', 'setsysvolume', '%s' % percent_to_real(self.input_gain[i]), self.input_device[i] ], timeout_secs=self.timeout_secs)
def reset(self): self._board.send_reset() logger.debug("Sent reset to Arduino board")
def _kill(self): logger.info("Terminating microphone...") logger.debug("Ending microphone process") try: self._p.terminate() # failing here is probably bad except Exception as b: logger.warning("Failed to terminate microphone process") logger.debug(b, exc_info=True) logger.debug("Ending microphone stream") try: self._stream.stop_stream() except Exception as b: logger.warning("Failed to stop microphone stream") logger.debug(b, exc_info=True) logger.debug("Closing microphone stream") try: self._stream.close() except Exception as b: logger.warning("Failed to close microphone process") logger.debug(b, exc_info=True) self._p = None # ; self._thread = None logger.debug("Microphone exited") logger.info("Terminated microphone.")