__init__.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. """
  2. Trixy Network System
  3. This module provides the complete network protocol implementation for the Trixy
  4. voice assistant system. It includes:
  5. - Custom Trixy Protocol implementation (binary streaming, not HTTP/REST)
  6. - Command socket management (Port 2101)
  7. - Audio streaming sockets (Ports 2102, 2103, 2104)
  8. - Multi-client support with thread safety
  9. - Serializable command classes for network communication
  10. - Server and client socket handling
  11. - Integration with event system and application container
  12. The network system implements the specifications from CLAUDE.md:
  13. - Binary streaming protocol with magic number "TRXI"
  14. - Message structure with version, datetime, option flags, MD5 checksum
  15. - Support for serialized Python classes and dictionaries
  16. - Hard-coded performance commands (TRXINOOP, TRXIPING, etc.)
  17. - Multi-socket architecture for different data types
  18. Usage:
  19. from trixy_core.network import NetworkManager, TrixyProtocol, TrixyMessage
  20. # Create network manager
  21. network_manager = NetworkManager(application_container)
  22. # Start server mode
  23. network_manager.start_server(command_port=2101)
  24. # Or start client mode
  25. network_manager.connect_to_server("192.168.1.100", 2101)
  26. # Send commands
  27. from trixy_core.network.cmd import SatelliteHelloCommand
  28. cmd = SatelliteHelloCommand(room="kitchen", alias="main")
  29. network_manager.send_command(cmd)
  30. """
  31. from .protocol import (
  32. # Core protocol classes
  33. TrixyProtocol,
  34. TrixyMessage,
  35. MessageOptions,
  36. MessageFlags,
  37. ProtocolVersion,
  38. # Protocol exceptions
  39. ProtocolError,
  40. InvalidMessageError,
  41. ChecksumMismatchError,
  42. UnsupportedVersionError,
  43. # Serialization utilities
  44. serialize_object,
  45. deserialize_object,
  46. calculate_checksum,
  47. compress_data,
  48. decompress_data,
  49. )
  50. from .network_manager import (
  51. # Main network manager
  52. NetworkManager,
  53. NetworkManagerError,
  54. # Connection management
  55. ConnectionManager,
  56. ConnectionState,
  57. ConnectionInfo,
  58. # Audio streaming
  59. AudioStreamManager,
  60. AudioStreamType,
  61. AudioStreamConfig,
  62. )
  63. from .server_socket import (
  64. # Server-side networking
  65. TrixyServer,
  66. ServerSocketHandler,
  67. ClientConnection,
  68. # Server exceptions
  69. ServerError,
  70. PortInUseError,
  71. ClientConnectionError,
  72. )
  73. from .client_socket import (
  74. # Client-side networking
  75. TrixyClient,
  76. ClientSocketHandler,
  77. ConnectionAttempt,
  78. # Client exceptions
  79. ClientError,
  80. ConnectionFailedError,
  81. AuthenticationError,
  82. )
  83. # Command classes - imported from cmd package
  84. from .cmd import (
  85. # Base command class
  86. TrixyCommand,
  87. CommandResponse,
  88. # Hard-coded commands
  89. NoOpCommand,
  90. PingCommand,
  91. PongCommand,
  92. PrintCommand,
  93. HelloCommand,
  94. # Satellite commands
  95. SatelliteHelloCommand,
  96. SatelliteRegistrationCommand,
  97. SatelliteConnectionCommand,
  98. SatelliteDisconnectCommand,
  99. # Wakeword commands
  100. WakewordDetectedCommand,
  101. WakewordConfigCommand,
  102. # Audio commands
  103. AudioStreamStartCommand,
  104. AudioStreamStopCommand,
  105. AudioDataCommand,
  106. # Configuration commands
  107. ConfigUpdateCommand,
  108. ConfigRequestCommand,
  109. # Status commands
  110. StatusRequestCommand,
  111. HealthCheckCommand,
  112. )
  113. # Network constants
  114. DEFAULT_COMMAND_PORT = 2101
  115. DEFAULT_AUDIO_INPUT_PORT = 2102
  116. DEFAULT_AUDIO_OUTPUT_PORT = 2103
  117. DEFAULT_MUSIC_PORT = 2104
  118. PROTOCOL_MAGIC = b"TRXI"
  119. PROTOCOL_VERSION_MAJOR = 1
  120. PROTOCOL_VERSION_MINOR = 0
  121. PROTOCOL_VERSION_REVISION = 0
  122. # Hard-coded command strings for performance optimization
  123. HARDCODED_COMMANDS = {
  124. "TRXINOOP": "no_op",
  125. "TRXIPING": "ping",
  126. "TRXIPONG": "pong",
  127. "TRXIPRNT": "print",
  128. "TRXYHELO": "hello",
  129. }
  130. # Version information
  131. __version__ = "1.0.0"
  132. __author__ = "Trixy Development Team"
  133. # Public API
  134. __all__ = [
  135. # Core protocol
  136. "TrixyProtocol",
  137. "TrixyMessage",
  138. "MessageOptions",
  139. "MessageFlags",
  140. "ProtocolVersion",
  141. # Network management
  142. "NetworkManager",
  143. "NetworkManagerError",
  144. "ConnectionManager",
  145. "ConnectionState",
  146. "ConnectionInfo",
  147. # Audio streaming
  148. "AudioStreamManager",
  149. "AudioStreamType",
  150. "AudioStreamConfig",
  151. # Server components
  152. "TrixyServer",
  153. "ServerSocketHandler",
  154. "ClientConnection",
  155. # Client components
  156. "TrixyClient",
  157. "ClientSocketHandler",
  158. "ConnectionAttempt",
  159. # Commands
  160. "TrixyCommand",
  161. "CommandResponse",
  162. "NoOpCommand",
  163. "PingCommand",
  164. "PongCommand",
  165. "PrintCommand",
  166. "HelloCommand",
  167. "SatelliteHelloCommand",
  168. "SatelliteRegistrationCommand",
  169. "SatelliteConnectionCommand",
  170. "SatelliteDisconnectCommand",
  171. "WakewordDetectedCommand",
  172. "WakewordConfigCommand",
  173. "AudioStreamStartCommand",
  174. "AudioStreamStopCommand",
  175. "AudioDataCommand",
  176. "ConfigUpdateCommand",
  177. "ConfigRequestCommand",
  178. "StatusRequestCommand",
  179. "HealthCheckCommand",
  180. # Protocol utilities
  181. "serialize_object",
  182. "deserialize_object",
  183. "calculate_checksum",
  184. "compress_data",
  185. "decompress_data",
  186. # Exceptions
  187. "ProtocolError",
  188. "InvalidMessageError",
  189. "ChecksumMismatchError",
  190. "UnsupportedVersionError",
  191. "ServerError",
  192. "PortInUseError",
  193. "ClientConnectionError",
  194. "ClientError",
  195. "ConnectionFailedError",
  196. "AuthenticationError",
  197. # Constants
  198. "DEFAULT_COMMAND_PORT",
  199. "DEFAULT_AUDIO_INPUT_PORT",
  200. "DEFAULT_AUDIO_OUTPUT_PORT",
  201. "DEFAULT_MUSIC_PORT",
  202. "PROTOCOL_MAGIC",
  203. "PROTOCOL_VERSION_MAJOR",
  204. "PROTOCOL_VERSION_MINOR",
  205. "PROTOCOL_VERSION_REVISION",
  206. "HARDCODED_COMMANDS",
  207. ]
  208. def pprint(message: str) -> None:
  209. """
  210. Network module logging function that adapts based on mode.
  211. Uses the same pattern as specified in CLAUDE.md.
  212. """
  213. # For now use simple printing - will integrate with proper logging
  214. print(f"[NETWORK] {message}")
  215. def create_default_network_manager(application_container):
  216. """
  217. Create a NetworkManager with default configuration.
  218. Args:
  219. application_container: The main application container
  220. Returns:
  221. NetworkManager: Configured network manager instance
  222. """
  223. return NetworkManager(application_container)
  224. def get_protocol_version() -> ProtocolVersion:
  225. """
  226. Get the current protocol version.
  227. Returns:
  228. ProtocolVersion: Current protocol version
  229. """
  230. return ProtocolVersion(
  231. major=PROTOCOL_VERSION_MAJOR,
  232. minor=PROTOCOL_VERSION_MINOR,
  233. revision=PROTOCOL_VERSION_REVISION
  234. )
  235. def validate_port(port: int) -> bool:
  236. """
  237. Validate if a port number is valid for the Trixy protocol.
  238. Args:
  239. port: Port number to validate
  240. Returns:
  241. bool: True if port is valid
  242. """
  243. return 1024 <= port <= 65535
  244. def get_default_ports() -> dict:
  245. """
  246. Get the default port configuration.
  247. Returns:
  248. dict: Default port mappings
  249. """
  250. return {
  251. "command": DEFAULT_COMMAND_PORT,
  252. "audio_input": DEFAULT_AUDIO_INPUT_PORT,
  253. "audio_output": DEFAULT_AUDIO_OUTPUT_PORT,
  254. "music": DEFAULT_MUSIC_PORT,
  255. }
  256. # Initialize logging
  257. def _init_logging():
  258. """Initialize logging for the network module."""
  259. # This will be enhanced when integrated with the main logging system
  260. pass
  261. # Initialize the module
  262. _init_logging()
  263. pprint("Network module initialized")