TcpClient¶
- class lsst.ts.m2com.TcpClient(host: str, port: int, callback_process_message: Callable[[...], Coroutine], *args: Any, log: Logger | None = None, sequence_generator: Generator | None = None, name: str = 'tcp-client', check_message_rate: bool = False)¶
Bases:
Client
TCP/IP client.
Parameters¶
- host
str
Host address.
- port
int
Port to connect.
- callback_process_message
coroutine
Function to process the received message. It must has a keyward argument of “message” to receive the message as a dictionary.
- *args
args
Arguments needed in “callback_process_message” function call.
- log
logging.Logger
or None, optional A logger. If None, a logger will be instantiated. (the default is None)
- sequence_generator
generator
orNone
, optional Sequence generator. (the default is None)
- name
str
, optional Name of the tcp-client. Used for logging/debugging purposes. The default is “tcp-client”)
- check_message_rate
bool
, optional Check the message rate or not. If True, the rate of message will be calculated and recorded in the debug logging message. (the default is False)
Attributes¶
- log
logging.Logger
A logger.
- timeout
float
Read timeout in second.
- last_sequence_id
int
Last sequence ID of command.
Attributes Summary
Return True if self._reader and self._writer are connected.
Methods Summary
Close the connected client socket, if any, and set done_task done.
Call self.__connect_callback.
close
()Cancel the task and close the connection.
connect
([timeout])Connect to the server.
read
(n)Read up to n bytes.
read_into
(struct)Read binary data from a stream reader into a
ctypes.Structure
.Read JSON data.
read_str
()Read and decode a terminated str; strip the terminator.
readexactly
(n)Read exactly n bytes.
readline
()Read a sequence of bytes ending with
\n
.readuntil
([separator])Read one line, where “line” is a sequence of bytes ending with
separator
.start
(**kwargs)Connect to the TCP/IP server.
write
(data)Write data and call
drain
.write_from
(*structs)Write binary data from one or more
ctypes.Structure
s.write_json
(data)Write data in JSON format.
write_message
(msg_type, msg_name[, ...])Writes message to the server.
write_str
(line)Encode, terminate, and write a str.
writelines
(lines)Write an iterable of bytes and call
drain
.Attributes Documentation
- connected¶
Return True if self._reader and self._writer are connected.
Note: if the other end drops the connection and if you are not trying to read data (e.g. in a background loop), then it takes the operating system awhile to realize the connection is lost. So this can return true for some unknown time after the connection has been dropped.
Methods Documentation
- async basic_close() None ¶
Close the connected client socket, if any, and set done_task done.
Like
close
except does not clearself.should_be_connected
, nor cancelself._monitor_connection_task
.
- async call_connect_callback() None ¶
Call self.__connect_callback.
This is always safe to call. It only calls the callback function if that function is not None and if the connection state has changed since the last time this method was called.
- async close() None ¶
Cancel the task and close the connection.
Note: this function is safe to call even though there is no connection.
- async connect(timeout: float = 10.0) None ¶
Connect to the server.
Parameters¶
- timeout
float
, optional Timeout in second. (default is 10.0)
- timeout
- async read(n: int) bytes ¶
Read up to n bytes.
Parameters¶
- n
int
The number of bytes to read. If -1 then block until the other end closes its writer, then return all data seen.
Raises¶
ConnectionError
If the connection is lost before, or while, reading.
- n
- async read_into(struct: Structure) None ¶
Read binary data from a stream reader into a
ctypes.Structure
.Parameters¶
- struct
ctypes.Structure
Structure to set.
Raises¶
ConnectionError
If the connection is lost before, or while, reading.
asyncio.IncompleteReadError
If EOF is reached before
n
bytes can be read. Use theIncompleteReadError.partial
attribute to get the partially read data.
- struct
- async read_json() Any ¶
Read JSON data.
Read the data with
read_str
and return the json-decoded result.Returns¶
- data
typing.Any
Data decoded from JSON.
Raises¶
ConnectionError
If the connection is lost before, or while, reading.
asyncio.IncompleteReadError
If EOF is reached before the complete separator is found and the internal buffer is reset.
LimitOverrunError
If the amount of data read exceeds the configured stream lmit. The data is left in the internal buffer and can be read again.
TypeError
If the data are of a type that cannot be decoded from JSON.
json.JSONDecodeError
If the data cannot be decoded from JSON.
- data
- async read_str() str ¶
Read and decode a terminated str; strip the terminator.
Read until
self.terminator
, strip the terminator, and decode the data asself.encoding
with strict error handling.Returns¶
- line
str
Line of data, as a str with the terminator stripped.
Raises¶
ConnectionError
If the connection is lost before, or while, reading.
asyncio.IncompleteReadError
If EOF is reached before the complete separator is found and the internal buffer is reset.
LimitOverrunError
If the amount of data read exceeds the configured stream lmit. The data is left in the internal buffer and can be read again.
UnicodeError
If decoding fails.
- line
- async readexactly(n: int) bytes ¶
Read exactly n bytes.
Parameters¶
- n
int
The number of bytes to read.
Raises¶
ConnectionError
If the connection is lost before, or while, reading.
asyncio.IncompleteReadError
If EOF is reached before
n
bytes can be read. Use theIncompleteReadError.partial
attribute to get the partially read data.
- n
- async readline() bytes ¶
Read a sequence of bytes ending with
\n
.If EOF is received and
\n
was not found, the method returns partially read data.Raises¶
ConnectionError
If the connection is lost before, or while, reading.
- async readuntil(separator: bytes = b'\n') bytes ¶
Read one line, where “line” is a sequence of bytes ending with
separator
.Read data from the stream until separator is found.
On success, the data and separator will be removed from the internal buffer (consumed). Returned data will include the separator at the end.
See also
read_str
, which is more convenient for most use cases.Parameters¶
- separator
bytes
The desired separator. The default matches the standard library, rather than using
terminator
.
Raises¶
ConnectionError
If the connection is lost before, or while, reading.
asyncio.IncompleteReadError
If EOF is reached before the complete separator is found and the internal buffer is reset.
LimitOverrunError
If the amount of data read exceeds the configured stream lmit. The data is left in the internal buffer and can be read again.
- separator
- async start(**kwargs: Any) None ¶
Connect to the TCP/IP server.
This is called automatically by the constructor, and is not intended to be called by the user. It is a public method so that subclasses can override it.
Parameters¶
- **kwargs
dict
[str
,typing.Any
] Additional keyword arguments for
asyncio.open_connection
, beyond host and port.
Raises¶
RuntimeError
If start already called.
- **kwargs
- async write(data: bytes) None ¶
Write data and call
drain
.Parameters¶
- data
bytes
The data to write.
Raises¶
ConnectionError
If
self.connected
false before writing begins.
- data
- async write_from(*structs: Structure) None ¶
Write binary data from one or more
ctypes.Structure
s.Parameters¶
- structs
list
[ctypes.Structure
] Structures to write.
Raises¶
ConnectionError
If
self.connected
false before writing begins.
- structs
- async write_json(data: Any) None ¶
Write data in JSON format.
Encode the data as json and write the result with
write_str
.Parameters¶
- data
any
The data to be written. Typically a dict, but any json-encodable data is acceptable.
Raises¶
ConnectionError
If the connection is lost before, or while, reading.
UnicodeError
If encoding fails.
json.JSONEncodeError
If the data cannot be json-encoded.
- data
- async write_message(msg_type: MsgType, msg_name: str, msg_details: dict | None = None, comp_name: str | None = None) None ¶
Writes message to the server.
Parameters¶
- msg_typeenum
MsgType
Message type.
- msg_name
str
Message name.
- msg_details
dict
or None, optional Message details. (the default is None)
- comp_name
str
or None, optional Specific component name used in the event or telemetry. (the default is None)
Raises¶
- RuntimeError
When there is no TCP/IP connection.
- ValueError
If ‘id’ is in the message details already.
- ValueError
When the message type is not supported.
- msg_typeenum
- async write_str(line: str) None ¶
Encode, terminate, and write a str.
Encode the str as
self.encoding
with strict error handling, and appendself.terminator
.Parameters¶
- line
str
The line of data to be written.
Raises¶
ConnectionError
If the connection is lost before, or while, reading.
UnicodeError
If encoding fails.
- line
- host