Skip to content

Instantly share code, notes, and snippets.

@Dregu
Last active October 25, 2024 14:32
Show Gist options
  • Save Dregu/1163dddcd879d0ed390707a2b3dead30 to your computer and use it in GitHub Desktop.
Save Dregu/1163dddcd879d0ed390707a2b3dead30 to your computer and use it in GitHub Desktop.
Scripts to start and stop moonlight or moonlight-embedded systemd service automatically only when the TV is turned on, by connecting the 5V/500mA USB from the TV to Raspberry Pi (3B+) GPIO17 via a 25kΩ/50kΩ voltage divider for a (hopefully) suitable 3.3V signal. Smaller resistors might also work, but this is what I had and it works for me.
#!/usr/bin/env python
import dbus
from gpiozero import Button
from signal import pause
sysbus = dbus.SystemBus()
systemd1 = sysbus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager')
def on():
print('TV is ON')
manager.StartUnit('moonlight.service', 'fail')
def off():
print('TV is OFF')
manager.StopUnit('moonlight.service', 'fail')
tv = Button(pin=17, pull_up=False, bounce_time=1)
tv.when_activated = on
tv.when_deactivated = off
if tv.is_pressed:
on()
else:
off()
pause()
[Unit]
Description=Moonlight GPIO button
After=network.target
[Service]
ExecStart=/home/pi/moonlight-gpio.py
Restart=always
RestartSec=3
User=root
[Install]
WantedBy=multi-user.target
# This unit is disabled, but is started on boot by the other one if the TV is on,
# or toggled by the GPIO cable when the tv turns on or off
[Unit]
Description=Moonlight stream
After=network.target
[Service]
ExecStart=moonlight stream -1080 -bitrate 20000 -app Desktop PC
Restart=always
RestartSec=3
User=pi
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment