hass_get_state.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. from plugins_func.register import register_function, ToolType, ActionResponse, Action
  2. from plugins_func.functions.hass_init import initialize_hass_handler
  3. from config.logger import setup_logging
  4. import asyncio
  5. import requests
  6. from typing import TYPE_CHECKING
  7. if TYPE_CHECKING:
  8. from core.connection import ConnectionHandler
  9. TAG = __name__
  10. logger = setup_logging()
  11. hass_get_state_function_desc = {
  12. "type": "function",
  13. "function": {
  14. "name": "hass_get_state",
  15. "description": "获取homeassistant里设备的状态,包括查询灯光亮度、颜色、色温,媒体播放器的音量,设备的暂停、继续操作",
  16. "parameters": {
  17. "type": "object",
  18. "properties": {
  19. "entity_id": {
  20. "type": "string",
  21. "description": "需要操作的设备id,homeassistant里的entity_id",
  22. }
  23. },
  24. "required": ["entity_id"],
  25. },
  26. },
  27. }
  28. @register_function("hass_get_state", hass_get_state_function_desc, ToolType.SYSTEM_CTL)
  29. def hass_get_state(conn: "ConnectionHandler", entity_id=""):
  30. try:
  31. ha_response = handle_hass_get_state(conn, entity_id)
  32. return ActionResponse(Action.REQLLM, ha_response, None)
  33. except asyncio.TimeoutError:
  34. logger.bind(tag=TAG).error("获取Home Assistant状态超时")
  35. return ActionResponse(Action.ERROR, "请求超时", None)
  36. except Exception as e:
  37. error_msg = f"执行Home Assistant操作失败"
  38. logger.bind(tag=TAG).error(error_msg)
  39. return ActionResponse(Action.ERROR, error_msg, None)
  40. def handle_hass_get_state(conn: "ConnectionHandler", entity_id):
  41. ha_config = initialize_hass_handler(conn)
  42. api_key = ha_config.get("api_key")
  43. base_url = ha_config.get("base_url")
  44. url = f"{base_url}/api/states/{entity_id}"
  45. headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
  46. response = requests.get(url, headers=headers, timeout=5)
  47. if response.status_code == 200:
  48. responsetext = "设备状态:" + response.json()["state"] + " "
  49. logger.bind(tag=TAG).info(f"api返回内容: {response.json()}")
  50. if "media_title" in response.json()["attributes"]:
  51. responsetext = (
  52. responsetext
  53. + "正在播放的是:"
  54. + str(response.json()["attributes"]["media_title"])
  55. + " "
  56. )
  57. if "volume_level" in response.json()["attributes"]:
  58. responsetext = (
  59. responsetext
  60. + "音量是:"
  61. + str(response.json()["attributes"]["volume_level"])
  62. + " "
  63. )
  64. if "color_temp_kelvin" in response.json()["attributes"]:
  65. responsetext = (
  66. responsetext
  67. + "色温是:"
  68. + str(response.json()["attributes"]["color_temp_kelvin"])
  69. + " "
  70. )
  71. if "rgb_color" in response.json()["attributes"]:
  72. responsetext = (
  73. responsetext
  74. + "rgb颜色是:"
  75. + str(response.json()["attributes"]["rgb_color"])
  76. + " "
  77. )
  78. if "brightness" in response.json()["attributes"]:
  79. responsetext = (
  80. responsetext
  81. + "亮度是:"
  82. + str(response.json()["attributes"]["brightness"])
  83. + " "
  84. )
  85. logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}")
  86. return responsetext
  87. # return response.json()['attributes']
  88. # response.attributes
  89. else:
  90. return f"切换失败,错误码: {response.status_code}"