buttons.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. from gpiozero import Button
  2. from signal import pause
  3. import time
  4. import subprocess
  5. import pathlib
  6. venv_path = f"{pathlib.Path(__file__).parent.resolve()}/venv/bin/python3"
  7. player_path = f"{pathlib.Path(__file__).parent.resolve()}/player.py"
  8. Button.was_held = False
  9. def vol_up(btn):
  10. btn.was_held = True
  11. while btn.was_held:
  12. print("Vol Up")
  13. result = subprocess.run(
  14. [f"mpc volume +10"],
  15. stdout=subprocess.PIPE,
  16. shell=True,
  17. ).stdout.decode("utf-8")
  18. time.sleep(0.3)
  19. def vol_down(btn):
  20. btn.was_held = True
  21. while btn.was_held:
  22. print("Vol Down")
  23. result = subprocess.run(
  24. [f"mpc volume -10"],
  25. stdout=subprocess.PIPE,
  26. shell=True,
  27. ).stdout.decode("utf-8")
  28. time.sleep(0.3)
  29. def mute(btn):
  30. btn.was_held = True
  31. while btn.was_held:
  32. print("Mute")
  33. result = subprocess.run(
  34. [f"mpc volume -10"],
  35. stdout=subprocess.PIPE,
  36. shell=True,
  37. ).stdout.decode("utf-8")
  38. time.sleep(0.3)
  39. def playpause_down(btn):
  40. btn.was_held = True
  41. while btn.was_held:
  42. print("playpause")
  43. time.sleep(0.3)
  44. def released(btn):
  45. if not btn.was_held:
  46. pressed(btn)
  47. btn.was_held = False
  48. def pressed(btn):
  49. if btn._pin.number == up_pin:
  50. print("next")
  51. result = subprocess.run(
  52. [f"{venv_path} {player_path} next"],
  53. stdout=subprocess.PIPE,
  54. shell=True,
  55. ).stdout.decode("utf-8")
  56. elif btn._pin.number == down_pin:
  57. print("back")
  58. result = subprocess.run(
  59. [f"{venv_path} {player_path} previous"],
  60. stdout=subprocess.PIPE,
  61. shell=True,
  62. ).stdout.decode("utf-8")
  63. elif btn._pin.number == playpause_pin:
  64. print("playpause")
  65. result = subprocess.run(
  66. [f"{venv_path} {player_path} playpause"],
  67. stdout=subprocess.PIPE,
  68. shell=True,
  69. ).stdout.decode("utf-8")
  70. elif btn._pin.number == shuffle_pin:
  71. print("shuffle")
  72. result = subprocess.run(
  73. [f"{venv_path} {player_path} shuffle"],
  74. stdout=subprocess.PIPE,
  75. shell=True,
  76. ).stdout.decode("utf-8")
  77. up_pin = 24
  78. down_pin = 15
  79. playpause_pin = 14
  80. shuffle_pin = 23
  81. up_btn = Button(up_pin)
  82. down_button = Button(down_pin)
  83. playpause_button = Button(playpause_pin)
  84. shuffle_button = Button(shuffle_pin)
  85. up_btn.when_held = vol_up
  86. up_btn.when_released = released
  87. down_button.when_held = vol_down
  88. down_button.when_released = released
  89. playpause_button.when_held = mute
  90. playpause_button.when_released = released
  91. shuffle_button.when_released = released
  92. pause()