Skip to content

Instantly share code, notes, and snippets.

@willwhui
Last active January 20, 2018 08:59
Show Gist options
  • Save willwhui/26990b37b2fdbd43d2e68f6f550691d1 to your computer and use it in GitHub Desktop.
Save willwhui/26990b37b2fdbd43d2e68f6f550691d1 to your computer and use it in GitHub Desktop.
利用hass的shell_command重启hass服务
@willwhui
Copy link
Author

willwhui commented Jan 20, 2018

完整方案:

先配置好检测部分:

运行

crontab -e 

在文件中追加:

# check a flag for hass restarting every 1min (for x times, see .sh file. And must run in background)
*/1 * * * * . /home/pi/check-hass-restart-flag.sh &

即:每分钟执行一次。注意必须以后台运行的方式执行,否则会导致阻塞

check-hass-restart-flag.sh 内容如下:

. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh
sleep 5
. /home/pi/check-hass-restart-flag-2.sh

即:每5秒运行一次实质的检查代码

check-hass-restart-flag-2.sh的内容:

isfound=$(ls /home/homeassistant/.homeassistant/flags | grep "restart.flag" | grep -v "grep"); if [ -z "$isfound" ]; then echo "not found"; else . /home/pi/check-hass-restart-flag-3.sh; fi

即:检测到存在一个flag文件(restart.flag),就调用重启的脚本

check-hass-restart-flag-3.sh内容如下:

sudo rm /home/homeassistant/.homeassistant/flags/restart.flag
. /home/pi/hassrestart.sh

hassrestart.sh内容如下:

sudo systemctl restart home-assistant@homeassistant

然后配置hass:
增加shell_command:

set_restart_hass_flag: echo "restart" > ~/.homeassistant/flags/restart.flag

这样的到了一个shell_command.set_restart_hass_flag服务

在automation中增加:

- alias: "Restart hass: trigger set flag up by button"
  #hide_entity: true
  trigger:
    platform: event
    event_type: click
    event_data:
      entity_id: !secret wireless_button_2_id
      click_type: double
  action:
    - service: shell_command.set_restart_hass_flag

这样双击button,就可以在5秒钟内重启hass了

@willwhui
Copy link
Author

willwhui commented Jan 20, 2018

收尾

增加一个启动时删除flag文件的自动化规则,以防万一陷入无限重启:

- alias: "Restart hass: remove flag after restarting"
  #hide_entity: true
  trigger:
      - platform: homeassistant
      event: start
  action:
    - service: shell_command.remove_restart_hass_flag

对应的shell command很简单:

remove_restart_hass_flag: rm -f ~/.homeassistant/flags/restart.flag

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment