system_state.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. SystemState - 机器人系统状态
  3. 存储机器人自身的状态信息,如电量、位置、任务等
  4. """
  5. from __future__ import annotations
  6. from dataclasses import dataclass, field
  7. from enum import Enum
  8. import time
  9. class RobotMode(Enum):
  10. """机器人模式枚举"""
  11. IDLE = "idle"
  12. WORKING = "working"
  13. CHARGING = "charging"
  14. ERROR = "error"
  15. MAINTENANCE = "maintenance"
  16. @dataclass
  17. class SystemState:
  18. """
  19. 系统状态类
  20. Attributes:
  21. battery: 电量 (0-100)
  22. position: 位置 [x, y, z]
  23. mode: 当前模式
  24. current_task: 当前任务
  25. error_code: 错误码 (0 表示无错误)
  26. timestamp: 状态时间戳
  27. """
  28. battery: float = 100.0
  29. position: list = field(default_factory=lambda: [0.0, 0.0, 0.0])
  30. mode: str = "idle"
  31. current_task: str = ""
  32. error_code: int = 0
  33. timestamp: float = field(default_factory=time.time)
  34. def update(self, new_data: dict, current_time: float | None = None) -> dict:
  35. """
  36. 更新系统状态,返回变化部分
  37. Args:
  38. new_data: 新数据字典
  39. current_time: 当前时间戳
  40. Returns:
  41. 变化的数据字典
  42. """
  43. if current_time is None:
  44. current_time = time.time()
  45. diff = {}
  46. for key, value in new_data.items():
  47. if hasattr(self, key):
  48. old_value = getattr(self, key)
  49. if old_value != value:
  50. diff[key] = {'old': old_value, 'new': value}
  51. setattr(self, key, value)
  52. self.timestamp = current_time
  53. return diff
  54. def to_dict(self) -> dict:
  55. """转换为字典"""
  56. return {
  57. 'battery': self.battery,
  58. 'position': self.position,
  59. 'mode': self.mode,
  60. 'current_task': self.current_task,
  61. 'error_code': self.error_code,
  62. 'timestamp': self.timestamp,
  63. }
  64. @classmethod
  65. def from_dict(cls, data: dict) -> SystemState:
  66. """从字典创建"""
  67. return cls(
  68. battery=data.get('battery', 100.0),
  69. position=data.get('position', [0.0, 0.0, 0.0]),
  70. mode=data.get('mode', 'idle'),
  71. current_task=data.get('current_task', ''),
  72. error_code=data.get('error_code', 0),
  73. timestamp=data.get('timestamp', time.time()),
  74. )