コード例 #1
0
ファイル: test_json.py プロジェクト: jbouwh/core
def test_json_dumps_named_tuple_subclass():
    """Test the json dumps a tuple subclass."""
    class NamedTupleSubclass(NamedTuple):
        """A NamedTuple subclass."""

        name: str

    nts = NamedTupleSubclass("a")

    assert json_dumps(nts) == '["a"]'
コード例 #2
0
ファイル: __init__.py プロジェクト: jbouwh/core
        async def forward_events(event):
            """Forward events to the open request."""
            if restrict and event.event_type not in restrict:
                return

            _LOGGER.debug("STREAM %s FORWARDING %s", id(stop_obj), event)

            if event.event_type == EVENT_HOMEASSISTANT_STOP:
                data = stop_obj
            else:
                data = json_dumps(event)

            await to_write.put(data)
コード例 #3
0
ファイル: schema_state.py プロジェクト: jbouwh/core
 async def async_send_command(self, command, params=None, **kwargs):
     """Send a command to a vacuum cleaner."""
     if self.supported_features & VacuumEntityFeature.SEND_COMMAND == 0:
         return None
     if params:
         message = {"command": command}
         message.update(params)
         message = json_dumps(message)
     else:
         message = command
     await self.async_publish(
         self._send_command_topic,
         message,
         self._config[CONF_QOS],
         self._config[CONF_RETAIN],
         self._config[CONF_ENCODING],
     )
コード例 #4
0
ファイル: schema_legacy.py プロジェクト: jbouwh/core
 async def async_send_command(self, command, params=None, **kwargs):
     """Send a command to a vacuum cleaner."""
     if self.supported_features & VacuumEntityFeature.SEND_COMMAND == 0:
         return
     if params:
         message = {"command": command}
         message.update(params)
         message = json_dumps(message)
     else:
         message = command
     await self.async_publish(
         self._send_command_topic,
         message,
         self._qos,
         self._retain,
         self._encoding,
     )
     self._status = f"Sending command {message}..."
     self.async_write_ha_state()
コード例 #5
0
    async def async_turn_off(self, **kwargs):
        """Turn the device off.

        This method is a coroutine.
        """
        message = {"state": "OFF"}

        self._set_flash_and_transition(message, **kwargs)

        await self.async_publish(
            self._topic[CONF_COMMAND_TOPIC],
            json_dumps(message),
            self._config[CONF_QOS],
            self._config[CONF_RETAIN],
            self._config[CONF_ENCODING],
        )

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = False
            self.async_write_ha_state()
コード例 #6
0
ファイル: siren.py プロジェクト: jbouwh/core
 async def _async_publish(
     self,
     topic: str,
     template: str,
     value: Any,
     variables: dict[str, Any] | None = None,
 ) -> None:
     """Publish MQTT payload with optional command template."""
     template_variables = {STATE: value}
     if variables is not None:
         template_variables.update(variables)
     payload = (self._command_templates[template](value, template_variables)
                if self._command_templates[template] else
                json_dumps(template_variables))
     if payload and payload not in PAYLOAD_NONE:
         await self.async_publish(
             self._config[topic],
             payload,
             self._config[CONF_QOS],
             self._config[CONF_RETAIN],
             self._config[CONF_ENCODING],
         )
コード例 #7
0
ファイル: aiohttp.py プロジェクト: jbouwh/core
    def __init__(
        self,
        method,
        url,
        status=HTTPStatus.OK,
        response=None,
        json=None,
        text=None,
        cookies=None,
        exc=None,
        headers=None,
        side_effect=None,
    ):
        """Initialize a fake response."""
        if json is not None:
            text = json_dumps(json)
        if text is not None:
            response = text.encode("utf-8")
        if response is None:
            response = b""

        self.charset = "utf-8"
        self.method = method
        self._url = url
        self.status = status
        self.response = response
        self.exc = exc
        self.side_effect = side_effect
        self._headers = CIMultiDict(headers or {})
        self._cookies = {}

        if cookies:
            for name, data in cookies.items():
                cookie = mock.MagicMock()
                cookie.value = data
                self._cookies[name] = cookie
コード例 #8
0
ファイル: test_json.py プロジェクト: jbouwh/core
def test_json_dumps_tuple_subclass():
    """Test the json dumps a tuple subclass."""

    tt = time.struct_time((1999, 3, 17, 32, 44, 55, 2, 76, 0))

    assert json_dumps(tt) == "[1999,3,17,32,44,55,2,76,0]"
コード例 #9
0
ファイル: test_json.py プロジェクト: jbouwh/core
def test_json_dumps_float_subclass():
    """Test the json dumps a float subclass."""
    class FloatSubclass(float):
        """A float subclass."""

    assert json_dumps({"c": FloatSubclass(1.2)}) == '{"c":1.2}'
