From 99b2070a2e3a60a9ff4349e904a252a7b234e483 Mon Sep 17 00:00:00 2001 From: Mike Cifelli <1836280-mike-cifelli@users.noreply.gitlab.com> Date: Thu, 6 May 2021 14:13:55 -0400 Subject: [PATCH] Create power button service and installer --- README.md | 3 +++ install | 31 +++++++++++++++++++++++++++++++ power-button.py | 16 ++++++++++++++++ power-button.service | 12 ++++++++++++ 4 files changed, 62 insertions(+) create mode 100755 install create mode 100644 power-button.py create mode 100644 power-button.service diff --git a/README.md b/README.md index 3f9c98a..8aa5e03 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ # power-button +# Dependencies +sudo apt install python3-pip +sudo apt install python3-gpiozero diff --git a/install b/install new file mode 100755 index 0000000..68f2f82 --- /dev/null +++ b/install @@ -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]) diff --git a/power-button.py b/power-button.py new file mode 100644 index 0000000..ffecda7 --- /dev/null +++ b/power-button.py @@ -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() diff --git a/power-button.service b/power-button.service new file mode 100644 index 0000000..fede011 --- /dev/null +++ b/power-button.service @@ -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