Skip to content

Commit

Permalink
fix: improve dnd sync
Browse files Browse the repository at this point in the history
This should drastically improve DND status updates to match external
changes.
closes #950
  • Loading branch information
alandtse committed Sep 30, 2020
1 parent 9bfb96e commit 5805a0b
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 11 deletions.
51 changes: 49 additions & 2 deletions custom_components/alexa_media/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import dt
from homeassistant import util
import voluptuous as vol

from .config_flow import in_progess_instances
Expand All @@ -54,6 +55,8 @@
DEFAULT_QUEUE_DELAY,
DOMAIN,
ISSUE_URL,
MIN_TIME_BETWEEN_FORCED_SCANS,
MIN_TIME_BETWEEN_SCANS,
SCAN_INTERVAL,
STARTUP,
)
Expand Down Expand Up @@ -546,6 +549,22 @@ async def update_bluetooth_state(login_obj, device_serial):
)
return None

@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
@_catch_login_errors
async def update_dnd_state(login_obj) -> None:
"""Update the dnd state on ws dnd combo event."""
dnd = await AlexaAPI.get_dnd_state(login_obj)

if "doNotDisturbDeviceStatusList" in dnd:
async_dispatcher_send(
hass,
f"{DOMAIN}_{hide_email(email)}"[0:32],
{"dnd_update": dnd["doNotDisturbDeviceStatusList"]},
)
return
_LOGGER.debug("%s: get_dnd_state failed: dnd:%s", hide_email(email), dnd)
return

async def ws_connect() -> WebsocketEchoClient:
"""Open WebSocket connection.
Expand Down Expand Up @@ -607,9 +626,11 @@ async def ws_handler(message_obj):
hide_serial(json_payload),
)
serial = None
command_time = time.time()
if command not in seen_commands:
seen_commands[command] = time.time()
_LOGGER.debug("Adding %s to seen_commands: %s", command, seen_commands)
seen_commands[command] = command_time

if (
"dopplerId" in json_payload
and "deviceSerialNumber" in json_payload["dopplerId"]
Expand Down Expand Up @@ -740,9 +761,35 @@ async def ws_handler(message_obj):
ISSUE_URL,
)
if serial in existing_serials:
history = hass.data[DATA_ALEXAMEDIA]["accounts"][email][
"websocket_activity"
]["serials"].get(serial)
if history is None or (
history and command_time - history[len(history) - 1][1] > 2
):
history = [(command, command_time)]
else:
history.append([command, command_time])
hass.data[DATA_ALEXAMEDIA]["accounts"][email]["websocket_activity"][
"serials"
][serial] = time.time()
][serial] = history
events = []
for old_command, old_command_time in history:
if (
old_command
in {"PUSH_VOLUME_CHANGE", "PUSH_EQUALIZER_STATE_CHANGE"}
and command_time - old_command_time < 1
):
events.append(
(old_command, round(command_time - old_command_time, 2))
)
if len(events) >= 4:
_LOGGER.debug(
"Detected potential DND websocket change with %s events %s",
len(events),
events,
)
await update_dnd_state(login_obj)
if (
serial
and serial not in existing_serials
Expand Down
21 changes: 12 additions & 9 deletions custom_components/alexa_media/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,20 +304,23 @@ def icon(self):
return super()._icon("mdi:do-not-disturb", "mdi:do-not-disturb-off")

def _handle_event(self, event):
"""Handle events.
This will update PUSH_EQUALIZER_STATE_CHANGE events to see if the DND switch
should be updated.
"""
"""Handle events."""
try:
if not self.enabled:
return
except AttributeError:
pass
if "player_state" in event:
queue_state = event["player_state"]
if queue_state["dopplerId"]["deviceSerialNumber"] == self._client.unique_id:
self._state = getattr(self._client, self._switch_property)
if "dnd_update" in event:
result = list(
filter(
lambda x: x["deviceSerialNumber"] == self._client.unique_id,
event["dnd_update"],
)
)
state = result[0]["enabled"] is True
if result and state != self.is_on:
_LOGGER.debug("Detected %s changed to %s", self, state)
setattr(self._client, self._switch_property, state)
self.async_write_ha_state()


Expand Down

0 comments on commit 5805a0b

Please sign in to comment.