|
3 | 3 | import logging
|
4 | 4 | from typing import Any
|
5 | 5 |
|
| 6 | +from hassil.expression import Sentence |
6 | 7 | from hassil.recognize import RecognizeResult
|
7 | 8 | from homeassistant.components.conversation.default_agent import (
|
8 | 9 | DATA_DEFAULT_ENTITY,
|
@@ -71,14 +72,17 @@ async def handle_trigger(
|
71 | 72 | device_id was added in 2024.4.0
|
72 | 73 | """
|
73 | 74 |
|
| 75 | + # RecognizeResult in 2024.12 is not serializable, so we need to convert it to a serializable format |
| 76 | + serialized = convert_recognize_result_to_dict(result) |
| 77 | + |
74 | 78 | _LOGGER.debug(f"Sentence trigger: {sentence}")
|
75 | 79 | connection.send_message(
|
76 | 80 | event_message(
|
77 | 81 | message_id,
|
78 | 82 | {
|
79 | 83 | "data": {
|
80 | 84 | "sentence": sentence,
|
81 |
| - "result": result, |
| 85 | + "result": serialized, |
82 | 86 | "deviceId": device_id,
|
83 | 87 | "responseId": message_id,
|
84 | 88 | }
|
@@ -174,3 +178,34 @@ async def websocket_sentence_response(
|
174 | 178 | connection.send_message(
|
175 | 179 | error_message(message_id, "sentence_response_not_found", message),
|
176 | 180 | )
|
| 181 | + |
| 182 | + |
| 183 | +def convert_recognize_result_to_dict(result: Any) -> dict: |
| 184 | + """ |
| 185 | + Serializes a RecognizeResult object into a JSON-serializable dictionary. |
| 186 | + """ |
| 187 | + |
| 188 | + def serialize(obj): |
| 189 | + if isinstance(obj, Sentence): |
| 190 | + # Custom serialization for Sentence |
| 191 | + return { |
| 192 | + "text": obj.text, |
| 193 | + "pattern": obj.pattern.pattern if obj.pattern else None, |
| 194 | + } |
| 195 | + elif hasattr(obj, "__dict__"): |
| 196 | + # For objects with attributes, serialize attributes |
| 197 | + return {key: serialize(value) for key, value in vars(obj).items()} |
| 198 | + elif isinstance(obj, list): |
| 199 | + # Recursively handle lists |
| 200 | + return [serialize(item) for item in obj] |
| 201 | + elif isinstance(obj, dict): |
| 202 | + # Recursively handle dictionaries |
| 203 | + return {key: serialize(value) for key, value in obj.items()} |
| 204 | + elif isinstance(obj, (int, float, str, type(None))): |
| 205 | + # Primitive types are already serializable |
| 206 | + return obj |
| 207 | + else: |
| 208 | + # Fallback for non-serializable types |
| 209 | + return str(obj) |
| 210 | + |
| 211 | + return serialize(result) |
0 commit comments