power_shutdown.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // ============================================================================
  2. //go:build !service
  3. // power_shutdown.go — 延时关机(工具页)
  4. //
  5. // 用户在工具页输入「多少分钟后关机」,调用 ShutdownDelay 下发系统关机倒计时。
  6. // 复用 pccontrol.go 的系统命令构造(shutdown /s /t N /f),交给 Windows 系统计时,
  7. // 即使本程序退出,倒计时仍由系统执行。返回计划执行时间供前端展示。
  8. // ============================================================================
  9. package main
  10. import (
  11. "fmt"
  12. "strings"
  13. "time"
  14. )
  15. // ShutdownDelay 在指定分钟后执行关机。
  16. // minutes 必须 > 0;返回计划执行时间(HH:MM:SS)与提示信息。
  17. func (s *SettingsService) ShutdownDelay(minutes int) (string, error) {
  18. if minutes <= 0 {
  19. return "", fmt.Errorf("关机分钟数必须大于 0")
  20. }
  21. if minutes > 24*60 {
  22. return "", fmt.Errorf("关机分钟数过大(最多 24 小时)")
  23. }
  24. delaySec := minutes * 60
  25. cmd := pcSystemCommand(pcPoweroff, delaySec)
  26. if cmd == nil {
  27. return "", fmt.Errorf("当前系统不支持 shutdown 命令")
  28. }
  29. // 标记为待执行(与 API 路由共用状态,便于「主机」页取消)
  30. pcMu.Lock()
  31. if pcPending {
  32. remaining := time.Until(pcExecuteAt).Round(time.Second)
  33. pcMu.Unlock()
  34. return "", fmt.Errorf("已有待执行的电源命令,剩余 %v", remaining)
  35. }
  36. pcPending = true
  37. pcPendingCmd = pcPoweroff
  38. pcExecuteAt = time.Now().Add(time.Duration(delaySec) * time.Second)
  39. pcSystemTimer = true
  40. pcLastCmd = pcPoweroff
  41. pcLastTime = time.Now()
  42. pcRequested = true
  43. pcMu.Unlock()
  44. if output, err := cmd.CombinedOutput(); err != nil {
  45. pcMu.Lock()
  46. pcPending = false
  47. pcPendingCmd = ""
  48. pcExecuteAt = time.Time{}
  49. pcSystemTimer = false
  50. pcMu.Unlock()
  51. return "", fmt.Errorf("关机命令下发失败: %v | %s", err, strings.TrimSpace(string(output)))
  52. }
  53. execAt := pcExecuteAt.Format("15:04:05")
  54. fmt.Fprintf(apiLogRing, "[SYS] 工具页延时关机 | %d 分钟后(%s)\n", minutes, execAt)
  55. return execAt, nil
  56. }
  57. // CancelShutdown 取消延时关机(工具页「取消」按钮调用)。
  58. func (s *SettingsService) CancelShutdown() error {
  59. pcMu.Lock()
  60. if !pcPending || pcPendingCmd != pcPoweroff {
  61. pcMu.Unlock()
  62. return fmt.Errorf("当前没有待执行的关机命令")
  63. }
  64. pcPending = false
  65. pcPendingCmd = ""
  66. pcExecuteAt = time.Time{}
  67. pcSystemTimer = false
  68. pcMu.Unlock()
  69. pcAbortShutdown()
  70. fmt.Fprintln(apiLogRing, "[SYS] 工具页取消延时关机")
  71. return nil
  72. }