endpoints done

This commit is contained in:
rooba 2022-11-29 15:14:56 -08:00
parent 72a98b8541
commit cf95790544
6 changed files with 413 additions and 323 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
**/.venv
**/poetry.lock
**/__pycache__
**/testing

View File

@ -1,6 +1,6 @@
from .api import Router
from .models import (
Archetype,
_Archetype,
Room,
Light,
Scene,
@ -25,7 +25,7 @@ from .models import (
__all__ = (
"Router",
"Archetype",
"_Archetype",
"Room",
"Light",
"Scene",

View File

@ -1,5 +1,6 @@
__all__ = ("Router", "route", "RouterMeta", "SubRouter", "HughApi")
from asyncio import get_running_loop, sleep
from inspect import signature
from re import compile
from typing import Any, Literal, Optional
@ -7,6 +8,11 @@ from uuid import UUID
from httpx import AsyncClient
from httpx._urls import URL as _URL
from httpx._exceptions import ConnectTimeout
from httpcore._exceptions import ReadTimeout
from json import loads
from pydantic import BaseModel
try:
from yarl import URL as UR
@ -24,6 +30,21 @@ from . import models
STR_FMT_RE = compile(r"""(?=(\{([^:]+)(?::([^}]+))?\}))\1""")
URL_TYPES = {"str": str, "int": int}
MSG_RE = compile(
b"""(?=((?P<hello>^hi\\n\\n$)|^id:\\s(?P<id>[0-9]+:\\d*?)\\ndata:(?P<data>[^$]+)\\n\\n))\\1"""
)
TYPE_CACHE = {}
for k in models.__all__:
if (
k == "Literal"
or k.startswith("_")
or not issubclass(getattr(models, k), BaseModel)
):
continue
# print(getattr(models, k).__dict__)
TYPE_CACHE[getattr(models, k).__fields__["type"].default] = getattr(models, k)
def get_url_args(url):
kwds = {}
@ -62,7 +83,6 @@ def ret_cls(cls):
if isinstance(ret, list):
for r in ret:
print(r)
_rets.append(cls(**r))
else:
return cls(**ret)
@ -85,6 +105,10 @@ def route(method, endpoint) -> Any:
):
params = params or {}
data = data or {}
if "headers" in kwargs:
headers = kwargs.pop("headers")
else:
headers = None
for param_name, param in signature(fn).parameters.items():
if param_name == "self":
continue
@ -137,13 +161,24 @@ def route(method, endpoint) -> Any:
else:
new_endpoint = URL(f"{self._api_path}") / endpoint
return await self._client.request(
method,
new_endpoint,
content=content,
data=data,
params=params,
)
if headers and headers.get("Accept", "") == "text/event-stream":
return self._client.stream(
method,
new_endpoint,
content=content,
data=data,
params=params,
headers=headers,
)
else:
return await self._client.request(
method,
new_endpoint,
content=content,
data=data,
params=params,
headers=headers,
)
return sub_wrap
@ -652,8 +687,49 @@ class HughApi(SubRouter):
async def get_resources(self):
...
@route("GET", "/../../eventstream/clip/v2")
async def listen_events(self):
...
class Router(HughApi, root="https://192.168.69.104"):
def __init__(self, hue_api_key: str):
super().__init__(hue_api_key)
self._client = AsyncClient(headers=self._headers, verify=False)
self._subscription = None
def subscribe(self, *args, **kwargs):
if not self._subscription or self._subscription.done():
self._subscription = get_running_loop().create_task(self._subscribe())
async def _subscribe(self, *args, **kwargs):
stream = await self.listen_events(
headers={"Accept": "text/event-stream"} | self._headers
)
while get_running_loop().is_running():
resp = await stream.gen.__anext__()
_bound = resp.stream._stream._httpcore_stream
try:
async for msg in _bound:
payload = []
_match = MSG_RE.search(msg)
id_ = ""
if _match:
if _match.groupdict().get("hello", None):
# Handshake / Heartbeat
...
else:
payload = loads(_match.group("data"))
id_ = _match.group("id").decode()
objs = []
for event in payload:
for ob in event["data"]:
objs.append(TYPE_CACHE[ob["type"]](**ob))
print(objs)
except ReadTimeout:
stream = await self.listen_events(
headers={"Accept": "text/event-stream"} | self._headers
)

View File

@ -1,13 +1,20 @@
from typing import Any, Literal, Optional, Generic, TypeAlias, TypeVar
from uuid import UUID
from dataclasses import dataclass
from enum import Enum, auto
from typing import (
Any as _Any,
Literal,
Optional as _Optional,
Generic as _Generic,
TypeAlias as _TypeAlias,
TypeVar as _TypeVar,
)
from uuid import UUID as _UUID
from dataclasses import dataclass as _dataclass
from enum import Enum as _Enum, auto as _auto
from pydantic import BaseModel, Field
from pydantic import BaseModel as _BaseModel, Field as _Field
__all__ = (
"Archetype",
"RoomType",
"_Archetype",
"_RoomType",
"Room",
"Light",
"Scene",
@ -33,138 +40,138 @@ __all__ = (
"Homekit",
)
_T_M: TypeAlias = "Archetype | Room | Light | Scene | Zone | BridgeHome | GroupedLight | Device | Bridge | DevicePower | ZigbeeConnectivity | ZGPConnectivity | Motion | Temperature | LightLevel | Button | BehaviorScript | BehaviorInstance | GeofenceClient | Geolocation | EntertainmentConfiguration | Entertainment | Resource | Homekit"
_T_M: _TypeAlias = "_RoomType | _Archetype | Room | Light | Scene | Zone | BridgeHome | GroupedLight | Device | Bridge | DevicePower | ZigbeeConnectivity | ZGPConnectivity | Motion | Temperature | LightLevel | Button | BehaviorScript | BehaviorInstance | GeofenceClient | Geolocation | EntertainmentConfiguration | Entertainment | Resource | Homekit"
_T = TypeVar("_T")
_T = _TypeVar("_T")
class RoomType(Enum):
class _RoomType(_Enum):
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return name.lower()
LIVING_ROOM = auto()
KITCHEN = auto()
DINING = auto()
BEDROOM = auto()
KIDS_BEDROOM = auto()
BATHROOM = auto()
NURSERY = auto()
RECREATION = auto()
OFFICE = auto()
GYM = auto()
HALLWAY = auto()
TOILET = auto()
FRONT_DOOR = auto()
GARAGE = auto()
TERRACE = auto()
GARDEN = auto()
DRIVEWAY = auto()
CARPORT = auto()
HOME = auto()
DOWNSTAIRS = auto()
UPSTAIRS = auto()
TOP_FLOOR = auto()
ATTIC = auto()
GUEST_ROOM = auto()
STAIRCASE = auto()
LOUNGE = auto()
MAN_CAVE = auto()
COMPUTER = auto()
STUDIO = auto()
MUSIC = auto()
TV = auto()
READING = auto()
CLOSET = auto()
STORAGE = auto()
LAUNDRY_ROOM = auto()
BALCONY = auto()
PORCH = auto()
BARBECUE = auto()
POOL = auto()
OTHER = auto()
LIVING_ROOM = _auto()
KITCHEN = _auto()
DINING = _auto()
BEDROOM = _auto()
KIDS_BEDROOM = _auto()
BATHROOM = _auto()
NURSERY = _auto()
RECREATION = _auto()
OFFICE = _auto()
GYM = _auto()
HALLWAY = _auto()
TOILET = _auto()
FRONT_DOOR = _auto()
GARAGE = _auto()
TERRACE = _auto()
GARDEN = _auto()
DRIVEWAY = _auto()
CARPORT = _auto()
HOME = _auto()
DOWNSTAIRS = _auto()
UPSTAIRS = _auto()
TOP_FLOOR = _auto()
ATTIC = _auto()
GUEST_ROOM = _auto()
STAIRCASE = _auto()
LOUNGE = _auto()
MAN_CAVE = _auto()
COMPUTER = _auto()
STUDIO = _auto()
MUSIC = _auto()
TV = _auto()
READING = _auto()
CLOSET = _auto()
STORAGE = _auto()
LAUNDRY_ROOM = _auto()
BALCONY = _auto()
PORCH = _auto()
BARBECUE = _auto()
POOL = _auto()
OTHER = _auto()
class Archetype(Enum):
class _Archetype(_Enum):
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return name.lower()
BRIDGE_V2 = auto()
UNKNOWN_ARCHETYPE = auto()
CLASSIC_BULB = auto()
SULTAN_BULB = auto()
FLOOD_BULB = auto()
SPOT_BULB = auto()
CANDLE_BULB = auto()
LUSTER_BULB = auto()
PENDANT_ROUND = auto()
PENDANT_LONG = auto()
CEILING_ROUND = auto()
CEILING_SQUARE = auto()
FLOOR_SHADE = auto()
FLOOR_LANTERN = auto()
TABLE_SHADE = auto()
RECESSED_CEILING = auto()
RECESSED_FLOOR = auto()
SINGLE_SPOT = auto()
DOUBLE_SPOT = auto()
TABLE_WASH = auto()
WALL_LANTERN = auto()
WALL_SHADE = auto()
FLEXIBLE_LAMP = auto()
GROUND_SPOT = auto()
WALL_SPOT = auto()
PLUG = auto()
HUE_GO = auto()
HUE_LIGHTSTRIP = auto()
HUE_IRIS = auto()
HUE_BLOOM = auto()
BOLLARD = auto()
WALL_WASHER = auto()
HUE_PLAY = auto()
VINTAGE_BULB = auto()
CHRISTMAS_TREE = auto()
HUE_CENTRIS = auto()
HUE_LIGHTSTRIP_TV = auto()
HUE_TUBE = auto()
HUE_SIGNE = auto()
BRIDGE_V2 = _auto()
UNKNOWN_ARCHETYPE = _auto()
CLASSIC_BULB = _auto()
SULTAN_BULB = _auto()
FLOOD_BULB = _auto()
SPOT_BULB = _auto()
CANDLE_BULB = _auto()
LUSTER_BULB = _auto()
PENDANT_ROUND = _auto()
PENDANT_LONG = _auto()
CEILING_ROUND = _auto()
CEILING_SQUARE = _auto()
FLOOR_SHADE = _auto()
FLOOR_LANTERN = _auto()
TABLE_SHADE = _auto()
RECESSED_CEILING = _auto()
RECESSED_FLOOR = _auto()
SINGLE_SPOT = _auto()
DOUBLE_SPOT = _auto()
TABLE_WASH = _auto()
WALL_LANTERN = _auto()
WALL_SHADE = _auto()
FLEXIBLE_LAMP = _auto()
GROUND_SPOT = _auto()
WALL_SPOT = _auto()
PLUG = _auto()
HUE_GO = _auto()
HUE_LIGHTSTRIP = _auto()
HUE_IRIS = _auto()
HUE_BLOOM = _auto()
BOLLARD = _auto()
WALL_WASHER = _auto()
HUE_PLAY = _auto()
VINTAGE_BULB = _auto()
CHRISTMAS_TREE = _auto()
HUE_CENTRIS = _auto()
HUE_LIGHTSTRIP_TV = _auto()
HUE_TUBE = _auto()
HUE_SIGNE = _auto()
@dataclass
@_dataclass
class _Dimming:
brightness: float
min_dim_level: Optional[float] = Field(0, repr=False)
min_dim_level: _Optional[float] = _Field(0, repr=False)
@dataclass
@_dataclass
class _XY:
x: float
y: float
@dataclass
@_dataclass
class _On:
on: bool = Field(..., alias="on")
on: bool = _Field(..., alias="on")
@dataclass
@_dataclass
class _ColorPoint:
xy: _XY
@dataclass(frozen=True)
@_dataclass(frozen=True)
class _Identifier:
rid: str
rtype: str
@dataclass(frozen=True)
@_dataclass(frozen=True)
class _Metadata:
name: str
archetype: Optional[Archetype | RoomType] = Archetype.UNKNOWN_ARCHETYPE
image: Optional[_Identifier] = Field(None, repr=False)
archetype: _Optional[_Archetype | _RoomType] = _Archetype.UNKNOWN_ARCHETYPE
image: _Optional[_Identifier] = _Field(None, repr=False)
class _HueGroupedMeta(type):
@ -179,101 +186,101 @@ class _HueGrouped(metaclass=_HueGroupedMeta):
class _Lights(_HueGrouped):
class ColorTemperature(BaseModel):
mirek: Optional[int]
class ColorTemperature(_BaseModel):
mirek: _Optional[int]
mirek_valid: bool
mirek_schema: dict[str, float]
class Gamut(BaseModel):
class Gamut(_BaseModel):
red: _XY
green: _XY
blue: _XY
class Color(BaseModel):
xy: _XY
gamut: "_Lights.Gamut"
gamut_type: Literal["A"] | Literal["B"] | Literal["C"]
class Color(_BaseModel):
xy: _XY = _Field(None)
gamut: "_Lights.Gamut" = _Field(None)
gamut_type: Literal["A", "B", "C"] = _Field(None)
class Dynamics(BaseModel):
status: str
status_values: list[str]
speed: float
speed_valid: bool
class Dynamics(_BaseModel):
status: str = _Field(None)
status_values: list[str] = _Field(None)
speed: float = _Field(None)
speed_valid: bool = _Field(None)
class Gradient(BaseModel):
points: list[_ColorPoint]
points_capable: int
class Gradient(_BaseModel):
points: list[_ColorPoint] = _Field([])
points_capable: int = _Field(0)
class Effects(BaseModel):
effect: Optional[list[str]] = Field(repr=False)
status_values: list[str] = Field(repr=False)
status: str
effect_values: list[str] = Field(repr=False)
class Effects(_BaseModel):
effect: _Optional[list[str]] = _Field(repr=False)
status_values: list[str] = _Field(repr=False)
status: str = _Field("")
effect_values: list[str] = _Field(repr=False)
class TimedEffects(BaseModel):
effect: str
duration: int
status_values: list[str] = Field(repr=False)
status: str
effect_values: list[str] = Field(repr=False)
class TimedEffects(_BaseModel):
effect: str = _Field("")
duration: int = _Field(0)
status_values: list[str] = _Field(repr=False)
status: str = _Field("")
effect_values: list[str] = _Field(repr=False)
class Light(Generic[_T], BaseModel):
id: UUID
id_v1: Optional[str] = Field(
class Light(_Generic[_T], _BaseModel):
id: _UUID
id_v1: _Optional[str] = _Field(
..., regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$"
)
owner: _Identifier
metadata: _Metadata
on: _On = Field(repr=False)
dimming: _Dimming
dimming_delta: dict
color_temperature: Optional["_Lights.ColorTemperature"]
color_temperature_delta: Optional[dict]
color: Optional["_Lights.Color"]
gradient: Optional["_Lights.Gradient"]
dynamics: "_Lights.Dynamics"
alert: dict[str, list[str]]
signaling: dict
mode: str
effects: "_Lights.Effects"
type: Literal["light"]
owner: _Optional[_Identifier]
metadata: _Optional[_Metadata]
on: _Optional[_On] = _Field(repr=False)
dimming: _Optional[_Dimming]
dimming_delta: _Optional[dict]
color_temperature: _Optional["_Lights.ColorTemperature"]
color_temperature_delta: _Optional[dict]
color: _Optional["_Lights.Color"]
gradient: _Optional["_Lights.Gradient"]
dynamics: _Optional["_Lights.Dynamics"]
alert: _Optional[dict[str, list[str]]]
signaling: _Optional[dict]
mode: _Optional[str]
effects: _Optional["_Lights.Effects"]
type: Literal["light"] = "light"
_Lights.update()
class _Scenes(_HueGrouped):
class Action(BaseModel):
on: Optional[_On]
dimming: Optional[_Dimming]
color: Optional[_ColorPoint]
color_temperature: Optional[dict[str, float]]
gradient: Optional[dict[str, list[_ColorPoint]]]
effects: Optional[dict[str, str]]
dynamics: Optional[dict[str, float]]
class Action(_BaseModel):
on: _Optional[_On]
dimming: _Optional[_Dimming]
color: _Optional[_ColorPoint]
color_temperature: _Optional[dict[str, float]]
gradient: _Optional[dict[str, list[_ColorPoint]]]
effects: _Optional[dict[str, str]]
dynamics: _Optional[dict[str, float]]
class Actions(BaseModel):
class Actions(_BaseModel):
target: _Identifier
action: "_Scenes.Action" = Field(repr=False)
dimming: Optional[_Dimming]
color: Optional[_ColorPoint]
action: "_Scenes.Action" = _Field(repr=False)
dimming: _Optional[_Dimming]
color: _Optional[_ColorPoint]
class PaletteColor(BaseModel):
class PaletteColor(_BaseModel):
color: _ColorPoint
dimming: _Dimming
class PaletteTemperature(BaseModel):
class PaletteTemperature(_BaseModel):
color_temperature: dict[str, float]
dimming: _Dimming
class Palette(BaseModel):
class Palette(_BaseModel):
color: list["_Scenes.PaletteColor"]
dimming: Optional[list[_Dimming]]
dimming: _Optional[list[_Dimming]]
color_temperature: list["_Scenes.PaletteTemperature"]
class Scene(BaseModel):
id: UUID
id_v1: Optional[str] = Field(
class Scene(_BaseModel):
id: _UUID
id_v1: _Optional[str] = _Field(
..., regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$"
)
metadata: _Metadata
@ -282,90 +289,90 @@ class _Scenes(_HueGrouped):
palette: "_Scenes.Palette"
speed: float
auto_dynamic: bool
type: Literal["scene"]
type: Literal["scene"] = "scene"
_Scenes.update()
class Room(BaseModel):
type: Literal["room"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Room(_BaseModel):
type: Literal["room"] = "room"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
services: list[_Identifier]
metadata: _Metadata
children: list[_Identifier]
class Zone(BaseModel):
type: Literal["zone"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Zone(_BaseModel):
type: Literal["zone"] = "zone"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
services: list[_Identifier]
metadata: _Metadata
children: list[_Identifier]
class BridgeHome(BaseModel):
type: Literal["bridge_home"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class BridgeHome(_BaseModel):
type: Literal["bridge_home"] = "bridge_home"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
services: list[_Identifier]
children: list[_Identifier]
class GroupedLight(BaseModel):
type: Literal["grouped_light"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
on: _On = Field(repr=False)
class GroupedLight(_BaseModel):
type: Literal["grouped_light"] = "grouped_light"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
on: _On = _Field(repr=False)
alert: dict[str, list[str]]
class _ProductData(BaseModel):
class _ProductData(_BaseModel):
model_id: str
manufacturer_name: str
product_name: str
product_archetype: Archetype
product_archetype: _Archetype
certified: bool
software_version: Optional[str]
hardware_platform_type: Optional[str]
software_version: _Optional[str]
hardware_platform_type: _Optional[str]
class Device(BaseModel):
type: Literal["device"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Device(_BaseModel):
type: Literal["device"] = "device"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
services: list[_Identifier]
metadata: _Metadata
product_data: _ProductData
class Bridge(BaseModel):
type: Literal["bridge"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Bridge(_BaseModel):
type: Literal["bridge"] = "bridge"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
bridge_id: str
time_zone: dict[str, str]
class _PowerState(BaseModel):
class _PowerState(_BaseModel):
battery_state: Literal["normal", "low", "critical"]
battery_level: float = Field(le=100.0, ge=0.0)
battery_level: float = _Field(le=100.0, ge=0.0)
class DevicePower(BaseModel):
type: Literal["device_power"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class DevicePower(_BaseModel):
type: Literal["device_power"] = "device_power"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Identifier
power_state: _PowerState
class ZigbeeConnectivity(BaseModel):
type: Literal["zigbee_connectivity"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class ZigbeeConnectivity(_BaseModel):
type: Literal["zigbee_connectivity"] = "zigbee_connectivity"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Identifier
status: Literal[
"connected", "disconnected", "connectivity_issue", "unidirectional_incoming"
@ -373,10 +380,10 @@ class ZigbeeConnectivity(BaseModel):
mac_address: str
class ZGPConnectivity(BaseModel):
type: Literal["zgp_connectivity"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class ZGPConnectivity(_BaseModel):
type: Literal["zgp_connectivity"] = "zgp_connectivity"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Identifier
status: Literal[
"connected", "disconnected", "connectivity_issue", "unidirectional_incoming"
@ -384,47 +391,47 @@ class ZGPConnectivity(BaseModel):
source_id: str
class Motion(BaseModel):
type: Literal["motion"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Motion(_BaseModel):
type: Literal["motion"] = "motion"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Identifier
enabled: bool
motion: dict[str, bool]
class _Temp(BaseModel):
temperature: float = Field(lt=100.0, gt=-100.0)
class _Temp(_BaseModel):
temperature: float = _Field(lt=100.0, gt=-100.0)
temperature_valid: bool
class Temperature(BaseModel):
type: Literal["temperature"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Temperature(_BaseModel):
type: Literal["temperature"] = "temperature"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Identifier
enabled: bool
enabled: _Optional[bool]
temperature: _Temp
class _Light(BaseModel):
light_level: int
light_level_valid: bool
class _Light(_BaseModel):
light_level: _Optional[int]
light_level_valid: _Optional[bool]
class LightLevel(BaseModel):
type: Literal["light_level"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Identifier
enabled: bool
light: _Light
class LightLevel(_BaseModel):
type: Literal["light_level"] = "light_level"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Optional[_Identifier]
enabled: _Optional[bool]
light: _Optional[_Light]
class Button(BaseModel):
type: Literal["button"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Button(_BaseModel):
type: Literal["button"] = "button"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Identifier
metadata: dict[Literal["control_id"], int]
button: dict[
@ -439,133 +446,133 @@ class Button(BaseModel):
]
class BehaviorScript(BaseModel):
type: Literal["behavior_script"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class BehaviorScript(_BaseModel):
type: Literal["behavior_script"] = "behavior_script"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
description: str
configuration_schema: dict[str, Any]
trigger_schema: dict[str, Any]
state_schema: dict[str, Any]
configuration_schema: dict[str, _Any]
trigger_schema: dict[str, _Any]
state_schema: dict[str, _Any]
version: str
metadata: dict[str, str]
class _Dependee(BaseModel):
class _Dependee(_BaseModel):
type: str
target: _Identifier
level: str
class BehaviorInstance(BaseModel):
type: Literal["behavior_instance"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class BehaviorInstance(_BaseModel):
type: Literal["behavior_instance"] = "behavior_instance"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
script_id: str
enabled: bool
state: Optional[dict[str, Any]]
configuration: dict[str, Any]
state: _Optional[dict[str, _Any]]
configuration: dict[str, _Any]
dependees: list[_Dependee]
status: Literal["initializing", "running", "disabled", "errored"]
last_error: str
metadata: dict[Literal["name"], str]
migrated_from: Optional[str] = None
migrated_from: _Optional[str] = None
class GeofenceClient(BaseModel):
type: Literal["geofence_client"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class GeofenceClient(_BaseModel):
type: Literal["geofence_client"] = "geofence_client"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
name: str
class Geolocation(BaseModel):
type: Literal["geolocation"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Geolocation(_BaseModel):
type: Literal["geolocation"] = "geolocation"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
is_configured: bool = False
class _StreamProxy(BaseModel):
class _StreamProxy(_BaseModel):
mode: Literal["auto", "manual"]
node: _Identifier
class _XYZ(BaseModel):
x: float = Field(ge=-1.0, le=1.0)
y: float = Field(ge=-1.0, le=1.0)
z: float = Field(ge=-1.0, le=1.0)
class _XYZ(_BaseModel):
x: float = _Field(ge=-1.0, le=1.0)
y: float = _Field(ge=-1.0, le=1.0)
z: float = _Field(ge=-1.0, le=1.0)
class _SegmentRef(BaseModel):
class _SegmentRef(_BaseModel):
service: _Identifier
index: int
class _EntertainmentChannel(BaseModel):
channel_id: int = Field(ge=0, le=255)
class _EntertainmentChannel(_BaseModel):
channel_id: int = _Field(ge=0, le=255)
position: _XYZ
members: list[_SegmentRef]
class _ServiceLocation(BaseModel):
class _ServiceLocation(_BaseModel):
service: _Identifier
position: _XYZ
positions: list[_XYZ] = Field(max_items=2, min_items=1)
positions: list[_XYZ] = _Field(max_items=2, min_items=1)
class _EntertainmentLocation(BaseModel):
service_location: Optional[list[_ServiceLocation]] = []
class _EntertainmentLocation(_BaseModel):
service_location: _Optional[list[_ServiceLocation]] = []
class EntertainmentConfiguration(BaseModel):
type: Literal["entertainment_configuration"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class EntertainmentConfiguration(_BaseModel):
type: Literal["entertainment_configuration"] = "entertainment_configuration"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
metadata: dict[Literal["name"], str]
name: Optional[str] = ""
name: _Optional[str] = ""
configuration_type: Literal["screen", "monitor", "music", "3dspace", "other"]
status: Literal["active", "inactive"]
active_streamer: Optional[_Identifier] = None
active_streamer: _Optional[_Identifier] = None
stream_proxy: _StreamProxy
channels: list[_EntertainmentChannel]
locations: Optional[_EntertainmentLocation] = None
locations: _Optional[_EntertainmentLocation] = None
light_services: list[_Identifier]
class _Segment(BaseModel):
start: int = Field(..., ge=0)
length: int = Field(..., ge=1)
class _Segment(_BaseModel):
start: int = _Field(..., ge=0)
length: int = _Field(..., ge=1)
class _SegmentManager(BaseModel):
class _SegmentManager(_BaseModel):
configurable: bool
max_segments: int = Field(..., ge=1)
max_segments: int = _Field(..., ge=1)
segments: list[_Segment]
class Entertainment(BaseModel):
type: Literal["entertainment"]
id: UUID
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Entertainment(_BaseModel):
type: Literal["entertainment"] = "entertainment"
id: _UUID
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
owner: _Identifier
renderer: bool
proxy: bool
max_streams: Optional[int] = Field(1, ge=1)
segments: Optional[_SegmentManager] = None
max_streams: _Optional[int] = _Field(1, ge=1)
segments: _Optional[_SegmentManager] = None
class Homekit(BaseModel):
id: UUID
type: Optional[str]
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Homekit(_BaseModel):
id: _UUID
type: _Optional[str] = "resource"
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
status: Literal["paired", "pairing", "unpaired"]
class Resource(BaseModel):
id: UUID
type: Optional[str]
id_v1: Optional[str] = Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
class Resource(_BaseModel):
id: _UUID
type: _Optional[str] = "device"
id_v1: _Optional[str] = _Field("", regex=r"^(\/[a-z]{4,32}\/[0-9a-zA-Z-]{1,32})?$")
Light = _Lights.Light

View File

@ -9,6 +9,9 @@ python = ">=3.11,<4.0.0"
httpx = ">=0.23.1"
pydantic = ">=1.10.2"
yarl = ">=1.8.1"
ujson = "^5.5.0"
loguru = "^0.6.0"
orjson = "^3.8.2"
[tool.poetry.dev-dependencies]
black = ">=22.10.0"

43
test.py
View File

@ -1,4 +1,4 @@
from asyncio import run
from asyncio import run, sleep
from phlyght.api import Router
@ -9,31 +9,34 @@ except ImportError:
async def main():
router = Router("your api key")
router = Router("ur key")
print(await router.get_lights())
print(await router.get_scenes())
print(await router.get_devices())
print(await router.get_rooms())
print(await router.get_zones())
print(await router.get_bridge_homes())
print(await router.get_grouped_lights())
print(await router.get_bridges())
print(await router.get_device_powers())
print(await router.get_zigbee_connectivities())
print(await router.get_zgb_connectivities())
await router.get_rooms()
await router.get_zones()
await router.get_bridge_homes()
await router.get_grouped_lights()
await router.get_bridges()
await router.get_device_powers()
await router.get_zigbee_connectivities()
await router.get_zgb_connectivities()
print(await router.get_motions())
print(await router.get_temperatures())
print(await router.get_light_levels())
print(await router.get_buttons())
print(await router.get_behavior_scripts())
print(await router.get_behavior_instances())
print(await router.get_geofence_clients())
print(await router.get_geolocations())
print(await router.get_entertainment_configurations())
print(await router.get_entertainments())
print(await router.get_homekits())
print(await router.get_resources())
await router.get_light_levels()
await router.get_buttons()
await router.get_behavior_scripts()
await router.get_behavior_instances()
await router.get_geofence_clients()
await router.get_geolocations()
await router.get_entertainment_configurations()
await router.get_entertainments()
await router.get_homekits()
await router.get_resources()
await router._subscribe()
while True:
await sleep(5)
run(main())