conson-xp 1.48.0__py3-none-any.whl → 1.50.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,335 +0,0 @@
1
- """
2
- Conbus Protocol for XP telegram communication.
3
-
4
- This module implements the Twisted protocol for Conbus communication.
5
- """
6
-
7
- import logging
8
- from typing import Any, Optional
9
-
10
- from twisted.internet import protocol
11
- from twisted.internet.base import DelayedCall
12
- from twisted.internet.interfaces import IAddress, IConnector
13
- from twisted.internet.posixbase import PosixReactorBase
14
- from twisted.python.failure import Failure
15
-
16
- from xp.models import ConbusClientConfig
17
- from xp.models.protocol.conbus_protocol import (
18
- TelegramReceivedEvent,
19
- )
20
- from xp.models.telegram.system_function import SystemFunction
21
- from xp.models.telegram.telegram_type import TelegramType
22
- from xp.utils import calculate_checksum
23
-
24
-
25
- class ConbusProtocol(protocol.Protocol, protocol.ClientFactory):
26
- """
27
- Twisted protocol for XP telegram communication.
28
-
29
- Attributes:
30
- buffer: Buffer for incoming telegram data.
31
- logger: Logger instance for this protocol.
32
- cli_config: Conbus configuration settings.
33
- reactor: Twisted reactor instance.
34
- timeout_seconds: Timeout duration in seconds.
35
- timeout_call: Delayed call handle for timeout management.
36
- """
37
-
38
- buffer: bytes
39
-
40
- def __init__(
41
- self,
42
- cli_config: ConbusClientConfig,
43
- reactor: PosixReactorBase,
44
- ) -> None:
45
- """
46
- Initialize ConbusProtocol.
47
-
48
- Args:
49
- cli_config: Configuration for Conbus client connection.
50
- reactor: Twisted reactor for event handling.
51
- """
52
- self.buffer = b""
53
- self.logger = logging.getLogger(__name__)
54
- self.cli_config = cli_config.conbus
55
- self.reactor = reactor
56
- self.timeout_seconds = self.cli_config.timeout
57
- self.timeout_call: Optional[DelayedCall] = None
58
-
59
- def connectionMade(self) -> None:
60
- """
61
- Handle connection established event.
62
-
63
- Called when TCP connection is successfully established. Starts inactivity
64
- timeout monitoring.
65
- """
66
- self.logger.debug("connectionMade")
67
- self.connection_established()
68
- # Start inactivity timeout
69
- self._reset_timeout()
70
-
71
- def dataReceived(self, data: bytes) -> None:
72
- """
73
- Handle received data from TCP connection.
74
-
75
- Parses incoming telegram frames and dispatches events.
76
-
77
- Args:
78
- data: Raw bytes received from connection.
79
- """
80
- self.logger.debug("dataReceived")
81
- self.buffer += data
82
-
83
- while True:
84
- start = self.buffer.find(b"<")
85
- if start == -1:
86
- break
87
-
88
- end = self.buffer.find(b">", start)
89
- if end == -1:
90
- break
91
-
92
- # <S0123450001F02D12FK>
93
- # <R0123450001F02D12FK>
94
- # <E12L01I08MAK>
95
- frame = self.buffer[start : end + 1] # <S0123450001F02D12FK>
96
- self.buffer = self.buffer[end + 1 :]
97
- telegram = frame[1:-1] # S0123450001F02D12FK
98
- telegram_type = telegram[0:1].decode() # S
99
- payload = telegram[:-2] # S0123450001F02D12
100
- checksum = telegram[-2:].decode() # FK
101
- serial_number = (
102
- telegram[1:11] if telegram_type in ("S", "R") else b""
103
- ) # 0123450001
104
- calculated_checksum = calculate_checksum(payload.decode(encoding="latin-1"))
105
-
106
- checksum_valid = checksum == calculated_checksum
107
- if not checksum_valid:
108
- self.logger.debug(
109
- f"Invalid checksum: {checksum}, calculated: {calculated_checksum}"
110
- )
111
-
112
- self.logger.debug(
113
- f"frameReceived payload: {payload.decode('latin-1')}, checksum: {checksum}"
114
- )
115
-
116
- # Reset timeout on activity
117
- self._reset_timeout()
118
-
119
- telegram_received = TelegramReceivedEvent(
120
- protocol=self,
121
- frame=frame.decode("latin-1"),
122
- telegram=telegram.decode("latin-1"),
123
- payload=payload.decode("latin-1"),
124
- telegram_type=telegram_type,
125
- serial_number=serial_number,
126
- checksum=checksum,
127
- checksum_valid=checksum_valid,
128
- )
129
- self.telegram_received(telegram_received)
130
-
131
- def sendFrame(self, data: bytes) -> None:
132
- """
133
- Send telegram frame.
134
-
135
- Args:
136
- data: Raw telegram payload (without checksum/framing).
137
-
138
- Raises:
139
- IOError: If transport is not open.
140
- """
141
- # Calculate full frame (add checksum and brackets)
142
- checksum = calculate_checksum(data.decode())
143
- frame_data = data.decode() + checksum
144
- frame = b"<" + frame_data.encode() + b">"
145
-
146
- if not self.transport:
147
- self.logger.info("Invalid transport")
148
- raise IOError("Transport is not open")
149
-
150
- self.logger.debug(f"Sending frame: {frame.decode()}")
151
- self.transport.write(frame) # type: ignore
152
- self.telegram_sent(frame.decode())
153
- self._reset_timeout()
154
-
155
- def send_telegram(
156
- self,
157
- telegram_type: TelegramType,
158
- serial_number: str,
159
- system_function: SystemFunction,
160
- data_value: str,
161
- ) -> None:
162
- """
163
- Send telegram with specified parameters.
164
-
165
- Args:
166
- telegram_type: Type of telegram to send.
167
- serial_number: Device serial number.
168
- system_function: System function code.
169
- data_value: Data value to send.
170
- """
171
- payload = (
172
- f"{telegram_type.value}"
173
- f"{serial_number}"
174
- f"F{system_function.value}"
175
- f"D{data_value}"
176
- )
177
- self.sendFrame(payload.encode())
178
-
179
- def buildProtocol(self, addr: IAddress) -> protocol.Protocol:
180
- """
181
- Build protocol instance for connection.
182
-
183
- Args:
184
- addr: Address of the connection.
185
-
186
- Returns:
187
- Protocol instance for this connection.
188
- """
189
- self.logger.debug(f"buildProtocol: {addr}")
190
- return self
191
-
192
- def clientConnectionFailed(self, connector: IConnector, reason: Failure) -> None:
193
- """
194
- Handle client connection failure.
195
-
196
- Args:
197
- connector: Connection connector instance.
198
- reason: Failure reason details.
199
- """
200
- self.logger.debug(f"clientConnectionFailed: {reason}")
201
- self.connection_failed(reason)
202
- self._cancel_timeout()
203
- self._stop_reactor()
204
-
205
- def clientConnectionLost(self, connector: IConnector, reason: Failure) -> None:
206
- """
207
- Handle client connection lost event.
208
-
209
- Args:
210
- connector: Connection connector instance.
211
- reason: Reason for connection loss.
212
- """
213
- self.logger.debug(f"clientConnectionLost: {reason}")
214
- self.connection_lost(reason)
215
- self._cancel_timeout()
216
- self._stop_reactor()
217
-
218
- def timeout(self) -> bool:
219
- """
220
- Handle timeout event.
221
-
222
- Returns:
223
- True to continue waiting for next timeout, False to stop.
224
- """
225
- self.logger.info("Timeout after: %ss", self.timeout_seconds)
226
- self.failed(f"Timeout after: {self.timeout_seconds}s")
227
- return False
228
-
229
- def connection_failed(self, reason: Failure) -> None:
230
- """
231
- Handle connection failure.
232
-
233
- Args:
234
- reason: Failure reason details.
235
- """
236
- self.logger.debug(f"Client connection failed: {reason}")
237
- self.failed(reason.getErrorMessage())
238
-
239
- def _reset_timeout(self) -> None:
240
- """Reset the inactivity timeout."""
241
- self._cancel_timeout()
242
- self.timeout_call = self.reactor.callLater(
243
- self.timeout_seconds, self._on_timeout
244
- )
245
-
246
- def _cancel_timeout(self) -> None:
247
- """Cancel the inactivity timeout."""
248
- if self.timeout_call and self.timeout_call.active():
249
- self.timeout_call.cancel()
250
-
251
- def _on_timeout(self) -> None:
252
- """Handle inactivity timeout expiration."""
253
- self.logger.debug(f"Conbus timeout after {self.timeout_seconds} seconds")
254
- continue_work = self.timeout()
255
- if not continue_work:
256
- self._stop_reactor()
257
-
258
- def _stop_reactor(self) -> None:
259
- """Stop the reactor if it's running."""
260
- if self.reactor.running:
261
- self.logger.info("Stopping reactor")
262
- self.reactor.stop()
263
-
264
- def start_reactor(self) -> None:
265
- """Start the reactor if it's running."""
266
- # Connect to TCP server
267
- self.logger.info(
268
- f"Connecting to TCP server {self.cli_config.ip}:{self.cli_config.port}"
269
- )
270
- self.reactor.connectTCP(self.cli_config.ip, self.cli_config.port, self)
271
-
272
- # Run the reactor (which now uses asyncio underneath)
273
- self.logger.info("Starting reactor event loop.")
274
- self.reactor.run()
275
-
276
- def __enter__(self) -> "ConbusProtocol":
277
- """
278
- Enter context manager.
279
-
280
- Returns:
281
- Self for context management.
282
- """
283
- return self
284
-
285
- def __exit__(
286
- self,
287
- _exc_type: Optional[type],
288
- _exc_val: Optional[BaseException],
289
- _exc_tb: Optional[Any],
290
- ) -> None:
291
- """Context manager exit - ensure connection is closed."""
292
- self.logger.debug("Exiting the event loop.")
293
- self._stop_reactor()
294
-
295
- """Override methods."""
296
-
297
- def telegram_sent(self, telegram_sent: str) -> None:
298
- """
299
- Override callback when telegram has been sent.
300
-
301
- Args:
302
- telegram_sent: The telegram that was sent.
303
- """
304
- pass
305
-
306
- def telegram_received(self, telegram_received: TelegramReceivedEvent) -> None:
307
- """
308
- Override callback when telegram is received.
309
-
310
- Args:
311
- telegram_received: Event containing received telegram details.
312
- """
313
- pass
314
-
315
- def connection_established(self) -> None:
316
- """Override callback when connection established."""
317
- pass
318
-
319
- def connection_lost(self, reason: Failure) -> None:
320
- """
321
- Override callback when connection is lost.
322
-
323
- Args:
324
- reason: Reason for connection loss.
325
- """
326
- pass
327
-
328
- def failed(self, message: str) -> None:
329
- """
330
- Override callback when connection failed.
331
-
332
- Args:
333
- message: Error message describing the failure.
334
- """
335
- pass