async def subscribe_states(self, on_state: Callable[[Any], None]) -> None:
        self._check_authenticated()

        response_types = {
            pb.BinarySensorStateResponse: BinarySensorState,
            pb.CoverStateResponse: CoverState,
            pb.FanStateResponse: FanState,
            pb.LightStateResponse: LightState,
            pb.SensorStateResponse: SensorState,
            pb.SwitchStateResponse: SwitchState,
            pb.TextSensorStateResponse: TextSensorState,
        }

        def on_msg(msg):
            for resp_type, cls in response_types.items():
                if isinstance(msg, resp_type):
                    break
            else:
                return

            kwargs = {}
            for key, _ in attr.fields_dict(cls).items():
                kwargs[key] = getattr(msg, key)
            on_state(cls(**kwargs))

        await self._connection.send_message_callback_response(pb.SubscribeStatesRequest(), on_msg)
Beispiel #2
0
    async def subscribe_states(self, on_state: Callable[[Any], None]) -> None:
        self._check_authenticated()

        response_types = {
            pb.BinarySensorStateResponse: BinarySensorState,
            pb.CoverStateResponse: CoverState,
            pb.FanStateResponse: FanState,
            pb.LightStateResponse: LightState,
            pb.SensorStateResponse: SensorState,
            pb.SwitchStateResponse: SwitchState,
            pb.TextSensorStateResponse: TextSensorState,
            pb.ClimateStateResponse: ClimateState,
        }

        image_stream = {}

        def on_msg(msg):
            if isinstance(msg, pb.CameraImageResponse):
                data = image_stream.pop(msg.key, bytes()) + msg.data
                if msg.done:
                    on_state(CameraState(key=msg.key, image=data))
                else:
                    image_stream[msg.key] = data
                return

            for resp_type, cls in response_types.items():
                if isinstance(msg, resp_type):
                    break
            else:
                return

            kwargs = {}
            # pylint: disable=undefined-loop-variable
            for key, _ in attr.fields_dict(cls).items():
                kwargs[key] = getattr(msg, key)
            on_state(cls(**kwargs))

        await self._connection.send_message_callback_response(
            pb.SubscribeStatesRequest(), on_msg)