floppy-ytube-player/buttons.py

64 lines
2.4 KiB
Python
Raw Normal View History

2024-09-20 17:23:30 +01:00
import RPi.GPIO as GPIO
import time
2024-09-20 21:15:46 +01:00
from lib.mqtt import create_client, control_player, create_config, check_current_status, check_current_disc, update_disc
2024-09-20 17:23:30 +01:00
2024-09-20 17:44:22 +01:00
client = create_client()
2024-09-20 17:23:30 +01:00
create_config(client)
# Set up GPIO pins for each button
BUTTON_PINS = [17, 18, 27] # Replace with your GPIO pin numbers
GPIO.setmode(GPIO.BCM) # Use BCM numbering
# Set up each button pin as input with internal pull-up resistors
for pin in BUTTON_PINS:
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Callback functions to handle button presses
def button_callback_1(channel):
2024-09-20 20:48:35 +01:00
client = create_client()
if check_current_status(client) == "PLAY":
2024-09-20 20:46:33 +01:00
print("Button 1 pressed! Pausing playback.")
control_player(client, "PAUSE")
else:
print("Button 1 pressed! Playing.")
control_player(client, "PLAY")
2024-09-20 17:23:30 +01:00
def button_callback_2(channel):
print("Button 2 pressed!")
2024-09-20 20:46:33 +01:00
client = create_client()
2024-09-20 20:52:07 +01:00
control_player(client, "SKIP")
control_player(client, "PLAY")
2024-09-20 17:23:30 +01:00
2024-09-20 21:02:54 +01:00
# Handling button 3 with a hold check
2024-09-20 17:23:30 +01:00
def button_callback_3(channel):
2024-09-20 21:02:54 +01:00
start_time = time.time()
2024-09-20 21:12:59 +01:00
client = create_client()
2024-09-21 08:10:34 +01:00
disc_data = check_current_disc(client)
2024-09-20 21:02:54 +01:00
# Wait until the button is released or held for more than 3 seconds
while GPIO.input(BUTTON_PINS[2]) == GPIO.LOW: # Button is pressed (active low)
if time.time() - start_time >= 3: # Check if 3 seconds have passed
print("Button 3 held for 3 seconds! Sending RADIO2.")
2024-09-20 21:21:33 +01:00
update_disc(client, ["ytmusic",disc_data['name'],disc_data['type'],"RESET"])
update_disc(client, ["ytmusic",disc_data['name'],disc_data['type'],disc_data['id']])
2024-09-20 21:02:54 +01:00
return # Exit after sending RADIO2
# If button was not held for 3 seconds, send RADIO
print("Button 3 pressed briefly! Sending RADIO.")
2024-09-20 20:58:48 +01:00
control_player(client, "RADIO")
2024-09-20 17:23:30 +01:00
# Add event detection for each button press
GPIO.add_event_detect(BUTTON_PINS[0], GPIO.FALLING, callback=button_callback_1, bouncetime=200)
GPIO.add_event_detect(BUTTON_PINS[1], GPIO.FALLING, callback=button_callback_2, bouncetime=200)
GPIO.add_event_detect(BUTTON_PINS[2], GPIO.FALLING, callback=button_callback_3, bouncetime=200)
try:
# Keep the script running to detect button presses
while True:
time.sleep(1) # Sleep to reduce CPU usage
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup() # Clean up GPIO on exit