Loop over list in a script

Alright, answering to myself ^^

I’ve come to modify my python script to handle multiple id in a same command line.

Here’s the script:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from time import sleep
import websocket
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-i", "--id", help="Intergation's ID (see .storage/core.config_entries)", nargs='+', required=True)
parser.add_argument("-s", "--state", help="enable/diable integration", choices=['enable', 'disable'], required=True)
parser.add_argument("-b", "--bearer", help="bearer token", required=True)
args = parser.parse_args()

ha = "127.0.0.1:8123"
ids = args.id
state = args.state
bearer = args.bearer

ws = websocket.WebSocket()
ws.connect("ws://"+ha+"/api/websocket")

json_auth = "{\"type\":\"auth\",\"access_token\":\""+bearer+"\"}"
ws.send(json_auth)
wsid = 0

for id in ids:
  wsid += 1
  if state == 'enable':
      json_state = "{\"type\":\"config_entries/disable\",\"entry_id\":\""+id+"\",\"disabled_by\":null,\"id\":"+str(wsid)+"}"
  elif state == 'disable':
      json_state = "{\"type\":\"config_entries/disable\",\"entry_id\":\""+id+"\",\"disabled_by\":\"user\",\"id\":"+str(wsid)+"}"
  ws.send(json_state)

and the corresponding shell_command:

integration: python /config/shell/integration.py -i {{ id }} -s {{ state }} -b <TOKEN>

I can then use this in a script to activate/deactivate yi-hack integrations when I start/stop alarmo:

cameras_start:
  alias: cameras_start
  sequence:
  - service: switch.turn_on
    data:
      entity_id: group.plugs_cameras
  - service: shell_command.integration
    data:
      id: '{%- set mylist = ''20a45378cfe4c36c89ad16e056da59b1 e5633f2cf5aea5403e54b6d87a96e843
        8cb9b789e7d1a4332f7e0c7381965d13 f007dc7017cb69eeab71a93bc740d79c'' -%} {{mylist.split("
        ")}}

        '
      state: enable
  - service: homeassistant.restart
    data: {}
  mode: single

And finally use this script in an automation when the state of alarmo is on arming.

It’s not very HA-style but it works :slight_smile: If anybody has a better solution, like looping over each id in a set or by using a input_select, be my guest!

Side note: I haven’t been able to store the token in the secrets.yml file, I only get errors stating that token does not exist, while it works very well for integrations. Is there any limitations with this file? Doesn’t it work for anything other than integrations?

Thanks!

1 Like