Handler for JSON-RPC communication with FL::Remote devices. Parses and stores JSON responses that are prefixed with "REMOTE: ".
| 14 | |
| 15 | |
| 16 | class JsonRpcHandler: |
| 17 | """Handler for JSON-RPC communication with FL::Remote devices. |
| 18 | |
| 19 | Parses and stores JSON responses that are prefixed with "REMOTE: ". |
| 20 | """ |
| 21 | |
| 22 | REMOTE_PREFIX = "REMOTE: " |
| 23 | |
| 24 | def __init__(self): |
| 25 | """Initialize the JSON-RPC handler.""" |
| 26 | self.responses: list[dict[str, Any]] = [] |
| 27 | self.raw_lines: list[str] = [] |
| 28 | |
| 29 | def process_line(self, line: str) -> dict[str, Any] | None: |
| 30 | """Process a line of output, extracting JSON-RPC responses. |
| 31 | |
| 32 | Args: |
| 33 | line: Line of text from serial output |
| 34 | |
| 35 | Returns: |
| 36 | Parsed JSON object if line contains valid RPC response, None otherwise |
| 37 | """ |
| 38 | # Check if line starts with REMOTE: prefix |
| 39 | if not line.startswith(self.REMOTE_PREFIX): |
| 40 | return None |
| 41 | |
| 42 | # Extract JSON portion (everything after prefix) |
| 43 | json_str = line[len(self.REMOTE_PREFIX) :].strip() |
| 44 | self.raw_lines.append(json_str) |
| 45 | |
| 46 | # Parse JSON |
| 47 | try: |
| 48 | response = json.loads(json_str) |
| 49 | self.responses.append(response) |
| 50 | return response |
| 51 | except json.JSONDecodeError as e: |
| 52 | print(f"⚠️ Warning: Failed to parse REMOTE JSON: {e}") |
| 53 | print(f" Raw line: {json_str}") |
| 54 | return None |
| 55 | |
| 56 | def get_responses(self) -> list[dict[str, Any]]: |
| 57 | """Get all parsed JSON-RPC responses. |
| 58 | |
| 59 | Returns: |
| 60 | List of parsed JSON response objects |
| 61 | """ |
| 62 | return self.responses |
| 63 | |
| 64 | def get_response_by_function(self, function_name: str) -> dict[str, Any] | None: |
| 65 | """Get the first response for a specific function. |
| 66 | |
| 67 | Args: |
| 68 | function_name: Name of the RPC function |
| 69 | |
| 70 | Returns: |
| 71 | First matching response object, or None if not found |
| 72 | """ |
| 73 | for response in self.responses: |