__init__.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. """
  2. Trixy Satellite Management System
  3. This module provides comprehensive satellite (client) management for the Trixy application.
  4. It includes satellite registration, connection management, status monitoring, and advanced
  5. access patterns for managing multiple satellites simultaneously.
  6. The satellite management system implements the architecture specified in CLAUDE.md:
  7. - SatelliteManager: Central management of all registered satellites
  8. - Satellite: Individual satellite representation and control
  9. - Registration system: MAC-based registration file management
  10. - Query system: Advanced satellite filtering and selection
  11. - Event integration: Full integration with the event system
  12. - Network integration: Socket management and communication
  13. Key Features:
  14. - Thread-safe operations for multi-satellite support
  15. - Advanced access patterns (index, query-based, bulk operations)
  16. - Connection state management (registered, not connected, connected)
  17. - Satellite registration and blacklist management
  18. - Integration with existing event and network systems
  19. - Comprehensive logging and error handling
  20. Usage Example:
  21. from trixy_core.satellites import SatelliteManager, Satellite
  22. # Create satellite manager (usually via application container)
  23. satellite_manager = SatelliteManager(application)
  24. # Access satellites
  25. satellite = satellite_manager[0] # Direct index access
  26. satellites = satellite_manager["status=connected,room=kitchen"] # Query-based
  27. # Bulk operations
  28. satellite_manager.disconnect_all("room=living_room")
  29. satellite_manager.say_all("Hello everyone!", "status=connected")
  30. # Individual satellite operations
  31. satellite.say("Hello from the kitchen!")
  32. status = satellite.get_status()
  33. satellite.disconnect()
  34. """
  35. from .satellite_manager import (
  36. SatelliteManager,
  37. SatelliteManagerError,
  38. SatelliteNotFoundError,
  39. SatelliteRegistrationError,
  40. SatelliteConnectionError,
  41. ConnectionState,
  42. SatelliteStats,
  43. )
  44. from .satellite import (
  45. Satellite,
  46. SatelliteError,
  47. SatelliteStatus,
  48. SatelliteCapability,
  49. AudioPortInfo,
  50. SatelliteInfo,
  51. )
  52. from .registration import (
  53. SatelliteRegistration,
  54. RegistrationManager,
  55. RegistrationError,
  56. RegistrationStatus,
  57. BlacklistEntry,
  58. BlacklistManager,
  59. )
  60. from .query_parser import (
  61. QueryParser,
  62. QueryError,
  63. QueryCondition,
  64. QueryOperator,
  65. parse_query,
  66. validate_query,
  67. )
  68. # Version information
  69. __version__ = "1.0.0"
  70. __author__ = "Trixy Development Team"
  71. # Public API
  72. __all__ = [
  73. # Core classes
  74. "SatelliteManager",
  75. "Satellite",
  76. "SatelliteRegistration",
  77. "RegistrationManager",
  78. "BlacklistManager",
  79. "QueryParser",
  80. # Exception classes
  81. "SatelliteManagerError",
  82. "SatelliteNotFoundError",
  83. "SatelliteRegistrationError",
  84. "SatelliteConnectionError",
  85. "SatelliteError",
  86. "RegistrationError",
  87. "QueryError",
  88. # Enums and data classes
  89. "ConnectionState",
  90. "SatelliteStatus",
  91. "SatelliteCapability",
  92. "RegistrationStatus",
  93. "QueryOperator",
  94. "SatelliteStats",
  95. "AudioPortInfo",
  96. "SatelliteInfo",
  97. "BlacklistEntry",
  98. "QueryCondition",
  99. # Utility functions
  100. "parse_query",
  101. "validate_query",
  102. ]
  103. def pprint(message: str) -> None:
  104. """
  105. Satellite system logging function.
  106. This uses the same pattern as specified in CLAUDE.md.
  107. """
  108. print(f"[SATELLITES] {message}")
  109. def create_satellite_manager(application, **kwargs) -> SatelliteManager:
  110. """
  111. Convenience function to create a SatelliteManager instance.
  112. Args:
  113. application: Application container instance
  114. **kwargs: Additional arguments for SatelliteManager
  115. Returns:
  116. SatelliteManager: Configured satellite manager
  117. """
  118. return SatelliteManager(application, **kwargs)
  119. def get_supported_query_operators():
  120. """
  121. Get a list of all supported query operators.
  122. Returns:
  123. List[QueryOperator]: All supported query operators
  124. """
  125. return list(QueryOperator)
  126. def get_supported_satellite_capabilities():
  127. """
  128. Get a list of all supported satellite capabilities.
  129. Returns:
  130. List[SatelliteCapability]: All supported capabilities
  131. """
  132. return list(SatelliteCapability)
  133. def validate_mac_address(mac_address: str) -> bool:
  134. """
  135. Validate a MAC address format.
  136. Args:
  137. mac_address: MAC address to validate
  138. Returns:
  139. bool: True if valid, False otherwise
  140. """
  141. if not isinstance(mac_address, str):
  142. return False
  143. parts = mac_address.split(':')
  144. if len(parts) != 6:
  145. return False
  146. for part in parts:
  147. if len(part) != 2:
  148. return False
  149. try:
  150. int(part, 16)
  151. except ValueError:
  152. return False
  153. return True
  154. def normalize_mac_address(mac_address: str) -> str:
  155. """
  156. Normalize a MAC address to lowercase with colons.
  157. Args:
  158. mac_address: MAC address to normalize
  159. Returns:
  160. str: Normalized MAC address
  161. Raises:
  162. ValueError: If MAC address is invalid
  163. """
  164. if not validate_mac_address(mac_address):
  165. raise ValueError(f"Invalid MAC address format: {mac_address}")
  166. return mac_address.lower()
  167. def get_satellite_documentation():
  168. """
  169. Get documentation for satellite management system.
  170. Returns:
  171. Dict[str, str]: Documentation mapping
  172. """
  173. return {
  174. "satellite_manager": "Central management system for all registered satellites",
  175. "satellite": "Individual satellite representation with control methods",
  176. "registration": "MAC-based registration file management system",
  177. "query_parser": "Advanced query system for satellite filtering and selection",
  178. "connection_states": "registered, not_connected, connected, error",
  179. "access_patterns": "Direct index, query-based, bulk operations",
  180. "integration": "Full integration with event and network systems",
  181. }
  182. # Initialize logging for the module
  183. def _init_satellite_logging():
  184. """Initialize logging for the satellite management system."""
  185. # This will be enhanced when integrated with proper logging system
  186. pass
  187. # Initialize the module
  188. _init_satellite_logging()
  189. # Module-level configuration
  190. SATELLITE_CONFIG_DEFAULTS = {
  191. "max_satellites": 50,
  192. "registration_timeout": 60.0,
  193. "connection_timeout": 30.0,
  194. "heartbeat_interval": 30.0,
  195. "max_reconnect_attempts": 3,
  196. "registration_file_dir": "config/satellites",
  197. "blacklist_file": "config/satellites/blacklist.json",
  198. "enable_auto_registration": False,
  199. "default_audio_ports": {
  200. "raw_input": 2102,
  201. "raw_output": 2103,
  202. "music_output": 2104,
  203. }
  204. }
  205. def get_satellite_config_defaults():
  206. """
  207. Get default configuration values for satellite management.
  208. Returns:
  209. Dict[str, Any]: Default configuration values
  210. """
  211. return SATELLITE_CONFIG_DEFAULTS.copy()
  212. # Convenience function for quick satellite manager setup
  213. def setup_satellite_system(
  214. application,
  215. registration_dir: str = None,
  216. max_satellites: int = 50,
  217. enable_auto_registration: bool = False
  218. ) -> SatelliteManager:
  219. """
  220. Set up a complete satellite management system with reasonable defaults.
  221. Args:
  222. application: Application container instance
  223. registration_dir: Directory for registration files
  224. max_satellites: Maximum number of satellites
  225. enable_auto_registration: Enable automatic registration
  226. Returns:
  227. SatelliteManager: Configured and ready-to-use satellite manager
  228. """
  229. satellite_manager = SatelliteManager(
  230. application,
  231. registration_dir=registration_dir,
  232. max_satellites=max_satellites,
  233. enable_auto_registration=enable_auto_registration
  234. )
  235. pprint(f"Satellite system initialized (max: {max_satellites}, auto_reg: {enable_auto_registration})")
  236. return satellite_manager
  237. # Export additional utility functions
  238. __all__.extend([
  239. "create_satellite_manager",
  240. "get_supported_query_operators",
  241. "get_supported_satellite_capabilities",
  242. "validate_mac_address",
  243. "normalize_mac_address",
  244. "get_satellite_documentation",
  245. "get_satellite_config_defaults",
  246. "setup_satellite_system",
  247. "pprint",
  248. ])