コード例 #10
0
ファイル: test_json.py プロジェクト: jbouwh/core
def test_json_dumps_rgb_color_subclass():
    """Test the json dumps of RGBColor."""
    rgb = RGBColor(4, 2, 1)

    assert json_dumps(rgb) == "[4,2,1]"
コード例 #11
0
    async def async_turn_on(self, **kwargs):  # noqa: C901
        """Turn the device on.

        This method is a coroutine.
        """
        should_update = False

        message = {"state": "ON"}

        if ATTR_HS_COLOR in kwargs and (
            self._config[CONF_HS] or self._config[CONF_RGB] or self._config[CONF_XY]
        ):
            hs_color = kwargs[ATTR_HS_COLOR]
            message["color"] = {}
            if self._config[CONF_RGB]:
                # If there's a brightness topic set, we don't want to scale the
                # RGB values given using the brightness.
                if self._config[CONF_BRIGHTNESS]:
                    brightness = 255
                else:
                    brightness = kwargs.get(ATTR_BRIGHTNESS, 255)
                rgb = color_util.color_hsv_to_RGB(
                    hs_color[0], hs_color[1], brightness / 255 * 100
                )
                message["color"]["r"] = rgb[0]
                message["color"]["g"] = rgb[1]
                message["color"]["b"] = rgb[2]
            if self._config[CONF_XY]:
                xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
                message["color"]["x"] = xy_color[0]
                message["color"]["y"] = xy_color[1]
            if self._config[CONF_HS]:
                message["color"]["h"] = hs_color[0]
                message["color"]["s"] = hs_color[1]

            if self._optimistic:
                self._hs = kwargs[ATTR_HS_COLOR]
                should_update = True

        if ATTR_HS_COLOR in kwargs and self._supports_color_mode(ColorMode.HS):
            hs_color = kwargs[ATTR_HS_COLOR]
            message["color"] = {"h": hs_color[0], "s": hs_color[1]}
            if self._optimistic:
                self._color_mode = ColorMode.HS
                self._hs = hs_color
                should_update = True

        if ATTR_RGB_COLOR in kwargs and self._supports_color_mode(ColorMode.RGB):
            rgb = self._scale_rgbxx(kwargs[ATTR_RGB_COLOR], kwargs)
            message["color"] = {"r": rgb[0], "g": rgb[1], "b": rgb[2]}
            if self._optimistic:
                self._color_mode = ColorMode.RGB
                self._rgb = rgb
                should_update = True

        if ATTR_RGBW_COLOR in kwargs and self._supports_color_mode(ColorMode.RGBW):
            rgb = self._scale_rgbxx(kwargs[ATTR_RGBW_COLOR], kwargs)
            message["color"] = {"r": rgb[0], "g": rgb[1], "b": rgb[2], "w": rgb[3]}
            if self._optimistic:
                self._color_mode = ColorMode.RGBW
                self._rgbw = rgb
                should_update = True

        if ATTR_RGBWW_COLOR in kwargs and self._supports_color_mode(ColorMode.RGBWW):
            rgb = self._scale_rgbxx(kwargs[ATTR_RGBWW_COLOR], kwargs)
            message["color"] = {
                "r": rgb[0],
                "g": rgb[1],
                "b": rgb[2],
                "c": rgb[3],
                "w": rgb[4],
            }
            if self._optimistic:
                self._color_mode = ColorMode.RGBWW
                self._rgbww = rgb
                should_update = True

        if ATTR_XY_COLOR in kwargs and self._supports_color_mode(ColorMode.XY):
            xy = kwargs[ATTR_XY_COLOR]  # pylint: disable=invalid-name
            message["color"] = {"x": xy[0], "y": xy[1]}
            if self._optimistic:
                self._color_mode = ColorMode.XY
                self._xy = xy
                should_update = True

        self._set_flash_and_transition(message, **kwargs)

        if ATTR_BRIGHTNESS in kwargs and self._config[CONF_BRIGHTNESS]:
            brightness_normalized = kwargs[ATTR_BRIGHTNESS] / DEFAULT_BRIGHTNESS_SCALE
            brightness_scale = self._config[CONF_BRIGHTNESS_SCALE]
            device_brightness = min(
                round(brightness_normalized * brightness_scale), brightness_scale
            )
            # Make sure the brightness is not rounded down to 0
            device_brightness = max(device_brightness, 1)
            message["brightness"] = device_brightness

            if self._optimistic:
                self._brightness = kwargs[ATTR_BRIGHTNESS]
                should_update = True

        if ATTR_COLOR_TEMP in kwargs:
            message["color_temp"] = int(kwargs[ATTR_COLOR_TEMP])

            if self._optimistic:
                self._color_temp = kwargs[ATTR_COLOR_TEMP]
                should_update = True

        if ATTR_EFFECT in kwargs:
            message["effect"] = kwargs[ATTR_EFFECT]

            if self._optimistic:
                self._effect = kwargs[ATTR_EFFECT]
                should_update = True

        if ATTR_WHITE_VALUE in kwargs:
            message["white_value"] = int(kwargs[ATTR_WHITE_VALUE])

            if self._optimistic:
                self._white_value = kwargs[ATTR_WHITE_VALUE]
                should_update = True

        await self.async_publish(
            self._topic[CONF_COMMAND_TOPIC],
            json_dumps(message),
            self._config[CONF_QOS],
            self._config[CONF_RETAIN],
            self._config[CONF_ENCODING],
        )

        if self._optimistic:
            # Optimistically assume that the light has changed state.
            self._state = True
            should_update = True

        if should_update:
            self.async_write_ha_state()
コード例 #12
0
def statement_for_request(
    start_day: dt,
    end_day: dt,
    event_types: tuple[str, ...],
    entity_ids: list[str] | None = None,
    device_ids: list[str] | None = None,
    filters: Filters | None = None,
    context_id: str | None = None,
) -> StatementLambdaElement:
    """Generate the logbook statement for a logbook request."""

    # No entities: logbook sends everything for the timeframe
    # limited by the context_id and the yaml configured filter
    if not entity_ids and not device_ids:
        states_entity_filter = filters.states_entity_filter() if filters else None
        events_entity_filter = filters.events_entity_filter() if filters else None
        return all_stmt(
            start_day,
            end_day,
            event_types,
            states_entity_filter,
            events_entity_filter,
            context_id,
        )

    # sqlalchemy caches object quoting, the
    # json quotable ones must be a different
    # object from the non-json ones to prevent
    # sqlalchemy from quoting them incorrectly

    # entities and devices: logbook sends everything for the timeframe for the entities and devices
    if entity_ids and device_ids:
        json_quoted_entity_ids = [json_dumps(entity_id) for entity_id in entity_ids]
        json_quoted_device_ids = [json_dumps(device_id) for device_id in device_ids]
        return entities_devices_stmt(
            start_day,
            end_day,
            event_types,
            entity_ids,
            json_quoted_entity_ids,
            json_quoted_device_ids,
        )

    # entities: logbook sends everything for the timeframe for the entities
    if entity_ids:
        json_quoted_entity_ids = [json_dumps(entity_id) for entity_id in entity_ids]
        return entities_stmt(
            start_day,
            end_day,
            event_types,
            entity_ids,
            json_quoted_entity_ids,
        )

    # devices: logbook sends everything for the timeframe for the devices
    assert device_ids is not None
    json_quoted_device_ids = [json_dumps(device_id) for device_id in device_ids]
    return devices_stmt(
        start_day,
        end_day,
        event_types,
        json_quoted_device_ids,
    )
コード例 #13
0
ファイル: sensor.py プロジェクト: jbouwh/core
    def _update_from_rest_data(self):
        """Update state from the rest data."""
        value = self.rest.data
        _LOGGER.debug("Data fetched from resource: %s", value)
        if self.rest.headers is not None:
            # If the http request failed, headers will be None
            content_type = self.rest.headers.get("content-type")

            if content_type and (
                    content_type.startswith("text/xml")
                    or content_type.startswith("application/xml")
                    or content_type.startswith("application/xhtml+xml")
                    or content_type.startswith("application/rss+xml")):
                try:
                    value = json_dumps(xmltodict.parse(value))
                    _LOGGER.debug("JSON converted from XML: %s", value)
                except ExpatError:
                    _LOGGER.warning(
                        "REST xml result could not be parsed and converted to JSON"
                    )
                    _LOGGER.debug("Erroneous XML: %s", value)

        if self._json_attrs:
            self._attributes = {}
            if value:
                try:
                    json_dict = json_loads(value)
                    if self._json_attrs_path is not None:
                        json_dict = jsonpath(json_dict, self._json_attrs_path)
                    # jsonpath will always store the result in json_dict[0]
                    # so the next line happens to work exactly as needed to
                    # find the result
                    if isinstance(json_dict, list):
                        json_dict = json_dict[0]
                    if isinstance(json_dict, dict):
                        attrs = {
                            k: json_dict[k]
                            for k in self._json_attrs if k in json_dict
                        }
                        self._attributes = attrs
                    else:
                        _LOGGER.warning(
                            "JSON result was not a dictionary"
                            " or list with 0th element a dictionary")
                except ValueError:
                    _LOGGER.warning("REST result could not be parsed as JSON")
                    _LOGGER.debug("Erroneous JSON: %s", value)

            else:
                _LOGGER.warning("Empty reply found when expecting JSON data")

        if value is not None and self._value_template is not None:
            value = self._value_template.async_render_with_possible_json_value(
                value, None)

        if value is None or self.device_class not in (
                SensorDeviceClass.DATE,
                SensorDeviceClass.TIMESTAMP,
        ):
            self._state = value
            return

        self._state = async_parse_date_datetime(value, self.entity_id,
                                                self.device_class)