Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8082

Beginners • Re: PiHut Pi4B On/Off switch

$
0
0
I was just about to look for the latest instructions for the shutdown switch.
FWIW, here is my setup with an indicator light and push button.

Code:

# BUTTON_ACTION.PY - Display Status of PI & Provide manual reboot/shutdown button__version__ = "V3.3"__program__ = "BUTTON_ACTION"# This is based on the project at https://gist.github.com/lbussy/9e81cbcc617952f1250e353bd42e7775# I chose to implement the 'scripted method' since the project was# going to run 24x7 and I only needed to provide some way for# someone else to reboot/shutdown the PI.# This program needs to be run with the -u Python3 option so as not# to buffer output.# Here is the meaning of the led# BLINKING - Running, waiting for reboot/shutdown button to be pushed# ON has 2 meanings#    BUTTON HELD - Waiting x seconds to ensure reboot/shutdown requested#    BUTTON RELEASED - An error has occurred. This is likely short#                      lived since the service will restart and#                      the light will start blinking again.# OFF - PI is shutting down or starting up.__status__ = "Production"__success__ = 0__failure__ = 1from gpiozero import LED, Buttonfrom datetime import datetimeimport argparsefrom time import sleepfrom sys import exc_infoimport syssys.path.append("/media/work/bin")from sys import exit as sys_exit # Named so to avoid confusion with Pt exit()from traceback import extract_tbimport tracebackimport signal#************************************************************************************************def pdt():    import datetime as dttm    now = dttm.datetime.now()    return "["+now.strftime("%m-%d %H:%M:%S")+"] "#************************************************************************************************# https://docs.python.org/3/library/argparse.htmldef doArgs():    # parser will print errors. Only need to trap to return failure    try:        parser = argparse.ArgumentParser()        parser.add_argument("--shutdown", action="store_true",\                            help="Shutdown instead of rebooting", default=False)        parser.add_argument("--debug", action="store_true",\                            help="Debug. No action taken", default=False)        args = parser.parse_args()            except:        exc_type, exc_value, exc_traceback = sys.exc_info()        type=exc_type.__name__        summ = str(traceback.extract_tb(exc_traceback))        print (pdt()+"BUTTON_ACTION: Exception '"+type+"="+str(exc_value)+"'. Traceback: "+summ)        return False   # --debug Provide information using for debugging    global shutdown,debug     shutdown = args.shutdown    debug = args.debug        return True# End of doArgs()#*****************************************************************************************# Trap Stop Signal from SYSTEMD and turn off LEDdef signal_handler(sig, frame):    global stop_called    print(pdt()+'Ctl-C or stop signal received')    global led    led.off()    sys.exit(stop_called)#*****************************************************************************************    # Mainlinedef main():    global stop_called    stop_called = 255    print(pdt(),__program__,__version__)        # Parse Arguements    if not doArgs():        return False        if debug: print(pdt()+"DEBUG - No action will be taken")        if shutdown: print(pdt()+"Will shutdown instead of rebooting")    # Trap terminate from SYSTEMD and local CTL-C    signal.signal(signal.SIGINT, signal_handler)    signal.signal(signal.SIGTERM, signal_handler)        global led    led = LED(19) # GPIO 19    led.blink() # Indicates running and waiting for button push    button = Button(6) # GPIO6 # Loop checking every few seconds to see if the button has been# pressed and held. When the button is first pressed, the led# changes from blinking to on. This is visual feedback to the# operator. If the button is held down, the led is turned off to# indicate the PI is rebooting/shutting down.# If the led is left on, a problem has occurred.    loop_sleep_time = 2 # Time to wait between checking for button pressed    next_check_net_cnt = 0 # Current loop count between network check    net_check_after = (60*60/loop_sleep_time) # Check network every 60 mins V3.2    next_check_net_cnt = net_check_after + 1 # For check on first pass    print_net_info_once = True    try:        # ***** MAIN LOOP ****        while True: # Ends only with a reboot/shutdown or exception exit                            if button.is_pressed:                print(pdt()+__program__+": Button pressed")                led.on() # Led user know the button pressed detected                sleep(5) # User has to hold the button down                if button.is_pressed:                    led.off() # Let user know reboot/shutdown in progress                    sleep(1)                    if not debug:                        if shutdown:                            print(pdt()+"Shutting down")                            call(["sudo","shutdown","-h","now"])                        else:                            print(pdt(),"Rebooting")                            call(["sudo","reboot"])                    else:                        print(pdt()+"DEBUG: Action not performed")                    led.blink() # Let user know reboot/shutdown was not initiated                                sleep(loop_sleep_time) # Don't make too short or higher CPU is used.            # There should not be exceptions# If there is, make sure we log it nicely    except SystemExit as e:        print(pdt()+__program__+" Program stop called="+str(e))        return __success__    except:        led.on() # Keep light on to say there is a problem.        exc_type, exc_value, exc_traceback = exc_info()        type=exc_type.__name__        summ = str(extract_tb(exc_traceback))        print (pdt()+__program__+": Exception '"+type+"="+str(exc_value)+"'. Traceback: "+summ)        return __failure__ # Return error#    return __success__ # We should never get here.      # MAIN  if __name__ == "__main__":    rtn=main()    sys_exit(rtn)

Statistics: Posted by DS256 — Thu Oct 23, 2025 1:00 pm



Viewing all articles
Browse latest Browse all 8082

Trending Articles