# piplayer3 - AudioSaucer # http://www.tilman.de/piplayer3 import RPi.GPIO as GPIO import logging import time import subprocess import select # for polling zbarcam, see http://stackoverflow.com/a/10759061/3761783 import os import requests import urllib import threading from threading import Thread logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s - %(message)s') logging.info('Initializing') # Configuration MUSIC_BASE_DIRECTORY = "/media/share/Kinder/" SOUND_SCANNING = "file:///home/pi/sounds/scanning.mp3" SOUND_OK = "file:///home/pi/sounds/ok.mp3" SOUND_SCAN_FAIL = "file:///home/pi/sounds/fail.mp3" SOUND_PLAYBACK_ERROR = "file:///home/pi/sounds/error.mp3" QR_SCANNER_TIMEOUT = 3 MOPIDY_RPC_URL = 'http://127.0.0.1:6680/mopidy/rpc' MUSIC_EXTENSIONS = ('.aac', '.ac3', '.aiff', '.amr', '.au', '.flac', '.m4a', '.mid', '.mka', '.mp3', '.ogg', '.ra', '.voc', '.wav', '.wma') REQUEST_TIMEOUT = 5 qr_scanning = False creating_playlist = False # photo sensor on PIN 17 PIN_SENSOR = 17 # IR LED on PIN 22 PIN_IR_LED = 22 # LED on PIN 27 PIN_LED = 27 # Buttons on PINs 9, 10 and 11 PIN_PREV = 9 PIN_PLAY = 10 PIN_NEXT = 11 GPIO.setmode(GPIO.BCM) GPIO.setup(PIN_SENSOR, GPIO.IN) GPIO.setup(PIN_IR_LED, GPIO.OUT) GPIO.output(PIN_IR_LED, GPIO.LOW) GPIO.setup(PIN_LED, GPIO.OUT) GPIO.output(PIN_LED, GPIO.LOW) GPIO.setup(PIN_PREV, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(PIN_PLAY, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(PIN_NEXT, GPIO.IN, pull_up_down=GPIO.PUD_UP) def call(method, params=None): if (params is None): json = '{"jsonrpc": "2.0", "id": 1, "method": "' + method + '"}' else: json = '{"jsonrpc": "2.0", "id": 1, "method": "' + method + '" , "params": ' + params + '}' logging.info('Request: ' + json) try: response = requests.post(MOPIDY_RPC_URL, data=json, timeout=REQUEST_TIMEOUT) logging.info('Response: ' + response.text) except requests.exceptions.Timeout: logging.error('The request timed out') return response def add_uri(filename): logging.debug('Adding ' + filename) call('core.tracklist.add', '{"uri": "' + filename + '"}') def play_sound(filename): call('core.tracklist.clear') logging.debug('Cleared tracklist, now playing ' + filename) add_uri(filename) call('core.playback.play') def list_files(dir): r = [] for path, dirs, files in os.walk(dir): dirs.sort() files.sort() for name in files: r.append(os.path.join(path, name)) return r def create_playlist(qr_code): logging.info('Creating playlist') creating_playlist = True if (qr_scanning): creating_playlist = False logging.info('Stopping creating playlist') return if (not (qr_code.startswith("http://") or qr_code.startswith("spotify:"))): # create full path if (qr_code.startswith("/")): qr_code = qr_code[1:] full_path = MUSIC_BASE_DIRECTORY + qr_code if (not os.path.isfile(full_path)): logging.debug("Not a file, recursively add all audio files in directory") filenames = list_files(full_path) playback_started = False for filename in filenames: # if a new code is being scanned, stop adding to the playlist if (qr_scanning): creating_playlist = False logging.info('Stopping creating playlist') return if filename.lower().endswith(MUSIC_EXTENSIONS): add_uri("file://" + urllib.parse.quote(filename)) if (not playback_started): playback_started = True call('core.playback.play') else: logging.debug("It's a file") add_uri("file://" + urllib.parse.quote(full_path)) call('core.playback.play') else: logging.debug("URL, open directly") add_uri(qr_code) call('core.playback.play') def prev_callback(channel): logging.info("PREV") json = call('core.playback.get_time_position').json() if (json['result'] < 4000): call('core.playback.previous') else: call('core.playback.seek', '{ "time_position": 0 }') def play_callback(channel): logging.info("PLAY/PAUSE") json = call('core.playback.get_state').json() if (json['result'] == 'playing'): call('core.playback.pause') else: call('core.playback.play') def next_callback(channel): logging.info("NEXT") call('core.playback.next') GPIO.add_event_detect(PIN_PREV, GPIO.FALLING, callback=prev_callback, bouncetime=400) GPIO.add_event_detect(PIN_PLAY, GPIO.FALLING, callback=play_callback, bouncetime=400) GPIO.add_event_detect(PIN_NEXT, GPIO.FALLING, callback=next_callback, bouncetime=400) try: # wait for the web server to be available response = '' while response == '': try: logging.info("Trying to connect to the server...") response = requests.post(MOPIDY_RPC_URL, data='{"jsonrpc": "2.0", "id": 1, "method": "core.tracklist.clear"}', timeout=REQUEST_TIMEOUT) except: logging.debug("Timeout while connecting to the server") time.sleep(5) continue play_sound(SOUND_OK) while True: logging.info('Wait for photo sensor') GPIO.wait_for_edge(PIN_SENSOR, GPIO.RISING) logging.info('Photo sensor active, activating light and camera') qr_scanning = True while (creating_playlist): logging.info('Waiting for the playlist creation to stop') time.sleep(1) play_sound(SOUND_SCANNING) # turn LED on GPIO.output(PIN_LED, GPIO.HIGH) # scan QR code zbarcam = subprocess.Popen(['zbarcam', '--quiet', '--nodisplay', '--raw', '-Sdisable', '-Sqrcode.enable', '--prescale=320x240', '/dev/video0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) poll_obj = select.poll() poll_obj.register(zbarcam.stdout, select.POLLIN) # wait for scan result (or timeout) start_time = time.time() poll_result = False while ((time.time() - start_time) < QR_SCANNER_TIMEOUT and (not poll_result)): poll_result = poll_obj.poll(100) qr_scanning = False if (poll_result): try: # play confirmation sound play_sound(SOUND_OK) call('core.tracklist.clear') logging.info("Stopped") qr_code = zbarcam.stdout.readline().rstrip() qr_code = qr_code.decode("utf-8") # python3 logging.info("QR Code: " + qr_code) Thread(target = create_playlist, args=(qr_code,)).start() except FileNotFoundError as e: creating_playlist = False logging.error("Could not open directory {}".format(directory)) play_sound(SOUND_PLAYBACK_ERROR) else: logging.warning('Timeout on zbarcam') play_sound(SOUND_SCAN_FAIL) zbarcam.terminate() GPIO.output(PIN_LED, GPIO.LOW) # wait until sensor is not blocked anymore if (GPIO.input(PIN_SENSOR) == GPIO.HIGH): GPIO.wait_for_edge(PIN_SENSOR, GPIO.FALLING) time.sleep(1) # Exit when Ctrl-C is pressed except KeyboardInterrupt: logging.info('Shutdown') finally: logging.info('Reset GPIO configuration and close') GPIO.cleanup()