|
| 1 | +# should be run in raspberry with sudo |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import RPi.GPIO as GPIO |
| 6 | +import time |
| 7 | + |
| 8 | +from hibernate_server import hibernate_server |
| 9 | + |
| 10 | +def set_led_item(index,item,value): |
| 11 | + with open("/sys/class/leds/led%d/%s" % (index,item),"w") as f: |
| 12 | + f.write(value) |
| 13 | + |
| 14 | + |
| 15 | +# turn off red LED |
| 16 | +set_led_item(1,"trigger","none") |
| 17 | +set_led_item(1,"brightness","0") |
| 18 | + |
| 19 | +# turn on green LED |
| 20 | +set_led_item(0,"trigger","none") |
| 21 | +set_led_item(0,"brightness","0") |
| 22 | +time.sleep(0.5) # I had to use this trick to make the green led stay on |
| 23 | +set_led_item(0,"brightness","1") |
| 24 | + |
| 25 | +# should run the script with "shutdown_button" to handle shutdown button/relay |
| 26 | +# code inspired from this tutorial https://www.quartoknows.com/page/raspberry-pi-shutdown-button |
| 27 | +if len(sys.argv) == 2 and sys.argv[1] == "shutdown_button": |
| 28 | + print("shutdown button enabled") |
| 29 | + |
| 30 | + # Use the Broadcom SOC Pin numbers |
| 31 | + GPIO.setmode(GPIO.BCM) |
| 32 | + |
| 33 | + # Setup the pin with internal pullups enabled and pin in reading mode. |
| 34 | + GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP) |
| 35 | + |
| 36 | + # Our function on what to do when the button is pressed |
| 37 | + def Shutdown(channel): |
| 38 | + print("shutdown pressed") |
| 39 | + brightness = 0 |
| 40 | + now = time.time() # get current time |
| 41 | + brightness_timer = now |
| 42 | + while time.time() - now < 5: # if during 5 seconds the channel is high |
| 43 | + if GPIO.input(channel): # abort shutdown |
| 44 | + set_led_item(0,"brightness","0") |
| 45 | + time.sleep(0.2) |
| 46 | + set_led_item(0,"brightness","1") |
| 47 | + print("shutdown aborted") |
| 48 | + return |
| 49 | + |
| 50 | + if time.time() - brightness_timer >= 0.1: # blink green led to display response to button |
| 51 | + print(brightness) |
| 52 | + set_led_item(0,"brightness","%d" % brightness) |
| 53 | + brightness_timer = time.time() |
| 54 | + brightness = 1 - brightness |
| 55 | + |
| 56 | + print("Shutting Down") |
| 57 | + |
| 58 | + set_led_item(0,"trigger","none") |
| 59 | + set_led_item(0,"brightness","0") # turn off green led to display that it's going to shutdown |
| 60 | + hibernate_server(False) # send 'hibernate' command to PC |
| 61 | + os.system("sudo shutdown -h now") |
| 62 | + exit() |
| 63 | + |
| 64 | + # Add our function to execute when the button pressed event happens |
| 65 | + GPIO.add_event_detect(21, GPIO.FALLING, callback=Shutdown, bouncetime=2000) |
| 66 | + # Now wait! |
| 67 | + while 1: |
| 68 | + time.sleep(1) |
0 commit comments