cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 1 | #! python |
| 2 | # |
| 3 | # Python Serial Port Extension for Win32, Linux, BSD, Jython |
| 4 | # see __init__.py |
| 5 | # |
| 6 | # This module implements a RFC2217 compatible client. RF2217 descibes a |
| 7 | # protocol to access serial ports over TCP/IP and allows setting the baud rate, |
| 8 | # modem control lines etc. |
| 9 | # |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 10 | # (C) 2001-2015 Chris Liechti <cliechti@gmx.net> |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 11 | # this is distributed under a free software license, see license.txt |
| 12 | |
| 13 | # TODO: |
| 14 | # - setting control line -> answer is not checked (had problems with one of the |
| 15 | # severs). consider implementing a compatibility mode flag to make check |
| 16 | # conditional |
| 17 | # - write timeout not implemented at all |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 18 | |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 19 | ############################################################################## |
| 20 | # observations and issues with servers |
| 21 | #============================================================================= |
| 22 | # sredird V2.2.1 |
| 23 | # - http://www.ibiblio.org/pub/Linux/system/serial/ sredird-2.2.2.tar.gz |
| 24 | # - does not acknowledge SET_CONTROL (RTS/DTR) correctly, always responding |
| 25 | # [105 1] instead of the actual value. |
| 26 | # - SET_BAUDRATE answer contains 4 extra null bytes -> probably for larger |
| 27 | # numbers than 2**32? |
| 28 | # - To get the signature [COM_PORT_OPTION 0] has to be sent. |
| 29 | # - run a server: while true; do nc -l -p 7000 -c "sredird debug /dev/ttyUSB0 /var/lock/sredir"; done |
| 30 | #============================================================================= |
| 31 | # telnetcpcd (untested) |
| 32 | # - http://ftp.wayne.edu/kermit/sredird/telnetcpcd-1.09.tar.gz |
| 33 | # - To get the signature [COM_PORT_OPTION] w/o data has to be sent. |
| 34 | #============================================================================= |
| 35 | # ser2net |
| 36 | # - does not negotiate BINARY or COM_PORT_OPTION for his side but at least |
| 37 | # acknowledges that the client activates these options |
| 38 | # - The configuration may be that the server prints a banner. As this client |
| 39 | # implementation does a flushInput on connect, this banner is hidden from |
| 40 | # the user application. |
| 41 | # - NOTIFY_MODEMSTATE: the poll interval of the server seems to be one |
| 42 | # second. |
| 43 | # - To get the signature [COM_PORT_OPTION 0] has to be sent. |
| 44 | # - run a server: run ser2net daemon, in /etc/ser2net.conf: |
| 45 | # 2000:telnet:0:/dev/ttyS0:9600 remctl banner |
| 46 | ############################################################################## |
| 47 | |
| 48 | # How to identify ports? pySerial might want to support other protocols in the |
| 49 | # future, so lets use an URL scheme. |
| 50 | # for RFC2217 compliant servers we will use this: |
| 51 | # rfc2217://<host>:<port>[/option[/option...]] |
| 52 | # |
| 53 | # options: |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 54 | # - "logging" set log level print diagnostic messages (e.g. "logging=debug") |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 55 | # - "ign_set_control": do not look at the answers to SET_CONTROL |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 56 | # - "poll_modem": issue NOTIFY_MODEMSTATE requests when CTS/DTR/RI/CD is read. |
| 57 | # Without this option it expects that the server sends notifications |
| 58 | # automatically on change (which most servers do and is according to the |
| 59 | # RFC). |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 60 | # the order of the options is not relevant |
| 61 | |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 62 | import logging |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 63 | import socket |
| 64 | import struct |
| 65 | import threading |
| 66 | import time |
| 67 | try: |
| 68 | import urlparse |
| 69 | except ImportError: |
| 70 | import urllib.parse as urlparse |
Chris Liechti | d214600 | 2015-08-04 16:57:16 +0200 | [diff] [blame] | 71 | try: |
| 72 | import Queue |
| 73 | except ImportError: |
| 74 | import queue as Queue |
| 75 | |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 76 | from serial.serialutil import * |
| 77 | |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 78 | # port string is expected to be something like this: |
| 79 | # rfc2217://host:port |
| 80 | # host may be an IP or including domain, whatever. |
| 81 | # port is 0...65535 |
| 82 | |
cliechti | 86844e8 | 2009-08-12 00:05:33 +0000 | [diff] [blame] | 83 | # map log level names to constants. used in fromURL() |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 84 | LOGGER_LEVELS = { |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 85 | 'debug': logging.DEBUG, |
| 86 | 'info': logging.INFO, |
| 87 | 'warning': logging.WARNING, |
| 88 | 'error': logging.ERROR, |
| 89 | } |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 90 | |
| 91 | |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 92 | # telnet protocol characters |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 93 | SE = b'\xf0' # Subnegotiation End |
| 94 | NOP = b'\xf1' # No Operation |
| 95 | DM = b'\xf2' # Data Mark |
| 96 | BRK = b'\xf3' # Break |
| 97 | IP = b'\xf4' # Interrupt process |
| 98 | AO = b'\xf5' # Abort output |
| 99 | AYT = b'\xf6' # Are You There |
| 100 | EC = b'\xf7' # Erase Character |
| 101 | EL = b'\xf8' # Erase Line |
| 102 | GA = b'\xf9' # Go Ahead |
| 103 | SB = b'\xfa' # Subnegotiation Begin |
| 104 | WILL = b'\xfb' |
| 105 | WONT = b'\xfc' |
| 106 | DO = b'\xfd' |
| 107 | DONT = b'\xfe' |
| 108 | IAC = b'\xff' # Interpret As Command |
| 109 | IAC_DOUBLED = b'\xff\xff' |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 110 | |
| 111 | # selected telnet options |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 112 | BINARY = b'\x00' # 8-bit data path |
| 113 | ECHO = b'\x01' # echo |
| 114 | SGA = b'\x03' # suppress go ahead |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 115 | |
| 116 | # RFC2217 |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 117 | COM_PORT_OPTION = b'\x2c' |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 118 | |
| 119 | # Client to Access Server |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 120 | SET_BAUDRATE = b'\x01' |
| 121 | SET_DATASIZE = b'\x02' |
| 122 | SET_PARITY = b'\x03' |
| 123 | SET_STOPSIZE = b'\x04' |
| 124 | SET_CONTROL = b'\x05' |
| 125 | NOTIFY_LINESTATE = b'\x06' |
| 126 | NOTIFY_MODEMSTATE = b'\x07' |
| 127 | FLOWCONTROL_SUSPEND = b'\x08' |
| 128 | FLOWCONTROL_RESUME = b'\x09' |
| 129 | SET_LINESTATE_MASK = b'\x0a' |
| 130 | SET_MODEMSTATE_MASK = b'\x0b' |
| 131 | PURGE_DATA = b'\x0c' |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 132 | |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 133 | SERVER_SET_BAUDRATE = b'\x65' |
| 134 | SERVER_SET_DATASIZE = b'\x66' |
| 135 | SERVER_SET_PARITY = b'\x67' |
| 136 | SERVER_SET_STOPSIZE = b'\x68' |
| 137 | SERVER_SET_CONTROL = b'\x69' |
| 138 | SERVER_NOTIFY_LINESTATE = b'\x6a' |
| 139 | SERVER_NOTIFY_MODEMSTATE = b'\x6b' |
| 140 | SERVER_FLOWCONTROL_SUSPEND = b'\x6c' |
| 141 | SERVER_FLOWCONTROL_RESUME = b'\x6d' |
| 142 | SERVER_SET_LINESTATE_MASK = b'\x6e' |
| 143 | SERVER_SET_MODEMSTATE_MASK = b'\x6f' |
| 144 | SERVER_PURGE_DATA = b'\x70' |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 145 | |
| 146 | RFC2217_ANSWER_MAP = { |
| 147 | SET_BAUDRATE: SERVER_SET_BAUDRATE, |
| 148 | SET_DATASIZE: SERVER_SET_DATASIZE, |
| 149 | SET_PARITY: SERVER_SET_PARITY, |
| 150 | SET_STOPSIZE: SERVER_SET_STOPSIZE, |
| 151 | SET_CONTROL: SERVER_SET_CONTROL, |
| 152 | NOTIFY_LINESTATE: SERVER_NOTIFY_LINESTATE, |
| 153 | NOTIFY_MODEMSTATE: SERVER_NOTIFY_MODEMSTATE, |
| 154 | FLOWCONTROL_SUSPEND: SERVER_FLOWCONTROL_SUSPEND, |
| 155 | FLOWCONTROL_RESUME: SERVER_FLOWCONTROL_RESUME, |
| 156 | SET_LINESTATE_MASK: SERVER_SET_LINESTATE_MASK, |
| 157 | SET_MODEMSTATE_MASK: SERVER_SET_MODEMSTATE_MASK, |
| 158 | PURGE_DATA: SERVER_PURGE_DATA, |
| 159 | } |
| 160 | |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 161 | SET_CONTROL_REQ_FLOW_SETTING = b'\x00' # Request Com Port Flow Control Setting (outbound/both) |
| 162 | SET_CONTROL_USE_NO_FLOW_CONTROL = b'\x01' # Use No Flow Control (outbound/both) |
| 163 | SET_CONTROL_USE_SW_FLOW_CONTROL = b'\x02' # Use XON/XOFF Flow Control (outbound/both) |
| 164 | SET_CONTROL_USE_HW_FLOW_CONTROL = b'\x03' # Use HARDWARE Flow Control (outbound/both) |
| 165 | SET_CONTROL_REQ_BREAK_STATE = b'\x04' # Request BREAK State |
| 166 | SET_CONTROL_BREAK_ON = b'\x05' # Set BREAK State ON |
| 167 | SET_CONTROL_BREAK_OFF = b'\x06' # Set BREAK State OFF |
| 168 | SET_CONTROL_REQ_DTR = b'\x07' # Request DTR Signal State |
| 169 | SET_CONTROL_DTR_ON = b'\x08' # Set DTR Signal State ON |
| 170 | SET_CONTROL_DTR_OFF = b'\x09' # Set DTR Signal State OFF |
| 171 | SET_CONTROL_REQ_RTS = b'\x0a' # Request RTS Signal State |
| 172 | SET_CONTROL_RTS_ON = b'\x0b' # Set RTS Signal State ON |
| 173 | SET_CONTROL_RTS_OFF = b'\x0c' # Set RTS Signal State OFF |
| 174 | SET_CONTROL_REQ_FLOW_SETTING_IN = b'\x0d' # Request Com Port Flow Control Setting (inbound) |
| 175 | SET_CONTROL_USE_NO_FLOW_CONTROL_IN = b'\x0e' # Use No Flow Control (inbound) |
| 176 | SET_CONTROL_USE_SW_FLOW_CONTOL_IN = b'\x0f' # Use XON/XOFF Flow Control (inbound) |
| 177 | SET_CONTROL_USE_HW_FLOW_CONTOL_IN = b'\x10' # Use HARDWARE Flow Control (inbound) |
| 178 | SET_CONTROL_USE_DCD_FLOW_CONTROL = b'\x11' # Use DCD Flow Control (outbound/both) |
| 179 | SET_CONTROL_USE_DTR_FLOW_CONTROL = b'\x12' # Use DTR Flow Control (inbound) |
| 180 | SET_CONTROL_USE_DSR_FLOW_CONTROL = b'\x13' # Use DSR Flow Control (outbound/both) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 181 | |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 182 | LINESTATE_MASK_TIMEOUT = 128 # Time-out Error |
| 183 | LINESTATE_MASK_SHIFTREG_EMPTY = 64 # Transfer Shift Register Empty |
| 184 | LINESTATE_MASK_TRANSREG_EMPTY = 32 # Transfer Holding Register Empty |
| 185 | LINESTATE_MASK_BREAK_DETECT = 16 # Break-detect Error |
| 186 | LINESTATE_MASK_FRAMING_ERROR = 8 # Framing Error |
| 187 | LINESTATE_MASK_PARTIY_ERROR = 4 # Parity Error |
| 188 | LINESTATE_MASK_OVERRUN_ERROR = 2 # Overrun Error |
| 189 | LINESTATE_MASK_DATA_READY = 1 # Data Ready |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 190 | |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 191 | MODEMSTATE_MASK_CD = 128 # Receive Line Signal Detect (also known as Carrier Detect) |
| 192 | MODEMSTATE_MASK_RI = 64 # Ring Indicator |
| 193 | MODEMSTATE_MASK_DSR = 32 # Data-Set-Ready Signal State |
| 194 | MODEMSTATE_MASK_CTS = 16 # Clear-To-Send Signal State |
| 195 | MODEMSTATE_MASK_CD_CHANGE = 8 # Delta Receive Line Signal Detect |
| 196 | MODEMSTATE_MASK_RI_CHANGE = 4 # Trailing-edge Ring Detector |
| 197 | MODEMSTATE_MASK_DSR_CHANGE = 2 # Delta Data-Set-Ready |
| 198 | MODEMSTATE_MASK_CTS_CHANGE = 1 # Delta Clear-To-Send |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 199 | |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 200 | PURGE_RECEIVE_BUFFER = b'\x01' # Purge access server receive data buffer |
| 201 | PURGE_TRANSMIT_BUFFER = b'\x02' # Purge access server transmit data buffer |
| 202 | PURGE_BOTH_BUFFERS = b'\x03' # Purge both the access server receive data buffer and the access server transmit data buffer |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 203 | |
| 204 | |
| 205 | RFC2217_PARITY_MAP = { |
| 206 | PARITY_NONE: 1, |
| 207 | PARITY_ODD: 2, |
| 208 | PARITY_EVEN: 3, |
| 209 | PARITY_MARK: 4, |
| 210 | PARITY_SPACE: 5, |
| 211 | } |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 212 | RFC2217_REVERSE_PARITY_MAP = dict((v,k) for k,v in RFC2217_PARITY_MAP.items()) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 213 | |
| 214 | RFC2217_STOPBIT_MAP = { |
| 215 | STOPBITS_ONE: 1, |
| 216 | STOPBITS_ONE_POINT_FIVE: 3, |
| 217 | STOPBITS_TWO: 2, |
| 218 | } |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 219 | RFC2217_REVERSE_STOPBIT_MAP = dict((v,k) for k,v in RFC2217_STOPBIT_MAP.items()) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 220 | |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 221 | # Telnet filter states |
| 222 | M_NORMAL = 0 |
| 223 | M_IAC_SEEN = 1 |
| 224 | M_NEGOTIATE = 2 |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 225 | |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 226 | # TelnetOption and TelnetSubnegotiation states |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 227 | REQUESTED = 'REQUESTED' |
| 228 | ACTIVE = 'ACTIVE' |
| 229 | INACTIVE = 'INACTIVE' |
| 230 | REALLY_INACTIVE = 'REALLY_INACTIVE' |
| 231 | |
| 232 | class TelnetOption(object): |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 233 | """Manage a single telnet option, keeps track of DO/DONT WILL/WONT.""" |
| 234 | |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 235 | def __init__(self, connection, name, option, send_yes, send_no, ack_yes, ack_no, initial_state, activation_callback=None): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 236 | """\ |
| 237 | Initialize option. |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 238 | :param connection: connection used to transmit answers |
| 239 | :param name: a readable name for debug outputs |
| 240 | :param send_yes: what to send when option is to be enabled. |
| 241 | :param send_no: what to send when option is to be disabled. |
| 242 | :param ack_yes: what to expect when remote agrees on option. |
| 243 | :param ack_no: what to expect when remote disagrees on option. |
| 244 | :param initial_state: options initialized with REQUESTED are tried to |
| 245 | be enabled on startup. use INACTIVE for all others. |
| 246 | """ |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 247 | self.connection = connection |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 248 | self.name = name |
| 249 | self.option = option |
| 250 | self.send_yes = send_yes |
| 251 | self.send_no = send_no |
| 252 | self.ack_yes = ack_yes |
| 253 | self.ack_no = ack_no |
| 254 | self.state = initial_state |
| 255 | self.active = False |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 256 | self.activation_callback = activation_callback |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 257 | |
| 258 | def __repr__(self): |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 259 | """String for debug outputs""" |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 260 | return "%s:%s(%s)" % (self.name, self.active, self.state) |
| 261 | |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 262 | def process_incoming(self, command): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 263 | """\ |
| 264 | A DO/DONT/WILL/WONT was received for this option, update state and |
| 265 | answer when needed. |
| 266 | """ |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 267 | if command == self.ack_yes: |
| 268 | if self.state is REQUESTED: |
| 269 | self.state = ACTIVE |
| 270 | self.active = True |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 271 | if self.activation_callback is not None: |
| 272 | self.activation_callback() |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 273 | elif self.state is ACTIVE: |
| 274 | pass |
| 275 | elif self.state is INACTIVE: |
| 276 | self.state = ACTIVE |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 277 | self.connection.telnetSendOption(self.send_yes, self.option) |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 278 | self.active = True |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 279 | if self.activation_callback is not None: |
| 280 | self.activation_callback() |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 281 | elif self.state is REALLY_INACTIVE: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 282 | self.connection.telnetSendOption(self.send_no, self.option) |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 283 | else: |
| 284 | raise ValueError('option in illegal state %r' % self) |
| 285 | elif command == self.ack_no: |
| 286 | if self.state is REQUESTED: |
| 287 | self.state = INACTIVE |
| 288 | self.active = False |
| 289 | elif self.state is ACTIVE: |
| 290 | self.state = INACTIVE |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 291 | self.connection.telnetSendOption(self.send_no, self.option) |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 292 | self.active = False |
| 293 | elif self.state is INACTIVE: |
| 294 | pass |
| 295 | elif self.state is REALLY_INACTIVE: |
| 296 | pass |
| 297 | else: |
| 298 | raise ValueError('option in illegal state %r' % self) |
| 299 | |
| 300 | |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 301 | class TelnetSubnegotiation(object): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 302 | """\ |
| 303 | A object to handle subnegotiation of options. In this case actually |
| 304 | sub-sub options for RFC 2217. It is used to track com port options. |
| 305 | """ |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 306 | |
| 307 | def __init__(self, connection, name, option, ack_option=None): |
| 308 | if ack_option is None: ack_option = option |
| 309 | self.connection = connection |
| 310 | self.name = name |
| 311 | self.option = option |
| 312 | self.value = None |
| 313 | self.ack_option = ack_option |
| 314 | self.state = INACTIVE |
| 315 | |
| 316 | def __repr__(self): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 317 | """String for debug outputs.""" |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 318 | return "%s:%s" % (self.name, self.state) |
| 319 | |
| 320 | def set(self, value): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 321 | """\ |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 322 | Request a change of the value. a request is sent to the server. if |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 323 | the client needs to know if the change is performed he has to check the |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 324 | state of this object. |
| 325 | """ |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 326 | self.value = value |
| 327 | self.state = REQUESTED |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 328 | self.connection.rfc2217SendSubnegotiation(self.option, self.value) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 329 | if self.connection.logger: |
| 330 | self.connection.logger.debug("SB Requesting %s -> %r" % (self.name, self.value)) |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 331 | |
| 332 | def isReady(self): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 333 | """\ |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 334 | Check if answer from server has been received. when server rejects |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 335 | the change, raise a ValueError. |
| 336 | """ |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 337 | if self.state == REALLY_INACTIVE: |
| 338 | raise ValueError("remote rejected value for option %r" % (self.name)) |
| 339 | return self.state == ACTIVE |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 340 | # add property to have a similar interface as TelnetOption |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 341 | active = property(isReady) |
| 342 | |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 343 | def wait(self, timeout=3): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 344 | """\ |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 345 | Wait until the subnegotiation has been acknowledged or timeout. It |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 346 | can also throw a value error when the answer from the server does not |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 347 | match the value sent. |
| 348 | """ |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 349 | timeout_time = time.time() + timeout |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 350 | while time.time() < timeout_time: |
| 351 | time.sleep(0.05) # prevent 100% CPU load |
| 352 | if self.isReady(): |
| 353 | break |
| 354 | else: |
| 355 | raise SerialException("timeout while waiting for option %r" % (self.name)) |
| 356 | |
| 357 | def checkAnswer(self, suboption): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 358 | """\ |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 359 | Check an incoming subnegotiation block. The parameter already has |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 360 | cut off the header like sub option number and com port option value. |
| 361 | """ |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 362 | if self.value == suboption[:len(self.value)]: |
| 363 | self.state = ACTIVE |
| 364 | else: |
| 365 | # error propagation done in isReady |
| 366 | self.state = REALLY_INACTIVE |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 367 | if self.connection.logger: |
| 368 | self.connection.logger.debug("SB Answer %s -> %r -> %s" % (self.name, suboption, self.state)) |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 369 | |
| 370 | |
Chris Liechti | ef6b7b4 | 2015-08-06 22:19:26 +0200 | [diff] [blame] | 371 | class Serial(SerialBase): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 372 | """Serial port implementation for RFC 2217 remote serial ports.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 373 | |
| 374 | BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, |
| 375 | 9600, 19200, 38400, 57600, 115200) |
| 376 | |
| 377 | def open(self): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 378 | """\ |
| 379 | Open port with current settings. This may throw a SerialException |
| 380 | if the port cannot be opened. |
| 381 | """ |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 382 | self.logger = None |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 383 | self._ignore_set_control_answer = False |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 384 | self._poll_modem_state = False |
cliechti | dfe2d27 | 2009-08-10 22:19:41 +0000 | [diff] [blame] | 385 | self._network_timeout = 3 |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 386 | if self._port is None: |
| 387 | raise SerialException("Port must be configured before it can be used.") |
cliechti | 8f69e70 | 2011-03-19 00:22:32 +0000 | [diff] [blame] | 388 | if self._isOpen: |
| 389 | raise SerialException("Port is already open.") |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 390 | try: |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 391 | self._socket = socket.create_connection(self.fromURL(self.portstr)) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 392 | self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 393 | except Exception as msg: |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 394 | self._socket = None |
| 395 | raise SerialException("Could not open port %s: %s" % (self.portstr, msg)) |
| 396 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 397 | self._socket.settimeout(5) # XXX good value? |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 398 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 399 | # use a thread save queue as buffer. it also simplifies implementing |
| 400 | # the read timeout |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 401 | self._read_buffer = Queue.Queue() |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 402 | # to ensure that user writes does not interfere with internal |
| 403 | # telnet/rfc2217 options establish a lock |
| 404 | self._write_lock = threading.Lock() |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 405 | # name the following separately so that, below, a check can be easily done |
| 406 | mandadory_options = [ |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 407 | TelnetOption(self, 'we-BINARY', BINARY, WILL, WONT, DO, DONT, INACTIVE), |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 408 | TelnetOption(self, 'we-RFC2217', COM_PORT_OPTION, WILL, WONT, DO, DONT, REQUESTED), |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 409 | ] |
| 410 | # all supported telnet options |
| 411 | self._telnet_options = [ |
cliechti | a29275e | 2009-08-03 00:08:04 +0000 | [diff] [blame] | 412 | TelnetOption(self, 'ECHO', ECHO, DO, DONT, WILL, WONT, REQUESTED), |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 413 | TelnetOption(self, 'we-SGA', SGA, WILL, WONT, DO, DONT, REQUESTED), |
| 414 | TelnetOption(self, 'they-SGA', SGA, DO, DONT, WILL, WONT, REQUESTED), |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 415 | TelnetOption(self, 'they-BINARY', BINARY, DO, DONT, WILL, WONT, INACTIVE), |
| 416 | TelnetOption(self, 'they-RFC2217', COM_PORT_OPTION, DO, DONT, WILL, WONT, REQUESTED), |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 417 | ] + mandadory_options |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 418 | # RFC 2217 specific states |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 419 | # COM port settings |
| 420 | self._rfc2217_port_settings = { |
| 421 | 'baudrate': TelnetSubnegotiation(self, 'baudrate', SET_BAUDRATE, SERVER_SET_BAUDRATE), |
| 422 | 'datasize': TelnetSubnegotiation(self, 'datasize', SET_DATASIZE, SERVER_SET_DATASIZE), |
| 423 | 'parity': TelnetSubnegotiation(self, 'parity', SET_PARITY, SERVER_SET_PARITY), |
| 424 | 'stopsize': TelnetSubnegotiation(self, 'stopsize', SET_STOPSIZE, SERVER_SET_STOPSIZE), |
| 425 | } |
cliechti | cb20a4f | 2011-04-25 02:25:54 +0000 | [diff] [blame] | 426 | # There are more subnegotiation objects, combine all in one dictionary |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 427 | # for easy access |
| 428 | self._rfc2217_options = { |
| 429 | 'purge': TelnetSubnegotiation(self, 'purge', PURGE_DATA, SERVER_PURGE_DATA), |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 430 | 'control': TelnetSubnegotiation(self, 'control', SET_CONTROL, SERVER_SET_CONTROL), |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 431 | } |
| 432 | self._rfc2217_options.update(self._rfc2217_port_settings) |
| 433 | # cache for line and modem states that the server sends to us |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 434 | self._linestate = 0 |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 435 | self._modemstate = None |
| 436 | self._modemstate_expires = 0 |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 437 | # RFC 2217 flow control between server and client |
cliechti | 672d029 | 2009-08-03 02:01:57 +0000 | [diff] [blame] | 438 | self._remote_suspend_flow = False |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 439 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 440 | self._thread = threading.Thread(target=self._telnetReadLoop) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 441 | self._thread.setDaemon(True) |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 442 | self._thread.setName('pySerial RFC 2217 reader thread for %s' % (self._port,)) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 443 | self._thread.start() |
| 444 | |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 445 | # negotiate Telnet/RFC 2217 -> send initial requests |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 446 | for option in self._telnet_options: |
| 447 | if option.state is REQUESTED: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 448 | self.telnetSendOption(option.send_yes, option.option) |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 449 | # now wait until important options are negotiated |
cliechti | dfe2d27 | 2009-08-10 22:19:41 +0000 | [diff] [blame] | 450 | timeout_time = time.time() + self._network_timeout |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 451 | while time.time() < timeout_time: |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 452 | time.sleep(0.05) # prevent 100% CPU load |
cliechti | 7c213a9 | 2014-07-31 15:29:34 +0000 | [diff] [blame] | 453 | if sum(o.active for o in mandadory_options) == sum(o.state != INACTIVE for o in mandadory_options): |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 454 | break |
| 455 | else: |
| 456 | raise SerialException("Remote does not seem to support RFC2217 or BINARY mode %r" % mandadory_options) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 457 | if self.logger: |
| 458 | self.logger.info("Negotiated options: %s" % self._telnet_options) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 459 | |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 460 | # fine, go on, set RFC 2271 specific things |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 461 | self._reconfigurePort() |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 462 | # all things set up get, now a clean start |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 463 | self._isOpen = True |
| 464 | if not self._rtscts: |
| 465 | self.setRTS(True) |
| 466 | self.setDTR(True) |
| 467 | self.flushInput() |
| 468 | self.flushOutput() |
| 469 | |
| 470 | def _reconfigurePort(self): |
| 471 | """Set communication parameters on opened port.""" |
| 472 | if self._socket is None: |
| 473 | raise SerialException("Can only operate on open ports") |
| 474 | |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 475 | # if self._timeout != 0 and self._interCharTimeout is not None: |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 476 | # XXX |
| 477 | |
| 478 | if self._writeTimeout is not None: |
| 479 | raise NotImplementedError('writeTimeout is currently not supported') |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 480 | # XXX |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 481 | |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 482 | # Setup the connection |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 483 | # to get good performance, all parameter changes are sent first... |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 484 | if not 0 < self._baudrate < 2**32: |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 485 | raise ValueError("invalid baudrate: %r" % (self._baudrate)) |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 486 | self._rfc2217_port_settings['baudrate'].set(struct.pack(b'!I', self._baudrate)) |
| 487 | self._rfc2217_port_settings['datasize'].set(struct.pack(b'!B', self._bytesize)) |
| 488 | self._rfc2217_port_settings['parity'].set(struct.pack(b'!B', RFC2217_PARITY_MAP[self._parity])) |
| 489 | self._rfc2217_port_settings['stopsize'].set(struct.pack(b'!B', RFC2217_STOPBIT_MAP[self._stopbits])) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 490 | |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 491 | # and now wait until parameters are active |
| 492 | items = self._rfc2217_port_settings.values() |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 493 | if self.logger: |
| 494 | self.logger.debug("Negotiating settings: %s" % (items,)) |
cliechti | dfe2d27 | 2009-08-10 22:19:41 +0000 | [diff] [blame] | 495 | timeout_time = time.time() + self._network_timeout |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 496 | while time.time() < timeout_time: |
| 497 | time.sleep(0.05) # prevent 100% CPU load |
| 498 | if sum(o.active for o in items) == len(items): |
| 499 | break |
| 500 | else: |
| 501 | raise SerialException("Remote does not accept parameter change (RFC2217): %r" % items) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 502 | if self.logger: |
| 503 | self.logger.info("Negotiated settings: %s" % (items,)) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 504 | |
| 505 | if self._rtscts and self._xonxoff: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 506 | raise ValueError('xonxoff and rtscts together are not supported') |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 507 | elif self._rtscts: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 508 | self.rfc2217SetControl(SET_CONTROL_USE_HW_FLOW_CONTROL) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 509 | elif self._xonxoff: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 510 | self.rfc2217SetControl(SET_CONTROL_USE_SW_FLOW_CONTROL) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 511 | else: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 512 | self.rfc2217SetControl(SET_CONTROL_USE_NO_FLOW_CONTROL) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 513 | |
| 514 | def close(self): |
| 515 | """Close port""" |
| 516 | if self._isOpen: |
| 517 | if self._socket: |
| 518 | try: |
| 519 | self._socket.shutdown(socket.SHUT_RDWR) |
| 520 | self._socket.close() |
| 521 | except: |
| 522 | # ignore errors. |
| 523 | pass |
| 524 | self._socket = None |
| 525 | if self._thread: |
| 526 | self._thread.join() |
| 527 | self._isOpen = False |
| 528 | # in case of quick reconnects, give the server some time |
| 529 | time.sleep(0.3) |
| 530 | |
| 531 | def makeDeviceName(self, port): |
| 532 | raise SerialException("there is no sensible way to turn numbers into URLs") |
| 533 | |
| 534 | def fromURL(self, url): |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 535 | """extract host and port from an URL string""" |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 536 | parts = urlparse.urlsplit(url) |
| 537 | if parts.scheme.lower() != "rfc2217": |
Chris Liechti | c4bca9e | 2015-08-07 14:40:41 +0200 | [diff] [blame] | 538 | raise SerialException('expected a string in the form "rfc2217://<host>:<port>[/option[/option...]]": not starting with rfc2217:// (%r)' % (parts.scheme,)) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 539 | try: |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 540 | # process options now, directly altering self |
| 541 | for option in parts.path.lower().split('/'): |
| 542 | if '=' in option: |
| 543 | option, value = option.split('=', 1) |
| 544 | else: |
| 545 | value = None |
| 546 | if not option: |
| 547 | pass |
| 548 | elif option == 'logging': |
| 549 | logging.basicConfig() # XXX is that good to call it here? |
| 550 | self.logger = logging.getLogger('pySerial.rfc2217') |
| 551 | self.logger.setLevel(LOGGER_LEVELS[value]) |
| 552 | self.logger.debug('enabled logging') |
| 553 | elif option == 'ign_set_control': |
| 554 | self._ignore_set_control_answer = True |
| 555 | elif option == 'poll_modem': |
| 556 | self._poll_modem_state = True |
| 557 | elif option == 'timeout': |
| 558 | self._network_timeout = float(value) |
| 559 | else: |
| 560 | raise ValueError('unknown option: %r' % (option,)) |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 561 | # get host and port |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 562 | host, port = parts.hostname, parts.port |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 563 | if not 0 <= port < 65536: raise ValueError("port not in range 0...65535") |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 564 | except ValueError as e: |
Chris Liechti | a422211 | 2015-08-07 01:03:12 +0200 | [diff] [blame] | 565 | raise SerialException('expected a string in the form "rfc2217://<host>:<port>[/option[/option...]]": %s' % e) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 566 | return (host, port) |
| 567 | |
| 568 | # - - - - - - - - - - - - - - - - - - - - - - - - |
| 569 | |
| 570 | def inWaiting(self): |
| 571 | """Return the number of characters currently in the input buffer.""" |
| 572 | if not self._isOpen: raise portNotOpenError |
| 573 | return self._read_buffer.qsize() |
| 574 | |
| 575 | def read(self, size=1): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 576 | """\ |
| 577 | Read size bytes from the serial port. If a timeout is set it may |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 578 | return less characters as requested. With no timeout it will block |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 579 | until the requested number of bytes is read. |
| 580 | """ |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 581 | if not self._isOpen: raise portNotOpenError |
| 582 | data = bytearray() |
| 583 | try: |
| 584 | while len(data) < size: |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 585 | if self._thread is None: |
| 586 | raise SerialException('connection failed (reader thread died)') |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 587 | data += self._read_buffer.get(True, self._timeout) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 588 | except Queue.Empty: # -> timeout |
| 589 | pass |
| 590 | return bytes(data) |
| 591 | |
| 592 | def write(self, data): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 593 | """\ |
| 594 | Output the given string over the serial port. Can block if the |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 595 | connection is blocked. May raise SerialException if the connection is |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 596 | closed. |
| 597 | """ |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 598 | if not self._isOpen: raise portNotOpenError |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 599 | with self._write_lock: |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 600 | try: |
cliechti | 3807712 | 2013-10-16 02:57:27 +0000 | [diff] [blame] | 601 | self._socket.sendall(to_bytes(data).replace(IAC, IAC_DOUBLED)) |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 602 | except socket.error as e: |
cliechti | cb20a4f | 2011-04-25 02:25:54 +0000 | [diff] [blame] | 603 | raise SerialException("connection failed (socket error): %s" % e) # XXX what exception if socket connection fails |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 604 | return len(data) |
| 605 | |
| 606 | def flushInput(self): |
| 607 | """Clear input buffer, discarding all that is in the buffer.""" |
| 608 | if not self._isOpen: raise portNotOpenError |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 609 | self.rfc2217SendPurge(PURGE_RECEIVE_BUFFER) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 610 | # empty read buffer |
| 611 | while self._read_buffer.qsize(): |
| 612 | self._read_buffer.get(False) |
| 613 | |
| 614 | def flushOutput(self): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 615 | """\ |
| 616 | Clear output buffer, aborting the current output and |
| 617 | discarding all that is in the buffer. |
| 618 | """ |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 619 | if not self._isOpen: raise portNotOpenError |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 620 | self.rfc2217SendPurge(PURGE_TRANSMIT_BUFFER) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 621 | |
| 622 | def sendBreak(self, duration=0.25): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 623 | """\ |
| 624 | Send break condition. Timed, returns to idle state after given |
| 625 | duration. |
| 626 | """ |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 627 | if not self._isOpen: raise portNotOpenError |
| 628 | self.setBreak(True) |
| 629 | time.sleep(duration) |
| 630 | self.setBreak(False) |
| 631 | |
| 632 | def setBreak(self, level=True): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 633 | """\ |
| 634 | Set break: Controls TXD. When active, to transmitting is |
| 635 | possible. |
| 636 | """ |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 637 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 638 | if self.logger: |
| 639 | self.logger.info('set BREAK to %s' % ('inactive', 'active')[bool(level)]) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 640 | if level: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 641 | self.rfc2217SetControl(SET_CONTROL_BREAK_ON) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 642 | else: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 643 | self.rfc2217SetControl(SET_CONTROL_BREAK_OFF) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 644 | |
| 645 | def setRTS(self, level=True): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 646 | """Set terminal status line: Request To Send.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 647 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 648 | if self.logger: |
| 649 | self.logger.info('set RTS to %s' % ('inactive', 'active')[bool(level)]) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 650 | if level: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 651 | self.rfc2217SetControl(SET_CONTROL_RTS_ON) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 652 | else: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 653 | self.rfc2217SetControl(SET_CONTROL_RTS_OFF) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 654 | |
| 655 | def setDTR(self, level=True): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 656 | """Set terminal status line: Data Terminal Ready.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 657 | if not self._isOpen: raise portNotOpenError |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 658 | if self.logger: |
| 659 | self.logger.info('set DTR to %s' % ('inactive', 'active')[bool(level)]) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 660 | if level: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 661 | self.rfc2217SetControl(SET_CONTROL_DTR_ON) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 662 | else: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 663 | self.rfc2217SetControl(SET_CONTROL_DTR_OFF) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 664 | |
| 665 | def getCTS(self): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 666 | """Read terminal status line: Clear To Send.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 667 | if not self._isOpen: raise portNotOpenError |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 668 | return bool(self.getModemState() & MODEMSTATE_MASK_CTS) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 669 | |
| 670 | def getDSR(self): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 671 | """Read terminal status line: Data Set Ready.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 672 | if not self._isOpen: raise portNotOpenError |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 673 | return bool(self.getModemState() & MODEMSTATE_MASK_DSR) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 674 | |
| 675 | def getRI(self): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 676 | """Read terminal status line: Ring Indicator.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 677 | if not self._isOpen: raise portNotOpenError |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 678 | return bool(self.getModemState() & MODEMSTATE_MASK_RI) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 679 | |
| 680 | def getCD(self): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 681 | """Read terminal status line: Carrier Detect.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 682 | if not self._isOpen: raise portNotOpenError |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 683 | return bool(self.getModemState() & MODEMSTATE_MASK_CD) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 684 | |
| 685 | # - - - platform specific - - - |
| 686 | # None so far |
| 687 | |
| 688 | # - - - RFC2217 specific - - - |
| 689 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 690 | def _telnetReadLoop(self): |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 691 | """Read loop for the socket.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 692 | mode = M_NORMAL |
| 693 | suboption = None |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 694 | try: |
| 695 | while self._socket is not None: |
| 696 | try: |
| 697 | data = self._socket.recv(1024) |
| 698 | except socket.timeout: |
| 699 | # just need to get out of recv form time to time to check if |
| 700 | # still alive |
| 701 | continue |
Chris Liechti | 68340d7 | 2015-08-03 14:15:48 +0200 | [diff] [blame] | 702 | except socket.error as e: |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 703 | # connection fails -> terminate loop |
cliechti | cb20a4f | 2011-04-25 02:25:54 +0000 | [diff] [blame] | 704 | if self.logger: |
| 705 | self.logger.debug("socket error in reader thread: %s" % (e,)) |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 706 | break |
cliechti | cb20a4f | 2011-04-25 02:25:54 +0000 | [diff] [blame] | 707 | if not data: break # lost connection |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 708 | #~ for byte in data: # fails for python3 as it returns ints instead of b'' |
| 709 | for x in range(len(data)): |
| 710 | byte = data[x:x+1] |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 711 | if mode == M_NORMAL: |
| 712 | # interpret as command or as data |
| 713 | if byte == IAC: |
| 714 | mode = M_IAC_SEEN |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 715 | else: |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 716 | # store data in read buffer or sub option buffer |
| 717 | # depending on state |
| 718 | if suboption is not None: |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 719 | suboption += byte |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 720 | else: |
| 721 | self._read_buffer.put(byte) |
| 722 | elif mode == M_IAC_SEEN: |
| 723 | if byte == IAC: |
| 724 | # interpret as command doubled -> insert character |
| 725 | # itself |
cliechti | f325c03 | 2009-12-25 16:09:49 +0000 | [diff] [blame] | 726 | if suboption is not None: |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 727 | suboption += IAC |
cliechti | f325c03 | 2009-12-25 16:09:49 +0000 | [diff] [blame] | 728 | else: |
| 729 | self._read_buffer.put(IAC) |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 730 | mode = M_NORMAL |
| 731 | elif byte == SB: |
| 732 | # sub option start |
| 733 | suboption = bytearray() |
| 734 | mode = M_NORMAL |
| 735 | elif byte == SE: |
| 736 | # sub option end -> process it now |
| 737 | self._telnetProcessSubnegotiation(bytes(suboption)) |
| 738 | suboption = None |
| 739 | mode = M_NORMAL |
| 740 | elif byte in (DO, DONT, WILL, WONT): |
| 741 | # negotiation |
| 742 | telnet_command = byte |
| 743 | mode = M_NEGOTIATE |
| 744 | else: |
| 745 | # other telnet commands |
| 746 | self._telnetProcessCommand(byte) |
| 747 | mode = M_NORMAL |
| 748 | elif mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following |
| 749 | self._telnetNegotiateOption(telnet_command, byte) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 750 | mode = M_NORMAL |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 751 | finally: |
| 752 | self._thread = None |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 753 | if self.logger: |
| 754 | self.logger.debug("read thread terminated") |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 755 | |
| 756 | # - incoming telnet commands and options |
| 757 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 758 | def _telnetProcessCommand(self, command): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 759 | """Process commands other than DO, DONT, WILL, WONT.""" |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 760 | # Currently none. RFC2217 only uses negotiation and subnegotiation. |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 761 | if self.logger: |
| 762 | self.logger.warning("ignoring Telnet command: %r" % (command,)) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 763 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 764 | def _telnetNegotiateOption(self, command, option): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 765 | """Process incoming DO, DONT, WILL, WONT.""" |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 766 | # check our registered telnet options and forward command to them |
| 767 | # they know themselves if they have to answer or not |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 768 | known = False |
| 769 | for item in self._telnet_options: |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 770 | # can have more than one match! as some options are duplicated for |
| 771 | # 'us' and 'them' |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 772 | if item.option == option: |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 773 | item.process_incoming(command) |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 774 | known = True |
| 775 | if not known: |
| 776 | # handle unknown options |
| 777 | # only answer to positive requests and deny them |
| 778 | if command == WILL or command == DO: |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 779 | self.telnetSendOption((command == WILL and DONT or WONT), option) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 780 | if self.logger: |
| 781 | self.logger.warning("rejected Telnet option: %r" % (option,)) |
cliechti | ac20532 | 2009-08-02 20:40:21 +0000 | [diff] [blame] | 782 | |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 783 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 784 | def _telnetProcessSubnegotiation(self, suboption): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 785 | """Process subnegotiation, the data between IAC SB and IAC SE.""" |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 786 | if suboption[0:1] == COM_PORT_OPTION: |
| 787 | if suboption[1:2] == SERVER_NOTIFY_LINESTATE and len(suboption) >= 3: |
cliechti | 672d029 | 2009-08-03 02:01:57 +0000 | [diff] [blame] | 788 | self._linestate = ord(suboption[2:3]) # ensure it is a number |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 789 | if self.logger: |
| 790 | self.logger.info("NOTIFY_LINESTATE: %s" % self._linestate) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 791 | elif suboption[1:2] == SERVER_NOTIFY_MODEMSTATE and len(suboption) >= 3: |
cliechti | 672d029 | 2009-08-03 02:01:57 +0000 | [diff] [blame] | 792 | self._modemstate = ord(suboption[2:3]) # ensure it is a number |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 793 | if self.logger: |
| 794 | self.logger.info("NOTIFY_MODEMSTATE: %s" % self._modemstate) |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 795 | # update time when we think that a poll would make sense |
| 796 | self._modemstate_expires = time.time() + 0.3 |
cliechti | 672d029 | 2009-08-03 02:01:57 +0000 | [diff] [blame] | 797 | elif suboption[1:2] == FLOWCONTROL_SUSPEND: |
| 798 | self._remote_suspend_flow = True |
| 799 | elif suboption[1:2] == FLOWCONTROL_RESUME: |
| 800 | self._remote_suspend_flow = False |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 801 | else: |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 802 | for item in self._rfc2217_options.values(): |
| 803 | if item.ack_option == suboption[1:2]: |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 804 | #~ print "processing COM_PORT_OPTION: %r" % list(suboption[1:]) |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 805 | item.checkAnswer(bytes(suboption[2:])) |
| 806 | break |
| 807 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 808 | if self.logger: |
| 809 | self.logger.warning("ignoring COM_PORT_OPTION: %r" % (suboption,)) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 810 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 811 | if self.logger: |
| 812 | self.logger.warning("ignoring subnegotiation: %r" % (suboption,)) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 813 | |
| 814 | # - outgoing telnet commands and options |
| 815 | |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 816 | def _internal_raw_write(self, data): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 817 | """internal socket write with no data escaping. used to send telnet stuff.""" |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 818 | with self._write_lock: |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 819 | self._socket.sendall(data) |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 820 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 821 | def telnetSendOption(self, action, option): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 822 | """Send DO, DONT, WILL, WONT.""" |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 823 | self._internal_raw_write(to_bytes([IAC, action, option])) |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 824 | |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 825 | def rfc2217SendSubnegotiation(self, option, value=b''): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 826 | """Subnegotiation of RFC2217 parameters.""" |
cliechti | f325c03 | 2009-12-25 16:09:49 +0000 | [diff] [blame] | 827 | value = value.replace(IAC, IAC_DOUBLED) |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 828 | self._internal_raw_write(to_bytes([IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE])) |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 829 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 830 | def rfc2217SendPurge(self, value): |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 831 | item = self._rfc2217_options['purge'] |
cliechti | 672d029 | 2009-08-03 02:01:57 +0000 | [diff] [blame] | 832 | item.set(value) # transmit desired purge type |
cliechti | dfe2d27 | 2009-08-10 22:19:41 +0000 | [diff] [blame] | 833 | item.wait(self._network_timeout) # wait for acknowledge from the server |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 834 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 835 | def rfc2217SetControl(self, value): |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 836 | item = self._rfc2217_options['control'] |
cliechti | cb20a4f | 2011-04-25 02:25:54 +0000 | [diff] [blame] | 837 | item.set(value) # transmit desired control type |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 838 | if self._ignore_set_control_answer: |
| 839 | # answers are ignored when option is set. compatibility mode for |
cliechti | cb20a4f | 2011-04-25 02:25:54 +0000 | [diff] [blame] | 840 | # servers that answer, but not the expected one... (or no answer |
cliechti | 81c5476 | 2009-08-03 23:53:27 +0000 | [diff] [blame] | 841 | # at all) i.e. sredird |
| 842 | time.sleep(0.1) # this helps getting the unit tests passed |
| 843 | else: |
cliechti | dfe2d27 | 2009-08-10 22:19:41 +0000 | [diff] [blame] | 844 | item.wait(self._network_timeout) # wait for acknowledge from the server |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 845 | |
cliechti | 1ef7e3e | 2009-08-03 02:38:43 +0000 | [diff] [blame] | 846 | def rfc2217FlowServerReady(self): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 847 | """\ |
| 848 | check if server is ready to receive data. block for some time when |
| 849 | not. |
| 850 | """ |
cliechti | 672d029 | 2009-08-03 02:01:57 +0000 | [diff] [blame] | 851 | #~ if self._remote_suspend_flow: |
| 852 | #~ wait--- |
| 853 | |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 854 | def getModemState(self): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 855 | """\ |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 856 | get last modem state (cached value. If value is "old", request a new |
| 857 | one. This cache helps that we don't issue to many requests when e.g. all |
| 858 | status lines, one after the other is queried by the user (getCTS, getDSR |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 859 | etc.) |
| 860 | """ |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 861 | # active modem state polling enabled? is the value fresh enough? |
| 862 | if self._poll_modem_state and self._modemstate_expires < time.time(): |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 863 | if self.logger: |
| 864 | self.logger.debug('polling modem state') |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 865 | # when it is older, request an update |
| 866 | self.rfc2217SendSubnegotiation(NOTIFY_MODEMSTATE) |
cliechti | dfe2d27 | 2009-08-10 22:19:41 +0000 | [diff] [blame] | 867 | timeout_time = time.time() + self._network_timeout |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 868 | while time.time() < timeout_time: |
| 869 | time.sleep(0.05) # prevent 100% CPU load |
| 870 | # when expiration time is updated, it means that there is a new |
| 871 | # value |
| 872 | if self._modemstate_expires > time.time(): |
| 873 | break |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 874 | else: |
| 875 | if self.logger: |
| 876 | self.logger.warning('poll for modem state failed') |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 877 | # even when there is a timeout, do not generate an error just |
| 878 | # return the last known value. this way we can support buggy |
| 879 | # servers that do not respond to polls, but send automatic |
| 880 | # updates. |
| 881 | if self._modemstate is not None: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 882 | if self.logger: |
| 883 | self.logger.debug('using cached modem state') |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 884 | return self._modemstate |
| 885 | else: |
| 886 | # never received a notification from the server |
cliechti | 8fb119c | 2009-08-05 23:39:45 +0000 | [diff] [blame] | 887 | raise SerialException("remote sends no NOTIFY_MODEMSTATE") |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 888 | |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 889 | |
cliechti | 595ed5b | 2009-08-10 01:43:32 +0000 | [diff] [blame] | 890 | ############################################################################# |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 891 | # The following is code that helps implementing an RFC 2217 server. |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 892 | |
cliechti | 8ccc2ff | 2009-08-05 12:44:46 +0000 | [diff] [blame] | 893 | class PortManager(object): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 894 | """\ |
| 895 | This class manages the state of Telnet and RFC 2217. It needs a serial |
cliechti | cb20a4f | 2011-04-25 02:25:54 +0000 | [diff] [blame] | 896 | instance and a connection to work with. Connection is expected to implement |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 897 | a (thread safe) write function, that writes the string to the network. |
| 898 | """ |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 899 | |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 900 | def __init__(self, serial_port, connection, logger=None): |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 901 | self.serial = serial_port |
| 902 | self.connection = connection |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 903 | self.logger = logger |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 904 | self._client_is_rfc2217 = False |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 905 | |
| 906 | # filter state machine |
| 907 | self.mode = M_NORMAL |
| 908 | self.suboption = None |
| 909 | self.telnet_command = None |
| 910 | |
| 911 | # states for modem/line control events |
| 912 | self.modemstate_mask = 255 |
| 913 | self.last_modemstate = None |
| 914 | self.linstate_mask = 0 |
| 915 | |
| 916 | # all supported telnet options |
| 917 | self._telnet_options = [ |
| 918 | TelnetOption(self, 'ECHO', ECHO, WILL, WONT, DO, DONT, REQUESTED), |
| 919 | TelnetOption(self, 'we-SGA', SGA, WILL, WONT, DO, DONT, REQUESTED), |
| 920 | TelnetOption(self, 'they-SGA', SGA, DO, DONT, WILL, WONT, INACTIVE), |
| 921 | TelnetOption(self, 'we-BINARY', BINARY, WILL, WONT, DO, DONT, INACTIVE), |
| 922 | TelnetOption(self, 'they-BINARY', BINARY, DO, DONT, WILL, WONT, REQUESTED), |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 923 | TelnetOption(self, 'we-RFC2217', COM_PORT_OPTION, WILL, WONT, DO, DONT, REQUESTED, self._client_ok), |
| 924 | TelnetOption(self, 'they-RFC2217', COM_PORT_OPTION, DO, DONT, WILL, WONT, INACTIVE, self._client_ok), |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 925 | ] |
| 926 | |
| 927 | # negotiate Telnet/RFC2217 -> send initial requests |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 928 | if self.logger: |
| 929 | self.logger.debug("requesting initial Telnet/RFC 2217 options") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 930 | for option in self._telnet_options: |
| 931 | if option.state is REQUESTED: |
| 932 | self.telnetSendOption(option.send_yes, option.option) |
| 933 | # issue 1st modem state notification |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 934 | |
| 935 | def _client_ok(self): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 936 | """\ |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 937 | callback of telnet option. It gets called when option is activated. |
| 938 | This one here is used to detect when the client agrees on RFC 2217. A |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 939 | flag is set so that other functions like check_modem_lines know if the |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 940 | client is OK. |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 941 | """ |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 942 | # The callback is used for we and they so if one party agrees, we're |
| 943 | # already happy. it seems not all servers do the negotiation correctly |
| 944 | # and i guess there are incorrect clients too.. so be happy if client |
| 945 | # answers one or the other positively. |
| 946 | self._client_is_rfc2217 = True |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 947 | if self.logger: |
| 948 | self.logger.info("client accepts RFC 2217") |
cliechti | 8fb119c | 2009-08-05 23:39:45 +0000 | [diff] [blame] | 949 | # this is to ensure that the client gets a notification, even if there |
| 950 | # was no change |
| 951 | self.check_modem_lines(force_notification=True) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 952 | |
| 953 | # - outgoing telnet commands and options |
| 954 | |
| 955 | def telnetSendOption(self, action, option): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 956 | """Send DO, DONT, WILL, WONT.""" |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 957 | self.connection.write(to_bytes([IAC, action, option])) |
| 958 | |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 959 | def rfc2217SendSubnegotiation(self, option, value=b''): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 960 | """Subnegotiation of RFC 2217 parameters.""" |
cliechti | f325c03 | 2009-12-25 16:09:49 +0000 | [diff] [blame] | 961 | value = value.replace(IAC, IAC_DOUBLED) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 962 | self.connection.write(to_bytes([IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE])) |
| 963 | |
| 964 | # - check modem lines, needs to be called periodically from user to |
| 965 | # establish polling |
| 966 | |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 967 | def check_modem_lines(self, force_notification=False): |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 968 | modemstate = ( |
| 969 | (self.serial.getCTS() and MODEMSTATE_MASK_CTS) | |
| 970 | (self.serial.getDSR() and MODEMSTATE_MASK_DSR) | |
| 971 | (self.serial.getRI() and MODEMSTATE_MASK_RI) | |
| 972 | (self.serial.getCD() and MODEMSTATE_MASK_CD) |
| 973 | ) |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 974 | # check what has changed |
| 975 | deltas = modemstate ^ (self.last_modemstate or 0) # when last is None -> 0 |
| 976 | if deltas & MODEMSTATE_MASK_CTS: |
| 977 | modemstate |= MODEMSTATE_MASK_CTS_CHANGE |
| 978 | if deltas & MODEMSTATE_MASK_DSR: |
| 979 | modemstate |= MODEMSTATE_MASK_DSR_CHANGE |
| 980 | if deltas & MODEMSTATE_MASK_RI: |
| 981 | modemstate |= MODEMSTATE_MASK_RI_CHANGE |
| 982 | if deltas & MODEMSTATE_MASK_CD: |
| 983 | modemstate |= MODEMSTATE_MASK_CD_CHANGE |
| 984 | # if new state is different and the mask allows this change, send |
cliechti | 86b593e | 2009-08-05 16:28:12 +0000 | [diff] [blame] | 985 | # notification. suppress notifications when client is not rfc2217 |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 986 | if modemstate != self.last_modemstate or force_notification: |
cliechti | 8fb119c | 2009-08-05 23:39:45 +0000 | [diff] [blame] | 987 | if (self._client_is_rfc2217 and (modemstate & self.modemstate_mask)) or force_notification: |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 988 | self.rfc2217SendSubnegotiation( |
| 989 | SERVER_NOTIFY_MODEMSTATE, |
| 990 | to_bytes([modemstate & self.modemstate_mask]) |
| 991 | ) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 992 | if self.logger: |
| 993 | self.logger.info("NOTIFY_MODEMSTATE: %s" % (modemstate,)) |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 994 | # save last state, but forget about deltas. |
| 995 | # otherwise it would also notify about changing deltas which is |
| 996 | # probably not very useful |
| 997 | self.last_modemstate = modemstate & 0xf0 |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 998 | |
cliechti | 32c1033 | 2009-08-05 13:23:43 +0000 | [diff] [blame] | 999 | # - outgoing data escaping |
| 1000 | |
| 1001 | def escape(self, data): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1002 | """\ |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 1003 | This generator function is for the user. All outgoing data has to be |
cliechti | cb20a4f | 2011-04-25 02:25:54 +0000 | [diff] [blame] | 1004 | properly escaped, so that no IAC character in the data stream messes up |
| 1005 | the Telnet state machine in the server. |
cliechti | 32c1033 | 2009-08-05 13:23:43 +0000 | [diff] [blame] | 1006 | |
| 1007 | socket.sendall(escape(data)) |
| 1008 | """ |
| 1009 | for byte in data: |
| 1010 | if byte == IAC: |
| 1011 | yield IAC |
| 1012 | yield IAC |
| 1013 | else: |
| 1014 | yield byte |
| 1015 | |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1016 | # - incoming data filter |
| 1017 | |
| 1018 | def filter(self, data): |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1019 | """\ |
cliechti | 7d44856 | 2014-08-03 21:57:45 +0000 | [diff] [blame] | 1020 | Handle a bunch of incoming bytes. This is a generator. It will yield |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 1021 | all characters not of interest for Telnet/RFC 2217. |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1022 | |
| 1023 | The idea is that the reader thread pushes data from the socket through |
| 1024 | this filter: |
| 1025 | |
| 1026 | for byte in filter(socket.recv(1024)): |
| 1027 | # do things like CR/LF conversion/whatever |
| 1028 | # and write data to the serial port |
| 1029 | serial.write(byte) |
| 1030 | |
| 1031 | (socket error handling code left as exercise for the reader) |
| 1032 | """ |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1033 | #~ for byte in data: # XXX fails for python3 as it returns ints instead of bytes |
| 1034 | for x in range(len(data)): |
| 1035 | byte = data[x:x+1] |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1036 | if self.mode == M_NORMAL: |
| 1037 | # interpret as command or as data |
| 1038 | if byte == IAC: |
| 1039 | self.mode = M_IAC_SEEN |
| 1040 | else: |
| 1041 | # store data in sub option buffer or pass it to our |
| 1042 | # consumer depending on state |
| 1043 | if self.suboption is not None: |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1044 | self.suboption += byte |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1045 | else: |
| 1046 | yield byte |
| 1047 | elif self.mode == M_IAC_SEEN: |
| 1048 | if byte == IAC: |
| 1049 | # interpret as command doubled -> insert character |
| 1050 | # itself |
cliechti | f325c03 | 2009-12-25 16:09:49 +0000 | [diff] [blame] | 1051 | if self.suboption is not None: |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1052 | self.suboption += byte |
cliechti | f325c03 | 2009-12-25 16:09:49 +0000 | [diff] [blame] | 1053 | else: |
| 1054 | yield byte |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1055 | self.mode = M_NORMAL |
| 1056 | elif byte == SB: |
| 1057 | # sub option start |
| 1058 | self.suboption = bytearray() |
| 1059 | self.mode = M_NORMAL |
| 1060 | elif byte == SE: |
| 1061 | # sub option end -> process it now |
| 1062 | self._telnetProcessSubnegotiation(bytes(self.suboption)) |
| 1063 | self.suboption = None |
| 1064 | self.mode = M_NORMAL |
| 1065 | elif byte in (DO, DONT, WILL, WONT): |
| 1066 | # negotiation |
| 1067 | self.telnet_command = byte |
| 1068 | self.mode = M_NEGOTIATE |
| 1069 | else: |
| 1070 | # other telnet commands |
| 1071 | self._telnetProcessCommand(byte) |
| 1072 | self.mode = M_NORMAL |
| 1073 | elif self.mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following |
| 1074 | self._telnetNegotiateOption(self.telnet_command, byte) |
| 1075 | self.mode = M_NORMAL |
| 1076 | |
| 1077 | # - incoming telnet commands and options |
| 1078 | |
| 1079 | def _telnetProcessCommand(self, command): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 1080 | """Process commands other than DO, DONT, WILL, WONT.""" |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1081 | # Currently none. RFC2217 only uses negotiation and subnegotiation. |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1082 | if self.logger: |
| 1083 | self.logger.warning("ignoring Telnet command: %r" % (command,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1084 | |
| 1085 | def _telnetNegotiateOption(self, command, option): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 1086 | """Process incoming DO, DONT, WILL, WONT.""" |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1087 | # check our registered telnet options and forward command to them |
| 1088 | # they know themselves if they have to answer or not |
| 1089 | known = False |
| 1090 | for item in self._telnet_options: |
| 1091 | # can have more than one match! as some options are duplicated for |
| 1092 | # 'us' and 'them' |
| 1093 | if item.option == option: |
| 1094 | item.process_incoming(command) |
| 1095 | known = True |
| 1096 | if not known: |
| 1097 | # handle unknown options |
| 1098 | # only answer to positive requests and deny them |
| 1099 | if command == WILL or command == DO: |
| 1100 | self.telnetSendOption((command == WILL and DONT or WONT), option) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1101 | if self.logger: |
| 1102 | self.logger.warning("rejected Telnet option: %r" % (option,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1103 | |
| 1104 | |
| 1105 | def _telnetProcessSubnegotiation(self, suboption): |
cliechti | 044d866 | 2009-08-11 21:40:31 +0000 | [diff] [blame] | 1106 | """Process subnegotiation, the data between IAC SB and IAC SE.""" |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1107 | if suboption[0:1] == COM_PORT_OPTION: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1108 | if self.logger: |
| 1109 | self.logger.debug('received COM_PORT_OPTION: %r' % (suboption,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1110 | if suboption[1:2] == SET_BAUDRATE: |
| 1111 | backup = self.serial.baudrate |
| 1112 | try: |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1113 | (baudrate,) = struct.unpack(b"!I", suboption[2:6]) |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1114 | if baudrate != 0: |
| 1115 | self.serial.baudrate = baudrate |
Chris Liechti | d214600 | 2015-08-04 16:57:16 +0200 | [diff] [blame] | 1116 | except ValueError as e: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1117 | if self.logger: |
| 1118 | self.logger.error("failed to set baud rate: %s" % (e,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1119 | self.serial.baudrate = backup |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 1120 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1121 | if self.logger: |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1122 | self.logger.info("%s baud rate: %s" % (baudrate and 'set' or 'get', self.serial.baudrate)) |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1123 | self.rfc2217SendSubnegotiation(SERVER_SET_BAUDRATE, struct.pack(b"!I", self.serial.baudrate)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1124 | elif suboption[1:2] == SET_DATASIZE: |
| 1125 | backup = self.serial.bytesize |
| 1126 | try: |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1127 | (datasize,) = struct.unpack("!B", suboption[2:3]) |
| 1128 | if datasize != 0: |
| 1129 | self.serial.bytesize = datasize |
Chris Liechti | d214600 | 2015-08-04 16:57:16 +0200 | [diff] [blame] | 1130 | except ValueError as e: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1131 | if self.logger: |
| 1132 | self.logger.error("failed to set data size: %s" % (e,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1133 | self.serial.bytesize = backup |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 1134 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1135 | if self.logger: |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1136 | self.logger.info("%s data size: %s" % (datasize and 'set' or 'get', self.serial.bytesize)) |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1137 | self.rfc2217SendSubnegotiation(SERVER_SET_DATASIZE, struct.pack(b"!B", self.serial.bytesize)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1138 | elif suboption[1:2] == SET_PARITY: |
| 1139 | backup = self.serial.parity |
| 1140 | try: |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1141 | parity = struct.unpack(b"!B", suboption[2:3])[0] |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1142 | if parity != 0: |
| 1143 | self.serial.parity = RFC2217_REVERSE_PARITY_MAP[parity] |
Chris Liechti | d214600 | 2015-08-04 16:57:16 +0200 | [diff] [blame] | 1144 | except ValueError as e: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1145 | if self.logger: |
| 1146 | self.logger.error("failed to set parity: %s" % (e,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1147 | self.serial.parity = backup |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 1148 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1149 | if self.logger: |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1150 | self.logger.info("%s parity: %s" % (parity and 'set' or 'get', self.serial.parity)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1151 | self.rfc2217SendSubnegotiation( |
| 1152 | SERVER_SET_PARITY, |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 1153 | struct.pack(b"!B", RFC2217_PARITY_MAP[self.serial.parity]) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1154 | ) |
| 1155 | elif suboption[1:2] == SET_STOPSIZE: |
| 1156 | backup = self.serial.stopbits |
| 1157 | try: |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1158 | stopbits = struct.unpack(b"!B", suboption[2:3])[0] |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1159 | if stopbits != 0: |
| 1160 | self.serial.stopbits = RFC2217_REVERSE_STOPBIT_MAP[stopbits] |
Chris Liechti | d214600 | 2015-08-04 16:57:16 +0200 | [diff] [blame] | 1161 | except ValueError as e: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1162 | if self.logger: |
| 1163 | self.logger.error("failed to set stop bits: %s" % (e,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1164 | self.serial.stopbits = backup |
cliechti | 5cc3eb1 | 2009-08-11 23:04:30 +0000 | [diff] [blame] | 1165 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1166 | if self.logger: |
cliechti | eada4fd | 2013-07-31 16:26:07 +0000 | [diff] [blame] | 1167 | self.logger.info("%s stop bits: %s" % (stopbits and 'set' or 'get', self.serial.stopbits)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1168 | self.rfc2217SendSubnegotiation( |
| 1169 | SERVER_SET_STOPSIZE, |
Chris Liechti | 01587b1 | 2015-08-05 02:39:32 +0200 | [diff] [blame] | 1170 | struct.pack(b"!B", RFC2217_STOPBIT_MAP[self.serial.stopbits]) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1171 | ) |
| 1172 | elif suboption[1:2] == SET_CONTROL: |
| 1173 | if suboption[2:3] == SET_CONTROL_REQ_FLOW_SETTING: |
| 1174 | if self.serial.xonxoff: |
| 1175 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_SW_FLOW_CONTROL) |
| 1176 | elif self.serial.rtscts: |
| 1177 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_HW_FLOW_CONTROL) |
| 1178 | else: |
| 1179 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_NO_FLOW_CONTROL) |
| 1180 | elif suboption[2:3] == SET_CONTROL_USE_NO_FLOW_CONTROL: |
| 1181 | self.serial.xonxoff = False |
| 1182 | self.serial.rtscts = False |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1183 | if self.logger: |
| 1184 | self.logger.info("changed flow control to None") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1185 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_NO_FLOW_CONTROL) |
| 1186 | elif suboption[2:3] == SET_CONTROL_USE_SW_FLOW_CONTROL: |
| 1187 | self.serial.xonxoff = True |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1188 | if self.logger: |
| 1189 | self.logger.info("changed flow control to XON/XOFF") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1190 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_SW_FLOW_CONTROL) |
| 1191 | elif suboption[2:3] == SET_CONTROL_USE_HW_FLOW_CONTROL: |
| 1192 | self.serial.rtscts = True |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1193 | if self.logger: |
| 1194 | self.logger.info("changed flow control to RTS/CTS") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1195 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_HW_FLOW_CONTROL) |
| 1196 | elif suboption[2:3] == SET_CONTROL_REQ_BREAK_STATE: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1197 | if self.logger: |
| 1198 | self.logger.warning("requested break state - not implemented") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1199 | pass # XXX needs cached value |
| 1200 | elif suboption[2:3] == SET_CONTROL_BREAK_ON: |
| 1201 | self.serial.setBreak(True) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1202 | if self.logger: |
| 1203 | self.logger.info("changed BREAK to active") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1204 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_BREAK_ON) |
| 1205 | elif suboption[2:3] == SET_CONTROL_BREAK_OFF: |
| 1206 | self.serial.setBreak(False) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1207 | if self.logger: |
| 1208 | self.logger.info("changed BREAK to inactive") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1209 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_BREAK_OFF) |
| 1210 | elif suboption[2:3] == SET_CONTROL_REQ_DTR: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1211 | if self.logger: |
| 1212 | self.logger.warning("requested DTR state - not implemented") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1213 | pass # XXX needs cached value |
| 1214 | elif suboption[2:3] == SET_CONTROL_DTR_ON: |
| 1215 | self.serial.setDTR(True) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1216 | if self.logger: |
| 1217 | self.logger.info("changed DTR to active") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1218 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_DTR_ON) |
| 1219 | elif suboption[2:3] == SET_CONTROL_DTR_OFF: |
| 1220 | self.serial.setDTR(False) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1221 | if self.logger: |
| 1222 | self.logger.info("changed DTR to inactive") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1223 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_DTR_OFF) |
| 1224 | elif suboption[2:3] == SET_CONTROL_REQ_RTS: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1225 | if self.logger: |
| 1226 | self.logger.warning("requested RTS state - not implemented") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1227 | pass # XXX needs cached value |
| 1228 | #~ self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_ON) |
| 1229 | elif suboption[2:3] == SET_CONTROL_RTS_ON: |
| 1230 | self.serial.setRTS(True) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1231 | if self.logger: |
| 1232 | self.logger.info("changed RTS to active") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1233 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_ON) |
| 1234 | elif suboption[2:3] == SET_CONTROL_RTS_OFF: |
| 1235 | self.serial.setRTS(False) |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1236 | if self.logger: |
| 1237 | self.logger.info("changed RTS to inactive") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1238 | self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_OFF) |
| 1239 | #~ elif suboption[2:3] == SET_CONTROL_REQ_FLOW_SETTING_IN: |
| 1240 | #~ elif suboption[2:3] == SET_CONTROL_USE_NO_FLOW_CONTROL_IN: |
| 1241 | #~ elif suboption[2:3] == SET_CONTROL_USE_SW_FLOW_CONTOL_IN: |
| 1242 | #~ elif suboption[2:3] == SET_CONTROL_USE_HW_FLOW_CONTOL_IN: |
| 1243 | #~ elif suboption[2:3] == SET_CONTROL_USE_DCD_FLOW_CONTROL: |
| 1244 | #~ elif suboption[2:3] == SET_CONTROL_USE_DTR_FLOW_CONTROL: |
| 1245 | #~ elif suboption[2:3] == SET_CONTROL_USE_DSR_FLOW_CONTROL: |
| 1246 | elif suboption[1:2] == NOTIFY_LINESTATE: |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 1247 | # client polls for current state |
| 1248 | self.rfc2217SendSubnegotiation( |
| 1249 | SERVER_NOTIFY_LINESTATE, |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1250 | to_bytes([0]) # sorry, nothing like that implemented |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 1251 | ) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1252 | elif suboption[1:2] == NOTIFY_MODEMSTATE: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1253 | if self.logger: |
| 1254 | self.logger.info("request for modem state") |
cliechti | 7cb78e8 | 2009-08-05 15:47:57 +0000 | [diff] [blame] | 1255 | # client polls for current state |
| 1256 | self.check_modem_lines(force_notification=True) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1257 | elif suboption[1:2] == FLOWCONTROL_SUSPEND: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1258 | if self.logger: |
| 1259 | self.logger.info("suspend") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1260 | self._remote_suspend_flow = True |
| 1261 | elif suboption[1:2] == FLOWCONTROL_RESUME: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1262 | if self.logger: |
| 1263 | self.logger.info("resume") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1264 | self._remote_suspend_flow = False |
| 1265 | elif suboption[1:2] == SET_LINESTATE_MASK: |
| 1266 | self.linstate_mask = ord(suboption[2:3]) # ensure it is a number |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1267 | if self.logger: |
cliechti | f325c03 | 2009-12-25 16:09:49 +0000 | [diff] [blame] | 1268 | self.logger.info("line state mask: 0x%02x" % (self.linstate_mask,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1269 | elif suboption[1:2] == SET_MODEMSTATE_MASK: |
| 1270 | self.modemstate_mask = ord(suboption[2:3]) # ensure it is a number |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1271 | if self.logger: |
cliechti | f325c03 | 2009-12-25 16:09:49 +0000 | [diff] [blame] | 1272 | self.logger.info("modem state mask: 0x%02x" % (self.modemstate_mask,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1273 | elif suboption[1:2] == PURGE_DATA: |
| 1274 | if suboption[2:3] == PURGE_RECEIVE_BUFFER: |
| 1275 | self.serial.flushInput() |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1276 | if self.logger: |
| 1277 | self.logger.info("purge in") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1278 | self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_RECEIVE_BUFFER) |
| 1279 | elif suboption[2:3] == PURGE_TRANSMIT_BUFFER: |
| 1280 | self.serial.flushOutput() |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1281 | if self.logger: |
| 1282 | self.logger.info("purge out") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1283 | self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_TRANSMIT_BUFFER) |
| 1284 | elif suboption[2:3] == PURGE_BOTH_BUFFERS: |
| 1285 | self.serial.flushInput() |
| 1286 | self.serial.flushOutput() |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1287 | if self.logger: |
| 1288 | self.logger.info("purge both") |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1289 | self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_BOTH_BUFFERS) |
| 1290 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1291 | if self.logger: |
| 1292 | self.logger.error("undefined PURGE_DATA: %r" % list(suboption[2:])) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1293 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1294 | if self.logger: |
| 1295 | self.logger.error("undefined COM_PORT_OPTION: %r" % list(suboption[1:])) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1296 | else: |
cliechti | 6a30077 | 2009-08-12 02:28:56 +0000 | [diff] [blame] | 1297 | if self.logger: |
| 1298 | self.logger.warning("unknown subnegotiation: %r" % (suboption,)) |
cliechti | 130d1f0 | 2009-08-04 02:10:58 +0000 | [diff] [blame] | 1299 | |
| 1300 | |
| 1301 | # simple client test |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 1302 | if __name__ == '__main__': |
| 1303 | import sys |
| 1304 | s = Serial('rfc2217://localhost:7000', 115200) |
| 1305 | sys.stdout.write('%s\n' % s) |
| 1306 | |
cliechti | 2b929b7 | 2009-08-02 23:49:02 +0000 | [diff] [blame] | 1307 | #~ s.baudrate = 1898 |
| 1308 | |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 1309 | sys.stdout.write("write...\n") |
Chris Liechti | b4cda3a | 2015-08-08 17:12:08 +0200 | [diff] [blame^] | 1310 | s.write(b"hello\n") |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 1311 | s.flush() |
cliechti | 8099bed | 2009-08-01 23:59:18 +0000 | [diff] [blame] | 1312 | sys.stdout.write("read: %s\n" % s.read(5)) |
| 1313 | |
| 1314 | #~ s.baudrate = 19200 |
| 1315 | #~ s.databits = 7 |
| 1316 | s.close() |