conson-xp 1.18.0__py3-none-any.whl → 1.20.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,51 +1,55 @@
1
1
  """Conbus Receive Service for receiving telegrams from Conbus servers.
2
2
 
3
- This service uses ConbusProtocol to provide receive-only functionality,
3
+ This service uses ConbusEventProtocol to provide receive-only functionality,
4
4
  allowing clients to receive waiting event telegrams using empty telegram sends.
5
5
  """
6
6
 
7
+ import asyncio
7
8
  import logging
8
- from typing import Callable, Optional
9
+ from typing import Any, Callable, Optional
9
10
 
10
- from twisted.internet.posixbase import PosixReactorBase
11
-
12
- from xp.models import ConbusClientConfig
13
11
  from xp.models.conbus.conbus_receive import ConbusReceiveResponse
14
12
  from xp.models.protocol.conbus_protocol import TelegramReceivedEvent
15
- from xp.services.protocol import ConbusProtocol
13
+ from xp.services.protocol.conbus_event_protocol import ConbusEventProtocol
16
14
 
17
15
 
18
- class ConbusReceiveService(ConbusProtocol):
16
+ class ConbusReceiveService:
19
17
  """
20
18
  Service for receiving telegrams from Conbus servers.
21
19
 
22
- Uses ConbusProtocol to provide receive-only functionality
20
+ Uses ConbusEventProtocol to provide receive-only functionality
23
21
  for collecting waiting event telegrams from the server.
22
+
23
+ Attributes:
24
+ conbus_protocol: Protocol instance for Conbus communication.
24
25
  """
25
26
 
26
- def __init__(
27
- self,
28
- cli_config: ConbusClientConfig,
29
- reactor: PosixReactorBase,
30
- ) -> None:
27
+ conbus_protocol: ConbusEventProtocol
28
+
29
+ def __init__(self, conbus_protocol: ConbusEventProtocol) -> None:
31
30
  """Initialize the Conbus receive service.
32
31
 
33
32
  Args:
34
- cli_config: Conbus client configuration.
35
- reactor: Twisted reactor instance.
33
+ conbus_protocol: ConbusEventProtocol instance.
36
34
  """
37
- super().__init__(cli_config, reactor)
38
35
  self.progress_callback: Optional[Callable[[str], None]] = None
39
36
  self.finish_callback: Optional[Callable[[ConbusReceiveResponse], None]] = None
40
37
  self.receive_response: ConbusReceiveResponse = ConbusReceiveResponse(
41
38
  success=True
42
39
  )
43
40
 
41
+ self.conbus_protocol: ConbusEventProtocol = conbus_protocol
42
+ self.conbus_protocol.on_connection_made.connect(self.connection_made)
43
+ self.conbus_protocol.on_telegram_sent.connect(self.telegram_sent)
44
+ self.conbus_protocol.on_telegram_received.connect(self.telegram_received)
45
+ self.conbus_protocol.on_timeout.connect(self.timeout)
46
+ self.conbus_protocol.on_failed.connect(self.failed)
47
+
44
48
  # Set up logging
45
49
  self.logger = logging.getLogger(__name__)
46
50
 
47
- def connection_established(self) -> None:
48
- """Handle connection established event."""
51
+ def connection_made(self) -> None:
52
+ """Handle connection made event."""
49
53
  self.logger.debug("Connection established, waiting for telegrams.")
50
54
 
51
55
  def telegram_sent(self, telegram_sent: str) -> None:
@@ -70,17 +74,13 @@ class ConbusReceiveService(ConbusProtocol):
70
74
  self.receive_response.received_telegrams = []
71
75
  self.receive_response.received_telegrams.append(telegram_received.frame)
72
76
 
73
- def timeout(self) -> bool:
74
- """Handle timeout event to stop receiving.
75
-
76
- Returns:
77
- False to stop the reactor.
78
- """
79
- self.logger.info("Receive stopped after: %ss", self.timeout_seconds)
77
+ def timeout(self) -> None:
78
+ """Handle timeout event to stop receiving."""
79
+ timeout = self.conbus_protocol.timeout_seconds
80
+ self.logger.info("Receive stopped after: %ss", timeout)
80
81
  self.receive_response.success = True
81
82
  if self.finish_callback:
82
83
  self.finish_callback(self.receive_response)
83
- return False
84
84
 
