Run the serial monitor until timeout or handler requests stop. Returns: True if all handlers succeeded, False otherwise
(self)
| 289 | self.mHandlers.append(handler) |
| 290 | |
| 291 | def run(self) -> bool: |
| 292 | """Run the serial monitor until timeout or handler requests stop. |
| 293 | |
| 294 | Returns: |
| 295 | True if all handlers succeeded, False otherwise |
| 296 | """ |
| 297 | # Open serial connection |
| 298 | try: |
| 299 | self.mSerialPort = serial.Serial(self.mPort, self.mBaudRate, timeout=1) |
| 300 | time.sleep(0.5) # Let serial connection stabilize |
| 301 | print(f"{Fore.GREEN}✅ Serial connection established{Style.RESET_ALL}\n") |
| 302 | except serial.SerialException as e: |
| 303 | print(f"{Fore.RED}❌ Failed to open serial port: {e}{Style.RESET_ALL}") |
| 304 | return False |
| 305 | |
| 306 | # Initialize handlers that need the serial port |
| 307 | for handler in self.mHandlers: |
| 308 | if isinstance(handler, InputTriggerHandler): |
| 309 | handler.set_serial_port(self.mSerialPort) |
| 310 | |
| 311 | start_time = time.time() |
| 312 | should_continue = True |
| 313 | |
| 314 | try: |
| 315 | while should_continue: |
| 316 | # Check timeout (unless in streaming mode) |
| 317 | if not self.mStream: |
| 318 | elapsed = time.time() - start_time |
| 319 | if elapsed >= self.mTimeoutSeconds: |
| 320 | print( |
| 321 | f"\n⏱️ Timeout reached ({self.mTimeoutSeconds}s), stopping monitor..." |
| 322 | ) |
| 323 | break |
| 324 | |
| 325 | # Read available serial data |
| 326 | if self.mSerialPort.in_waiting: |
| 327 | try: |
| 328 | line = ( |
| 329 | self.mSerialPort.readline() |
| 330 | .decode("utf-8", errors="ignore") |
| 331 | .strip() |
| 332 | ) |
| 333 | if line: |
| 334 | print(line) # Display line |
| 335 | |
| 336 | # Dispatch to all handlers |
| 337 | for handler in self.mHandlers: |
| 338 | if not handler.handle_line(line): |
| 339 | # Handler requested stop |
| 340 | should_continue = False |
| 341 | break |
| 342 | |
| 343 | except UnicodeDecodeError: |
| 344 | # Skip lines with decode errors |
| 345 | pass |
| 346 | |
| 347 | time.sleep(0.01) # Small delay to prevent busy-waiting |
| 348 |