123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import os
- import RPi.GPIO as GPIO
- import time
- from lib.mqtt import create_client, control_player, create_config, check_current_status, check_current_disc, update_disc
- from lib.home_assistant import load_disc, pause_media, play_media_again, set_shuffle, next_track
- from dotenv import load_dotenv
- load_dotenv()
- use_mqtt = os.environ["use_mqtt"].lower() == "true"
- if use_mqtt:
- client = create_client()
- create_config(client)
- print(f"Using MQTT: {use_mqtt}")
- BUTTON_PINS = [17, 18, 27, 22]
- GPIO.setmode(GPIO.BCM)
- for pin in BUTTON_PINS:
- GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
- def handle_button_1():
- if use_mqtt:
- if check_current_status(client) == "PLAY":
- print("Pausing playback via MQTT.")
- control_player(client, "PAUSE")
- else:
- print("Playing media via MQTT.")
- control_player(client, "PLAY")
- else:
- print("Pausing/Playing via Home Assistant.")
- if check_current_status(client) == "PLAY":
- pause_media()
- else:
- play_media_again()
- def handle_button_2():
- print("Skipping to the next track.")
- if use_mqtt:
- control_player(client, "SKIP")
- control_player(client, "PLAY")
- else:
- next_track()
- def handle_button_3():
- start_time = time.time()
- if use_mqtt:
- disc_data = check_current_disc(client)
-
- while GPIO.input(BUTTON_PINS[2]) == GPIO.LOW:
- if time.time() - start_time >= 3:
- print("Button 3 held for 3 seconds! Resetting to RADIO2 via MQTT.")
- update_disc(client, ["ytmusic", disc_data['name'], disc_data['type'], "RESET"])
- control_player(client, "PLAY")
- update_disc(client, ["ytmusic", disc_data['name'], disc_data['type'], disc_data['id']])
- return
- print("Button 3 pressed briefly! Sending RADIO via MQTT.")
- control_player(client, "RADIO")
- else:
- print("Button 3 functionality not implemented for Home Assistant.")
- def handle_button_4():
- print("Toggling shuffle mode.")
- if use_mqtt:
- control_player(client, "SHUFFLE")
- control_player(client, "PLAY")
- else:
- set_shuffle()
- def button_callback(channel):
- if channel == BUTTON_PINS[0]:
- handle_button_1()
- elif channel == BUTTON_PINS[1]:
- handle_button_2()
- elif channel == BUTTON_PINS[2]:
- handle_button_3()
- elif channel == BUTTON_PINS[3]:
- handle_button_4()
- for pin in BUTTON_PINS:
- GPIO.add_event_detect(pin, GPIO.FALLING, callback=button_callback, bouncetime=200)
- try:
-
- while True:
- time.sleep(1)
- except KeyboardInterrupt:
- pass
- finally:
- GPIO.cleanup()
|