85
85
  def failed(self, message: str) -> None:
86
86
  """Handle failed connection event.
@@ -94,22 +94,50 @@ class ConbusReceiveService(ConbusProtocol):
94
94
  if self.finish_callback:
95
95
  self.finish_callback(self.receive_response)
96
96
 
97
- def start(
97
+ def init(
98
98
  self,
99
99
  progress_callback: Callable[[str], None],
100
100
  finish_callback: Callable[[ConbusReceiveResponse], None],
101
101
  timeout_seconds: Optional[float] = None,
102
+ event_loop: Optional[asyncio.AbstractEventLoop] = None,
102
103
  ) -> None:
103
- """Run reactor in dedicated thread with its own event loop.
104
+ """Setup callbacks and timeout for receiving telegrams.
104
105
 
105
106
  Args:
106
107
  progress_callback: Callback for each received telegram.
107
108
  finish_callback: Callback when receiving completes.
108
109
  timeout_seconds: Optional timeout in seconds.
110
+ event_loop: Optional event loop to use for async operations.
109
111
  """
110
112
  self.logger.info("Starting receive")
111
113
  if timeout_seconds:
112
- self.timeout_seconds = timeout_seconds
114
+ self.conbus_protocol.timeout_seconds = timeout_seconds
113
115
  self.progress_callback = progress_callback
114
116
  self.finish_callback = finish_callback
115
- self.start_reactor()
117
+
118
+ if event_loop:
119
+ self.conbus_protocol.set_event_loop(event_loop)
120
+
121
+ def start_reactor(self) -> None:
122
+ """Start the reactor."""
123
+ self.conbus_protocol.start_reactor()
124
+
125
+ def __enter__(self) -> "ConbusReceiveService":
126
+ """Enter context manager.
127
+
128
+ Returns:
129
+ Self for context manager protocol.
130
+ """
131
+ # Reset state for singleton reuse
132
+ self.receive_response = ConbusReceiveResponse(success=True)
133
+ return self
134
+
135
+ def __exit__(
136
+ self, _exc_type: Optional[type], _exc_val: Optional[Exception], _exc_tb: Any
137
+ ) -> None:
138
+ """Exit context manager and disconnect signals."""
139
+ self.conbus_protocol.on_connection_made.disconnect(self.connection_made)
140
+ self.conbus_protocol.on_telegram_sent.disconnect(self.telegram_sent)
141
+ self.conbus_protocol.on_telegram_received.disconnect(self.telegram_received)
142
+ self.conbus_protocol.on_timeout.disconnect(self.timeout)
143
+ self.conbus_protocol.on_failed.disconnect(self.failed)
@@ -3,6 +3,7 @@
3
3
  This module implements the Twisted protocol for Conbus communication.
4
4
  """
5
5
 
6
+ import asyncio
6
7
  import logging
7
8
  from queue import SimpleQueue
8
9
  from random import randint
@@ -302,14 +303,21 @@ class ConbusEventProtocol(protocol.Protocol, protocol.ClientFactory):
302
303
  self.logger.info("Stopping reactor")
303
304
  self._reactor.stop()
304
305
 
305
- def start_reactor(self) -> None:
306
- """Start the reactor if it's running."""
307
- # Connect to TCP server
306
+ def connect(self) -> None:
307
+ """Connect to TCP server."""
308
308
  self.logger.info(
309
309
  f"Connecting to TCP server {self.cli_config.ip}:{self.cli_config.port}"
310
310
  )
311
311
  self._reactor.connectTCP(self.cli_config.ip, self.cli_config.port, self)
312
312
 
313
+ def disconnect(self) -> None:
314
+ """Disconnect from TCP server."""
315
+ self.logger.info("Disconnecting TCP server")
316
+ self._reactor.disconnectAll()
317
+
318
+ def start_reactor(self) -> None:
319
+ """Start the reactor if it's running."""
320
+ self.connect()
313
321
  # Run the reactor (which now uses asyncio underneath)
314
322
  self.logger.info("Starting reactor event loop.")
315
323
  self._reactor.run()
@@ -340,6 +348,23 @@ class ConbusEventProtocol(protocol.Protocol, protocol.ClientFactory):
340
348
  later = randint(10, 80) / 100
341
349
  self.call_later(later, self.process_telegram_queue)
342
350
 
