Skip to content

Instantly share code, notes, and snippets.

@hadrianw
Created February 17, 2022 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadrianw/8422aa6f3d03890052bc34b1cfdb90e6 to your computer and use it in GitHub Desktop.
Save hadrianw/8422aa6f3d03890052bc34b1cfdb90e6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
A service to toggle play/pause of a Chromecast via Play multimedia key.
Requires running as root because of the "keyboard" module.
requirements: pychromecast keyboard
"""
chromecast_name = "Salon"
import os, pwd, grp
import pychromecast
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
if os.getuid() != 0:
return
running_uid = pwd.getpwnam(uid_name).pw_uid
running_gid = grp.getgrnam(gid_name).gr_gid
os.setgroups([])
os.setgid(running_gid)
os.setuid(running_uid)
old_umask = os.umask(0o77)
def toggle():
chromecasts, browser = pychromecast.get_listed_chromecasts(friendly_names=[chromecast_name])
cast = chromecasts[0]
cast.wait()
cast.media_controller.block_until_active()
if cast.media_controller.is_playing:
cast.media_controller.pause()
elif cast.media_controller.is_paused:
cast.media_controller.play()
browser.stop_discovery()
import keyboard
keyboard.add_hotkey(164, toggle)
drop_privileges()
keyboard.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment