Run any command whenever power is plugged in or unplugged.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

107 linhas
1.9 KiB

  1. #!/bin/bash
  2. # on-ac-power-state-change
  3. # Copyright 2019 Mike Peralta
  4. # Released under the MIT license (https://opensource.org/licenses/MIT)
  5. # Check out my music https://www.MikePeralta.com
  6. # This script will execute a command each time the power state is changed (ie: laptop power unplugged or plugged back in)
  7. # Pass your desired command to execute as arguments to this script
  8. # Example:
  9. # $ on-ac-power-state-change echo "My power state has changed!"
  10. # Written and tested with acpi version 1.7
  11. # Enjoy!
  12. # (Note: Use with caution; It will execute any parameters received verbatim)
  13. #
  14. COMMANDS_FOR_STATE_CHANGE="$@"
  15. CHECKED_AT_LEAST_ONCE="0"
  16. LAST_KNOWN_PLUGGED_IN_STATE=""
  17. CURRENT_PLUGGED_IN_STATE=""
  18. #
  19. do_log()
  20. {
  21. logger "[on-ac-power-state-change] $1"
  22. echo "[on-ac-power-state-change] $1"
  23. }
  24. do_complaint()
  25. {
  26. logger -s "[on-ac-power-state-change] $1"
  27. }
  28. do_die()
  29. {
  30. do_complaint "Fatal: $1"
  31. exit 1
  32. }
  33. #
  34. demand_acpi()
  35. {
  36. which acpi > /dev/null
  37. if [ $? -ne 0 ];then
  38. do_die "acpi doesn't seem to be installed"
  39. fi
  40. }
  41. #
  42. is_ac_connected()
  43. {
  44. # Grab output of acpi
  45. demand_acpi
  46. ACPI=$(acpi -a)
  47. #
  48. echo "$ACPI" | grep "on-line" > /dev/null
  49. if [ $? -eq 0 ];then
  50. #echo "Power seems to be plugged in"
  51. echo "1"
  52. fi
  53. echo "$ACPI" | grep "off-line" > /dev/null
  54. if [ $? -eq 0 ];then
  55. #echo "Power seems to be unplugged"
  56. echo "0"
  57. fi
  58. }
  59. #
  60. handle_acpi_state_change()
  61. {
  62. #
  63. CURRENT_PLUGGED_IN_STATE=$(is_ac_connected)
  64. #
  65. if [ "$CHECKED_AT_LEAST_ONCE" = "1" ];then
  66. if [ "$CURRENT_PLUGGED_IN_STATE" != "$LAST_KNOWN_PLUGGED_IN_STATE" ];then
  67. do_log "Power state has changed!"
  68. do_log "Executing commands: $COMMANDS_FOR_STATE_CHANGE"
  69. eval "$COMMANDS_FOR_STATE_CHANGE"
  70. fi
  71. else
  72. CHECKED_AT_LEAST_ONCE="1"
  73. fi
  74. #
  75. LAST_KNOWN_PLUGGED_IN_STATE="$CURRENT_PLUGGED_IN_STATE"
  76. }
  77. #
  78. main_loop()
  79. {
  80. #
  81. do_log "Begin main loop"
  82. while [ true ];do
  83. handle_acpi_state_change
  84. sleep 1
  85. done
  86. do_log "Done with main loop"
  87. }
  88. do_log "Begin"
  89. main_loop
  90. do_log "Exiting"