-
Notifications
You must be signed in to change notification settings - Fork 35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow listening for Hue events #48
Changes from 2 commits
f87f43c
173b59b
873dbee
f8b0e61
4b6fbaa
1855540
06b9c17
6c82a5c
e2d952c
7ce2eda
3123f12
16e895a
9d4ea71
ab7c2d7
cc4b11a
15e288f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,13 @@ | ||
from aiohttp.client_exceptions import ClientConnectionError | ||
from __future__ import annotations | ||
import asyncio | ||
|
||
import logging | ||
|
||
import aiohttp | ||
from aiohttp import client_exceptions | ||
|
||
from .config import Config | ||
from .clip import Clip | ||
from .groups import Groups | ||
from .lights import Lights | ||
from .scenes import Scenes | ||
|
@@ -11,7 +18,14 @@ | |
class Bridge: | ||
"""Control a Hue bridge.""" | ||
|
||
def __init__(self, host, websession, *, username=None, bridge_id=None): | ||
def __init__( | ||
self, | ||
host: str, | ||
websession: aiohttp.ClientSession, | ||
*, | ||
username: str | None = None, | ||
bridge_id: str | None = None, | ||
): | ||
self.host = host | ||
self.username = username | ||
self.websession = websession | ||
|
@@ -23,6 +37,9 @@ def __init__(self, host, websession, *, username=None, bridge_id=None): | |
self.lights = None | ||
self.scenes = None | ||
self.sensors = None | ||
self.clip = Clip(self.request_2) | ||
|
||
self.logger = logging.getLogger(f"{__name__}.{host}") | ||
|
||
# self.capabilities = None | ||
# self.rules = None | ||
|
@@ -48,13 +65,15 @@ async def create_user(self, device_type): | |
async def initialize(self): | ||
result = await self.request("get", "") | ||
|
||
self.config = Config(result["config"], self.request) | ||
self.groups = Groups(result["groups"], self.request) | ||
self.lights = Lights(result["lights"], self.request) | ||
self.config = Config(result.pop("config"), self.request) | ||
self.groups = Groups(result.pop("groups"), self.request) | ||
self.lights = Lights(result.pop("lights"), self.request) | ||
if "scenes" in result: | ||
self.scenes = Scenes(result["scenes"], self.request) | ||
self.scenes = Scenes(result.pop("scenes"), self.request) | ||
if "sensors" in result: | ||
self.sensors = Sensors(result["sensors"], self.request) | ||
self.sensors = Sensors(result.pop("sensors"), self.request) | ||
|
||
logging.getLogger(__name__).debug("Unused result: %s", result) | ||
|
||
async def request(self, method, path, json=None, auth=True): | ||
"""Make a request to the API.""" | ||
|
@@ -85,13 +104,73 @@ async def request(self, method, path, json=None, auth=True): | |
_raise_on_error(data) | ||
return data | ||
|
||
except ClientConnectionError: | ||
except client_exceptions.ClientConnectionError: | ||
if self.proto is not None: | ||
raise | ||
|
||
self.proto = "http" | ||
return await self.request(method, path, json, auth) | ||
|
||
async def request_2(self, method, path): | ||
"""Make a request to any path with Hue's new request method. | ||
|
||
This method has the auth in a header. | ||
""" | ||
url = f"{self.proto}://{self.host}/{path}" | ||
|
||
async with self.websession.request( | ||
method, | ||
url, | ||
ssl=False, | ||
headers={"hue-application-key": self.username}, | ||
) as res: | ||
res.raise_for_status() | ||
return await res.json() | ||
|
||
async def listen_events(self): | ||
"""Listen to events and apply changes to objects.""" | ||
loop = asyncio.get_running_loop() | ||
pending_events = asyncio.Queue() | ||
|
||
async def receive_events(): | ||
while True: | ||
self.logger.debug("Subscribing to events") | ||
try: | ||
for event in await self.clip.next_events(): | ||
self.logger.debug("Received event: %s", event) | ||
pending_events.put_nowait(event) | ||
except client_exceptions.ClientResponseError as err: | ||
self.logger.debug("Event endpoint %s", err.status) | ||
if err.status == 503: | ||
self.logger.debug("Sleeping while waiting for 503 to resolve") | ||
await asyncio.sleep(1) | ||
except asyncio.TimeoutError: | ||
pass | ||
|
||
event_task = loop.create_task(receive_events()) | ||
try: | ||
while True: | ||
event = await pending_events.get() | ||
|
||
if event["type"] != "update": | ||
self.logger.debug("Unknown event type: %s", event) | ||
continue | ||
|
||
for update in event["data"]: | ||
item_type = update["id_v1"].split("/", 2)[1] | ||
|
||
if item_type == "lights": | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For first version we're only going to support update events for lights. |
||
obj = self.lights.process_update_event(update) | ||
# if obj is None, we didn't know the object | ||
# We could consider triggering a full refresh | ||
if obj is not None: | ||
yield obj | ||
|
||
except asyncio.CancelledError: | ||
MartinHjelmare marked this conversation as resolved.
Show resolved
Hide resolved
|
||
event_task.cancel() | ||
await event_task | ||
raise | ||
|
||
|
||
def _raise_on_error(data): | ||
"""Check response for error message.""" | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
class Clip: | ||
"""Represent Hue clip.""" | ||
|
||
def __init__(self, request_2): | ||
self._request_2 = request_2 | ||
|
||
async def next_events(self): | ||
"""Note, this method will be pending until next event.""" | ||
return await self._request_2("get", "eventstream/clip/v2") | ||
|
||
async def resources(self): | ||
"""Fetch resources from Hue. | ||
|
||
Available types: | ||
|
||
homekit | ||
device | ||
bridge | ||
zigbee_connectivity | ||
entertainment | ||
light | ||
bridge_home | ||
grouped_light | ||
room | ||
scene | ||
""" | ||
return await self._request_2("get", "clip/v2/resource") | ||
|
||
@staticmethod | ||
balloob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
async def initialize(request_2): | ||
balloob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
raw = await request_2("get", "clip/v2/resource") | ||
return Clip(raw, request_2) | ||
balloob marked this conversation as resolved.
Show resolved
Hide resolved
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -90,6 +90,25 @@ def colorgamut(self): | |
|
||
return color_gamut | ||
|
||
def process_update_event(self, update): | ||
state = dict(self.state) | ||
|
||
if (color := update.get("color")) : | ||
state["xy"] = [color["xy"]["x"], color["xy"]["y"]] | ||
|
||
if ct := update.get("color_temperature"): | ||
state["ct"] = ct["mirek"] | ||
|
||
if "on" in update: | ||
state["on"] = update["on"]["on"] | ||
|
||
if dimming := update.get("dimming"): | ||
state["bri"] = dimming["brightness"] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Update events have their own format. These are the ones that I found so far for lights. |
||
|
||
state["reachable"] = True | ||
|
||
self.raw = {**self.raw, "state": state} | ||
|
||
async def set_state( | ||
self, | ||
on=None, | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am available for all your naming inquiries.