From 8c222d05b33f17bd9b55fc77c8404b8e4593ef29 Mon Sep 17 00:00:00 2001 From: hoellen Date: Fri, 8 Jan 2021 12:29:40 +0100 Subject: [PATCH] Move code to initialization and clean up --- __init__.py | 48 ++++++++++++++++++++++-------------------------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/__init__.py b/__init__.py index 31d5968..22d333e 100644 --- a/__init__.py +++ b/__init__.py @@ -18,10 +18,10 @@ __py_deps__ =["requests"] # global variables +config = {} configurationFileName = "homeassistant_config.json" configuration_directory = os.path.join(configLocation()) configuration_file = os.path.join(configuration_directory, configurationFileName) -config = {} config["sort_order"] = {"light": 1, "switch": 1, "scene": 2, "group": 2, "automation": 3} icon_files = { @@ -58,6 +58,15 @@ def initialize(): except OSError: critical("There was an error making the directory: %s" % configuration_directory) + # Set up HASS state query + config["hass_url"] = config["hass_url"].strip("/") + config["state_query"] = config["hass_url"] + "/api/states" + config["headers"]= { + "Authorization": "Bearer " + config["hass_key"], + "content-type": "application/json", + } + + # Set up sort_order config["sort_order"]["."] = 999 # Wildcard for sorting config["sort_order"] = RegexDict(config["sort_order"]) @@ -90,8 +99,6 @@ def handleQuery(query): text="Invalid Home Assistant URL", subtext=config["hass_url"]) - # Trim hass URL - config["hass_url"] = config["hass_url"].strip("/") if "hass_key" not in config or not config["hass_key"]: return Item(id=__title__, @@ -112,28 +119,15 @@ def showEntities(query): return Item(id=__title__, icon=os.path.dirname(__file__) + "/" + icon_files["logo"], text=__title__, - subtext="Enter a query to control your Home Assistant", + subtext="Enter the name of the entity which you want to control", actions=[UrlAction("Open in Browser", config["hass_url"])]) entity_query_list = query.string.split() - if not entity_query_list: - return Item(id=__title__, - icon=os.path.dirname(__file__) + "/" + icon_files["logo"], - text="Enter the name of the entity which you want to control", - subtext="Open Home Assistant in Browser", - actions=[UrlAction("Open in Browser", config["hass_url"])]) - - - # Set up HASS state query - state_query = config["hass_url"] + "/api/states" - headers = { - "Authorization": "Bearer " + config["hass_key"], - "content-type": "application/json", - } + # query entities from HASS try: - response = requests.get(state_query, headers=headers) + response = requests.get(config["state_query"], headers=config["headers"]) response.raise_for_status() except requests.exceptions.RequestException as error: return Item(id=__title__, @@ -142,12 +136,14 @@ def showEntities(query): subtext=str(error)) # Sort entries by class - entities = sorted(response.json(), key=lambda e: config["sort_order"].get_matching(e["entity_id"].split(".")[0])) + entities = sorted(response.json(), key=lambda e: + config["sort_order"].get_matching(e["entity_id"].split(".")[0])) # Sort entries by query matching entities = sorted(entities, key=lambda e: RegexDict({query.string.lower() + ".": 0, ".": 1}) - .get_matching(e["attributes"]["friendly_name"].lower() if "friendly_name" in e["attributes"] else e["entity_id"])) + .get_matching(e["attributes"]["friendly_name"].lower() + if "friendly_name" in e["attributes"] else e["entity_id"])) # Parse all entities and states for entity in entities: @@ -189,8 +185,6 @@ def showEntities(query): data = { "endpoint": "{}/api/services/".format(config["hass_url"]), "service_data": {"entity_id": entity["entity_id"]}, - "hass_key": config["hass_key"], - "headers": headers, } state = entity["state"] state_colored = "{}".format( @@ -198,6 +192,8 @@ def showEntities(query): "Red" if entity["state"] == "off" else "", entity["state"].capitalize() ) + + # build item for list item = Item(id=__title__, icon=entity_icon, text=entity["attributes"]["friendly_name"], @@ -205,6 +201,7 @@ def showEntities(query): subtext="%s  |  %s" % (state_colored, entity_class.capitalize()) ) + # add actions depending on class if entity_class in toggle_types: item.addAction(FuncAction("Toggle", lambda d=data: sendCommand(d, "homeassistant/toggle"))) @@ -237,19 +234,18 @@ def sendCommand(data, service): data["endpoint"] += service debug(__title__ + ": Sending command \"" + service + "\" to " + data["service_data"]["entity_id"]) - # Make POST request to HA service try: response = requests.post( data["endpoint"], data=json.dumps(data["service_data"]), - headers=data["headers"], + headers=config["headers"], ) response.raise_for_status() except requests.exceptions.RequestException as error: warning("Error while sending command to Home Assistant:\n%s" % (str(error))) -# New class to match dict keys with regex +# New dictionary class to match keys with regex class RegexDict(dict): def get_matching(self, event): return next(self[key] for key in self if re.match(key, event))