forked from esisco/retroflag-picase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSafeShutdown.py
executable file
·97 lines (76 loc) · 2.21 KB
/
SafeShutdown.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env python3
from gpiozero import Button, LED
import os
import signal
import subprocess
import time
powerPin = 3
resetPin = 2
ledPin = 14
powerenPin = 4
hold = 1
led = LED(ledPin)
led.on()
power = LED(powerenPin)
power.on()
def get_es_pid():
try:
output = int(subprocess.check_output(
'pgrep -f "^/opt/retropie/supplementary/.*/emulationstation([^.]|$)"',
shell=True))
except subprocess.CalledProcessError:
output = 0
return output
def get_rc_pid():
try:
output = int(subprocess.check_output('pgrep -f "^bash .*/runcommand.sh"', shell=True))
except subprocess.CalledProcessError:
output = 0
return output
def wait_for_close(process_pid):
loop = True
while loop:
if os.path.exists('/proc/{}'.format(process_pid)):
time.sleep(0.1)
else:
loop = False
def close_emulators(process_pid):
try:
subprocess.call('pkill -TERM -P {}'.format(process_pid), shell=True, timeout=5)
wait_for_close(process_pid)
except subprocess.TimeoutExpired:
subprocess.call('pkill -KILL -P {}'.format(process_pid), shell=True) # Force close if timeout expires
wait_for_close(process_pid)
def exit_es(exit_command, es_pid):
subprocess.call('touch /tmp/{}'.format(exit_command), shell=True)
subprocess.call('chown pi:pi /tmp/{}'.format(exit_command), shell=True)
subprocess.call('kill {}'.format(es_pid), shell=True)
wait_for_close(es_pid)
# functions that handle button events
def power_switch_off():
led.blink(.2, .2)
es_pid = get_es_pid()
if es_pid:
rc_pid = get_rc_pid()
if rc_pid:
close_emulators(rc_pid)
exit_es('es-shutdown', es_pid)
else:
os.system("sudo shutdown -h now")
def power_switch_on():
led.on()
def reset_pressed():
es_pid = get_es_pid()
if es_pid:
rc_pid = get_rc_pid()
if rc_pid:
close_emulators(rc_pid)
else:
os.system("clear")
# Setup button handlers
btn = Button(powerPin, hold_time=hold)
rebootBtn = Button(resetPin)
rebootBtn.when_pressed = reset_pressed
btn.when_pressed = power_switch_off
btn.when_released = power_switch_on
signal.pause()