Compare commits
2 Commits
db63cab455
...
8c222d05b3
Author | SHA1 | Date | |
---|---|---|---|
8c222d05b3 | |||
4bc0e85bad |
58
__init__.py
58
__init__.py
@ -18,11 +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", "switch"], ["scene", "group"], ["automation"]]
|
||||
config["sort_order"] = {"light": 1, "switch": 1, "scene": 2, "group": 2, "automation": 3}
|
||||
|
||||
icon_files = {
|
||||
@ -59,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"])
|
||||
|
||||
@ -91,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__,
|
||||
@ -113,30 +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"])])
|
||||
|
||||
action_word = query.string.split()[0].lower().strip()
|
||||
#is_action_word = action_word in action_words
|
||||
entity_query_list = query.string.split()#[1:] if is_action_word else 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"])])
|
||||
entity_query_list = query.string.split()
|
||||
|
||||
|
||||
# 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__,
|
||||
@ -144,8 +135,15 @@ def showEntities(query):
|
||||
text="Error while getting entity states from Home Assistant",
|
||||
subtext=str(error))
|
||||
|
||||
# Sort entries
|
||||
entities = sorted(response.json(), key=lambda e: config["sort_order"].get_matching(e["entity_id"].split(".")[0]))
|
||||
# Sort entries by class
|
||||
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"]))
|
||||
|
||||
# Parse all entities and states
|
||||
for entity in entities:
|
||||
@ -187,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 = "<font color=\"{}\">{}</font>".format(
|
||||
@ -196,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"],
|
||||
@ -203,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")))
|
||||
|
||||
@ -235,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))
|
||||
|
Loading…
x
Reference in New Issue
Block a user