Skip to content

Instantly share code, notes, and snippets.

@imduffy15
Created February 11, 2023 13:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imduffy15/0cca90b1b73b3e56ac00c6c1ce221bb4 to your computer and use it in GitHub Desktop.
Save imduffy15/0cca90b1b73b3e56ac00c6c1ce221bb4 to your computer and use it in GitHub Desktop.
My home assistant organiser

cleaner.py

This hides things and renames things.

area-assigner.py

This assigns things to areas based on their name

alexa-sync.py

  • This deletes all groups on alexa.
  • Creates groups on alexa from home assistant areas.
  • Adds echo devices to the newly created groups

alexa-entities.py

  • Outputs all dashboard visible entities in a list that you can copy/paste into your alexa.yaml
#!/usr/bin/env python
import json
entity_registry_file = open("core.entity_registry", "r+")
entity_registry = json.load(entity_registry_file)
for entity in entity_registry["data"]["entities"]:
if entity["hidden_by"] != "user" and entity["area_id"] is not None:
print(" - " + entity["entity_id"])
#!/usr/bin/env python
import json
import requests
import urllib3
urllib3.disable_warnings()
cookie = open("cookie.txt").readline().strip()
csrf_token = [x.split("=") for x in cookie.split(";") if "csrf" in x][0][1]
headers = {"csrf": csrf_token, "Cookie": cookie}
# Get all existing groups...
groups = requests.get(
"https://alexa.amazon.co.uk/api/phoenix/group", headers=headers, verify=False
)
groups = groups.json()
# Delete all existing groups
for group in groups["applianceGroups"]:
print(f"Deleting group {group.get('name')}")
delete = requests.delete(
f"https://alexa.amazon.co.uk/api/phoenix/group/{group.get('groupId')}",
headers=headers,
verify=False,
)
delete.raise_for_status()
# Get home assistant entities and their areas
entity_registry_file = open("core.entity_registry")
entity_registry = json.load(entity_registry_file)
entity_registry = {
x["entity_id"]: {"area_id": x.get("area_id")}
for x in entity_registry["data"]["entities"]
if x.get("area_id")
}
# Get the areas so we have their pretty name format
area_registry_file = open("core.area_registry")
area_registry = json.load(area_registry_file)
areas = {
x.get("id"): x.get("name") for x in area_registry.get("data", []).get("areas", [])
}
# Get all devices on alexa
# This fails for some reason sometimes so there's terrible retry logic here.
raw_devices_json = None
while raw_devices_json is None:
try:
raw_devices = requests.get(
"https://alexa.amazon.co.uk/api/phoenix", headers=headers, verify=False
).json()
raw_devices_json = json.loads(raw_devices["networkDetail"])
except Exception:
time.sleep(1)
group_updates = {}
# Map the alexa devices to their home assistant device and pull the area
# id from home assistant
for skill, details in raw_devices_json["locationDetails"]["locationDetails"][
"Default_Location"
]["amazonBridgeDetails"]["amazonBridgeDetails"].items():
details = details["applianceDetails"]["applianceDetails"]
for device, value in details.items():
if value.get("manufacturerName", "") == "Royal Philips Electronics":
delete = requests.delete(
f"https://alexa.amazon.co.uk/api/phoenix/appliance/{value.get('applianceId', '')}",
headers=headers,
verify=False,
)
delete.raise_for_status()
elif value.get("friendlyDescription", "") == "Amazon smart device":
name = value.get("friendlyName", "").lower().replace(" ", "_")
longestMatch = 0
area_id = None
for area in areas:
if area in name:
if len(area) > longestMatch:
longestMatch = len(area)
area_id = area
group_name = areas.get(area_id)
updates = group_updates.get(group_name, [])
updates.append(value.get("applianceId"))
group_updates[group_name] = updates
elif value.get("manufacturerName", "") == "Home Assistant":
home_assistant_entity_id = (
value.get("friendlyDescription").split(" ")[0].strip()
)
group_name = areas.get(
entity_registry.get(home_assistant_entity_id, {}).get("area_id", ""), {}
)
if group_name:
updates = group_updates.get(group_name, [])
updates.append(value.get("applianceId"))
group_updates[group_name] = updates
# Create all the groups with their devices
for group_name, devices in group_updates.items():
body = {
"applianceIds": devices,
"name": group_name,
}
try:
pretty = {"group": group_name, "devices": [device.split("#")[1] if '#' in device else device for device in devices]}
print(json.dumps(pretty, indent=2))
update_group = requests.post(
f"https://alexa.amazon.co.uk/api/phoenix/group",
headers=headers,
verify=False,
json=body,
)
update_group.raise_for_status()
except:
print("Failed to process this payload:")
print(json.dumps(body, indent=2))
#!/usr/bin/env python
import json
device_registry_file = open("core.device_registry", "r+")
entity_registry_file = open("core.entity_registry", "r+")
entity_registry_file = open("core.entity_registry", "r+")
device_registry = json.load(device_registry_file)
entity_registry = json.load(entity_registry_file)
area_registry_file = open("core.area_registry")
area_registry = json.load(area_registry_file)
areas = [x.get("id") for x in area_registry.get("data", []).get("areas", [])]
outside_tags = ["garden", "front_door", "shed", "camera"]
back_room_tags = ["breakfast", "kitchen", "dining", "sitting_room", "valetudo_s7"]
utility_tags = ["utility"]
front_bedroom_tags = ["s5"]
tags = [
{"tags": outside_tags, "area_id": "outside"},
{"tags": back_room_tags, "area_id": "back_room"},
{"tags": utility_tags, "area_id": "utility_room"},
{"tags": front_bedroom_tags, "area_id": "front_bedroom"}
]
for device in device_registry["data"]["devices"]:
device["area_id"] = None
try:
name = device.get("name", "").lower().replace(" ", "_")
longestMatch = 0
area_id = None
for area in areas:
if name.startsWith(area):
area_id = area
break
if area in name:
if len(area) > longestMatch:
longestMatch = len(area)
area_id = area
for area in tags:
for tag in area.get("tags", []):
if tag in name:
print(f"adding {tag} to {area.get('area_id')}")
device["area_id"] = area.get("area_id", None)
if device["area_id"] is None and area_id:
print(f"updating {name} to {area_id}")
device["area_id"] = area_id
except:
pass
for entity in entity_registry["data"]["entities"]:
entity["area_id"] = None
name = entity.get("entity_id", "").lower().replace(" ", "_")
if "android" in name:
name = entity.get("name", "").lower().replace(" ", "_")
longestMatch = 0
area_id = None
for area in areas:
if area in name:
if len(area) > longestMatch:
longestMatch = len(area)
area_id = area
for area in tags:
for tag in area.get("tags", []):
if tag in name:
print(f"adding {entity['entity_id']} to {area.get('area_id')}")
entity["area_id"] = area['area_id']
if entity["area_id"] is None and area_id:
print(f"updating {name} to {area_id}")
entity["area_id"] = area_id
device_registry_file.seek(0)
device_registry_file.write(json.dumps(device_registry, indent=4))
device_registry_file.truncate()
entity_registry_file.seek(0)
entity_registry_file.write(json.dumps(entity_registry, indent=4))
entity_registry_file.truncate()
#!/usr/bin/env python
import json
import re
entity_registry_file = open("core.entity_registry", "r+")
entity_registry = json.load(entity_registry_file)
device_registry_file = open("core.device_registry", "r+")
device_registry = json.load(device_registry_file)
config_registry_file = open("core.config_entries", "r+")
config_registry = json.load(config_registry_file)
hidden_entity_ids = []
hidden_device_ids = []
camera_entries = {}
for config_registry in config_registry["data"]["entries"]:
hidden_entity_ids = hidden_entity_ids + config_registry.get("options", {}).get("entities", [])
if "192.168.20.180" in config_registry.get("options", {}).get("still_image_url", ""):
camera_entries[config_registry["entry_id"]] = config_registry
for device in device_registry["data"]["devices"]:
if "LB02-5W-GU10-TAS" == device.get("model",""):
hidden_device_ids.append(device["id"])
for device in device_registry["data"]["devices"]:
if "LB02-5W-GU10-TAS" == device.get("model",""):
hidden_device_ids.append(device["id"])
for entity in entity_registry["data"]["entities"]:
name = entity.get("entity_id", "").lower().replace(" ", "_")
entity["hidden_by"] = None
if "live_feed" in name:
hidden_device_ids.append(entity["device_id"])
for entity in entity_registry["data"]["entities"]:
if entity["entity_id"] in ["dining_light"]:
entity["hidden_by"] = None
continue
if entity["config_entry_id"] in camera_entries:
entry_id = camera_entries.get(entity["config_entry_id"], {}).get("title").lower()
entity['entity_id'] = f"camera.{entry_id}"
if entity['entity_id'] in hidden_entity_ids:
entity["hidden_by"] = "user"
if entity["device_id"] in hidden_device_ids and not entity["entity_id"].startswith("light."):
print(f"hiding {entity['entity_id']} as it matches a hidden device id")
entity["hidden_by"] = "user"
if "media_player" in entity.get("entity_id") and "android" not in entity.get("entity_id"):
print(f"hiding {entity.get('entity_id')}")
entity["hidden_by"] = "user"
if "Room" in entity.get("model", ""):
entity["hidden_by"] = "user"
if "frigate" in entity["platform"]:
entity["hidden_by"] = "user"
if not entity["entity_id"].endswith("_frigate"):
entity["entity_id"] = entity["entity_id"] + "_frigate"
if entity.get("original_name") and "Wiser " in entity.get("original_name", ""):
entity["name"] = entity.get("original_name", "").replace("Wiser ", "")
entity["has_entity_name"] = True
if entity.get("original_name") and "Wiser " in entity.get("original_name", "") and "climate" in entity["entity_id"]:
entity["name"] = entity["name"] + " thermostat"
if "wiser" in entity["entity_id"] and "climate" not in entity["entity_id"] and "button.wiser_toggle_hot_water" not in entity["entity_id"]:
entity["hidden_by"] = "user"
if "wled" == entity["platform"] and not entity["entity_id"].startswith("light"):
entity["hidden_by"] = "user"
if "doorbell" in entity["entity_id"] and "camera" not in entity["entity_id"]:
entity["hidden_by"] = "user"
if len(re.findall(r'_[0-9]$', entity["entity_id"])) > 0:
entity["hidden_by"] = "user"
for keyword in ["camera.s5_map", "valetudo_s5_map_data", "select.", "camera.rockrobo_map", "valetudo_s7_map_data", "breakfast_bar", "sensor", "script", "automation", "button", "update", "person", "shellyem", "window_detection", "itrv", "smoke_alarm"]:
if keyword in entity["entity_id"]:
entity["hidden_by"] = "user"
entity_registry_file.seek(0)
entity_registry_file.write(json.dumps(entity_registry, indent=4))
entity_registry_file.truncate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment