Script: Event Listener in Add-on or Remote location and execute program

In order to let an Add-on action be triggered by a Home Assistant event, I created a script that connects to the Home Assistant webservice, subscribe to selected events, and execute a script when it happens.

The first parameter to the called script is the event name and the second parameter is the even-data provided as a JSON string.

The script is here:

usage: haevent2exec.py [-h] [--config-json CONFIG_JSON]
                       [--log-level {debug,info,warning,error}]
                       [--timeout TIMEOUT] --external-program
                       EXTERNAL_PROGRAM
                       events [events ...]

Home Assistant Event Listener

positional arguments:
  events                Events to listen to

optional arguments:
  -h, --help            show this help message and exit
  --config-json CONFIG_JSON
                        Configuration file with 'ha_server' and
                        'ha_token'
  --log-level {debug,info,warning,error}
                        Logging level (error,warning,info,debug)
  --timeout TIMEOUT     Execution timeout in seconds
  --external-program EXTERNAL_PROGRAM
                        Path to the external program

I have it call a shell script similar to the one below.

#!/bin/bash
{
TARGET_OPT=""
[[ "$1" == "event1" ]] && TARGET_OPT=--event1opt
[[ "$1" == "event2" ]] && TARGET_OPT=--event2opt
[[ "$TARGET_OPT" == "" ]] && ( echo "Unrecognized event '$1'" ; exit 1 )
date
python3 python_script.py $TARGET_OPT
echo "Done $(date)"
} >> "/config/addon.log" 2>&1

As-is it will read ha_server and ha_token from a config.json file. Inside the addon this is the resolve contents of:

{
  "ha_server": "http://supervisor/core",
  "ha_token": "$SUPERVISOR_TOKEN",
}

When used remotely, you need to use the public url/ip and a long lived token.