コード例 #1
0
ファイル: recorder.py プロジェクト: falue/waldo
def record_setup(project_name, channel_name):
    project_path = read_main_config()['project_path']

    # Channel file exist?
    if os.path.isfile(os.path.join(project_path, project_name, channel_name)):
        # overwite?
        answer = raw_input("'%s' already exists. Replace? [Y/N]\n" %
                           channel_name).lower()

        if answer == "y":
            # backup file in 'trash'
            try:
                os.makedirs(os.path.join(project_path, project_name, 'trash'))
            except OSError:
                pass

            copyfile(
                os.path.join(project_path, project_name, channel_name),
                os.path.join(
                    project_path, project_name, 'trash',
                    channel_name + "_" + time.strftime('%Y-%m-%d_%H_%M_%S')))
        elif answer == "n":
            print("Abort.")
            exit()
        else:
            print("[Y/N] murmel, murmel")
            record_setup(project_name, channel_name)
            return  # sure?

    else:
        set_servo(project_name, channel_name)
コード例 #2
0
    def __init__(self,
                 project_name,
                 play_from=0,
                 repeat=False,
                 mute_pins=None):
        """
        :type mute_pins: list
        """
        self._servo_channels = []
        self._mute_pins = mute_pins if mute_pins else []
        self._audio_player = None
        self.running = False
        self.project_name = project_name
        self.play_from = play_from
        self.repeat = repeat

        preferences = read_main_config()
        project_path = preferences['project_path']
        # FIXME: find a better name to distinguish between this projects path and the path of all projects
        self.song_path = os.path.join(project_path, self.project_name)

        # TODO: Auto-detect I2C devices: ServoHats
        # used_i2c_addresses = subprocess.Popen(['i2cdetect', '-y', '1'], stdout=subprocess.PIPE)
        self.used_i2c_addresses = preferences['used_i2c_addresses']

        self._read_config()
        self._create_servo_channels()
        self._create_audio_player()
コード例 #3
0
ファイル: recorder.py プロジェクト: falue/waldo
def new_project(project_name):
    """
    Create new folder structure and setup config file.
    """
    print('Creating new project structure for \'{}\''.format(project_name))

    # Get path
    project_path = read_main_config()['project_path']
    path = os.path.join(project_path, project_name)

    # Path not existent?
    if not os.path.exists(path):
        os.makedirs(path)
        os.makedirs(os.path.join(path, 'audio'))
        os.makedirs(os.path.join(path, 'trash'))

        answer = raw_input(
            "Copy config file from existing project? [Y/N] (For servo settings & recording connection type)\n"
        ).lower()
        if answer == "y":

            file_list = os.listdir(project_path)
            projects = sorted([a for a in file_list if not a.startswith(".")])
            if '_archive' in projects:
                projects.remove('_archive')
            if project_name in projects:
                projects.remove(project_name)

            if not projects:
                print("There are no project folders in '%s'." % project_path)
            else:
                project_list = list()
                print('Copy from where?')
                print('ID:\tProject:')
                # For each project to analyze
                for i, project in enumerate(projects):
                    print('%s\t%s' % (i, project))
                    project_list.append(i)

                answer = int(raw_input("Type your ID:\n").lower())

                if answer in project_list:
                    copy_from = os.path.join(project_path, projects[answer],
                                             'config')
                    copy_to = os.path.join(path, 'config')
                    copyfile(copy_from, copy_to)
                    pass
                else:
                    print('By god, this is not an acceptable answer.')

        print('Created new project structure.')
    else:
        print('✖  Project already exists.')
コード例 #4
0
ファイル: recorder.py プロジェクト: falue/waldo
def copy_channel(project_name,
                 channel_old,
                 channel_new,
                 preserve_pin='pin_inc'):
    """
    Copies file channel_old to channel_new with matching config data. preserve pin copies
    servo pin 1:1 if true, if false increments the total amount of servo channels.
    """
    project_path = read_main_config()['project_path']
    config = read_project_config(project_name)

    # Check if new channel already exists
    if not os.path.isfile(os.path.join(project_path, project_name, channel_new)) \
            and channel_new not in config['channels']:
        # Copy old to new
        copyfile(os.path.join(project_path, project_name, channel_old),
                 os.path.join(project_path, project_name, channel_new))

        if preserve_pin == "pin_inc":
            # Write new servo_pin
            preserve_pin = len(config['channels'])

        elif preserve_pin == "pin_copy":
            # Copy servo_pin old to servo_pin new
            preserve_pin = config['channels'][channel_old]['servo_pin']
        else:
            # Write user defined integer as servo_pin
            preserve_pin = int(preserve_pin)

        # Update config list
        config['channels'].update({
            channel_new: {
                'mcp_in': config['channels'][channel_old]['mcp_in'],
                'servo_pin': preserve_pin,
                'map_min': config['channels'][channel_old]['map_min'],
                'map_max': config['channels'][channel_old]['map_max'],
                'start_pos': config['channels'][channel_old]['start_pos']
            }
        })
        # Write in config file
        write_project_config(project_name, config)
        print(
            "File and config data for new channel '%s' in project '%s' copied from '%s'."
            % (channel_new, project_name, channel_old))
    else:
        print(
            "✖  File or config data for channel '%s' in project '%s' already exists."
            % (channel_new, project_name))
コード例 #5
0
def preload_players():
    logger.info('Pre-loading players')

    # Read preferences and set project folder path
    preferences = read_main_config()
    # do not expand user due to autostart user is 'root' not 'pi'
    project_path = preferences['project_path'] if not os.path.isdir(
        'projects') else 'projects'

    players = {}
    song_names = sorted([
        item for item in os.listdir(project_path)
        if not item.startswith('.') and not item == '_archive'
    ])

    for name in song_names:
        players[name] = Player(project_name=name)

    return players
コード例 #6
0
ファイル: keyboard_listener.py プロジェクト: falue/waldo
def run_listener(autostart=None):
    config = read_main_config()

    dev = wait_for_keyboard()

    players = preload_players()
    print('All players loaded.')
    AudioPlayer(
        os.path.expanduser('~/Scripts/waldo/waldo/sounds/chime.mp3')).play()
    rg_led('green')

    if autostart:
        players[autostart].play()

    try:
        read_loop(dev, config, players)
    except IOError:
        print('Keyboard unplugged.')
        run_listener(autostart=autostart)
コード例 #7
0
ファイル: recorder.py プロジェクト: falue/waldo
def get_dof(mcp_in, servo_pin):
    """
    Move servo, directly controlled via user input. Standard boundaries comply.
    On enter return of current value.
    """
    potentiometer = Potentiometer(mcp_in)
    main_config = read_main_config()
    servo = Servo(servo_pin,
                  used_i2c_addresses=main_config['used_i2c_addresses'])

    while True:
        reading = potentiometer.read()
        value = map_value(reading, 0, 1024, 600, 100)
        servo.set_pos(value)
        print("{}{}{}░".format(reading, ' ' * (5 - len(str(reading))),
                               "█" * (reading / 5)))

        # Exit loop when enter is pressed
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            print("Defined: %s" % value)
            servo.turn_off()
            return value
        sleep(1 / 50.0)
コード例 #8
0
ファイル: autostart.py プロジェクト: falue/waldo
def run_daemon():
    # Read preferences
    preferences = read_main_config()

    autostart = preferences['autostart']
    measure_temp = preferences['measure_temp']
    volume = preferences['volume']

    shutdown_on_button_press()

    # Set volume to 30%
    subprocess.call(['amixer', '-q', 'set', 'Speaker', '{}%'.format(volume)
                     ])  # amixer set PCM -- 100% amixer sset 'Master' 50%

    if measure_temp:
        monitor_temperature()

    if autostart:
        run_listener(autostart=autostart if type(autostart) is str else None)
    else:
        rg_led('green')

    while True:
        sleep(1)
コード例 #9
0
ファイル: recorder.py プロジェクト: falue/waldo
def record_channel(project_name, channel_name):
    """
    Listen to analog input via MCP3008, follow with single servo and store data in file.
    :type project_name: str
    :type channel_name: str
    """
    # Read config data for channel
    config = read_project_config(project_name)
    servo_pin = config['channels'][channel_name]['servo_pin']
    map_min = config['channels'][channel_name]['map_min']
    map_max = config['channels'][channel_name]['map_max']
    mcp_in = config['channels'][channel_name]['mcp_in']

    main_config = read_main_config()
    project_path = main_config['project_path']
    servo = Servo(servo_pin,
                  used_i2c_addresses=main_config['used_i2c_addresses'])
    potentiometer = Potentiometer(mcp_in)
    player = Player(project_name)

    data = []
    # Countdown for slow recordists
    print('Start recording in...')
    time.sleep(1)
    print('3')
    time.sleep(1)
    print('2')
    time.sleep(1)
    print('1')
    time.sleep(1)
    print('Go!')

    player._play_audio()

    # Open channel file, get start time of recording
    start_time = time.time()

    # Set up: first reading
    potentiometer_position = potentiometer.read()
    potentiometer_last_position = potentiometer_position
    data.append("%s: %s" % (0.0, potentiometer_position))

    # Record!
    while True:
        potentiometer_position = potentiometer.read()

        # Recording to file
        if potentiometer_position not in range(potentiometer_last_position - 8,
                                               potentiometer_last_position +
                                               8):
            # Playback on servo
            servo_value = map_value(int(potentiometer_position), 0, 1024,
                                    map_min, map_max)
            servo.set_pos(servo_value)

            timecode = round(time.time() - start_time, 3)
            data.append("%s: %s" % (timecode, potentiometer_position))
            potentiometer_last_position = potentiometer_position
            logger.info('Servo %s:\t%s\t%s' %
                        (servo_pin, potentiometer_position,
                         bar(potentiometer_position)))
        else:
            logger.info('----- %s:\t%s\t%s' %
                        (servo_pin, potentiometer_position,
                         bar(potentiometer_position)))
        # Exit loop when enter is pressed
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            player.stop()
            servo.turn_off()
            break

        time.sleep(0.001)

    player.stop()
    GPIO.cleanup()

    with open(os.path.join(project_path, project_name, channel_name),
              'w+') as record_file:
        record_file.write('\n'.join(data))

    logger.info("Recording ended.")

    # Get file size of recorded file
    file_size = get_filesize(
        os.path.getsize(os.path.join(project_path, project_name,
                                     channel_name)), 2)
    logger.info("Recorded file '%s' is %s." % (channel_name, file_size))
コード例 #10
0
ファイル: recorder.py プロジェクト: falue/waldo
def check_project(project_name):
    project_path = read_main_config()['project_path']

    if not os.path.isdir(os.path.join(project_path, project_name)):
        new_project(project_name)