1
1
#! /usr/bin/env python3
2
2
import logging
3
3
import shutil
4
+ import subprocess
4
5
from enum import Enum
5
6
from pathlib import Path
6
- from typing import Any , Callable
7
+ from typing import Any
7
8
8
9
import appdirs
9
10
import uvicorn
@@ -34,6 +35,25 @@ class ShutdownType(str, Enum):
34
35
POWEROFF = "poweroff"
35
36
36
37
38
+ def run_command (command : str ) -> "subprocess.CompletedProcess['bytes']" :
39
+ user = "pi"
40
+ password = "raspberry"
41
+
42
+ return subprocess .run (
43
+ [
44
+ "sshpass" ,
45
+ "-p" ,
46
+ password ,
47
+ "ssh" ,
48
+ "-o" ,
49
+ "StrictHostKeyChecking=no" ,
50
+ f"{ user } @localhost" ,
51
+ command ,
52
+ ],
53
+ check = True ,
54
+ )
55
+
56
+
37
57
# TODO: Update commander to work with openapi modules and improve modularity and code organization
38
58
@app .post ("/shutdown" , status_code = status .HTTP_200_OK )
39
59
@version (1 , 0 )
@@ -44,27 +64,13 @@ async def shutdown(response: Response, shutdown_type: ShutdownType, i_know_what_
44
64
detail = "Developer, you don't know what you are doing, command aborted." ,
45
65
)
46
66
try :
47
- # For more information about sysrq: https://www.kernel.org/doc/html/latest/admin-guide/sysrq.html
48
- ## We enable all functions of sysrq to allow a safe reboot/shutdown
49
- # pylint: disable=consider-using-with
50
- open ("/proc/sys/kernel/sysrq" , "wb" ).write (b"1" )
51
-
52
- # We are doing it!
53
- # pylint: disable=consider-using-with
54
- run_sysrq_command : Callable [[str ], int ] = lambda command : open ("/proc/sysrq-trigger" , "wb" ).write (
55
- command .encode ()
56
- )
57
- pre_commands = [
58
- "s" , # Will attempt to sync all mounted filesystems.
59
- "u" , # Will attempt to remount all mounted filesystems read-only. (To make sure that sync was done!)
60
- ]
61
- for command in pre_commands :
62
- run_sysrq_command (command )
63
-
67
+ hold_time_seconds = 5
64
68
if shutdown_type == ShutdownType .REBOOT :
65
- run_sysrq_command ("b" )
69
+ output = run_command (f"(sleep { hold_time_seconds } ; sudo shutdown --reboot -h now)&" )
70
+ logger .debug (f"reboot: { output } " )
66
71
elif shutdown_type == ShutdownType .POWEROFF :
67
- run_sysrq_command ("o" )
72
+ output = run_command (f"(sleep { hold_time_seconds } ; sudo shutdown --poweroff -h now)&" )
73
+ logger .debug (f"shutdown: { output } " )
68
74
69
75
return HTMLResponse (status_code = 200 )
70
76
except Exception as error :
0 commit comments