Skip to content

Commit

Permalink
Merge pull request #185 from mdeweerd/dev
Browse files Browse the repository at this point in the history
Fix #183 #184 *neighbours_and_routes djustments for refactored zigpy implementation.
  • Loading branch information
mdeweerd authored Jul 23, 2023
2 parents d2c4b2d + ba0c79d commit cc6ebeb
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 22 deletions.
5 changes: 3 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ repos:
- --show-error-codes
- --show-error-context
additional_dependencies:
- zigpy==0.43.0
- zigpy>=0.43.0
- cryptography==3.3.2 # Compatible/Available on cygwin
#- homeassistant-stubs>=2023.1.7
- pydantic
#- pydantic
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -792,8 +792,8 @@ data:
ieee: entity.my_thermostat_entity
cluster: 0x201
attribute: occupied_heating_setpoint
attr_val: "{% set t = states('sensor.tgt_temperature') %}{{ [(t|int+50) % 2300,2000]|max\
\ if is_number(t) else 2150 }}"
attr_val: "{% set t = states('sensor.tgt_temperature') %}{{ [(t|int+50) % 2300,2000]|max
if is_number(t) else 2150 }}"
state_id: sensor.tgt_temperature
allow_create: true
read_before_write: false
Expand Down
45 changes: 36 additions & 9 deletions custom_components/zha_toolkit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,11 @@
extra=vol.ALLOW_EXTRA,
),
S.GET_ROUTES_AND_NEIGHBOURS: vol.Schema(
{},
{
vol.Required(ATTR_IEEE): vol.Any(
cv.entity_id_or_uuid, t.EUI64.convert
),
},
extra=vol.ALLOW_EXTRA,
),
S.GET_ZLL_GROUPS: vol.Schema(
Expand Down Expand Up @@ -637,6 +641,11 @@ def register_services(hass): # noqa: C901
global LOADED_VERSION # pylint: disable=global-statement
hass_ref = hass

is_response_data_supported = u.is_ha_ge("2023.7.0")

if is_response_data_supported:
from home_assistant.core import ServiceCall

async def toolkit_service(service):
"""Run command from toolkit module."""
LOGGER.info("Running ZHA Toolkit service: %s", service)
Expand Down Expand Up @@ -737,8 +746,9 @@ async def toolkit_service(service):
LOGGER.debug("Handler: %s", handler)

handler_exception = None
handler_result = None
try:
await handler(
handler_result = await handler(
zha_gw.application_controller,
zha_gw,
ieee,
Expand Down Expand Up @@ -779,6 +789,13 @@ async def toolkit_service(service):
if not event_data["success"] and params[p.FAIL_EXCEPTION]:
raise Exception("Success expected, but failed")

if is_response_data_supported:
if service.return_response:
if handler_result is None:
return event_data

return handler_result

# Set up all service schemas
for key, value in SERVICE_SCHEMAS.items():
value.extend(COMMON_SCHEMA)
Expand All @@ -787,12 +804,22 @@ async def toolkit_service(service):
# by denying this option
value.extend(DENY_COMMAND_SCHEMA)
LOGGER.debug(f"Add service {DOMAIN}.{key}")
hass.services.async_register(
DOMAIN,
key,
toolkit_service,
schema=value,
)
if is_response_data_supported:
# See https://developers.home-assistant.io/docs/dev_101_services/#response-data
hass.services.async_register(
DOMAIN,
key,
toolkit_service,
schema=value,
supports_response=ServiceCall.OPTIONAL, # type:ignore[undefined-variable]
)
else:
hass.services.async_register(
DOMAIN,
key,
toolkit_service,
schema=value,
)

LOADED_VERSION = u.getVersion()

Expand Down Expand Up @@ -823,7 +850,7 @@ async def command_handler_default(
if cmd in CMD_TO_INTERNAL_MAP:
cmd = CMD_TO_INTERNAL_MAP.get(cmd)

await default.default(
return await default.default(
app, listener, ieee, cmd, data, service, params, event_data
)

Expand Down
24 changes: 17 additions & 7 deletions custom_components/zha_toolkit/neighbours.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@
from random import uniform

import zigpy.zdo.types as zdo_t
from homeassistant.util.json import save_json
from zigpy.exceptions import DeliveryError

from . import utils as u

LOGGER = logging.getLogger(__name__)


async def routes_and_neighbours(
async def get_routes_and_neighbours(
app, listener, ieee, cmd, data, service, params, event_data
):
if ieee is None:
Expand All @@ -31,7 +32,7 @@ async def routes_and_neighbours(
"scans",
f"routes_and_neighbours_{ieee_tail}.json",
)
save_json(fname, event_data["result"])
u.helper_save_json(fname, event_data["result"])

LOGGER.debug("Wrote scan results to '%s'", fname)

Expand Down Expand Up @@ -78,7 +79,7 @@ async def all_routes_and_neighbours(
"scans",
"all_routes_and_neighbours.json",
)
save_json(all_routes_name, all_routes)
u.helper_save_json(all_routes_name, all_routes)


async def async_get_neighbours(device):
Expand Down Expand Up @@ -122,13 +123,22 @@ def _process_neighbour(nbg):
LOGGER.debug("%s: Could not deliver 'Mgmt_Lqi_req'", device.ieee)
break

# LOGGER.debug(f"NEIGHBORS: {val!r}")
neighbours = val.neighbor_table_list
LOGGER.debug(f"NEIGHBORS: {val!r}")

if hasattr(val, "neighbor_table_list"):
neighbours = val.neighbor_table_list
entries = val.entries
else:
neighbours = val.NeighborTableList
entries = val.Entries

for neighbour in neighbours:
result.append(_process_neighbour(neighbour))
idx += 1
if idx >= val.entries:

if idx >= entries:
break

await asyncio.sleep(uniform(1.0, 1.5))

return sorted(result, key=lambda x: x["ieee"])
Expand Down
14 changes: 12 additions & 2 deletions custom_components/zha_toolkit/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ async def get_ieee(app, listener, ref):
entity_registry = (
# Deprecated >= 2022.6.0
await listener._hass.helpers.entity_registry.async_get_registry()
if parse_version(HA_VERSION) < parse_version("2022.6")
if not is_ha_ge("2022.6")
else listener._hass.helpers.entity_registry.async_get(
listener._hass
)
Expand All @@ -292,7 +292,7 @@ async def get_ieee(app, listener, ref):
device_registry = (
# Deprecated >= 2022.6.0
await listener._hass.helpers.device_registry.async_get_registry()
if parse_version(HA_VERSION) < parse_version("2022.6")
if not is_ha_ge("2022.6")
else listener._hass.helpers.device_registry.async_get(
listener._hass
)
Expand Down Expand Up @@ -460,6 +460,11 @@ def write_json_to_file(
LOGGER.debug(f"Finished writing {desc} in '{file_name}'")


def helper_save_json(file_name: str, data: typing.Any):
"""Helper because the actual method depends on the HA version"""
save_json(file_name, data)


def append_to_csvfile(
fields,
subdir,
Expand Down Expand Up @@ -959,3 +964,8 @@ def is_zigpy_ge(version: str) -> bool:
"""Test if zigpy library is newer than version"""
# Example version value: "0.45.0"
return parse_version(getZigpyVersion()) >= parse_version(version)


def is_ha_ge(version: str) -> bool:
"""Test if zigpy library is newer than version"""
return parse_version(getHaVersion()) >= parse_version(version)
4 changes: 4 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ exclude = .venv,.git,.tox
max-line-length = 79
# B028 is manually surrounded by quotes, consider using the `!r`
# W503 line break before binary operator
# E501 line too long
ignore =
B028,
W503

per-file-ignores =
custom_components/zha_toolkit/__init__.py:E501

# per-file-ignores =
# example/*:F811,F401,F403

Expand Down

0 comments on commit cc6ebeb

Please sign in to comment.