blob: be290ce763f2252f8516fc5590cb815358f72542 [file] [log] [blame]
cliechti8099bed2009-08-01 23:59:18 +00001#! 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 Liechti01587b12015-08-05 02:39:32 +020010# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +020011#
12# SPDX-License-Identifier: BSD-3-Clause
cliechti8099bed2009-08-01 23:59:18 +000013
14# TODO:
15# - setting control line -> answer is not checked (had problems with one of the
16# severs). consider implementing a compatibility mode flag to make check
17# conditional
18# - write timeout not implemented at all
cliechti8099bed2009-08-01 23:59:18 +000019
Chris Liechti033f17c2015-08-30 21:28:04 +020020# ###########################################################################
cliechti81c54762009-08-03 23:53:27 +000021# observations and issues with servers
Chris Liechti033f17c2015-08-30 21:28:04 +020022# ===========================================================================
cliechti81c54762009-08-03 23:53:27 +000023# sredird V2.2.1
24# - http://www.ibiblio.org/pub/Linux/system/serial/ sredird-2.2.2.tar.gz
25# - does not acknowledge SET_CONTROL (RTS/DTR) correctly, always responding
26# [105 1] instead of the actual value.
27# - SET_BAUDRATE answer contains 4 extra null bytes -> probably for larger
28# numbers than 2**32?
29# - To get the signature [COM_PORT_OPTION 0] has to be sent.
30# - run a server: while true; do nc -l -p 7000 -c "sredird debug /dev/ttyUSB0 /var/lock/sredir"; done
Chris Liechti033f17c2015-08-30 21:28:04 +020031# ===========================================================================
cliechti81c54762009-08-03 23:53:27 +000032# telnetcpcd (untested)
33# - http://ftp.wayne.edu/kermit/sredird/telnetcpcd-1.09.tar.gz
34# - To get the signature [COM_PORT_OPTION] w/o data has to be sent.
Chris Liechti033f17c2015-08-30 21:28:04 +020035# ===========================================================================
cliechti81c54762009-08-03 23:53:27 +000036# ser2net
37# - does not negotiate BINARY or COM_PORT_OPTION for his side but at least
38# acknowledges that the client activates these options
39# - The configuration may be that the server prints a banner. As this client
40# implementation does a flushInput on connect, this banner is hidden from
41# the user application.
42# - NOTIFY_MODEMSTATE: the poll interval of the server seems to be one
43# second.
44# - To get the signature [COM_PORT_OPTION 0] has to be sent.
45# - run a server: run ser2net daemon, in /etc/ser2net.conf:
46# 2000:telnet:0:/dev/ttyS0:9600 remctl banner
Chris Liechti033f17c2015-08-30 21:28:04 +020047# ###########################################################################
cliechti81c54762009-08-03 23:53:27 +000048
49# How to identify ports? pySerial might want to support other protocols in the
50# future, so lets use an URL scheme.
51# for RFC2217 compliant servers we will use this:
Chris Liechti142ae562015-08-23 01:11:06 +020052# rfc2217://<host>:<port>[?option[&option...]]
cliechti81c54762009-08-03 23:53:27 +000053#
54# options:
Chris Liechti01587b12015-08-05 02:39:32 +020055# - "logging" set log level print diagnostic messages (e.g. "logging=debug")
cliechti81c54762009-08-03 23:53:27 +000056# - "ign_set_control": do not look at the answers to SET_CONTROL
cliechti7cb78e82009-08-05 15:47:57 +000057# - "poll_modem": issue NOTIFY_MODEMSTATE requests when CTS/DTR/RI/CD is read.
58# Without this option it expects that the server sends notifications
59# automatically on change (which most servers do and is according to the
60# RFC).
cliechti81c54762009-08-03 23:53:27 +000061# the order of the options is not relevant
62
cliechti5cc3eb12009-08-11 23:04:30 +000063import logging
Chris Liechtic4bca9e2015-08-07 14:40:41 +020064import socket
65import struct
66import threading
67import time
68try:
69 import urlparse
70except ImportError:
71 import urllib.parse as urlparse
Chris Liechtid2146002015-08-04 16:57:16 +020072try:
73 import Queue
74except ImportError:
75 import queue as Queue
76
Chris Liechti033f17c2015-08-30 21:28:04 +020077import serial
78from serial.serialutil import SerialBase, SerialException, to_bytes, iterbytes, portNotOpenError
Chris Liechtib4cda3a2015-08-08 17:12:08 +020079
cliechti8099bed2009-08-01 23:59:18 +000080# port string is expected to be something like this:
81# rfc2217://host:port
82# host may be an IP or including domain, whatever.
83# port is 0...65535
84
Chris Liechti3ad62fb2015-08-29 21:53:32 +020085# map log level names to constants. used in from_url()
cliechti5cc3eb12009-08-11 23:04:30 +000086LOGGER_LEVELS = {
Chris Liechtic4bca9e2015-08-07 14:40:41 +020087 'debug': logging.DEBUG,
88 'info': logging.INFO,
89 'warning': logging.WARNING,
90 'error': logging.ERROR,
91 }
cliechti5cc3eb12009-08-11 23:04:30 +000092
93
cliechti8099bed2009-08-01 23:59:18 +000094# telnet protocol characters
Chris Liechti033f17c2015-08-30 21:28:04 +020095SE = b'\xf0' # Subnegotiation End
Chris Liechtib4cda3a2015-08-08 17:12:08 +020096NOP = b'\xf1' # No Operation
Chris Liechti033f17c2015-08-30 21:28:04 +020097DM = b'\xf2' # Data Mark
Chris Liechtib4cda3a2015-08-08 17:12:08 +020098BRK = b'\xf3' # Break
Chris Liechti033f17c2015-08-30 21:28:04 +020099IP = b'\xf4' # Interrupt process
100AO = b'\xf5' # Abort output
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200101AYT = b'\xf6' # Are You There
Chris Liechti033f17c2015-08-30 21:28:04 +0200102EC = b'\xf7' # Erase Character
103EL = b'\xf8' # Erase Line
104GA = b'\xf9' # Go Ahead
105SB = b'\xfa' # Subnegotiation Begin
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200106WILL = b'\xfb'
107WONT = b'\xfc'
Chris Liechti033f17c2015-08-30 21:28:04 +0200108DO = b'\xfd'
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200109DONT = b'\xfe'
Chris Liechti033f17c2015-08-30 21:28:04 +0200110IAC = b'\xff' # Interpret As Command
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200111IAC_DOUBLED = b'\xff\xff'
cliechti8099bed2009-08-01 23:59:18 +0000112
113# selected telnet options
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200114BINARY = b'\x00' # 8-bit data path
115ECHO = b'\x01' # echo
116SGA = b'\x03' # suppress go ahead
cliechti8099bed2009-08-01 23:59:18 +0000117
118# RFC2217
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200119COM_PORT_OPTION = b'\x2c'
cliechti8099bed2009-08-01 23:59:18 +0000120
121# Client to Access Server
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200122SET_BAUDRATE = b'\x01'
123SET_DATASIZE = b'\x02'
124SET_PARITY = b'\x03'
125SET_STOPSIZE = b'\x04'
126SET_CONTROL = b'\x05'
127NOTIFY_LINESTATE = b'\x06'
128NOTIFY_MODEMSTATE = b'\x07'
129FLOWCONTROL_SUSPEND = b'\x08'
130FLOWCONTROL_RESUME = b'\x09'
131SET_LINESTATE_MASK = b'\x0a'
132SET_MODEMSTATE_MASK = b'\x0b'
133PURGE_DATA = b'\x0c'
cliechti8099bed2009-08-01 23:59:18 +0000134
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200135SERVER_SET_BAUDRATE = b'\x65'
136SERVER_SET_DATASIZE = b'\x66'
137SERVER_SET_PARITY = b'\x67'
138SERVER_SET_STOPSIZE = b'\x68'
139SERVER_SET_CONTROL = b'\x69'
140SERVER_NOTIFY_LINESTATE = b'\x6a'
141SERVER_NOTIFY_MODEMSTATE = b'\x6b'
142SERVER_FLOWCONTROL_SUSPEND = b'\x6c'
143SERVER_FLOWCONTROL_RESUME = b'\x6d'
144SERVER_SET_LINESTATE_MASK = b'\x6e'
145SERVER_SET_MODEMSTATE_MASK = b'\x6f'
146SERVER_PURGE_DATA = b'\x70'
cliechti8099bed2009-08-01 23:59:18 +0000147
148RFC2217_ANSWER_MAP = {
149 SET_BAUDRATE: SERVER_SET_BAUDRATE,
150 SET_DATASIZE: SERVER_SET_DATASIZE,
151 SET_PARITY: SERVER_SET_PARITY,
152 SET_STOPSIZE: SERVER_SET_STOPSIZE,
153 SET_CONTROL: SERVER_SET_CONTROL,
154 NOTIFY_LINESTATE: SERVER_NOTIFY_LINESTATE,
155 NOTIFY_MODEMSTATE: SERVER_NOTIFY_MODEMSTATE,
156 FLOWCONTROL_SUSPEND: SERVER_FLOWCONTROL_SUSPEND,
157 FLOWCONTROL_RESUME: SERVER_FLOWCONTROL_RESUME,
158 SET_LINESTATE_MASK: SERVER_SET_LINESTATE_MASK,
159 SET_MODEMSTATE_MASK: SERVER_SET_MODEMSTATE_MASK,
160 PURGE_DATA: SERVER_PURGE_DATA,
161}
162
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200163SET_CONTROL_REQ_FLOW_SETTING = b'\x00' # Request Com Port Flow Control Setting (outbound/both)
164SET_CONTROL_USE_NO_FLOW_CONTROL = b'\x01' # Use No Flow Control (outbound/both)
165SET_CONTROL_USE_SW_FLOW_CONTROL = b'\x02' # Use XON/XOFF Flow Control (outbound/both)
166SET_CONTROL_USE_HW_FLOW_CONTROL = b'\x03' # Use HARDWARE Flow Control (outbound/both)
167SET_CONTROL_REQ_BREAK_STATE = b'\x04' # Request BREAK State
168SET_CONTROL_BREAK_ON = b'\x05' # Set BREAK State ON
169SET_CONTROL_BREAK_OFF = b'\x06' # Set BREAK State OFF
170SET_CONTROL_REQ_DTR = b'\x07' # Request DTR Signal State
171SET_CONTROL_DTR_ON = b'\x08' # Set DTR Signal State ON
172SET_CONTROL_DTR_OFF = b'\x09' # Set DTR Signal State OFF
173SET_CONTROL_REQ_RTS = b'\x0a' # Request RTS Signal State
174SET_CONTROL_RTS_ON = b'\x0b' # Set RTS Signal State ON
175SET_CONTROL_RTS_OFF = b'\x0c' # Set RTS Signal State OFF
176SET_CONTROL_REQ_FLOW_SETTING_IN = b'\x0d' # Request Com Port Flow Control Setting (inbound)
177SET_CONTROL_USE_NO_FLOW_CONTROL_IN = b'\x0e' # Use No Flow Control (inbound)
178SET_CONTROL_USE_SW_FLOW_CONTOL_IN = b'\x0f' # Use XON/XOFF Flow Control (inbound)
179SET_CONTROL_USE_HW_FLOW_CONTOL_IN = b'\x10' # Use HARDWARE Flow Control (inbound)
180SET_CONTROL_USE_DCD_FLOW_CONTROL = b'\x11' # Use DCD Flow Control (outbound/both)
181SET_CONTROL_USE_DTR_FLOW_CONTROL = b'\x12' # Use DTR Flow Control (inbound)
182SET_CONTROL_USE_DSR_FLOW_CONTROL = b'\x13' # Use DSR Flow Control (outbound/both)
cliechti8099bed2009-08-01 23:59:18 +0000183
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200184LINESTATE_MASK_TIMEOUT = 128 # Time-out Error
185LINESTATE_MASK_SHIFTREG_EMPTY = 64 # Transfer Shift Register Empty
186LINESTATE_MASK_TRANSREG_EMPTY = 32 # Transfer Holding Register Empty
187LINESTATE_MASK_BREAK_DETECT = 16 # Break-detect Error
188LINESTATE_MASK_FRAMING_ERROR = 8 # Framing Error
189LINESTATE_MASK_PARTIY_ERROR = 4 # Parity Error
190LINESTATE_MASK_OVERRUN_ERROR = 2 # Overrun Error
191LINESTATE_MASK_DATA_READY = 1 # Data Ready
cliechti8099bed2009-08-01 23:59:18 +0000192
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200193MODEMSTATE_MASK_CD = 128 # Receive Line Signal Detect (also known as Carrier Detect)
194MODEMSTATE_MASK_RI = 64 # Ring Indicator
195MODEMSTATE_MASK_DSR = 32 # Data-Set-Ready Signal State
196MODEMSTATE_MASK_CTS = 16 # Clear-To-Send Signal State
197MODEMSTATE_MASK_CD_CHANGE = 8 # Delta Receive Line Signal Detect
198MODEMSTATE_MASK_RI_CHANGE = 4 # Trailing-edge Ring Detector
199MODEMSTATE_MASK_DSR_CHANGE = 2 # Delta Data-Set-Ready
200MODEMSTATE_MASK_CTS_CHANGE = 1 # Delta Clear-To-Send
cliechti8099bed2009-08-01 23:59:18 +0000201
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200202PURGE_RECEIVE_BUFFER = b'\x01' # Purge access server receive data buffer
203PURGE_TRANSMIT_BUFFER = b'\x02' # Purge access server transmit data buffer
204PURGE_BOTH_BUFFERS = b'\x03' # Purge both the access server receive data buffer and the access server transmit data buffer
cliechti8099bed2009-08-01 23:59:18 +0000205
206
207RFC2217_PARITY_MAP = {
Chris Liechti033f17c2015-08-30 21:28:04 +0200208 serial.PARITY_NONE: 1,
209 serial.PARITY_ODD: 2,
210 serial.PARITY_EVEN: 3,
211 serial.PARITY_MARK: 4,
212 serial.PARITY_SPACE: 5,
cliechti8099bed2009-08-01 23:59:18 +0000213}
Chris Liechti033f17c2015-08-30 21:28:04 +0200214RFC2217_REVERSE_PARITY_MAP = dict((v, k) for k, v in RFC2217_PARITY_MAP.items())
cliechti8099bed2009-08-01 23:59:18 +0000215
216RFC2217_STOPBIT_MAP = {
Chris Liechti033f17c2015-08-30 21:28:04 +0200217 serial.STOPBITS_ONE: 1,
218 serial.STOPBITS_ONE_POINT_FIVE: 3,
219 serial.STOPBITS_TWO: 2,
cliechti8099bed2009-08-01 23:59:18 +0000220}
Chris Liechti033f17c2015-08-30 21:28:04 +0200221RFC2217_REVERSE_STOPBIT_MAP = dict((v, k) for k, v in RFC2217_STOPBIT_MAP.items())
cliechti8099bed2009-08-01 23:59:18 +0000222
cliechti130d1f02009-08-04 02:10:58 +0000223# Telnet filter states
224M_NORMAL = 0
225M_IAC_SEEN = 1
226M_NEGOTIATE = 2
cliechti8099bed2009-08-01 23:59:18 +0000227
cliechti130d1f02009-08-04 02:10:58 +0000228# TelnetOption and TelnetSubnegotiation states
cliechtiac205322009-08-02 20:40:21 +0000229REQUESTED = 'REQUESTED'
230ACTIVE = 'ACTIVE'
231INACTIVE = 'INACTIVE'
232REALLY_INACTIVE = 'REALLY_INACTIVE'
233
Chris Liechti033f17c2015-08-30 21:28:04 +0200234
cliechtiac205322009-08-02 20:40:21 +0000235class TelnetOption(object):
cliechti1ef7e3e2009-08-03 02:38:43 +0000236 """Manage a single telnet option, keeps track of DO/DONT WILL/WONT."""
237
cliechti86b593e2009-08-05 16:28:12 +0000238 def __init__(self, connection, name, option, send_yes, send_no, ack_yes, ack_no, initial_state, activation_callback=None):
cliechtieada4fd2013-07-31 16:26:07 +0000239 """\
240 Initialize option.
cliechti1ef7e3e2009-08-03 02:38:43 +0000241 :param connection: connection used to transmit answers
242 :param name: a readable name for debug outputs
243 :param send_yes: what to send when option is to be enabled.
244 :param send_no: what to send when option is to be disabled.
245 :param ack_yes: what to expect when remote agrees on option.
246 :param ack_no: what to expect when remote disagrees on option.
247 :param initial_state: options initialized with REQUESTED are tried to
248 be enabled on startup. use INACTIVE for all others.
249 """
cliechti2b929b72009-08-02 23:49:02 +0000250 self.connection = connection
cliechtiac205322009-08-02 20:40:21 +0000251 self.name = name
252 self.option = option
253 self.send_yes = send_yes
254 self.send_no = send_no
255 self.ack_yes = ack_yes
256 self.ack_no = ack_no
257 self.state = initial_state
258 self.active = False
cliechti86b593e2009-08-05 16:28:12 +0000259 self.activation_callback = activation_callback
cliechtiac205322009-08-02 20:40:21 +0000260
261 def __repr__(self):
cliechti1ef7e3e2009-08-03 02:38:43 +0000262 """String for debug outputs"""
cliechtiac205322009-08-02 20:40:21 +0000263 return "%s:%s(%s)" % (self.name, self.active, self.state)
264
cliechti2b929b72009-08-02 23:49:02 +0000265 def process_incoming(self, command):
cliechti7d448562014-08-03 21:57:45 +0000266 """\
267 A DO/DONT/WILL/WONT was received for this option, update state and
268 answer when needed.
269 """
cliechtiac205322009-08-02 20:40:21 +0000270 if command == self.ack_yes:
271 if self.state is REQUESTED:
272 self.state = ACTIVE
273 self.active = True
cliechti86b593e2009-08-05 16:28:12 +0000274 if self.activation_callback is not None:
275 self.activation_callback()
cliechtiac205322009-08-02 20:40:21 +0000276 elif self.state is ACTIVE:
277 pass
278 elif self.state is INACTIVE:
279 self.state = ACTIVE
cliechti1ef7e3e2009-08-03 02:38:43 +0000280 self.connection.telnetSendOption(self.send_yes, self.option)
cliechtiac205322009-08-02 20:40:21 +0000281 self.active = True
cliechti86b593e2009-08-05 16:28:12 +0000282 if self.activation_callback is not None:
283 self.activation_callback()
cliechtiac205322009-08-02 20:40:21 +0000284 elif self.state is REALLY_INACTIVE:
cliechti1ef7e3e2009-08-03 02:38:43 +0000285 self.connection.telnetSendOption(self.send_no, self.option)
cliechtiac205322009-08-02 20:40:21 +0000286 else:
287 raise ValueError('option in illegal state %r' % self)
288 elif command == self.ack_no:
289 if self.state is REQUESTED:
290 self.state = INACTIVE
291 self.active = False
292 elif self.state is ACTIVE:
293 self.state = INACTIVE
cliechti1ef7e3e2009-08-03 02:38:43 +0000294 self.connection.telnetSendOption(self.send_no, self.option)
cliechtiac205322009-08-02 20:40:21 +0000295 self.active = False
296 elif self.state is INACTIVE:
297 pass
298 elif self.state is REALLY_INACTIVE:
299 pass
300 else:
301 raise ValueError('option in illegal state %r' % self)
302
303
cliechti2b929b72009-08-02 23:49:02 +0000304class TelnetSubnegotiation(object):
cliechtieada4fd2013-07-31 16:26:07 +0000305 """\
306 A object to handle subnegotiation of options. In this case actually
307 sub-sub options for RFC 2217. It is used to track com port options.
308 """
cliechti2b929b72009-08-02 23:49:02 +0000309
310 def __init__(self, connection, name, option, ack_option=None):
Chris Liechti033f17c2015-08-30 21:28:04 +0200311 if ack_option is None:
312 ack_option = option
cliechti2b929b72009-08-02 23:49:02 +0000313 self.connection = connection
314 self.name = name
315 self.option = option
316 self.value = None
317 self.ack_option = ack_option
318 self.state = INACTIVE
319
320 def __repr__(self):
cliechti044d8662009-08-11 21:40:31 +0000321 """String for debug outputs."""
cliechti2b929b72009-08-02 23:49:02 +0000322 return "%s:%s" % (self.name, self.state)
323
324 def set(self, value):
cliechtieada4fd2013-07-31 16:26:07 +0000325 """\
cliechti7d448562014-08-03 21:57:45 +0000326 Request a change of the value. a request is sent to the server. if
cliechti2b929b72009-08-02 23:49:02 +0000327 the client needs to know if the change is performed he has to check the
cliechtieada4fd2013-07-31 16:26:07 +0000328 state of this object.
329 """
cliechti2b929b72009-08-02 23:49:02 +0000330 self.value = value
331 self.state = REQUESTED
cliechti1ef7e3e2009-08-03 02:38:43 +0000332 self.connection.rfc2217SendSubnegotiation(self.option, self.value)
cliechti6a300772009-08-12 02:28:56 +0000333 if self.connection.logger:
334 self.connection.logger.debug("SB Requesting %s -> %r" % (self.name, self.value))
cliechti2b929b72009-08-02 23:49:02 +0000335
336 def isReady(self):
cliechtieada4fd2013-07-31 16:26:07 +0000337 """\
cliechti7d448562014-08-03 21:57:45 +0000338 Check if answer from server has been received. when server rejects
cliechtieada4fd2013-07-31 16:26:07 +0000339 the change, raise a ValueError.
340 """
cliechti2b929b72009-08-02 23:49:02 +0000341 if self.state == REALLY_INACTIVE:
342 raise ValueError("remote rejected value for option %r" % (self.name))
343 return self.state == ACTIVE
cliechti1ef7e3e2009-08-03 02:38:43 +0000344 # add property to have a similar interface as TelnetOption
cliechti2b929b72009-08-02 23:49:02 +0000345 active = property(isReady)
346
cliechti044d8662009-08-11 21:40:31 +0000347 def wait(self, timeout=3):
cliechtieada4fd2013-07-31 16:26:07 +0000348 """\
cliechti7d448562014-08-03 21:57:45 +0000349 Wait until the subnegotiation has been acknowledged or timeout. It
cliechti1ef7e3e2009-08-03 02:38:43 +0000350 can also throw a value error when the answer from the server does not
cliechtieada4fd2013-07-31 16:26:07 +0000351 match the value sent.
352 """
cliechti044d8662009-08-11 21:40:31 +0000353 timeout_time = time.time() + timeout
cliechti2b929b72009-08-02 23:49:02 +0000354 while time.time() < timeout_time:
355 time.sleep(0.05) # prevent 100% CPU load
356 if self.isReady():
357 break
358 else:
359 raise SerialException("timeout while waiting for option %r" % (self.name))
360
361 def checkAnswer(self, suboption):
cliechtieada4fd2013-07-31 16:26:07 +0000362 """\
cliechti7d448562014-08-03 21:57:45 +0000363 Check an incoming subnegotiation block. The parameter already has
cliechtieada4fd2013-07-31 16:26:07 +0000364 cut off the header like sub option number and com port option value.
365 """
cliechti2b929b72009-08-02 23:49:02 +0000366 if self.value == suboption[:len(self.value)]:
367 self.state = ACTIVE
368 else:
369 # error propagation done in isReady
370 self.state = REALLY_INACTIVE
cliechti6a300772009-08-12 02:28:56 +0000371 if self.connection.logger:
372 self.connection.logger.debug("SB Answer %s -> %r -> %s" % (self.name, suboption, self.state))
cliechti2b929b72009-08-02 23:49:02 +0000373
374
Chris Liechtief6b7b42015-08-06 22:19:26 +0200375class Serial(SerialBase):
cliechti044d8662009-08-11 21:40:31 +0000376 """Serial port implementation for RFC 2217 remote serial ports."""
cliechti8099bed2009-08-01 23:59:18 +0000377
378 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
379 9600, 19200, 38400, 57600, 115200)
380
Chris Liechtibb5341b2015-10-31 23:31:26 +0100381 def __init__(self, *args, **kwargs):
382 super(Serial, self).__init__(*args, **kwargs)
383 self._thread = None
384 self._socket = None
385
cliechti8099bed2009-08-01 23:59:18 +0000386 def open(self):
cliechtieada4fd2013-07-31 16:26:07 +0000387 """\
388 Open port with current settings. This may throw a SerialException
389 if the port cannot be opened.
390 """
cliechti6a300772009-08-12 02:28:56 +0000391 self.logger = None
cliechti81c54762009-08-03 23:53:27 +0000392 self._ignore_set_control_answer = False
cliechti7cb78e82009-08-05 15:47:57 +0000393 self._poll_modem_state = False
cliechtidfe2d272009-08-10 22:19:41 +0000394 self._network_timeout = 3
cliechti8099bed2009-08-01 23:59:18 +0000395 if self._port is None:
396 raise SerialException("Port must be configured before it can be used.")
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200397 if self.is_open:
cliechti8f69e702011-03-19 00:22:32 +0000398 raise SerialException("Port is already open.")
cliechti8099bed2009-08-01 23:59:18 +0000399 try:
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200400 self._socket = socket.create_connection(self.from_url(self.portstr))
cliechti6a300772009-08-12 02:28:56 +0000401 self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
Chris Liechti68340d72015-08-03 14:15:48 +0200402 except Exception as msg:
cliechti8099bed2009-08-01 23:59:18 +0000403 self._socket = None
404 raise SerialException("Could not open port %s: %s" % (self.portstr, msg))
405
Chris Liechti033f17c2015-08-30 21:28:04 +0200406 self._socket.settimeout(5) # XXX good value?
cliechti8099bed2009-08-01 23:59:18 +0000407
cliechti1ef7e3e2009-08-03 02:38:43 +0000408 # use a thread save queue as buffer. it also simplifies implementing
409 # the read timeout
cliechti8099bed2009-08-01 23:59:18 +0000410 self._read_buffer = Queue.Queue()
cliechti81c54762009-08-03 23:53:27 +0000411 # to ensure that user writes does not interfere with internal
412 # telnet/rfc2217 options establish a lock
413 self._write_lock = threading.Lock()
cliechtiac205322009-08-02 20:40:21 +0000414 # name the following separately so that, below, a check can be easily done
415 mandadory_options = [
cliechti2b929b72009-08-02 23:49:02 +0000416 TelnetOption(self, 'we-BINARY', BINARY, WILL, WONT, DO, DONT, INACTIVE),
cliechti2b929b72009-08-02 23:49:02 +0000417 TelnetOption(self, 'we-RFC2217', COM_PORT_OPTION, WILL, WONT, DO, DONT, REQUESTED),
cliechtiac205322009-08-02 20:40:21 +0000418 ]
419 # all supported telnet options
420 self._telnet_options = [
cliechtia29275e2009-08-03 00:08:04 +0000421 TelnetOption(self, 'ECHO', ECHO, DO, DONT, WILL, WONT, REQUESTED),
cliechti2b929b72009-08-02 23:49:02 +0000422 TelnetOption(self, 'we-SGA', SGA, WILL, WONT, DO, DONT, REQUESTED),
423 TelnetOption(self, 'they-SGA', SGA, DO, DONT, WILL, WONT, REQUESTED),
cliechti81c54762009-08-03 23:53:27 +0000424 TelnetOption(self, 'they-BINARY', BINARY, DO, DONT, WILL, WONT, INACTIVE),
425 TelnetOption(self, 'they-RFC2217', COM_PORT_OPTION, DO, DONT, WILL, WONT, REQUESTED),
cliechtiac205322009-08-02 20:40:21 +0000426 ] + mandadory_options
cliechti044d8662009-08-11 21:40:31 +0000427 # RFC 2217 specific states
cliechti2b929b72009-08-02 23:49:02 +0000428 # COM port settings
429 self._rfc2217_port_settings = {
430 'baudrate': TelnetSubnegotiation(self, 'baudrate', SET_BAUDRATE, SERVER_SET_BAUDRATE),
431 'datasize': TelnetSubnegotiation(self, 'datasize', SET_DATASIZE, SERVER_SET_DATASIZE),
432 'parity': TelnetSubnegotiation(self, 'parity', SET_PARITY, SERVER_SET_PARITY),
433 'stopsize': TelnetSubnegotiation(self, 'stopsize', SET_STOPSIZE, SERVER_SET_STOPSIZE),
434 }
cliechticb20a4f2011-04-25 02:25:54 +0000435 # There are more subnegotiation objects, combine all in one dictionary
cliechti2b929b72009-08-02 23:49:02 +0000436 # for easy access
437 self._rfc2217_options = {
438 'purge': TelnetSubnegotiation(self, 'purge', PURGE_DATA, SERVER_PURGE_DATA),
cliechti81c54762009-08-03 23:53:27 +0000439 'control': TelnetSubnegotiation(self, 'control', SET_CONTROL, SERVER_SET_CONTROL),
cliechti2b929b72009-08-02 23:49:02 +0000440 }
441 self._rfc2217_options.update(self._rfc2217_port_settings)
442 # cache for line and modem states that the server sends to us
cliechti8099bed2009-08-01 23:59:18 +0000443 self._linestate = 0
cliechti7cb78e82009-08-05 15:47:57 +0000444 self._modemstate = None
445 self._modemstate_expires = 0
cliechti044d8662009-08-11 21:40:31 +0000446 # RFC 2217 flow control between server and client
cliechti672d0292009-08-03 02:01:57 +0000447 self._remote_suspend_flow = False
cliechti8099bed2009-08-01 23:59:18 +0000448
Chris Liechti39d52172015-10-25 22:53:51 +0100449 self.is_open = True
cliechti1ef7e3e2009-08-03 02:38:43 +0000450 self._thread = threading.Thread(target=self._telnetReadLoop)
cliechti8099bed2009-08-01 23:59:18 +0000451 self._thread.setDaemon(True)
cliechti5cc3eb12009-08-11 23:04:30 +0000452 self._thread.setName('pySerial RFC 2217 reader thread for %s' % (self._port,))
cliechti8099bed2009-08-01 23:59:18 +0000453 self._thread.start()
454
Chris Liechti39d52172015-10-25 22:53:51 +0100455 try: # must clean-up if open fails
456 # negotiate Telnet/RFC 2217 -> send initial requests
457 for option in self._telnet_options:
458 if option.state is REQUESTED:
459 self.telnetSendOption(option.send_yes, option.option)
460 # now wait until important options are negotiated
461 timeout_time = time.time() + self._network_timeout
462 while time.time() < timeout_time:
463 time.sleep(0.05) # prevent 100% CPU load
464 if sum(o.active for o in mandadory_options) == sum(o.state != INACTIVE for o in mandadory_options):
465 break
466 else:
467 raise SerialException("Remote does not seem to support RFC2217 or BINARY mode %r" % mandadory_options)
468 if self.logger:
469 self.logger.info("Negotiated options: %s" % self._telnet_options)
cliechti8099bed2009-08-01 23:59:18 +0000470
Chris Liechti39d52172015-10-25 22:53:51 +0100471 # fine, go on, set RFC 2271 specific things
472 self._reconfigure_port()
473 # all things set up get, now a clean start
474 if not self._dsrdtr:
475 self._update_dtr_state()
476 if not self._rtscts:
477 self._update_rts_state()
478 self.reset_input_buffer()
479 self.reset_output_buffer()
480 except:
481 self.close()
482 raise
cliechti8099bed2009-08-01 23:59:18 +0000483
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200484 def _reconfigure_port(self):
cliechti8099bed2009-08-01 23:59:18 +0000485 """Set communication parameters on opened port."""
486 if self._socket is None:
487 raise SerialException("Can only operate on open ports")
488
cliechti8099bed2009-08-01 23:59:18 +0000489 # if self._timeout != 0 and self._interCharTimeout is not None:
cliechti8099bed2009-08-01 23:59:18 +0000490 # XXX
491
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200492 if self._write_timeout is not None:
493 raise NotImplementedError('write_timeout is currently not supported')
cliechti2b929b72009-08-02 23:49:02 +0000494 # XXX
cliechti8099bed2009-08-01 23:59:18 +0000495
cliechti2b929b72009-08-02 23:49:02 +0000496 # Setup the connection
cliechti1ef7e3e2009-08-03 02:38:43 +0000497 # to get good performance, all parameter changes are sent first...
Chris Liechti01587b12015-08-05 02:39:32 +0200498 if not 0 < self._baudrate < 2**32:
cliechti81c54762009-08-03 23:53:27 +0000499 raise ValueError("invalid baudrate: %r" % (self._baudrate))
Chris Liechti01587b12015-08-05 02:39:32 +0200500 self._rfc2217_port_settings['baudrate'].set(struct.pack(b'!I', self._baudrate))
501 self._rfc2217_port_settings['datasize'].set(struct.pack(b'!B', self._bytesize))
502 self._rfc2217_port_settings['parity'].set(struct.pack(b'!B', RFC2217_PARITY_MAP[self._parity]))
503 self._rfc2217_port_settings['stopsize'].set(struct.pack(b'!B', RFC2217_STOPBIT_MAP[self._stopbits]))
cliechti8099bed2009-08-01 23:59:18 +0000504
cliechti2b929b72009-08-02 23:49:02 +0000505 # and now wait until parameters are active
506 items = self._rfc2217_port_settings.values()
cliechti6a300772009-08-12 02:28:56 +0000507 if self.logger:
508 self.logger.debug("Negotiating settings: %s" % (items,))
cliechtidfe2d272009-08-10 22:19:41 +0000509 timeout_time = time.time() + self._network_timeout
cliechti2b929b72009-08-02 23:49:02 +0000510 while time.time() < timeout_time:
511 time.sleep(0.05) # prevent 100% CPU load
512 if sum(o.active for o in items) == len(items):
513 break
514 else:
515 raise SerialException("Remote does not accept parameter change (RFC2217): %r" % items)
cliechti6a300772009-08-12 02:28:56 +0000516 if self.logger:
517 self.logger.info("Negotiated settings: %s" % (items,))
cliechti8099bed2009-08-01 23:59:18 +0000518
519 if self._rtscts and self._xonxoff:
cliechti1ef7e3e2009-08-03 02:38:43 +0000520 raise ValueError('xonxoff and rtscts together are not supported')
cliechti8099bed2009-08-01 23:59:18 +0000521 elif self._rtscts:
cliechti1ef7e3e2009-08-03 02:38:43 +0000522 self.rfc2217SetControl(SET_CONTROL_USE_HW_FLOW_CONTROL)
cliechti8099bed2009-08-01 23:59:18 +0000523 elif self._xonxoff:
cliechti1ef7e3e2009-08-03 02:38:43 +0000524 self.rfc2217SetControl(SET_CONTROL_USE_SW_FLOW_CONTROL)
cliechti8099bed2009-08-01 23:59:18 +0000525 else:
cliechti1ef7e3e2009-08-03 02:38:43 +0000526 self.rfc2217SetControl(SET_CONTROL_USE_NO_FLOW_CONTROL)
cliechti8099bed2009-08-01 23:59:18 +0000527
528 def close(self):
529 """Close port"""
Chris Liechti39d52172015-10-25 22:53:51 +0100530 self.is_open = False
531 if self._socket:
532 try:
533 self._socket.shutdown(socket.SHUT_RDWR)
534 self._socket.close()
535 except:
536 # ignore errors.
537 pass
538 if self._thread:
539 self._thread.join(7) # XXX more than socket timeout
540 self._thread = None
cliechti8099bed2009-08-01 23:59:18 +0000541 # in case of quick reconnects, give the server some time
542 time.sleep(0.3)
Chris Liechti39d52172015-10-25 22:53:51 +0100543 self._socket = None
cliechti8099bed2009-08-01 23:59:18 +0000544
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200545 def from_url(self, url):
cliechti1ef7e3e2009-08-03 02:38:43 +0000546 """extract host and port from an URL string"""
Chris Liechtia4222112015-08-07 01:03:12 +0200547 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200548 if parts.scheme != "rfc2217":
549 raise SerialException('expected a string in the form "rfc2217://<host>:<port>[?option[&option...]]": not starting with rfc2217:// (%r)' % (parts.scheme,))
cliechti8099bed2009-08-01 23:59:18 +0000550 try:
Chris Liechtia4222112015-08-07 01:03:12 +0200551 # process options now, directly altering self
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200552 for option, values in urlparse.parse_qs(parts.query, True).items():
553 if option == 'logging':
Chris Liechtia4222112015-08-07 01:03:12 +0200554 logging.basicConfig() # XXX is that good to call it here?
555 self.logger = logging.getLogger('pySerial.rfc2217')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200556 self.logger.setLevel(LOGGER_LEVELS[values[0]])
Chris Liechtia4222112015-08-07 01:03:12 +0200557 self.logger.debug('enabled logging')
558 elif option == 'ign_set_control':
559 self._ignore_set_control_answer = True
560 elif option == 'poll_modem':
561 self._poll_modem_state = True
562 elif option == 'timeout':
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200563 self._network_timeout = float(values[0])
Chris Liechtia4222112015-08-07 01:03:12 +0200564 else:
565 raise ValueError('unknown option: %r' % (option,))
cliechti81c54762009-08-03 23:53:27 +0000566 # get host and port
Chris Liechtia4222112015-08-07 01:03:12 +0200567 host, port = parts.hostname, parts.port
Chris Liechti033f17c2015-08-30 21:28:04 +0200568 if not 0 <= port < 65536:
569 raise ValueError("port not in range 0...65535")
Chris Liechti68340d72015-08-03 14:15:48 +0200570 except ValueError as e:
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200571 raise SerialException('expected a string in the form "rfc2217://<host>:<port>[?option[&option...]]": %s' % e)
cliechti8099bed2009-08-01 23:59:18 +0000572 return (host, port)
573
574 # - - - - - - - - - - - - - - - - - - - - - - - -
575
Chris Liechtief1fe252015-08-27 23:25:21 +0200576 @property
577 def in_waiting(self):
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200578 """Return the number of bytes currently in the input buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200579 if not self.is_open:
580 raise portNotOpenError
cliechti8099bed2009-08-01 23:59:18 +0000581 return self._read_buffer.qsize()
582
583 def read(self, size=1):
cliechtieada4fd2013-07-31 16:26:07 +0000584 """\
585 Read size bytes from the serial port. If a timeout is set it may
cliechti8099bed2009-08-01 23:59:18 +0000586 return less characters as requested. With no timeout it will block
cliechtieada4fd2013-07-31 16:26:07 +0000587 until the requested number of bytes is read.
588 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200589 if not self.is_open:
590 raise portNotOpenError
cliechti8099bed2009-08-01 23:59:18 +0000591 data = bytearray()
592 try:
593 while len(data) < size:
cliechti81c54762009-08-03 23:53:27 +0000594 if self._thread is None:
595 raise SerialException('connection failed (reader thread died)')
Chris Liechti01587b12015-08-05 02:39:32 +0200596 data += self._read_buffer.get(True, self._timeout)
Chris Liechti033f17c2015-08-30 21:28:04 +0200597 except Queue.Empty: # -> timeout
cliechti8099bed2009-08-01 23:59:18 +0000598 pass
599 return bytes(data)
600
601 def write(self, data):
cliechtieada4fd2013-07-31 16:26:07 +0000602 """\
Chris Liechti3ad62fb2015-08-29 21:53:32 +0200603 Output the given byte string over the serial port. Can block if the
cliechti8099bed2009-08-01 23:59:18 +0000604 connection is blocked. May raise SerialException if the connection is
cliechtieada4fd2013-07-31 16:26:07 +0000605 closed.
606 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200607 if not self.is_open:
608 raise portNotOpenError
Chris Liechti01587b12015-08-05 02:39:32 +0200609 with self._write_lock:
cliechti81c54762009-08-03 23:53:27 +0000610 try:
cliechti38077122013-10-16 02:57:27 +0000611 self._socket.sendall(to_bytes(data).replace(IAC, IAC_DOUBLED))
Chris Liechti68340d72015-08-03 14:15:48 +0200612 except socket.error as e:
Chris Liechti142ae562015-08-23 01:11:06 +0200613 raise SerialException("connection failed (socket error): %s" % (e,))
cliechti8099bed2009-08-01 23:59:18 +0000614 return len(data)
615
Chris Liechtief1fe252015-08-27 23:25:21 +0200616 def reset_input_buffer(self):
cliechti8099bed2009-08-01 23:59:18 +0000617 """Clear input buffer, discarding all that is in the buffer."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200618 if not self.is_open:
619 raise portNotOpenError
cliechti1ef7e3e2009-08-03 02:38:43 +0000620 self.rfc2217SendPurge(PURGE_RECEIVE_BUFFER)
cliechti8099bed2009-08-01 23:59:18 +0000621 # empty read buffer
622 while self._read_buffer.qsize():
623 self._read_buffer.get(False)
624
Chris Liechtief1fe252015-08-27 23:25:21 +0200625 def reset_output_buffer(self):
cliechtieada4fd2013-07-31 16:26:07 +0000626 """\
627 Clear output buffer, aborting the current output and
628 discarding all that is in the buffer.
629 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200630 if not self.is_open:
631 raise portNotOpenError
cliechti1ef7e3e2009-08-03 02:38:43 +0000632 self.rfc2217SendPurge(PURGE_TRANSMIT_BUFFER)
cliechti8099bed2009-08-01 23:59:18 +0000633
Chris Liechtief1fe252015-08-27 23:25:21 +0200634 def _update_break_state(self):
cliechtieada4fd2013-07-31 16:26:07 +0000635 """\
636 Set break: Controls TXD. When active, to transmitting is
637 possible.
638 """
Chris Liechti033f17c2015-08-30 21:28:04 +0200639 if not self.is_open:
640 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000641 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200642 self.logger.info('set BREAK to %s' % ('active' if self._break_state else 'inactive'))
643 if self._break_state:
cliechti1ef7e3e2009-08-03 02:38:43 +0000644 self.rfc2217SetControl(SET_CONTROL_BREAK_ON)
cliechti8099bed2009-08-01 23:59:18 +0000645 else:
cliechti1ef7e3e2009-08-03 02:38:43 +0000646 self.rfc2217SetControl(SET_CONTROL_BREAK_OFF)
cliechti8099bed2009-08-01 23:59:18 +0000647
Chris Liechtief1fe252015-08-27 23:25:21 +0200648 def _update_rts_state(self):
cliechti044d8662009-08-11 21:40:31 +0000649 """Set terminal status line: Request To Send."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200650 if not self.is_open:
651 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000652 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200653 self.logger.info('set RTS to %s' % ('active' if self._rts_state else 'inactive'))
654 if self._rts_state:
cliechti1ef7e3e2009-08-03 02:38:43 +0000655 self.rfc2217SetControl(SET_CONTROL_RTS_ON)
cliechti8099bed2009-08-01 23:59:18 +0000656 else:
cliechti1ef7e3e2009-08-03 02:38:43 +0000657 self.rfc2217SetControl(SET_CONTROL_RTS_OFF)
cliechti8099bed2009-08-01 23:59:18 +0000658
Chris Liechtief1fe252015-08-27 23:25:21 +0200659 def _update_dtr_state(self, level=True):
cliechti044d8662009-08-11 21:40:31 +0000660 """Set terminal status line: Data Terminal Ready."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200661 if not self.is_open:
662 raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000663 if self.logger:
Chris Liechtief1fe252015-08-27 23:25:21 +0200664 self.logger.info('set DTR to %s' % ('active' if self._dtr_state else 'inactive'))
665 if self._dtr_state:
cliechti1ef7e3e2009-08-03 02:38:43 +0000666 self.rfc2217SetControl(SET_CONTROL_DTR_ON)
cliechti8099bed2009-08-01 23:59:18 +0000667 else:
cliechti1ef7e3e2009-08-03 02:38:43 +0000668 self.rfc2217SetControl(SET_CONTROL_DTR_OFF)
cliechti8099bed2009-08-01 23:59:18 +0000669
Chris Liechtief1fe252015-08-27 23:25:21 +0200670 @property
671 def cts(self):
cliechti044d8662009-08-11 21:40:31 +0000672 """Read terminal status line: Clear To Send."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200673 if not self.is_open:
674 raise portNotOpenError
cliechti7cb78e82009-08-05 15:47:57 +0000675 return bool(self.getModemState() & MODEMSTATE_MASK_CTS)
cliechti8099bed2009-08-01 23:59:18 +0000676
Chris Liechtief1fe252015-08-27 23:25:21 +0200677 @property
678 def dsr(self):
cliechti044d8662009-08-11 21:40:31 +0000679 """Read terminal status line: Data Set Ready."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200680 if not self.is_open:
681 raise portNotOpenError
cliechti7cb78e82009-08-05 15:47:57 +0000682 return bool(self.getModemState() & MODEMSTATE_MASK_DSR)
cliechti8099bed2009-08-01 23:59:18 +0000683
Chris Liechtief1fe252015-08-27 23:25:21 +0200684 @property
685 def ri(self):
cliechti044d8662009-08-11 21:40:31 +0000686 """Read terminal status line: Ring Indicator."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200687 if not self.is_open:
688 raise portNotOpenError
cliechti7cb78e82009-08-05 15:47:57 +0000689 return bool(self.getModemState() & MODEMSTATE_MASK_RI)
cliechti8099bed2009-08-01 23:59:18 +0000690
Chris Liechtief1fe252015-08-27 23:25:21 +0200691 @property
692 def cd(self):
cliechti044d8662009-08-11 21:40:31 +0000693 """Read terminal status line: Carrier Detect."""
Chris Liechti033f17c2015-08-30 21:28:04 +0200694 if not self.is_open:
695 raise portNotOpenError
cliechti7cb78e82009-08-05 15:47:57 +0000696 return bool(self.getModemState() & MODEMSTATE_MASK_CD)
cliechti8099bed2009-08-01 23:59:18 +0000697
698 # - - - platform specific - - -
699 # None so far
700
701 # - - - RFC2217 specific - - -
702
cliechti1ef7e3e2009-08-03 02:38:43 +0000703 def _telnetReadLoop(self):
cliechti7d448562014-08-03 21:57:45 +0000704 """Read loop for the socket."""
cliechti8099bed2009-08-01 23:59:18 +0000705 mode = M_NORMAL
706 suboption = None
cliechti81c54762009-08-03 23:53:27 +0000707 try:
Chris Liechti39d52172015-10-25 22:53:51 +0100708 while self.is_open:
cliechti81c54762009-08-03 23:53:27 +0000709 try:
710 data = self._socket.recv(1024)
711 except socket.timeout:
712 # just need to get out of recv form time to time to check if
713 # still alive
714 continue
Chris Liechti68340d72015-08-03 14:15:48 +0200715 except socket.error as e:
cliechti81c54762009-08-03 23:53:27 +0000716 # connection fails -> terminate loop
cliechticb20a4f2011-04-25 02:25:54 +0000717 if self.logger:
718 self.logger.debug("socket error in reader thread: %s" % (e,))
cliechti81c54762009-08-03 23:53:27 +0000719 break
Chris Liechti033f17c2015-08-30 21:28:04 +0200720 if not data:
721 break # lost connection
Chris Liechtif99cd5c2015-08-13 22:54:16 +0200722 for byte in iterbytes(data):
cliechti81c54762009-08-03 23:53:27 +0000723 if mode == M_NORMAL:
724 # interpret as command or as data
725 if byte == IAC:
726 mode = M_IAC_SEEN
cliechti8099bed2009-08-01 23:59:18 +0000727 else:
cliechti81c54762009-08-03 23:53:27 +0000728 # store data in read buffer or sub option buffer
729 # depending on state
730 if suboption is not None:
Chris Liechti01587b12015-08-05 02:39:32 +0200731 suboption += byte
cliechti81c54762009-08-03 23:53:27 +0000732 else:
733 self._read_buffer.put(byte)
734 elif mode == M_IAC_SEEN:
735 if byte == IAC:
736 # interpret as command doubled -> insert character
737 # itself
cliechtif325c032009-12-25 16:09:49 +0000738 if suboption is not None:
Chris Liechti01587b12015-08-05 02:39:32 +0200739 suboption += IAC
cliechtif325c032009-12-25 16:09:49 +0000740 else:
741 self._read_buffer.put(IAC)
cliechti81c54762009-08-03 23:53:27 +0000742 mode = M_NORMAL
743 elif byte == SB:
744 # sub option start
745 suboption = bytearray()
746 mode = M_NORMAL
747 elif byte == SE:
748 # sub option end -> process it now
749 self._telnetProcessSubnegotiation(bytes(suboption))
750 suboption = None
751 mode = M_NORMAL
752 elif byte in (DO, DONT, WILL, WONT):
753 # negotiation
754 telnet_command = byte
755 mode = M_NEGOTIATE
756 else:
757 # other telnet commands
758 self._telnetProcessCommand(byte)
759 mode = M_NORMAL
Chris Liechti033f17c2015-08-30 21:28:04 +0200760 elif mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following
cliechti81c54762009-08-03 23:53:27 +0000761 self._telnetNegotiateOption(telnet_command, byte)
cliechti8099bed2009-08-01 23:59:18 +0000762 mode = M_NORMAL
cliechti81c54762009-08-03 23:53:27 +0000763 finally:
764 self._thread = None
cliechti6a300772009-08-12 02:28:56 +0000765 if self.logger:
766 self.logger.debug("read thread terminated")
cliechti8099bed2009-08-01 23:59:18 +0000767
768 # - incoming telnet commands and options
769
cliechti1ef7e3e2009-08-03 02:38:43 +0000770 def _telnetProcessCommand(self, command):
cliechti044d8662009-08-11 21:40:31 +0000771 """Process commands other than DO, DONT, WILL, WONT."""
cliechti1ef7e3e2009-08-03 02:38:43 +0000772 # Currently none. RFC2217 only uses negotiation and subnegotiation.
cliechti6a300772009-08-12 02:28:56 +0000773 if self.logger:
774 self.logger.warning("ignoring Telnet command: %r" % (command,))
cliechti8099bed2009-08-01 23:59:18 +0000775
cliechti1ef7e3e2009-08-03 02:38:43 +0000776 def _telnetNegotiateOption(self, command, option):
cliechti044d8662009-08-11 21:40:31 +0000777 """Process incoming DO, DONT, WILL, WONT."""
cliechti2b929b72009-08-02 23:49:02 +0000778 # check our registered telnet options and forward command to them
779 # they know themselves if they have to answer or not
cliechtiac205322009-08-02 20:40:21 +0000780 known = False
781 for item in self._telnet_options:
cliechti2b929b72009-08-02 23:49:02 +0000782 # can have more than one match! as some options are duplicated for
783 # 'us' and 'them'
cliechtiac205322009-08-02 20:40:21 +0000784 if item.option == option:
cliechti2b929b72009-08-02 23:49:02 +0000785 item.process_incoming(command)
cliechtiac205322009-08-02 20:40:21 +0000786 known = True
787 if not known:
788 # handle unknown options
789 # only answer to positive requests and deny them
790 if command == WILL or command == DO:
Chris Liechti142ae562015-08-23 01:11:06 +0200791 self.telnetSendOption((DONT if command == WILL else WONT), option)
cliechti6a300772009-08-12 02:28:56 +0000792 if self.logger:
793 self.logger.warning("rejected Telnet option: %r" % (option,))
cliechtiac205322009-08-02 20:40:21 +0000794
cliechti1ef7e3e2009-08-03 02:38:43 +0000795 def _telnetProcessSubnegotiation(self, suboption):
cliechti044d8662009-08-11 21:40:31 +0000796 """Process subnegotiation, the data between IAC SB and IAC SE."""
cliechti8099bed2009-08-01 23:59:18 +0000797 if suboption[0:1] == COM_PORT_OPTION:
798 if suboption[1:2] == SERVER_NOTIFY_LINESTATE and len(suboption) >= 3:
Chris Liechti033f17c2015-08-30 21:28:04 +0200799 self._linestate = ord(suboption[2:3]) # ensure it is a number
cliechti6a300772009-08-12 02:28:56 +0000800 if self.logger:
801 self.logger.info("NOTIFY_LINESTATE: %s" % self._linestate)
cliechti8099bed2009-08-01 23:59:18 +0000802 elif suboption[1:2] == SERVER_NOTIFY_MODEMSTATE and len(suboption) >= 3:
Chris Liechti033f17c2015-08-30 21:28:04 +0200803 self._modemstate = ord(suboption[2:3]) # ensure it is a number
cliechti6a300772009-08-12 02:28:56 +0000804 if self.logger:
805 self.logger.info("NOTIFY_MODEMSTATE: %s" % self._modemstate)
cliechti7cb78e82009-08-05 15:47:57 +0000806 # update time when we think that a poll would make sense
807 self._modemstate_expires = time.time() + 0.3
cliechti672d0292009-08-03 02:01:57 +0000808 elif suboption[1:2] == FLOWCONTROL_SUSPEND:
809 self._remote_suspend_flow = True
810 elif suboption[1:2] == FLOWCONTROL_RESUME:
811 self._remote_suspend_flow = False
cliechti8099bed2009-08-01 23:59:18 +0000812 else:
cliechti2b929b72009-08-02 23:49:02 +0000813 for item in self._rfc2217_options.values():
814 if item.ack_option == suboption[1:2]:
cliechti81c54762009-08-03 23:53:27 +0000815 #~ print "processing COM_PORT_OPTION: %r" % list(suboption[1:])
cliechti2b929b72009-08-02 23:49:02 +0000816 item.checkAnswer(bytes(suboption[2:]))
817 break
818 else:
cliechti6a300772009-08-12 02:28:56 +0000819 if self.logger:
820 self.logger.warning("ignoring COM_PORT_OPTION: %r" % (suboption,))
cliechti8099bed2009-08-01 23:59:18 +0000821 else:
cliechti6a300772009-08-12 02:28:56 +0000822 if self.logger:
823 self.logger.warning("ignoring subnegotiation: %r" % (suboption,))
cliechti8099bed2009-08-01 23:59:18 +0000824
825 # - outgoing telnet commands and options
826
cliechti81c54762009-08-03 23:53:27 +0000827 def _internal_raw_write(self, data):
cliechti044d8662009-08-11 21:40:31 +0000828 """internal socket write with no data escaping. used to send telnet stuff."""
Chris Liechti01587b12015-08-05 02:39:32 +0200829 with self._write_lock:
cliechti81c54762009-08-03 23:53:27 +0000830 self._socket.sendall(data)
cliechti81c54762009-08-03 23:53:27 +0000831
cliechti1ef7e3e2009-08-03 02:38:43 +0000832 def telnetSendOption(self, action, option):
cliechti044d8662009-08-11 21:40:31 +0000833 """Send DO, DONT, WILL, WONT."""
cliechti81c54762009-08-03 23:53:27 +0000834 self._internal_raw_write(to_bytes([IAC, action, option]))
cliechti8099bed2009-08-01 23:59:18 +0000835
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200836 def rfc2217SendSubnegotiation(self, option, value=b''):
cliechti044d8662009-08-11 21:40:31 +0000837 """Subnegotiation of RFC2217 parameters."""
cliechtif325c032009-12-25 16:09:49 +0000838 value = value.replace(IAC, IAC_DOUBLED)
cliechti81c54762009-08-03 23:53:27 +0000839 self._internal_raw_write(to_bytes([IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE]))
cliechti2b929b72009-08-02 23:49:02 +0000840
cliechti1ef7e3e2009-08-03 02:38:43 +0000841 def rfc2217SendPurge(self, value):
cliechti2b929b72009-08-02 23:49:02 +0000842 item = self._rfc2217_options['purge']
Chris Liechti033f17c2015-08-30 21:28:04 +0200843 item.set(value) # transmit desired purge type
844 item.wait(self._network_timeout) # wait for acknowledge from the server
cliechti2b929b72009-08-02 23:49:02 +0000845
cliechti1ef7e3e2009-08-03 02:38:43 +0000846 def rfc2217SetControl(self, value):
cliechti81c54762009-08-03 23:53:27 +0000847 item = self._rfc2217_options['control']
Chris Liechti033f17c2015-08-30 21:28:04 +0200848 item.set(value) # transmit desired control type
cliechti81c54762009-08-03 23:53:27 +0000849 if self._ignore_set_control_answer:
850 # answers are ignored when option is set. compatibility mode for
cliechticb20a4f2011-04-25 02:25:54 +0000851 # servers that answer, but not the expected one... (or no answer
cliechti81c54762009-08-03 23:53:27 +0000852 # at all) i.e. sredird
853 time.sleep(0.1) # this helps getting the unit tests passed
854 else:
cliechtidfe2d272009-08-10 22:19:41 +0000855 item.wait(self._network_timeout) # wait for acknowledge from the server
cliechti8099bed2009-08-01 23:59:18 +0000856
cliechti1ef7e3e2009-08-03 02:38:43 +0000857 def rfc2217FlowServerReady(self):
cliechtieada4fd2013-07-31 16:26:07 +0000858 """\
859 check if server is ready to receive data. block for some time when
860 not.
861 """
cliechti672d0292009-08-03 02:01:57 +0000862 #~ if self._remote_suspend_flow:
863 #~ wait---
864
cliechti7cb78e82009-08-05 15:47:57 +0000865 def getModemState(self):
cliechtieada4fd2013-07-31 16:26:07 +0000866 """\
cliechti7d448562014-08-03 21:57:45 +0000867 get last modem state (cached value. If value is "old", request a new
868 one. This cache helps that we don't issue to many requests when e.g. all
869 status lines, one after the other is queried by the user (getCTS, getDSR
cliechtieada4fd2013-07-31 16:26:07 +0000870 etc.)
871 """
cliechti7cb78e82009-08-05 15:47:57 +0000872 # active modem state polling enabled? is the value fresh enough?
873 if self._poll_modem_state and self._modemstate_expires < time.time():
cliechti6a300772009-08-12 02:28:56 +0000874 if self.logger:
875 self.logger.debug('polling modem state')
cliechti7cb78e82009-08-05 15:47:57 +0000876 # when it is older, request an update
877 self.rfc2217SendSubnegotiation(NOTIFY_MODEMSTATE)
cliechtidfe2d272009-08-10 22:19:41 +0000878 timeout_time = time.time() + self._network_timeout
cliechti7cb78e82009-08-05 15:47:57 +0000879 while time.time() < timeout_time:
880 time.sleep(0.05) # prevent 100% CPU load
881 # when expiration time is updated, it means that there is a new
882 # value
883 if self._modemstate_expires > time.time():
884 break
Chris Liechti01587b12015-08-05 02:39:32 +0200885 else:
886 if self.logger:
887 self.logger.warning('poll for modem state failed')
cliechti7cb78e82009-08-05 15:47:57 +0000888 # even when there is a timeout, do not generate an error just
889 # return the last known value. this way we can support buggy
890 # servers that do not respond to polls, but send automatic
891 # updates.
892 if self._modemstate is not None:
cliechti6a300772009-08-12 02:28:56 +0000893 if self.logger:
894 self.logger.debug('using cached modem state')
cliechti7cb78e82009-08-05 15:47:57 +0000895 return self._modemstate
896 else:
897 # never received a notification from the server
cliechti8fb119c2009-08-05 23:39:45 +0000898 raise SerialException("remote sends no NOTIFY_MODEMSTATE")
cliechti8099bed2009-08-01 23:59:18 +0000899
cliechti5cc3eb12009-08-11 23:04:30 +0000900
cliechti595ed5b2009-08-10 01:43:32 +0000901#############################################################################
cliechti5cc3eb12009-08-11 23:04:30 +0000902# The following is code that helps implementing an RFC 2217 server.
cliechti8099bed2009-08-01 23:59:18 +0000903
cliechti8ccc2ff2009-08-05 12:44:46 +0000904class PortManager(object):
cliechtieada4fd2013-07-31 16:26:07 +0000905 """\
906 This class manages the state of Telnet and RFC 2217. It needs a serial
cliechticb20a4f2011-04-25 02:25:54 +0000907 instance and a connection to work with. Connection is expected to implement
cliechtieada4fd2013-07-31 16:26:07 +0000908 a (thread safe) write function, that writes the string to the network.
909 """
cliechti130d1f02009-08-04 02:10:58 +0000910
cliechti6a300772009-08-12 02:28:56 +0000911 def __init__(self, serial_port, connection, logger=None):
cliechti130d1f02009-08-04 02:10:58 +0000912 self.serial = serial_port
913 self.connection = connection
cliechti6a300772009-08-12 02:28:56 +0000914 self.logger = logger
cliechti86b593e2009-08-05 16:28:12 +0000915 self._client_is_rfc2217 = False
cliechti130d1f02009-08-04 02:10:58 +0000916
917 # filter state machine
918 self.mode = M_NORMAL
919 self.suboption = None
920 self.telnet_command = None
921
922 # states for modem/line control events
923 self.modemstate_mask = 255
924 self.last_modemstate = None
925 self.linstate_mask = 0
926
927 # all supported telnet options
928 self._telnet_options = [
929 TelnetOption(self, 'ECHO', ECHO, WILL, WONT, DO, DONT, REQUESTED),
930 TelnetOption(self, 'we-SGA', SGA, WILL, WONT, DO, DONT, REQUESTED),
931 TelnetOption(self, 'they-SGA', SGA, DO, DONT, WILL, WONT, INACTIVE),
932 TelnetOption(self, 'we-BINARY', BINARY, WILL, WONT, DO, DONT, INACTIVE),
933 TelnetOption(self, 'they-BINARY', BINARY, DO, DONT, WILL, WONT, REQUESTED),
cliechti86b593e2009-08-05 16:28:12 +0000934 TelnetOption(self, 'we-RFC2217', COM_PORT_OPTION, WILL, WONT, DO, DONT, REQUESTED, self._client_ok),
935 TelnetOption(self, 'they-RFC2217', COM_PORT_OPTION, DO, DONT, WILL, WONT, INACTIVE, self._client_ok),
cliechti130d1f02009-08-04 02:10:58 +0000936 ]
937
938 # negotiate Telnet/RFC2217 -> send initial requests
cliechti6a300772009-08-12 02:28:56 +0000939 if self.logger:
940 self.logger.debug("requesting initial Telnet/RFC 2217 options")
cliechti130d1f02009-08-04 02:10:58 +0000941 for option in self._telnet_options:
942 if option.state is REQUESTED:
943 self.telnetSendOption(option.send_yes, option.option)
944 # issue 1st modem state notification
cliechti86b593e2009-08-05 16:28:12 +0000945
946 def _client_ok(self):
cliechtieada4fd2013-07-31 16:26:07 +0000947 """\
cliechti7d448562014-08-03 21:57:45 +0000948 callback of telnet option. It gets called when option is activated.
949 This one here is used to detect when the client agrees on RFC 2217. A
cliechti86b593e2009-08-05 16:28:12 +0000950 flag is set so that other functions like check_modem_lines know if the
cliechti7d448562014-08-03 21:57:45 +0000951 client is OK.
cliechtieada4fd2013-07-31 16:26:07 +0000952 """
cliechti86b593e2009-08-05 16:28:12 +0000953 # The callback is used for we and they so if one party agrees, we're
954 # already happy. it seems not all servers do the negotiation correctly
955 # and i guess there are incorrect clients too.. so be happy if client
956 # answers one or the other positively.
957 self._client_is_rfc2217 = True
cliechti6a300772009-08-12 02:28:56 +0000958 if self.logger:
959 self.logger.info("client accepts RFC 2217")
cliechti8fb119c2009-08-05 23:39:45 +0000960 # this is to ensure that the client gets a notification, even if there
961 # was no change
962 self.check_modem_lines(force_notification=True)
cliechti130d1f02009-08-04 02:10:58 +0000963
964 # - outgoing telnet commands and options
965
966 def telnetSendOption(self, action, option):
cliechti044d8662009-08-11 21:40:31 +0000967 """Send DO, DONT, WILL, WONT."""
cliechti130d1f02009-08-04 02:10:58 +0000968 self.connection.write(to_bytes([IAC, action, option]))
969
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200970 def rfc2217SendSubnegotiation(self, option, value=b''):
cliechti044d8662009-08-11 21:40:31 +0000971 """Subnegotiation of RFC 2217 parameters."""
cliechtif325c032009-12-25 16:09:49 +0000972 value = value.replace(IAC, IAC_DOUBLED)
cliechti130d1f02009-08-04 02:10:58 +0000973 self.connection.write(to_bytes([IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE]))
974
975 # - check modem lines, needs to be called periodically from user to
976 # establish polling
977
cliechti7cb78e82009-08-05 15:47:57 +0000978 def check_modem_lines(self, force_notification=False):
cliechti130d1f02009-08-04 02:10:58 +0000979 modemstate = (
Chris Liechti142ae562015-08-23 01:11:06 +0200980 (self.serial.getCTS() and MODEMSTATE_MASK_CTS) |
981 (self.serial.getDSR() and MODEMSTATE_MASK_DSR) |
982 (self.serial.getRI() and MODEMSTATE_MASK_RI) |
983 (self.serial.getCD() and MODEMSTATE_MASK_CD))
cliechti7cb78e82009-08-05 15:47:57 +0000984 # check what has changed
Chris Liechti033f17c2015-08-30 21:28:04 +0200985 deltas = modemstate ^ (self.last_modemstate or 0) # when last is None -> 0
cliechti7cb78e82009-08-05 15:47:57 +0000986 if deltas & MODEMSTATE_MASK_CTS:
987 modemstate |= MODEMSTATE_MASK_CTS_CHANGE
988 if deltas & MODEMSTATE_MASK_DSR:
989 modemstate |= MODEMSTATE_MASK_DSR_CHANGE
990 if deltas & MODEMSTATE_MASK_RI:
991 modemstate |= MODEMSTATE_MASK_RI_CHANGE
992 if deltas & MODEMSTATE_MASK_CD:
993 modemstate |= MODEMSTATE_MASK_CD_CHANGE
994 # if new state is different and the mask allows this change, send
cliechti86b593e2009-08-05 16:28:12 +0000995 # notification. suppress notifications when client is not rfc2217
cliechti7cb78e82009-08-05 15:47:57 +0000996 if modemstate != self.last_modemstate or force_notification:
cliechti8fb119c2009-08-05 23:39:45 +0000997 if (self._client_is_rfc2217 and (modemstate & self.modemstate_mask)) or force_notification:
cliechti7cb78e82009-08-05 15:47:57 +0000998 self.rfc2217SendSubnegotiation(
999 SERVER_NOTIFY_MODEMSTATE,
1000 to_bytes([modemstate & self.modemstate_mask])
1001 )
cliechti6a300772009-08-12 02:28:56 +00001002 if self.logger:
1003 self.logger.info("NOTIFY_MODEMSTATE: %s" % (modemstate,))
cliechti7cb78e82009-08-05 15:47:57 +00001004 # save last state, but forget about deltas.
1005 # otherwise it would also notify about changing deltas which is
1006 # probably not very useful
1007 self.last_modemstate = modemstate & 0xf0
cliechti130d1f02009-08-04 02:10:58 +00001008
cliechti32c10332009-08-05 13:23:43 +00001009 # - outgoing data escaping
1010
1011 def escape(self, data):
cliechtieada4fd2013-07-31 16:26:07 +00001012 """\
cliechti7d448562014-08-03 21:57:45 +00001013 This generator function is for the user. All outgoing data has to be
cliechticb20a4f2011-04-25 02:25:54 +00001014 properly escaped, so that no IAC character in the data stream messes up
1015 the Telnet state machine in the server.
cliechti32c10332009-08-05 13:23:43 +00001016
1017 socket.sendall(escape(data))
1018 """
Chris Liechtib15dc052015-10-19 23:17:16 +02001019 for byte in iterbytes(data):
cliechti32c10332009-08-05 13:23:43 +00001020 if byte == IAC:
1021 yield IAC
1022 yield IAC
1023 else:
1024 yield byte
1025
cliechti130d1f02009-08-04 02:10:58 +00001026 # - incoming data filter
1027
1028 def filter(self, data):
cliechtieada4fd2013-07-31 16:26:07 +00001029 """\
cliechti7d448562014-08-03 21:57:45 +00001030 Handle a bunch of incoming bytes. This is a generator. It will yield
cliechti044d8662009-08-11 21:40:31 +00001031 all characters not of interest for Telnet/RFC 2217.
cliechti130d1f02009-08-04 02:10:58 +00001032
1033 The idea is that the reader thread pushes data from the socket through
1034 this filter:
1035
1036 for byte in filter(socket.recv(1024)):
1037 # do things like CR/LF conversion/whatever
1038 # and write data to the serial port
1039 serial.write(byte)
1040
1041 (socket error handling code left as exercise for the reader)
1042 """
Chris Liechtif99cd5c2015-08-13 22:54:16 +02001043 for byte in iterbytes(data):
cliechti130d1f02009-08-04 02:10:58 +00001044 if self.mode == M_NORMAL:
1045 # interpret as command or as data
1046 if byte == IAC:
1047 self.mode = M_IAC_SEEN
1048 else:
1049 # store data in sub option buffer or pass it to our
1050 # consumer depending on state
1051 if self.suboption is not None:
Chris Liechti01587b12015-08-05 02:39:32 +02001052 self.suboption += byte
cliechti130d1f02009-08-04 02:10:58 +00001053 else:
1054 yield byte
1055 elif self.mode == M_IAC_SEEN:
1056 if byte == IAC:
1057 # interpret as command doubled -> insert character
1058 # itself
cliechtif325c032009-12-25 16:09:49 +00001059 if self.suboption is not None:
Chris Liechti01587b12015-08-05 02:39:32 +02001060 self.suboption += byte
cliechtif325c032009-12-25 16:09:49 +00001061 else:
1062 yield byte
cliechti130d1f02009-08-04 02:10:58 +00001063 self.mode = M_NORMAL
1064 elif byte == SB:
1065 # sub option start
1066 self.suboption = bytearray()
1067 self.mode = M_NORMAL
1068 elif byte == SE:
1069 # sub option end -> process it now
1070 self._telnetProcessSubnegotiation(bytes(self.suboption))
1071 self.suboption = None
1072 self.mode = M_NORMAL
1073 elif byte in (DO, DONT, WILL, WONT):
1074 # negotiation
1075 self.telnet_command = byte
1076 self.mode = M_NEGOTIATE
1077 else:
1078 # other telnet commands
1079 self._telnetProcessCommand(byte)
1080 self.mode = M_NORMAL
Chris Liechti033f17c2015-08-30 21:28:04 +02001081 elif self.mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following
cliechti130d1f02009-08-04 02:10:58 +00001082 self._telnetNegotiateOption(self.telnet_command, byte)
1083 self.mode = M_NORMAL
1084
1085 # - incoming telnet commands and options
1086
1087 def _telnetProcessCommand(self, command):
cliechti044d8662009-08-11 21:40:31 +00001088 """Process commands other than DO, DONT, WILL, WONT."""
cliechti130d1f02009-08-04 02:10:58 +00001089 # Currently none. RFC2217 only uses negotiation and subnegotiation.
cliechti6a300772009-08-12 02:28:56 +00001090 if self.logger:
1091 self.logger.warning("ignoring Telnet command: %r" % (command,))
cliechti130d1f02009-08-04 02:10:58 +00001092
1093 def _telnetNegotiateOption(self, command, option):
cliechti044d8662009-08-11 21:40:31 +00001094 """Process incoming DO, DONT, WILL, WONT."""
cliechti130d1f02009-08-04 02:10:58 +00001095 # check our registered telnet options and forward command to them
1096 # they know themselves if they have to answer or not
1097 known = False
1098 for item in self._telnet_options:
1099 # can have more than one match! as some options are duplicated for
1100 # 'us' and 'them'
1101 if item.option == option:
1102 item.process_incoming(command)
1103 known = True
1104 if not known:
1105 # handle unknown options
1106 # only answer to positive requests and deny them
1107 if command == WILL or command == DO:
Chris Liechti142ae562015-08-23 01:11:06 +02001108 self.telnetSendOption((DONT if command == WILL else WONT), option)
cliechti6a300772009-08-12 02:28:56 +00001109 if self.logger:
1110 self.logger.warning("rejected Telnet option: %r" % (option,))
cliechti130d1f02009-08-04 02:10:58 +00001111
cliechti130d1f02009-08-04 02:10:58 +00001112 def _telnetProcessSubnegotiation(self, suboption):
cliechti044d8662009-08-11 21:40:31 +00001113 """Process subnegotiation, the data between IAC SB and IAC SE."""
cliechti130d1f02009-08-04 02:10:58 +00001114 if suboption[0:1] == COM_PORT_OPTION:
cliechti6a300772009-08-12 02:28:56 +00001115 if self.logger:
1116 self.logger.debug('received COM_PORT_OPTION: %r' % (suboption,))
cliechti130d1f02009-08-04 02:10:58 +00001117 if suboption[1:2] == SET_BAUDRATE:
1118 backup = self.serial.baudrate
1119 try:
Chris Liechti01587b12015-08-05 02:39:32 +02001120 (baudrate,) = struct.unpack(b"!I", suboption[2:6])
cliechtieada4fd2013-07-31 16:26:07 +00001121 if baudrate != 0:
1122 self.serial.baudrate = baudrate
Chris Liechtid2146002015-08-04 16:57:16 +02001123 except ValueError as e:
cliechti6a300772009-08-12 02:28:56 +00001124 if self.logger:
1125 self.logger.error("failed to set baud rate: %s" % (e,))
cliechti130d1f02009-08-04 02:10:58 +00001126 self.serial.baudrate = backup
cliechti5cc3eb12009-08-11 23:04:30 +00001127 else:
cliechti6a300772009-08-12 02:28:56 +00001128 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +02001129 self.logger.info("%s baud rate: %s" % ('set' if baudrate else 'get', self.serial.baudrate))
Chris Liechti01587b12015-08-05 02:39:32 +02001130 self.rfc2217SendSubnegotiation(SERVER_SET_BAUDRATE, struct.pack(b"!I", self.serial.baudrate))
cliechti130d1f02009-08-04 02:10:58 +00001131 elif suboption[1:2] == SET_DATASIZE:
1132 backup = self.serial.bytesize
1133 try:
Chris Liechti142ae562015-08-23 01:11:06 +02001134 (datasize,) = struct.unpack(b"!B", suboption[2:3])
cliechtieada4fd2013-07-31 16:26:07 +00001135 if datasize != 0:
1136 self.serial.bytesize = datasize
Chris Liechtid2146002015-08-04 16:57:16 +02001137 except ValueError as e:
cliechti6a300772009-08-12 02:28:56 +00001138 if self.logger:
1139 self.logger.error("failed to set data size: %s" % (e,))
cliechti130d1f02009-08-04 02:10:58 +00001140 self.serial.bytesize = backup
cliechti5cc3eb12009-08-11 23:04:30 +00001141 else:
cliechti6a300772009-08-12 02:28:56 +00001142 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +02001143 self.logger.info("%s data size: %s" % ('set' if datasize else 'get', self.serial.bytesize))
Chris Liechti01587b12015-08-05 02:39:32 +02001144 self.rfc2217SendSubnegotiation(SERVER_SET_DATASIZE, struct.pack(b"!B", self.serial.bytesize))
cliechti130d1f02009-08-04 02:10:58 +00001145 elif suboption[1:2] == SET_PARITY:
1146 backup = self.serial.parity
1147 try:
Chris Liechti01587b12015-08-05 02:39:32 +02001148 parity = struct.unpack(b"!B", suboption[2:3])[0]
cliechtieada4fd2013-07-31 16:26:07 +00001149 if parity != 0:
1150 self.serial.parity = RFC2217_REVERSE_PARITY_MAP[parity]
Chris Liechtid2146002015-08-04 16:57:16 +02001151 except ValueError as e:
cliechti6a300772009-08-12 02:28:56 +00001152 if self.logger:
1153 self.logger.error("failed to set parity: %s" % (e,))
cliechti130d1f02009-08-04 02:10:58 +00001154 self.serial.parity = backup
cliechti5cc3eb12009-08-11 23:04:30 +00001155 else:
cliechti6a300772009-08-12 02:28:56 +00001156 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +02001157 self.logger.info("%s parity: %s" % ('set' if parity else 'get', self.serial.parity))
cliechti130d1f02009-08-04 02:10:58 +00001158 self.rfc2217SendSubnegotiation(
1159 SERVER_SET_PARITY,
Chris Liechtib4cda3a2015-08-08 17:12:08 +02001160 struct.pack(b"!B", RFC2217_PARITY_MAP[self.serial.parity])
cliechti130d1f02009-08-04 02:10:58 +00001161 )
1162 elif suboption[1:2] == SET_STOPSIZE:
1163 backup = self.serial.stopbits
1164 try:
Chris Liechti01587b12015-08-05 02:39:32 +02001165 stopbits = struct.unpack(b"!B", suboption[2:3])[0]
cliechtieada4fd2013-07-31 16:26:07 +00001166 if stopbits != 0:
1167 self.serial.stopbits = RFC2217_REVERSE_STOPBIT_MAP[stopbits]
Chris Liechtid2146002015-08-04 16:57:16 +02001168 except ValueError as e:
cliechti6a300772009-08-12 02:28:56 +00001169 if self.logger:
1170 self.logger.error("failed to set stop bits: %s" % (e,))
cliechti130d1f02009-08-04 02:10:58 +00001171 self.serial.stopbits = backup
cliechti5cc3eb12009-08-11 23:04:30 +00001172 else:
cliechti6a300772009-08-12 02:28:56 +00001173 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +02001174 self.logger.info("%s stop bits: %s" % ('set' if stopbits else 'get', self.serial.stopbits))
cliechti130d1f02009-08-04 02:10:58 +00001175 self.rfc2217SendSubnegotiation(
1176 SERVER_SET_STOPSIZE,
Chris Liechti01587b12015-08-05 02:39:32 +02001177 struct.pack(b"!B", RFC2217_STOPBIT_MAP[self.serial.stopbits])
cliechti130d1f02009-08-04 02:10:58 +00001178 )
1179 elif suboption[1:2] == SET_CONTROL:
1180 if suboption[2:3] == SET_CONTROL_REQ_FLOW_SETTING:
1181 if self.serial.xonxoff:
1182 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_SW_FLOW_CONTROL)
1183 elif self.serial.rtscts:
1184 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_HW_FLOW_CONTROL)
1185 else:
1186 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_NO_FLOW_CONTROL)
1187 elif suboption[2:3] == SET_CONTROL_USE_NO_FLOW_CONTROL:
1188 self.serial.xonxoff = False
1189 self.serial.rtscts = False
cliechti6a300772009-08-12 02:28:56 +00001190 if self.logger:
1191 self.logger.info("changed flow control to None")
cliechti130d1f02009-08-04 02:10:58 +00001192 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_NO_FLOW_CONTROL)
1193 elif suboption[2:3] == SET_CONTROL_USE_SW_FLOW_CONTROL:
1194 self.serial.xonxoff = True
cliechti6a300772009-08-12 02:28:56 +00001195 if self.logger:
1196 self.logger.info("changed flow control to XON/XOFF")
cliechti130d1f02009-08-04 02:10:58 +00001197 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_SW_FLOW_CONTROL)
1198 elif suboption[2:3] == SET_CONTROL_USE_HW_FLOW_CONTROL:
1199 self.serial.rtscts = True
cliechti6a300772009-08-12 02:28:56 +00001200 if self.logger:
1201 self.logger.info("changed flow control to RTS/CTS")
cliechti130d1f02009-08-04 02:10:58 +00001202 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_HW_FLOW_CONTROL)
1203 elif suboption[2:3] == SET_CONTROL_REQ_BREAK_STATE:
cliechti6a300772009-08-12 02:28:56 +00001204 if self.logger:
1205 self.logger.warning("requested break state - not implemented")
Chris Liechti033f17c2015-08-30 21:28:04 +02001206 pass # XXX needs cached value
cliechti130d1f02009-08-04 02:10:58 +00001207 elif suboption[2:3] == SET_CONTROL_BREAK_ON:
1208 self.serial.setBreak(True)
cliechti6a300772009-08-12 02:28:56 +00001209 if self.logger:
1210 self.logger.info("changed BREAK to active")
cliechti130d1f02009-08-04 02:10:58 +00001211 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_BREAK_ON)
1212 elif suboption[2:3] == SET_CONTROL_BREAK_OFF:
1213 self.serial.setBreak(False)
cliechti6a300772009-08-12 02:28:56 +00001214 if self.logger:
1215 self.logger.info("changed BREAK to inactive")
cliechti130d1f02009-08-04 02:10:58 +00001216 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_BREAK_OFF)
1217 elif suboption[2:3] == SET_CONTROL_REQ_DTR:
cliechti6a300772009-08-12 02:28:56 +00001218 if self.logger:
1219 self.logger.warning("requested DTR state - not implemented")
Chris Liechti033f17c2015-08-30 21:28:04 +02001220 pass # XXX needs cached value
cliechti130d1f02009-08-04 02:10:58 +00001221 elif suboption[2:3] == SET_CONTROL_DTR_ON:
1222 self.serial.setDTR(True)
cliechti6a300772009-08-12 02:28:56 +00001223 if self.logger:
1224 self.logger.info("changed DTR to active")
cliechti130d1f02009-08-04 02:10:58 +00001225 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_DTR_ON)
1226 elif suboption[2:3] == SET_CONTROL_DTR_OFF:
1227 self.serial.setDTR(False)
cliechti6a300772009-08-12 02:28:56 +00001228 if self.logger:
1229 self.logger.info("changed DTR to inactive")
cliechti130d1f02009-08-04 02:10:58 +00001230 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_DTR_OFF)
1231 elif suboption[2:3] == SET_CONTROL_REQ_RTS:
cliechti6a300772009-08-12 02:28:56 +00001232 if self.logger:
1233 self.logger.warning("requested RTS state - not implemented")
Chris Liechti033f17c2015-08-30 21:28:04 +02001234 pass # XXX needs cached value
cliechti130d1f02009-08-04 02:10:58 +00001235 #~ self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_ON)
1236 elif suboption[2:3] == SET_CONTROL_RTS_ON:
1237 self.serial.setRTS(True)
cliechti6a300772009-08-12 02:28:56 +00001238 if self.logger:
1239 self.logger.info("changed RTS to active")
cliechti130d1f02009-08-04 02:10:58 +00001240 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_ON)
1241 elif suboption[2:3] == SET_CONTROL_RTS_OFF:
1242 self.serial.setRTS(False)
cliechti6a300772009-08-12 02:28:56 +00001243 if self.logger:
1244 self.logger.info("changed RTS to inactive")
cliechti130d1f02009-08-04 02:10:58 +00001245 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_OFF)
1246 #~ elif suboption[2:3] == SET_CONTROL_REQ_FLOW_SETTING_IN:
1247 #~ elif suboption[2:3] == SET_CONTROL_USE_NO_FLOW_CONTROL_IN:
1248 #~ elif suboption[2:3] == SET_CONTROL_USE_SW_FLOW_CONTOL_IN:
1249 #~ elif suboption[2:3] == SET_CONTROL_USE_HW_FLOW_CONTOL_IN:
1250 #~ elif suboption[2:3] == SET_CONTROL_USE_DCD_FLOW_CONTROL:
1251 #~ elif suboption[2:3] == SET_CONTROL_USE_DTR_FLOW_CONTROL:
1252 #~ elif suboption[2:3] == SET_CONTROL_USE_DSR_FLOW_CONTROL:
1253 elif suboption[1:2] == NOTIFY_LINESTATE:
cliechti7cb78e82009-08-05 15:47:57 +00001254 # client polls for current state
1255 self.rfc2217SendSubnegotiation(
Chris Liechti142ae562015-08-23 01:11:06 +02001256 SERVER_NOTIFY_LINESTATE,
1257 to_bytes([0])) # sorry, nothing like that implemented
cliechti130d1f02009-08-04 02:10:58 +00001258 elif suboption[1:2] == NOTIFY_MODEMSTATE:
cliechti6a300772009-08-12 02:28:56 +00001259 if self.logger:
1260 self.logger.info("request for modem state")
cliechti7cb78e82009-08-05 15:47:57 +00001261 # client polls for current state
1262 self.check_modem_lines(force_notification=True)
cliechti130d1f02009-08-04 02:10:58 +00001263 elif suboption[1:2] == FLOWCONTROL_SUSPEND:
cliechti6a300772009-08-12 02:28:56 +00001264 if self.logger:
1265 self.logger.info("suspend")
cliechti130d1f02009-08-04 02:10:58 +00001266 self._remote_suspend_flow = True
1267 elif suboption[1:2] == FLOWCONTROL_RESUME:
cliechti6a300772009-08-12 02:28:56 +00001268 if self.logger:
1269 self.logger.info("resume")
cliechti130d1f02009-08-04 02:10:58 +00001270 self._remote_suspend_flow = False
1271 elif suboption[1:2] == SET_LINESTATE_MASK:
Chris Liechti033f17c2015-08-30 21:28:04 +02001272 self.linstate_mask = ord(suboption[2:3]) # ensure it is a number
cliechti6a300772009-08-12 02:28:56 +00001273 if self.logger:
cliechtif325c032009-12-25 16:09:49 +00001274 self.logger.info("line state mask: 0x%02x" % (self.linstate_mask,))
cliechti130d1f02009-08-04 02:10:58 +00001275 elif suboption[1:2] == SET_MODEMSTATE_MASK:
Chris Liechti033f17c2015-08-30 21:28:04 +02001276 self.modemstate_mask = ord(suboption[2:3]) # ensure it is a number
cliechti6a300772009-08-12 02:28:56 +00001277 if self.logger:
cliechtif325c032009-12-25 16:09:49 +00001278 self.logger.info("modem state mask: 0x%02x" % (self.modemstate_mask,))
cliechti130d1f02009-08-04 02:10:58 +00001279 elif suboption[1:2] == PURGE_DATA:
1280 if suboption[2:3] == PURGE_RECEIVE_BUFFER:
Chris Liechti3ad62fb2015-08-29 21:53:32 +02001281 self.serial.reset_input_buffer()
cliechti6a300772009-08-12 02:28:56 +00001282 if self.logger:
1283 self.logger.info("purge in")
cliechti130d1f02009-08-04 02:10:58 +00001284 self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_RECEIVE_BUFFER)
1285 elif suboption[2:3] == PURGE_TRANSMIT_BUFFER:
Chris Liechti3ad62fb2015-08-29 21:53:32 +02001286 self.serial.reset_output_buffer()
cliechti6a300772009-08-12 02:28:56 +00001287 if self.logger:
1288 self.logger.info("purge out")
cliechti130d1f02009-08-04 02:10:58 +00001289 self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_TRANSMIT_BUFFER)
1290 elif suboption[2:3] == PURGE_BOTH_BUFFERS:
Chris Liechti3ad62fb2015-08-29 21:53:32 +02001291 self.serial.reset_input_buffer()
1292 self.serial.reset_output_buffer()
cliechti6a300772009-08-12 02:28:56 +00001293 if self.logger:
1294 self.logger.info("purge both")
cliechti130d1f02009-08-04 02:10:58 +00001295 self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_BOTH_BUFFERS)
1296 else:
cliechti6a300772009-08-12 02:28:56 +00001297 if self.logger:
1298 self.logger.error("undefined PURGE_DATA: %r" % list(suboption[2:]))
cliechti130d1f02009-08-04 02:10:58 +00001299 else:
cliechti6a300772009-08-12 02:28:56 +00001300 if self.logger:
1301 self.logger.error("undefined COM_PORT_OPTION: %r" % list(suboption[1:]))
cliechti130d1f02009-08-04 02:10:58 +00001302 else:
cliechti6a300772009-08-12 02:28:56 +00001303 if self.logger:
1304 self.logger.warning("unknown subnegotiation: %r" % (suboption,))
cliechti130d1f02009-08-04 02:10:58 +00001305
1306
1307# simple client test
cliechti8099bed2009-08-01 23:59:18 +00001308if __name__ == '__main__':
1309 import sys
1310 s = Serial('rfc2217://localhost:7000', 115200)
1311 sys.stdout.write('%s\n' % s)
1312
cliechti8099bed2009-08-01 23:59:18 +00001313 sys.stdout.write("write...\n")
Chris Liechtib4cda3a2015-08-08 17:12:08 +02001314 s.write(b"hello\n")
cliechti8099bed2009-08-01 23:59:18 +00001315 s.flush()
cliechti8099bed2009-08-01 23:59:18 +00001316 sys.stdout.write("read: %s\n" % s.read(5))
cliechti8099bed2009-08-01 23:59:18 +00001317 s.close()