buttons.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import os
  2. import RPi.GPIO as GPIO
  3. import time
  4. from dotenv import load_dotenv
  5. from lib.mqtt import create_client, update_disc, control_player, create_config, check_current_disc
  6. # Load the .env file
  7. load_dotenv()
  8. # Define the MQTT server details
  9. broker = os.environ.get("broker")
  10. port = int(os.environ.get("port"))
  11. # MQTT username and password
  12. username = os.environ.get("username")
  13. password = os.environ.get("password")
  14. #print(f"Broker: {broker}, Port: {port}, Username: {username}")
  15. client = create_client(broker, port, username, password)
  16. create_config(client)
  17. # Set up GPIO pins for each button
  18. BUTTON_PINS = [17, 18, 27] # Replace with your GPIO pin numbers
  19. GPIO.setmode(GPIO.BCM) # Use BCM numbering
  20. # Set up each button pin as input with internal pull-up resistors
  21. for pin in BUTTON_PINS:
  22. GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  23. # Callback functions to handle button presses
  24. def button_callback_1(channel):
  25. print("Button 1 pressed!")
  26. control_player(client, "PLAY")
  27. def button_callback_2(channel):
  28. print("Button 2 pressed!")
  29. control_player(client, "PAUSE")
  30. def button_callback_3(channel):
  31. print("Button 3 pressed!")
  32. # Add event detection for each button press
  33. GPIO.add_event_detect(BUTTON_PINS[0], GPIO.FALLING, callback=button_callback_1, bouncetime=200)
  34. GPIO.add_event_detect(BUTTON_PINS[1], GPIO.FALLING, callback=button_callback_2, bouncetime=200)
  35. GPIO.add_event_detect(BUTTON_PINS[2], GPIO.FALLING, callback=button_callback_3, bouncetime=200)
  36. try:
  37. # Keep the script running to detect button presses
  38. while True:
  39. time.sleep(1) # Sleep to reduce CPU usage
  40. except KeyboardInterrupt:
  41. pass
  42. finally:
  43. GPIO.cleanup() # Clean up GPIO on exit