Debian Codegraph @

pymeasure/adapters/serial.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import logging
26
27 import serial
28 from .adapter import Adapter
29
30 log = logging.getLogger(__name__)
31 log.addHandler(logging.NullHandler())
32
33
34 class SerialAdapter(Adapter):
35 """ Adapter class for using the Python Serial package to allow
36 serial communication to instrument
37
38 :param port: Serial port
39 :param preprocess_reply: An optional callable used to preprocess strings
40 received from the instrument. The callable returns the processed string.
41
42 .. deprecated:: 0.11
43 Implement it in the instrument's `read` method instead.
44
45 :param write_termination: String appended to messages before writing them.
46 :param read_termination: String expected at end of read message and removed.
47 :param \\**kwargs: Any valid key-word argument for serial.Serial
48 """
49
50 def __init__(self, port, preprocess_reply=None,
51 write_termination="", read_termination="",
52 **kwargs):
53 super().__init__(preprocess_reply=preprocess_reply)
54 if isinstance(port, serial.SerialBase):
55 self.connection = port
56 else:
57 self.connection = serial.Serial(port, **kwargs)
58 self.write_termination = write_termination
59 self.read_termination = read_termination
60
61 def _write(self, command, **kwargs):
62 """Write a string command to the instrument appending `write_termination`.
63
64 :param str command: Command string to be sent to the instrument
65 (without termination).
66 :param \\**kwargs: Keyword arguments for the connection itself.
67 """
68 command += self.write_termination
69 self._write_bytes(command.encode(), **kwargs)
70
71 def _write_bytes(self, content, **kwargs):
72 """Write the bytes `content` to the instrument.
73
74 :param bytes content: The bytes to write to the instrument.
75 :param \\**kwargs: Keyword arguments for the connection itself.
76 """
77 self.connection.write(content, **kwargs)
78
79 def _read(self, **kwargs):
80 """Read up to (excluding) `read_termination` or the whole read buffer.
81
82 :param \\**kwargs: Keyword arguments for the connection itself.
83 :returns str: ASCII response of the instrument (read_termination is removed first).
84 """
85 read = self._read_bytes(-1, break_on_termchar=True, **kwargs).decode()
86 # Python>3.8 this shorter form is possible:
87 # self._read_bytes(-1).decode().removesuffix(self.read_termination)
88 if self.read_termination:
89 return read.split(self.read_termination)[0]
90 else:
91 return read
92
93 def _read_bytes(self, count, break_on_termchar, **kwargs):
94 """Read a certain number of bytes from the instrument.
95
96 :param int count: Number of bytes to read. A value of -1 indicates to
97 read from the whole read buffer (waits for timeout).
98 :param bool break_on_termchar: Stop reading at a termination character.
99 :param \\**kwargs: Keyword arguments for the connection itself.
100 :returns bytes: Bytes response of the instrument (including termination).
101 """
102 if break_on_termchar and self.read_termination:
103 return self.connection.read_until(self.read_termination.encode(),
104 count if count > 0 else None,
105 **kwargs)
106 elif count >= 0:
107 return self.connection.read(count, **kwargs)
108 else:
109 # For -1 we empty the buffer completely
110 return self._read_bytes_until_timeout()
111
112 def _read_bytes_until_timeout(self, chunk_size=256, **kwargs):
113 """Read from the serial until a timeout occurs, regardless of the number of bytes.
114
115 :chunk_size: The number of bytes attempted to in a single transaction.
116 Multiple of these transactions will occur.
117 """
118 # `Serial.readlines()` has an unpredictable timeout, see PR #866
119 data = bytes()
120 while True:
121 chunk = self.connection.read(chunk_size, **kwargs)
122 data += chunk
123 if len(chunk) < chunk_size: # If fewer bytes got returned, we had a timeout
124 return data
125
126 def flush_read_buffer(self):
127 """Flush and discard the input buffer."""
128 self.connection.reset_input_buffer()
129
130 def __repr__(self):
131 return "<SerialAdapter(port='%s')>" % self.connection.port