Create power button service and installer
This commit is contained in:
parent
7bd329791d
commit
99b2070a2e
|
@ -1,2 +1,5 @@
|
|||
# power-button
|
||||
|
||||
# Dependencies
|
||||
sudo apt install python3-pip
|
||||
sudo apt install python3-gpiozero
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
#! /usr/bin/env python3
|
||||
|
||||
import os
|
||||
from string import Template
|
||||
from subprocess import check_call
|
||||
|
||||
EXEC = 'power-button.py'
|
||||
SERVICE = 'power-button.service'
|
||||
SYSTEM_DIR = '/etc/systemd/system'
|
||||
|
||||
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
|
||||
EXEC_PATH = os.path.join(CURRENT_DIR, EXEC)
|
||||
SERVICE_TEMPLATE = os.path.join(CURRENT_DIR, SERVICE)
|
||||
SERVICE_FILE = os.path.join(SYSTEM_DIR, SERVICE)
|
||||
EXEC_START = f'python3 {EXEC}'
|
||||
|
||||
with open(SERVICE_TEMPLATE) as f:
|
||||
serviceTemplate = Template(f.read())
|
||||
|
||||
serviceFile = serviceTemplate.substitute(
|
||||
workingDirectory=CURRENT_DIR,
|
||||
execStart=EXEC_START
|
||||
)
|
||||
|
||||
with open(SERVICE_FILE, 'w') as f:
|
||||
f.write(serviceFile)
|
||||
|
||||
check_call(['systemctl', 'daemon-reload'])
|
||||
check_call(['systemctl', 'enable', '--no-pager', SERVICE])
|
||||
check_call(['systemctl', 'restart', '--no-pager', SERVICE])
|
||||
check_call(['systemctl', 'status', '--no-pager', SERVICE])
|
|
@ -0,0 +1,16 @@
|
|||
from gpiozero import Button
|
||||
from signal import pause
|
||||
from subprocess import check_call
|
||||
|
||||
BUTTON_GPIO_PIN = 3
|
||||
HOLD_TIME_IN_SECONDS = 2
|
||||
|
||||
|
||||
def poweroff():
|
||||
check_call(['sudo', 'poweroff'])
|
||||
|
||||
|
||||
button = Button(BUTTON_GPIO_PIN, hold_time=HOLD_TIME_IN_SECONDS)
|
||||
button.when_held = poweroff
|
||||
|
||||
pause()
|
|
@ -0,0 +1,12 @@
|
|||
[Unit]
|
||||
Description=Power Button Service
|
||||
After=multi.user.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=$workingDirectory
|
||||
ExecStart=$execStart
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
Loading…
Reference in New Issue