From b4e144afef63bdcbfab0cfbafbd38251370e33b7 Mon Sep 17 00:00:00 2001 From: Bao1573 <77220108+PG2047@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:07:40 +0800 Subject: [PATCH] =?UTF-8?q?fix(hass):=20hass=5Fget=5Fstate=20=E7=9A=84?= =?UTF-8?q?=E4=BA=AE=E5=BA=A6=E6=8C=89=E7=99=BE=E5=88=86=E6=AF=94=E6=8A=A5?= =?UTF-8?q?=20(#3542)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HA 的 brightness 量程是 0~255,原样交给模型会被念成"一百五十三";灯关着时是 null,还会报"亮度是:None"。换算成百分比,和设置亮度用的 brightness_pct 同一个单位,开着的灯最低报 1%(同 HA 前端);不是数字时不报这一项。附测试。 --- .../plugins_func/functions/hass_state.py | 13 ++-- .../tests/plugins_func/test_hass_state.py | 71 +++++++++++++++++++ 2 files changed, 77 insertions(+), 7 deletions(-) create mode 100644 main/xiaozhi-server/tests/plugins_func/test_hass_state.py diff --git a/main/xiaozhi-server/plugins_func/functions/hass_state.py b/main/xiaozhi-server/plugins_func/functions/hass_state.py index 240f7cd35..8dd7076d4 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_state.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_state.py @@ -142,13 +142,12 @@ async def handle_hass_get_state(conn: "ConnectionHandler", entity_id): + str(response.json()["attributes"]["rgb_color"]) + " " ) - if "brightness" in response.json()["attributes"]: - responsetext = ( - responsetext - + "亮度是:" - + str(response.json()["attributes"]["brightness"]) - + " " - ) + brightness = response.json()["attributes"].get("brightness") + if isinstance(brightness, (int, float)): + # HA 的 brightness 量程是 0~255,原样报出去会被念成"一百五十三"; + # 换算成百分比,和设置亮度(brightness_pct,1~100)同一个单位。开着的灯最低报 1%(同 HA 前端) + percent = max(1, round(brightness * 100 / 255)) if brightness > 0 else 0 + responsetext = responsetext + "亮度是:" + f"{percent}%" + " " logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}") return responsetext else: diff --git a/main/xiaozhi-server/tests/plugins_func/test_hass_state.py b/main/xiaozhi-server/tests/plugins_func/test_hass_state.py new file mode 100644 index 000000000..ed2c15ee2 --- /dev/null +++ b/main/xiaozhi-server/tests/plugins_func/test_hass_state.py @@ -0,0 +1,71 @@ +"""hass_get_state 交回的亮度按百分比报。 + +HA 的 brightness 量程是 0~255,原样报会被念成"一百五十三";灯关着时是 null,以前还会报"亮度是:None"。 +HTTP 层换成假的客户端,不出网。 +""" +import httpx +import pytest + +from plugins_func.functions import hass_state as hass_module + + +class FakeResponse: + def __init__(self, payload, status_code=200): + self.payload = payload + self.status_code = status_code + + def json(self): + return self.payload + + +class FakeAsyncClient: + payload = None + + def __init__(self, *args, **kwargs): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc_info): + return False + + async def get(self, url, headers=None): + return FakeResponse(FakeAsyncClient.payload) + + +class FakeConn: + def __init__(self): + self.load_function_plugin = True + self.config = { + "plugins": { + "home_assistant": { + "base_url": "http://homeassistant.local:8123", + "api_key": "test-token", + } + } + } + + +@pytest.fixture +def fake_http(monkeypatch): + monkeypatch.setattr(httpx, "AsyncClient", FakeAsyncClient) + return FakeAsyncClient + + +async def _get_state(fake_http, attributes, state="on"): + fake_http.payload = {"state": state, "attributes": attributes} + return await hass_module.handle_hass_get_state(FakeConn(), "light.desk_lamp") + + +@pytest.mark.parametrize("raw, shown", [(153, "60%"), (255, "100%"), (128, "50%"), (1, "1%"), (0, "0%")]) +async def test_brightness_reported_as_percent(fake_http, raw, shown): + text = await _get_state(fake_http, {"brightness": raw, "color_temp_kelvin": 4000}) + assert f"亮度是:{shown} " in text + assert text.startswith("设备状态:on ") and "色温是:4000 " in text + + +async def test_no_brightness_line_when_off_or_missing(fake_http): + # 灯关着时 HA 给 brightness: null + assert await _get_state(fake_http, {"brightness": None}, state="off") == "设备状态:off " + assert "亮度" not in await _get_state(fake_http, {"friendly_name": "台灯"})