351
+ def set_event_loop(self, event_loop: asyncio.AbstractEventLoop) -> None:
352
+ """Change the event loop.
353
+
354
+ Args:
355
+ event_loop: the event loop instance.
356
+ """
357
+ reactor = self._reactor
358
+ if hasattr(reactor, "_asyncioEventloop"):
359
+ reactor._asyncioEventloop = event_loop
360
+
361
+ # Set reactor to running state
362
+ if not reactor.running:
363
+ reactor.running = True
364
+ if hasattr(reactor, "startRunning"):
365
+ reactor.startRunning()
366
+ self.logger.info("Set reactor to running state")
367
+
343
368
  def __enter__(self) -> "ConbusEventProtocol":
344
369
  """Enter context manager.
345
370
 
xp/tui/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """TUI (Terminal User Interface) module for XP."""
xp/tui/app.py ADDED
@@ -0,0 +1,72 @@
1
+ """Protocol Monitor TUI Application."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Optional
5
+
6
+ from textual.app import App, ComposeResult
7
+ from textual.widgets import Footer, Header
8
+
9
+ from xp.tui.widgets.protocol_log import ProtocolLogWidget
10
+
11
+
12
+ class ProtocolMonitorApp(App[None]):
13
+ """Textual app for real-time protocol monitoring.
14
+
15
+ Displays live RX/TX telegram stream from Conbus server in an interactive
16
+ terminal interface with keyboard shortcuts for control.
17
+
18
+ Attributes:
19
+ container: ServiceContainer for dependency injection.
20
+ CSS_PATH: Path to CSS stylesheet file.
21
+ BINDINGS: Keyboard bindings for app actions.
22
+ TITLE: Application title displayed in header.
23
+ """
24
+
25
+ CSS_PATH = Path(__file__).parent / "protocol.tcss"
26
+ TITLE = "Protocol Monitor"
27
+
28
+ BINDINGS = [
29
+ ("q", "quit", "Quit"),
30
+ ("c", "connect", "Connect"),
31
+ ("d", "disconnect", "Disconnect"),
32
+ ("1", "discover", "Discover"),
33
+ ]
34
+
35
+ def __init__(self, container: Any) -> None:
36
+ """Initialize the Protocol Monitor app.
37
+
38
+ Args:
39
+ container: ServiceContainer for resolving services.
40
+ """
41
+ super().__init__()
42
+ self.container = container
43
+ self.protocol_widget: Optional[ProtocolLogWidget] = None
44
+
45
+ def compose(self) -> ComposeResult:
46
+ """Compose the app layout with widgets.
47
+
48
+ Yields:
49
+ Header, ProtocolLogWidget, and Footer widgets.
50
+ """
51
+ yield Header()
52
+ self.protocol_widget = ProtocolLogWidget(container=self.container)
53
+ yield self.protocol_widget
54
+ yield Footer()
55
+
56
+ def action_discover(self) -> None:
57
+ """Send discover telegram on 'D' key press.
58
+
59
+ Sends predefined discover telegram <S0000000000F01D00FA> to the bus.
60
+ """
61
+ if self.protocol_widget:
62
+ self.protocol_widget.send_discover()
63
+
64
+ def action_connect(self) -> None:
65
+ """Connect protocol on 'c' key press."""
66
+ if self.protocol_widget:
67
+ self.protocol_widget.connect()
68
+
69
+ def action_disconnect(self) -> None:
70
+ """Disconnect protocol on 'd' key press."""
71
+ if self.protocol_widget:
72
+ self.protocol_widget.disconnect()
xp/tui/protocol.tcss ADDED
@@ -0,0 +1,50 @@
1
+ /* Protocol Monitor TUI Styling */
2
+
3
+ /* App-level styling */
4
+ Screen {
5
+ background: $background;
6
+ }
7
+
8
+ /* Protocol Log Widget */
9
+ ProtocolLogWidget {
10
+ border: solid $primary;
11
+ height: 1fr;
12
+ background: $surface;
13
+ }
14
+
15
+ ProtocolLogWidget > .connection-status {
16
+ color: $text;
17
+ text-align: center;
18
+ padding: 1;
19
+ }
20
+
21
+ ProtocolLogWidget > .connection-status.connecting {
22
+ color: $warning;
23
+ }
24
+
25
+ ProtocolLogWidget > .connection-status.connected {
26
+ color: $success;
27
+ }
28
+
29
+ ProtocolLogWidget > .connection-status.failed {
30
+ color: $error;
31
+ }
32
+
33
+ /* Message display styling */
34
+ .message-tx {
35
+ color: $success;
36
+ }
37
+
38
+ .message-rx {
39
+ color: $success;
40
+ }
41
+
42
+ .message-frame {
43
+ color: $text-muted;
44
+ }
45
+
46
+ /* Footer styling */
47
+ Footer {
48
+ background: $panel;
49
+ color: $text;
50
+ }
@@ -0,0 +1 @@
1
+ """TUI widgets package."""
@@ -0,0 +1,312 @@
1
+ """Protocol Log Widget for displaying telegram stream."""
2
+
3
+ import asyncio
4
+ import logging
5
+ from enum import Enum
6
+ from typing import Any, Optional
7
+
8
+ from textual.reactive import reactive
9
+ from textual.widget import Widget
10
+ from textual.widgets import RichLog
11
+
12
+ from xp.models.protocol.conbus_protocol import TelegramReceivedEvent
13
+ from xp.services.conbus.conbus_receive_service import ConbusReceiveService
14
+ from xp.services.protocol import ConbusEventProtocol
15
+
16
+
17
+ class ConnectionState(str, Enum):
18
+ """Connection state enumeration.
19
+
20
+ Attributes:
21
+ DISCONNECTED: Not connected to server.
22
+ CONNECTING: Connection in progress.
23
+ CONNECTED: Successfully connected.
24
+ FAILED: Connection failed.
25
+ """
26
+
27
+ DISCONNECTED = "DISCONNECTED"
28
+ CONNECTING = "CONNECTING"
29
+ CONNECTED = "CONNECTED"
30
+ FAILED = "FAILED"
31
+
32
+
33
+ class ProtocolLogWidget(Widget):
34
+ """Widget for displaying protocol telegram stream.
35
+
36
+ Connects to Conbus server via ConbusReceiveService and displays
37
+ live RX/TX telegram stream with color-coded direction markers.
38
+
39
+ Attributes:
40
+ container: ServiceContainer for dependency injection.
41
+ connection_state: Current connection state (reactive).
42
+ protocol: Reference to ConbusEventProtocol (prevents duplicate connections).
43
+ service: ConbusReceiveService instance.
44
+ logger: Logger instance for this widget.
45
+ log_widget: RichLog widget for displaying messages.
46
+ """
47
+
48
+ connection_state = reactive(ConnectionState.DISCONNECTED)
49
+
50
+ def __init__(self, container: Any) -> None:
51
+ """Initialize the Protocol Log widget.
52
+
53
+ Args:
54
+ container: ServiceContainer for resolving services.
55
+ """
56
+ super().__init__()
57
+ self.container = container
58
+ self.protocol: Optional[ConbusEventProtocol] = None
59
+ self.service: Optional[ConbusReceiveService] = None
60
+ self.logger = logging.getLogger(__name__)
61
+ self.log_widget: Optional[RichLog] = None
62
+
63
+ def compose(self) -> Any:
64
+ """Compose the widget layout.
65
+
66
+ Yields:
67
+ RichLog widget for message display.
68
+ """
69
+ self.log_widget = RichLog(highlight=True, markup=True)
70
+ yield self.log_widget
71
+
72
+ async def on_mount(self) -> None:
73
+ """Initialize connection when widget mounts.
74
+
75
+ Delays connection by 0.5s to let UI render first.
76
+ Resolves ConbusReceiveService and connects signals.
77
+ """
78
+ # Resolve service from container (singleton)
79
+ self.service = self.container.resolve(ConbusReceiveService)
80
+ self.protocol = self.service.conbus_protocol
81
+
82
+ # Connect psygnal signals
83
+ self.protocol.on_connection_made.connect(self._on_connection_made)
84
+ self.protocol.on_telegram_received.connect(self._on_telegram_received)
85
+ self.protocol.on_telegram_sent.connect(self._on_telegram_sent)
86
+ self.protocol.on_timeout.connect(self._on_timeout)
87
+ self.protocol.on_failed.connect(self._on_failed)
88
+
89
+ # Delay connection to let UI render
90
+ await asyncio.sleep(0.5)
91
+ await self._start_connection_async()
92
+
93
+ async def _start_connection_async(self) -> None:
94
+ """Start TCP connection to Conbus server (async).
95
+
96
+ Guards against duplicate connections and sets up protocol signals.
97
+ Integrates Twisted reactor with Textual's asyncio loop cleanly.
98
+ """
99
+ # Guard against duplicate connections (race condition)
100
+ if self.service is None:
101
+ self.logger.error("Service not initialized")
102
+ return
103
+
104
+ if self.protocol is None:
105
+ self.logger.error("Protocol not initialized")
106
+ return
107
+
108
+ try:
109
+ # Set state to connecting
110
+ self.connection_state = ConnectionState.CONNECTING
111
+ if self.log_widget:
112
+ self.log_widget.write("[yellow]Connecting to Conbus server...[/yellow]")
113
+
114
+ # Store protocol reference
115
+ self.logger.info(f"Protocol object: {self.protocol}")
116
+ self.logger.info(f"Reactor object: {self.protocol._reactor}")
117
+ self.logger.info(f"Reactor running: {self.protocol._reactor.running}")
118
+
119
+ # Setup service callbacks
120
+ def progress_callback(telegram: str) -> None:
121
+ """Handle progress updates for telegram reception.
122
+
123
+ Args:
124
+ telegram: Received telegram string.
125
+ """
126
+ pass
127
+
128
+ def finish_callback(response: Any) -> None:
129
+ """Handle completion of telegram reception.
130
+
131
+ Args:
132
+ response: Response object from telegram reception.
133
+ """
134
+ pass
135
+
136
+ # Get the currently running asyncio event loop (Textual's loop)
137
+ event_loop = asyncio.get_running_loop()
138
+ self.logger.info(f"Current running loop: {event_loop}")
139
+ self.logger.info(f"Loop is running: {event_loop.is_running()}")
140
+
141
+ self.service.init(
142
+ progress_callback=progress_callback,
143
+ finish_callback=finish_callback,
144
+ timeout_seconds=None, # Continuous monitoring
145
+ event_loop=event_loop,
146
+ )
147
+
148
+ reactor = self.service.conbus_protocol._reactor
149
+ # Schedule the connection on the running asyncio loop
150
+ # This ensures connectTCP is called in the context of the running loop
151
+
152
+ def do_connect() -> None:
153
+ """Execute TCP connection in event loop context."""
154
+ self.logger.info("Executing connectTCP in event loop callback")
155
+ if self.protocol is not None:
156
+ reactor.connectTCP(
157
+ self.protocol.cli_config.ip,
158
+ self.protocol.cli_config.port,
159
+ self.protocol,
160
+ )
161
+
162
+ event_loop.call_soon(do_connect)
163
+ self.logger.info("Scheduled connectTCP on running loop")
164
+
165
+ if self.log_widget:
166
+ self.log_widget.write(
167
+ f"[dim]→ {self.protocol.cli_config.ip}:{self.protocol.cli_config.port}[/dim]"
168
+ )
169
+
170
+ # Wait for connection to establish
171
+ await asyncio.sleep(1.0)
172
+ self.logger.info(f"After 1s - transport: {self.protocol.transport}")
173
+
174
+ except Exception as e:
175
+ self.logger.error(f"Connection failed: {e}")
176
+ self.connection_state = ConnectionState.FAILED
177
+ if self.log_widget:
178
+ self.log_widget.write(f"[red]Connection error: {e}[/red]")
179
+ # Exit app after brief delay
180
+ self.set_timer(2.0, self.app.exit)
181
+
182
+ def _start_connection(self) -> None:
183
+ """Start connection (sync wrapper for async method)."""
184
+ # Use run_worker to run async method from sync context
185
+ self.run_worker(self._start_connection_async(), exclusive=True)
186
+
187
+ def _on_connection_made(self) -> None:
188
+ """Handle connection established signal.
189
+
190
+ Sets state to CONNECTED and displays success message.
191
+ """
192
+ self.connection_state = ConnectionState.CONNECTED
193
+ if self.log_widget:
194
+ self.log_widget.write("[green]Connected to Conbus server[/green]")
195
+ self.log_widget.write("[dim]---[/dim]")
196
+
197
+ def _on_telegram_received(self, event: TelegramReceivedEvent) -> None:
198
+ """Handle telegram received signal.
199
+
200
+ Args:
201
+ event: Telegram received event with frame data.
202
+ """
203
+ if self.log_widget:
204
+ # Display [RX] in green, frame in gray
205
+ self.log_widget.write(f"[green]\\[RX][/green] [dim]{event.frame}[/dim]")
206
+
207
+ def _on_telegram_sent(self, telegram: str) -> None:
208
+ """Handle telegram sent signal.
209
+
210
+ Args:
211
+ telegram: Sent telegram string.
212
+ """
213
+ if self.log_widget:
214
+ # Display [TX] in green, frame in gray
215
+ self.log_widget.write(f"[green]\\[TX][/green] [dim]{telegram}[/dim]")
216
+
217
+ def _on_timeout(self) -> None:
218
+ """Handle timeout signal.
219
+
220
+ Logs timeout but continues monitoring (no action needed).
221
+ """
222
+ self.logger.debug("Timeout occurred (continuous monitoring)")
223
+
224
+ def _on_failed(self, error: str) -> None:
225
+ """Handle connection failed signal.
226
+
227
+ Args:
228
+ error: Error message describing the failure.
229
+ """
230
+ self.connection_state = ConnectionState.FAILED
231
+ self.logger.error(f"Connection failed: {error}")
232
+
233
+ if self.log_widget:
234
+ self.log_widget.write(f"[red]Connection failed: {error}[/red]")
235
+
236
+ # Exit app after brief delay to show error
237
+ self.set_timer(2.0, self.app.exit)
238
+
239
+ def connect(self) -> None:
240
+ """Connect to Conbus server."""
241
+ self._start_connection()
242
+
243
+ def disconnect(self) -> None:
244
+ """Disconnect from Conbus server."""
245
+ if self.protocol:
246
+ self.protocol.disconnect()
247
+
248
+ def send_discover(self) -> None:
249
+ """Send discover telegram.
250
+
251
+ Sends predefined discover telegram <S0000000000F01D00FA> to the bus.
252
+ Called when user presses 'd' key.
253
+ """
254
+ if self.protocol is None:
255
+ self.logger.warning("Cannot send discover: not connected")
256
+ if self.log_widget:
257
+ self.log_widget.write(
258
+ "[yellow]Not connected, cannot send discover[/yellow]"
259
+ )
260
+ return
261
+
262
+ try:
263
+ # Send discover telegram
264
+ # Note: The telegram includes framing <>, but protocol may add it
265
+ # Check if protocol expects with or without brackets
266
+ from xp.models.telegram.system_function import SystemFunction
267
+ from xp.models.telegram.telegram_type import TelegramType
268
+
269
+ # Send discover: S 0000000000 F01 D00
270
+ self.protocol.send_telegram(
271
+ telegram_type=TelegramType.SYSTEM,
272
+ serial_number="0000000000",
273
+ system_function=SystemFunction.DISCOVERY,
274
+ data_value="00",
275
+ )
276
+
277
+ if self.log_widget:
278
+ self.log_widget.write("[yellow]Discover telegram sent[/yellow]")
279
+
280
+ except Exception as e:
281
+ self.logger.error(f"Failed to send discover: {e}")
282
+ if self.log_widget:
283
+ self.log_widget.write(f"[red]Failed to send discover: {e}[/red]")
284
+
285
+ def on_unmount(self) -> None:
286
+ """Clean up when widget unmounts.
287
+
288
+ Disconnects signals and closes transport connection.
289
+ """
290
+ if self.protocol is not None:
291
+ try:
292
+ # Disconnect all signals
293
+ self.protocol.on_connection_made.disconnect(self._on_connection_made)
294
+ self.protocol.on_telegram_received.disconnect(
295
+ self._on_telegram_received
296
+ )
297
+ self.protocol.on_telegram_sent.disconnect(self._on_telegram_sent)
298
+ self.protocol.on_timeout.disconnect(self._on_timeout)
299
+ self.protocol.on_failed.disconnect(self._on_failed)
300
+
301
+ # Close transport if connected
302
+ if self.protocol.transport:
303
+ self.protocol.disconnect()
304
+
305
+ # Reset protocol reference
306
+ self.protocol = None
307
+
308
+ # Set state to disconnected
309
+ self.connection_state = ConnectionState.DISCONNECTED
310
+
311
+ except Exception as e:
312
+ self.logger.error(f"Error during cleanup: {e}")