blob: 173b914d679323f157d4f5ff4f62b5dd56bbbf19 [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
cliechti81c54762009-08-03 23:53:27 +000020##############################################################################
21# observations and issues with servers
22#=============================================================================
23# 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
31#=============================================================================
32# 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.
35#=============================================================================
36# 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
47##############################################################################
48
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 Liechtib4cda3a2015-08-08 17:12:08 +020077from serial.serialutil import *
78
cliechti8099bed2009-08-01 23:59:18 +000079# port string is expected to be something like this:
80# rfc2217://host:port
81# host may be an IP or including domain, whatever.
82# port is 0...65535
83
cliechti86844e82009-08-12 00:05:33 +000084# map log level names to constants. used in fromURL()
cliechti5cc3eb12009-08-11 23:04:30 +000085LOGGER_LEVELS = {
Chris Liechtic4bca9e2015-08-07 14:40:41 +020086 'debug': logging.DEBUG,
87 'info': logging.INFO,
88 'warning': logging.WARNING,
89 'error': logging.ERROR,
90 }
cliechti5cc3eb12009-08-11 23:04:30 +000091
92
cliechti8099bed2009-08-01 23:59:18 +000093# telnet protocol characters
Chris Liechtib4cda3a2015-08-08 17:12:08 +020094SE = b'\xf0' # Subnegotiation End
95NOP = b'\xf1' # No Operation
96DM = b'\xf2' # Data Mark
97BRK = b'\xf3' # Break
98IP = b'\xf4' # Interrupt process
99AO = b'\xf5' # Abort output
100AYT = b'\xf6' # Are You There
101EC = b'\xf7' # Erase Character
102EL = b'\xf8' # Erase Line
103GA = b'\xf9' # Go Ahead
104SB = b'\xfa' # Subnegotiation Begin
105WILL = b'\xfb'
106WONT = b'\xfc'
107DO = b'\xfd'
108DONT = b'\xfe'
109IAC = b'\xff' # Interpret As Command
110IAC_DOUBLED = b'\xff\xff'
cliechti8099bed2009-08-01 23:59:18 +0000111
112# selected telnet options
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200113BINARY = b'\x00' # 8-bit data path
114ECHO = b'\x01' # echo
115SGA = b'\x03' # suppress go ahead
cliechti8099bed2009-08-01 23:59:18 +0000116
117# RFC2217
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200118COM_PORT_OPTION = b'\x2c'
cliechti8099bed2009-08-01 23:59:18 +0000119
120# Client to Access Server
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200121SET_BAUDRATE = b'\x01'
122SET_DATASIZE = b'\x02'
123SET_PARITY = b'\x03'
124SET_STOPSIZE = b'\x04'
125SET_CONTROL = b'\x05'
126NOTIFY_LINESTATE = b'\x06'
127NOTIFY_MODEMSTATE = b'\x07'
128FLOWCONTROL_SUSPEND = b'\x08'
129FLOWCONTROL_RESUME = b'\x09'
130SET_LINESTATE_MASK = b'\x0a'
131SET_MODEMSTATE_MASK = b'\x0b'
132PURGE_DATA = b'\x0c'
cliechti8099bed2009-08-01 23:59:18 +0000133
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200134SERVER_SET_BAUDRATE = b'\x65'
135SERVER_SET_DATASIZE = b'\x66'
136SERVER_SET_PARITY = b'\x67'
137SERVER_SET_STOPSIZE = b'\x68'
138SERVER_SET_CONTROL = b'\x69'
139SERVER_NOTIFY_LINESTATE = b'\x6a'
140SERVER_NOTIFY_MODEMSTATE = b'\x6b'
141SERVER_FLOWCONTROL_SUSPEND = b'\x6c'
142SERVER_FLOWCONTROL_RESUME = b'\x6d'
143SERVER_SET_LINESTATE_MASK = b'\x6e'
144SERVER_SET_MODEMSTATE_MASK = b'\x6f'
145SERVER_PURGE_DATA = b'\x70'
cliechti8099bed2009-08-01 23:59:18 +0000146
147RFC2217_ANSWER_MAP = {
148 SET_BAUDRATE: SERVER_SET_BAUDRATE,
149 SET_DATASIZE: SERVER_SET_DATASIZE,
150 SET_PARITY: SERVER_SET_PARITY,
151 SET_STOPSIZE: SERVER_SET_STOPSIZE,
152 SET_CONTROL: SERVER_SET_CONTROL,
153 NOTIFY_LINESTATE: SERVER_NOTIFY_LINESTATE,
154 NOTIFY_MODEMSTATE: SERVER_NOTIFY_MODEMSTATE,
155 FLOWCONTROL_SUSPEND: SERVER_FLOWCONTROL_SUSPEND,
156 FLOWCONTROL_RESUME: SERVER_FLOWCONTROL_RESUME,
157 SET_LINESTATE_MASK: SERVER_SET_LINESTATE_MASK,
158 SET_MODEMSTATE_MASK: SERVER_SET_MODEMSTATE_MASK,
159 PURGE_DATA: SERVER_PURGE_DATA,
160}
161
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200162SET_CONTROL_REQ_FLOW_SETTING = b'\x00' # Request Com Port Flow Control Setting (outbound/both)
163SET_CONTROL_USE_NO_FLOW_CONTROL = b'\x01' # Use No Flow Control (outbound/both)
164SET_CONTROL_USE_SW_FLOW_CONTROL = b'\x02' # Use XON/XOFF Flow Control (outbound/both)
165SET_CONTROL_USE_HW_FLOW_CONTROL = b'\x03' # Use HARDWARE Flow Control (outbound/both)
166SET_CONTROL_REQ_BREAK_STATE = b'\x04' # Request BREAK State
167SET_CONTROL_BREAK_ON = b'\x05' # Set BREAK State ON
168SET_CONTROL_BREAK_OFF = b'\x06' # Set BREAK State OFF
169SET_CONTROL_REQ_DTR = b'\x07' # Request DTR Signal State
170SET_CONTROL_DTR_ON = b'\x08' # Set DTR Signal State ON
171SET_CONTROL_DTR_OFF = b'\x09' # Set DTR Signal State OFF
172SET_CONTROL_REQ_RTS = b'\x0a' # Request RTS Signal State
173SET_CONTROL_RTS_ON = b'\x0b' # Set RTS Signal State ON
174SET_CONTROL_RTS_OFF = b'\x0c' # Set RTS Signal State OFF
175SET_CONTROL_REQ_FLOW_SETTING_IN = b'\x0d' # Request Com Port Flow Control Setting (inbound)
176SET_CONTROL_USE_NO_FLOW_CONTROL_IN = b'\x0e' # Use No Flow Control (inbound)
177SET_CONTROL_USE_SW_FLOW_CONTOL_IN = b'\x0f' # Use XON/XOFF Flow Control (inbound)
178SET_CONTROL_USE_HW_FLOW_CONTOL_IN = b'\x10' # Use HARDWARE Flow Control (inbound)
179SET_CONTROL_USE_DCD_FLOW_CONTROL = b'\x11' # Use DCD Flow Control (outbound/both)
180SET_CONTROL_USE_DTR_FLOW_CONTROL = b'\x12' # Use DTR Flow Control (inbound)
181SET_CONTROL_USE_DSR_FLOW_CONTROL = b'\x13' # Use DSR Flow Control (outbound/both)
cliechti8099bed2009-08-01 23:59:18 +0000182
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200183LINESTATE_MASK_TIMEOUT = 128 # Time-out Error
184LINESTATE_MASK_SHIFTREG_EMPTY = 64 # Transfer Shift Register Empty
185LINESTATE_MASK_TRANSREG_EMPTY = 32 # Transfer Holding Register Empty
186LINESTATE_MASK_BREAK_DETECT = 16 # Break-detect Error
187LINESTATE_MASK_FRAMING_ERROR = 8 # Framing Error
188LINESTATE_MASK_PARTIY_ERROR = 4 # Parity Error
189LINESTATE_MASK_OVERRUN_ERROR = 2 # Overrun Error
190LINESTATE_MASK_DATA_READY = 1 # Data Ready
cliechti8099bed2009-08-01 23:59:18 +0000191
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200192MODEMSTATE_MASK_CD = 128 # Receive Line Signal Detect (also known as Carrier Detect)
193MODEMSTATE_MASK_RI = 64 # Ring Indicator
194MODEMSTATE_MASK_DSR = 32 # Data-Set-Ready Signal State
195MODEMSTATE_MASK_CTS = 16 # Clear-To-Send Signal State
196MODEMSTATE_MASK_CD_CHANGE = 8 # Delta Receive Line Signal Detect
197MODEMSTATE_MASK_RI_CHANGE = 4 # Trailing-edge Ring Detector
198MODEMSTATE_MASK_DSR_CHANGE = 2 # Delta Data-Set-Ready
199MODEMSTATE_MASK_CTS_CHANGE = 1 # Delta Clear-To-Send
cliechti8099bed2009-08-01 23:59:18 +0000200
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200201PURGE_RECEIVE_BUFFER = b'\x01' # Purge access server receive data buffer
202PURGE_TRANSMIT_BUFFER = b'\x02' # Purge access server transmit data buffer
203PURGE_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 +0000204
205
206RFC2217_PARITY_MAP = {
207 PARITY_NONE: 1,
208 PARITY_ODD: 2,
209 PARITY_EVEN: 3,
210 PARITY_MARK: 4,
211 PARITY_SPACE: 5,
212}
cliechti130d1f02009-08-04 02:10:58 +0000213RFC2217_REVERSE_PARITY_MAP = dict((v,k) for k,v in RFC2217_PARITY_MAP.items())
cliechti8099bed2009-08-01 23:59:18 +0000214
215RFC2217_STOPBIT_MAP = {
216 STOPBITS_ONE: 1,
217 STOPBITS_ONE_POINT_FIVE: 3,
218 STOPBITS_TWO: 2,
219}
cliechti130d1f02009-08-04 02:10:58 +0000220RFC2217_REVERSE_STOPBIT_MAP = dict((v,k) for k,v in RFC2217_STOPBIT_MAP.items())
cliechti8099bed2009-08-01 23:59:18 +0000221
cliechti130d1f02009-08-04 02:10:58 +0000222# Telnet filter states
223M_NORMAL = 0
224M_IAC_SEEN = 1
225M_NEGOTIATE = 2
cliechti8099bed2009-08-01 23:59:18 +0000226
cliechti130d1f02009-08-04 02:10:58 +0000227# TelnetOption and TelnetSubnegotiation states
cliechtiac205322009-08-02 20:40:21 +0000228REQUESTED = 'REQUESTED'
229ACTIVE = 'ACTIVE'
230INACTIVE = 'INACTIVE'
231REALLY_INACTIVE = 'REALLY_INACTIVE'
232
233class TelnetOption(object):
cliechti1ef7e3e2009-08-03 02:38:43 +0000234 """Manage a single telnet option, keeps track of DO/DONT WILL/WONT."""
235
cliechti86b593e2009-08-05 16:28:12 +0000236 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 +0000237 """\
238 Initialize option.
cliechti1ef7e3e2009-08-03 02:38:43 +0000239 :param connection: connection used to transmit answers
240 :param name: a readable name for debug outputs
241 :param send_yes: what to send when option is to be enabled.
242 :param send_no: what to send when option is to be disabled.
243 :param ack_yes: what to expect when remote agrees on option.
244 :param ack_no: what to expect when remote disagrees on option.
245 :param initial_state: options initialized with REQUESTED are tried to
246 be enabled on startup. use INACTIVE for all others.
247 """
cliechti2b929b72009-08-02 23:49:02 +0000248 self.connection = connection
cliechtiac205322009-08-02 20:40:21 +0000249 self.name = name
250 self.option = option
251 self.send_yes = send_yes
252 self.send_no = send_no
253 self.ack_yes = ack_yes
254 self.ack_no = ack_no
255 self.state = initial_state
256 self.active = False
cliechti86b593e2009-08-05 16:28:12 +0000257 self.activation_callback = activation_callback
cliechtiac205322009-08-02 20:40:21 +0000258
259 def __repr__(self):
cliechti1ef7e3e2009-08-03 02:38:43 +0000260 """String for debug outputs"""
cliechtiac205322009-08-02 20:40:21 +0000261 return "%s:%s(%s)" % (self.name, self.active, self.state)
262
cliechti2b929b72009-08-02 23:49:02 +0000263 def process_incoming(self, command):
cliechti7d448562014-08-03 21:57:45 +0000264 """\
265 A DO/DONT/WILL/WONT was received for this option, update state and
266 answer when needed.
267 """
cliechtiac205322009-08-02 20:40:21 +0000268 if command == self.ack_yes:
269 if self.state is REQUESTED:
270 self.state = ACTIVE
271 self.active = True
cliechti86b593e2009-08-05 16:28:12 +0000272 if self.activation_callback is not None:
273 self.activation_callback()
cliechtiac205322009-08-02 20:40:21 +0000274 elif self.state is ACTIVE:
275 pass
276 elif self.state is INACTIVE:
277 self.state = ACTIVE
cliechti1ef7e3e2009-08-03 02:38:43 +0000278 self.connection.telnetSendOption(self.send_yes, self.option)
cliechtiac205322009-08-02 20:40:21 +0000279 self.active = True
cliechti86b593e2009-08-05 16:28:12 +0000280 if self.activation_callback is not None:
281 self.activation_callback()
cliechtiac205322009-08-02 20:40:21 +0000282 elif self.state is REALLY_INACTIVE:
cliechti1ef7e3e2009-08-03 02:38:43 +0000283 self.connection.telnetSendOption(self.send_no, self.option)
cliechtiac205322009-08-02 20:40:21 +0000284 else:
285 raise ValueError('option in illegal state %r' % self)
286 elif command == self.ack_no:
287 if self.state is REQUESTED:
288 self.state = INACTIVE
289 self.active = False
290 elif self.state is ACTIVE:
291 self.state = INACTIVE
cliechti1ef7e3e2009-08-03 02:38:43 +0000292 self.connection.telnetSendOption(self.send_no, self.option)
cliechtiac205322009-08-02 20:40:21 +0000293 self.active = False
294 elif self.state is INACTIVE:
295 pass
296 elif self.state is REALLY_INACTIVE:
297 pass
298 else:
299 raise ValueError('option in illegal state %r' % self)
300
301
cliechti2b929b72009-08-02 23:49:02 +0000302class TelnetSubnegotiation(object):
cliechtieada4fd2013-07-31 16:26:07 +0000303 """\
304 A object to handle subnegotiation of options. In this case actually
305 sub-sub options for RFC 2217. It is used to track com port options.
306 """
cliechti2b929b72009-08-02 23:49:02 +0000307
308 def __init__(self, connection, name, option, ack_option=None):
309 if ack_option is None: ack_option = option
310 self.connection = connection
311 self.name = name
312 self.option = option
313 self.value = None
314 self.ack_option = ack_option
315 self.state = INACTIVE
316
317 def __repr__(self):
cliechti044d8662009-08-11 21:40:31 +0000318 """String for debug outputs."""
cliechti2b929b72009-08-02 23:49:02 +0000319 return "%s:%s" % (self.name, self.state)
320
321 def set(self, value):
cliechtieada4fd2013-07-31 16:26:07 +0000322 """\
cliechti7d448562014-08-03 21:57:45 +0000323 Request a change of the value. a request is sent to the server. if
cliechti2b929b72009-08-02 23:49:02 +0000324 the client needs to know if the change is performed he has to check the
cliechtieada4fd2013-07-31 16:26:07 +0000325 state of this object.
326 """
cliechti2b929b72009-08-02 23:49:02 +0000327 self.value = value
328 self.state = REQUESTED
cliechti1ef7e3e2009-08-03 02:38:43 +0000329 self.connection.rfc2217SendSubnegotiation(self.option, self.value)
cliechti6a300772009-08-12 02:28:56 +0000330 if self.connection.logger:
331 self.connection.logger.debug("SB Requesting %s -> %r" % (self.name, self.value))
cliechti2b929b72009-08-02 23:49:02 +0000332
333 def isReady(self):
cliechtieada4fd2013-07-31 16:26:07 +0000334 """\
cliechti7d448562014-08-03 21:57:45 +0000335 Check if answer from server has been received. when server rejects
cliechtieada4fd2013-07-31 16:26:07 +0000336 the change, raise a ValueError.
337 """
cliechti2b929b72009-08-02 23:49:02 +0000338 if self.state == REALLY_INACTIVE:
339 raise ValueError("remote rejected value for option %r" % (self.name))
340 return self.state == ACTIVE
cliechti1ef7e3e2009-08-03 02:38:43 +0000341 # add property to have a similar interface as TelnetOption
cliechti2b929b72009-08-02 23:49:02 +0000342 active = property(isReady)
343
cliechti044d8662009-08-11 21:40:31 +0000344 def wait(self, timeout=3):
cliechtieada4fd2013-07-31 16:26:07 +0000345 """\
cliechti7d448562014-08-03 21:57:45 +0000346 Wait until the subnegotiation has been acknowledged or timeout. It
cliechti1ef7e3e2009-08-03 02:38:43 +0000347 can also throw a value error when the answer from the server does not
cliechtieada4fd2013-07-31 16:26:07 +0000348 match the value sent.
349 """
cliechti044d8662009-08-11 21:40:31 +0000350 timeout_time = time.time() + timeout
cliechti2b929b72009-08-02 23:49:02 +0000351 while time.time() < timeout_time:
352 time.sleep(0.05) # prevent 100% CPU load
353 if self.isReady():
354 break
355 else:
356 raise SerialException("timeout while waiting for option %r" % (self.name))
357
358 def checkAnswer(self, suboption):
cliechtieada4fd2013-07-31 16:26:07 +0000359 """\
cliechti7d448562014-08-03 21:57:45 +0000360 Check an incoming subnegotiation block. The parameter already has
cliechtieada4fd2013-07-31 16:26:07 +0000361 cut off the header like sub option number and com port option value.
362 """
cliechti2b929b72009-08-02 23:49:02 +0000363 if self.value == suboption[:len(self.value)]:
364 self.state = ACTIVE
365 else:
366 # error propagation done in isReady
367 self.state = REALLY_INACTIVE
cliechti6a300772009-08-12 02:28:56 +0000368 if self.connection.logger:
369 self.connection.logger.debug("SB Answer %s -> %r -> %s" % (self.name, suboption, self.state))
cliechti2b929b72009-08-02 23:49:02 +0000370
371
Chris Liechtief6b7b42015-08-06 22:19:26 +0200372class Serial(SerialBase):
cliechti044d8662009-08-11 21:40:31 +0000373 """Serial port implementation for RFC 2217 remote serial ports."""
cliechti8099bed2009-08-01 23:59:18 +0000374
375 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
376 9600, 19200, 38400, 57600, 115200)
377
378 def open(self):
cliechtieada4fd2013-07-31 16:26:07 +0000379 """\
380 Open port with current settings. This may throw a SerialException
381 if the port cannot be opened.
382 """
cliechti6a300772009-08-12 02:28:56 +0000383 self.logger = None
cliechti81c54762009-08-03 23:53:27 +0000384 self._ignore_set_control_answer = False
cliechti7cb78e82009-08-05 15:47:57 +0000385 self._poll_modem_state = False
cliechtidfe2d272009-08-10 22:19:41 +0000386 self._network_timeout = 3
cliechti8099bed2009-08-01 23:59:18 +0000387 if self._port is None:
388 raise SerialException("Port must be configured before it can be used.")
cliechti8f69e702011-03-19 00:22:32 +0000389 if self._isOpen:
390 raise SerialException("Port is already open.")
cliechti8099bed2009-08-01 23:59:18 +0000391 try:
Chris Liechtic4bca9e2015-08-07 14:40:41 +0200392 self._socket = socket.create_connection(self.fromURL(self.portstr))
cliechti6a300772009-08-12 02:28:56 +0000393 self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
Chris Liechti68340d72015-08-03 14:15:48 +0200394 except Exception as msg:
cliechti8099bed2009-08-01 23:59:18 +0000395 self._socket = None
396 raise SerialException("Could not open port %s: %s" % (self.portstr, msg))
397
cliechti1ef7e3e2009-08-03 02:38:43 +0000398 self._socket.settimeout(5) # XXX good value?
cliechti8099bed2009-08-01 23:59:18 +0000399
cliechti1ef7e3e2009-08-03 02:38:43 +0000400 # use a thread save queue as buffer. it also simplifies implementing
401 # the read timeout
cliechti8099bed2009-08-01 23:59:18 +0000402 self._read_buffer = Queue.Queue()
cliechti81c54762009-08-03 23:53:27 +0000403 # to ensure that user writes does not interfere with internal
404 # telnet/rfc2217 options establish a lock
405 self._write_lock = threading.Lock()
cliechtiac205322009-08-02 20:40:21 +0000406 # name the following separately so that, below, a check can be easily done
407 mandadory_options = [
cliechti2b929b72009-08-02 23:49:02 +0000408 TelnetOption(self, 'we-BINARY', BINARY, WILL, WONT, DO, DONT, INACTIVE),
cliechti2b929b72009-08-02 23:49:02 +0000409 TelnetOption(self, 'we-RFC2217', COM_PORT_OPTION, WILL, WONT, DO, DONT, REQUESTED),
cliechtiac205322009-08-02 20:40:21 +0000410 ]
411 # all supported telnet options
412 self._telnet_options = [
cliechtia29275e2009-08-03 00:08:04 +0000413 TelnetOption(self, 'ECHO', ECHO, DO, DONT, WILL, WONT, REQUESTED),
cliechti2b929b72009-08-02 23:49:02 +0000414 TelnetOption(self, 'we-SGA', SGA, WILL, WONT, DO, DONT, REQUESTED),
415 TelnetOption(self, 'they-SGA', SGA, DO, DONT, WILL, WONT, REQUESTED),
cliechti81c54762009-08-03 23:53:27 +0000416 TelnetOption(self, 'they-BINARY', BINARY, DO, DONT, WILL, WONT, INACTIVE),
417 TelnetOption(self, 'they-RFC2217', COM_PORT_OPTION, DO, DONT, WILL, WONT, REQUESTED),
cliechtiac205322009-08-02 20:40:21 +0000418 ] + mandadory_options
cliechti044d8662009-08-11 21:40:31 +0000419 # RFC 2217 specific states
cliechti2b929b72009-08-02 23:49:02 +0000420 # COM port settings
421 self._rfc2217_port_settings = {
422 'baudrate': TelnetSubnegotiation(self, 'baudrate', SET_BAUDRATE, SERVER_SET_BAUDRATE),
423 'datasize': TelnetSubnegotiation(self, 'datasize', SET_DATASIZE, SERVER_SET_DATASIZE),
424 'parity': TelnetSubnegotiation(self, 'parity', SET_PARITY, SERVER_SET_PARITY),
425 'stopsize': TelnetSubnegotiation(self, 'stopsize', SET_STOPSIZE, SERVER_SET_STOPSIZE),
426 }
cliechticb20a4f2011-04-25 02:25:54 +0000427 # There are more subnegotiation objects, combine all in one dictionary
cliechti2b929b72009-08-02 23:49:02 +0000428 # for easy access
429 self._rfc2217_options = {
430 'purge': TelnetSubnegotiation(self, 'purge', PURGE_DATA, SERVER_PURGE_DATA),
cliechti81c54762009-08-03 23:53:27 +0000431 'control': TelnetSubnegotiation(self, 'control', SET_CONTROL, SERVER_SET_CONTROL),
cliechti2b929b72009-08-02 23:49:02 +0000432 }
433 self._rfc2217_options.update(self._rfc2217_port_settings)
434 # cache for line and modem states that the server sends to us
cliechti8099bed2009-08-01 23:59:18 +0000435 self._linestate = 0
cliechti7cb78e82009-08-05 15:47:57 +0000436 self._modemstate = None
437 self._modemstate_expires = 0
cliechti044d8662009-08-11 21:40:31 +0000438 # RFC 2217 flow control between server and client
cliechti672d0292009-08-03 02:01:57 +0000439 self._remote_suspend_flow = False
cliechti8099bed2009-08-01 23:59:18 +0000440
cliechti1ef7e3e2009-08-03 02:38:43 +0000441 self._thread = threading.Thread(target=self._telnetReadLoop)
cliechti8099bed2009-08-01 23:59:18 +0000442 self._thread.setDaemon(True)
cliechti5cc3eb12009-08-11 23:04:30 +0000443 self._thread.setName('pySerial RFC 2217 reader thread for %s' % (self._port,))
cliechti8099bed2009-08-01 23:59:18 +0000444 self._thread.start()
445
cliechti044d8662009-08-11 21:40:31 +0000446 # negotiate Telnet/RFC 2217 -> send initial requests
cliechtiac205322009-08-02 20:40:21 +0000447 for option in self._telnet_options:
448 if option.state is REQUESTED:
cliechti1ef7e3e2009-08-03 02:38:43 +0000449 self.telnetSendOption(option.send_yes, option.option)
cliechtiac205322009-08-02 20:40:21 +0000450 # now wait until important options are negotiated
cliechtidfe2d272009-08-10 22:19:41 +0000451 timeout_time = time.time() + self._network_timeout
cliechtiac205322009-08-02 20:40:21 +0000452 while time.time() < timeout_time:
cliechtiac205322009-08-02 20:40:21 +0000453 time.sleep(0.05) # prevent 100% CPU load
cliechti7c213a92014-07-31 15:29:34 +0000454 if sum(o.active for o in mandadory_options) == sum(o.state != INACTIVE for o in mandadory_options):
cliechti2b929b72009-08-02 23:49:02 +0000455 break
456 else:
457 raise SerialException("Remote does not seem to support RFC2217 or BINARY mode %r" % mandadory_options)
cliechti6a300772009-08-12 02:28:56 +0000458 if self.logger:
459 self.logger.info("Negotiated options: %s" % self._telnet_options)
cliechti8099bed2009-08-01 23:59:18 +0000460
cliechti044d8662009-08-11 21:40:31 +0000461 # fine, go on, set RFC 2271 specific things
cliechti8099bed2009-08-01 23:59:18 +0000462 self._reconfigurePort()
cliechti2b929b72009-08-02 23:49:02 +0000463 # all things set up get, now a clean start
cliechti8099bed2009-08-01 23:59:18 +0000464 self._isOpen = True
465 if not self._rtscts:
466 self.setRTS(True)
467 self.setDTR(True)
468 self.flushInput()
469 self.flushOutput()
470
471 def _reconfigurePort(self):
472 """Set communication parameters on opened port."""
473 if self._socket is None:
474 raise SerialException("Can only operate on open ports")
475
cliechti8099bed2009-08-01 23:59:18 +0000476 # if self._timeout != 0 and self._interCharTimeout is not None:
cliechti8099bed2009-08-01 23:59:18 +0000477 # XXX
478
479 if self._writeTimeout is not None:
480 raise NotImplementedError('writeTimeout is currently not supported')
cliechti2b929b72009-08-02 23:49:02 +0000481 # XXX
cliechti8099bed2009-08-01 23:59:18 +0000482
cliechti2b929b72009-08-02 23:49:02 +0000483 # Setup the connection
cliechti1ef7e3e2009-08-03 02:38:43 +0000484 # to get good performance, all parameter changes are sent first...
Chris Liechti01587b12015-08-05 02:39:32 +0200485 if not 0 < self._baudrate < 2**32:
cliechti81c54762009-08-03 23:53:27 +0000486 raise ValueError("invalid baudrate: %r" % (self._baudrate))
Chris Liechti01587b12015-08-05 02:39:32 +0200487 self._rfc2217_port_settings['baudrate'].set(struct.pack(b'!I', self._baudrate))
488 self._rfc2217_port_settings['datasize'].set(struct.pack(b'!B', self._bytesize))
489 self._rfc2217_port_settings['parity'].set(struct.pack(b'!B', RFC2217_PARITY_MAP[self._parity]))
490 self._rfc2217_port_settings['stopsize'].set(struct.pack(b'!B', RFC2217_STOPBIT_MAP[self._stopbits]))
cliechti8099bed2009-08-01 23:59:18 +0000491
cliechti2b929b72009-08-02 23:49:02 +0000492 # and now wait until parameters are active
493 items = self._rfc2217_port_settings.values()
cliechti6a300772009-08-12 02:28:56 +0000494 if self.logger:
495 self.logger.debug("Negotiating settings: %s" % (items,))
cliechtidfe2d272009-08-10 22:19:41 +0000496 timeout_time = time.time() + self._network_timeout
cliechti2b929b72009-08-02 23:49:02 +0000497 while time.time() < timeout_time:
498 time.sleep(0.05) # prevent 100% CPU load
499 if sum(o.active for o in items) == len(items):
500 break
501 else:
502 raise SerialException("Remote does not accept parameter change (RFC2217): %r" % items)
cliechti6a300772009-08-12 02:28:56 +0000503 if self.logger:
504 self.logger.info("Negotiated settings: %s" % (items,))
cliechti8099bed2009-08-01 23:59:18 +0000505
506 if self._rtscts and self._xonxoff:
cliechti1ef7e3e2009-08-03 02:38:43 +0000507 raise ValueError('xonxoff and rtscts together are not supported')
cliechti8099bed2009-08-01 23:59:18 +0000508 elif self._rtscts:
cliechti1ef7e3e2009-08-03 02:38:43 +0000509 self.rfc2217SetControl(SET_CONTROL_USE_HW_FLOW_CONTROL)
cliechti8099bed2009-08-01 23:59:18 +0000510 elif self._xonxoff:
cliechti1ef7e3e2009-08-03 02:38:43 +0000511 self.rfc2217SetControl(SET_CONTROL_USE_SW_FLOW_CONTROL)
cliechti8099bed2009-08-01 23:59:18 +0000512 else:
cliechti1ef7e3e2009-08-03 02:38:43 +0000513 self.rfc2217SetControl(SET_CONTROL_USE_NO_FLOW_CONTROL)
cliechti8099bed2009-08-01 23:59:18 +0000514
515 def close(self):
516 """Close port"""
517 if self._isOpen:
518 if self._socket:
519 try:
520 self._socket.shutdown(socket.SHUT_RDWR)
521 self._socket.close()
522 except:
523 # ignore errors.
524 pass
525 self._socket = None
526 if self._thread:
527 self._thread.join()
528 self._isOpen = False
529 # in case of quick reconnects, give the server some time
530 time.sleep(0.3)
531
532 def makeDeviceName(self, port):
533 raise SerialException("there is no sensible way to turn numbers into URLs")
534
535 def fromURL(self, url):
cliechti1ef7e3e2009-08-03 02:38:43 +0000536 """extract host and port from an URL string"""
Chris Liechtia4222112015-08-07 01:03:12 +0200537 parts = urlparse.urlsplit(url)
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200538 if parts.scheme != "rfc2217":
539 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 +0000540 try:
Chris Liechtia4222112015-08-07 01:03:12 +0200541 # process options now, directly altering self
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200542 for option, values in urlparse.parse_qs(parts.query, True).items():
543 if option == 'logging':
Chris Liechtia4222112015-08-07 01:03:12 +0200544 logging.basicConfig() # XXX is that good to call it here?
545 self.logger = logging.getLogger('pySerial.rfc2217')
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200546 self.logger.setLevel(LOGGER_LEVELS[values[0]])
Chris Liechtia4222112015-08-07 01:03:12 +0200547 self.logger.debug('enabled logging')
548 elif option == 'ign_set_control':
549 self._ignore_set_control_answer = True
550 elif option == 'poll_modem':
551 self._poll_modem_state = True
552 elif option == 'timeout':
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200553 self._network_timeout = float(values[0])
Chris Liechtia4222112015-08-07 01:03:12 +0200554 else:
555 raise ValueError('unknown option: %r' % (option,))
cliechti81c54762009-08-03 23:53:27 +0000556 # get host and port
Chris Liechtia4222112015-08-07 01:03:12 +0200557 host, port = parts.hostname, parts.port
cliechti8099bed2009-08-01 23:59:18 +0000558 if not 0 <= port < 65536: raise ValueError("port not in range 0...65535")
Chris Liechti68340d72015-08-03 14:15:48 +0200559 except ValueError as e:
Chris Liechtid14b1ab2015-08-21 00:28:53 +0200560 raise SerialException('expected a string in the form "rfc2217://<host>:<port>[?option[&option...]]": %s' % e)
cliechti8099bed2009-08-01 23:59:18 +0000561 return (host, port)
562
563 # - - - - - - - - - - - - - - - - - - - - - - - -
564
565 def inWaiting(self):
566 """Return the number of characters currently in the input buffer."""
567 if not self._isOpen: raise portNotOpenError
568 return self._read_buffer.qsize()
569
570 def read(self, size=1):
cliechtieada4fd2013-07-31 16:26:07 +0000571 """\
572 Read size bytes from the serial port. If a timeout is set it may
cliechti8099bed2009-08-01 23:59:18 +0000573 return less characters as requested. With no timeout it will block
cliechtieada4fd2013-07-31 16:26:07 +0000574 until the requested number of bytes is read.
575 """
cliechti8099bed2009-08-01 23:59:18 +0000576 if not self._isOpen: raise portNotOpenError
577 data = bytearray()
578 try:
579 while len(data) < size:
cliechti81c54762009-08-03 23:53:27 +0000580 if self._thread is None:
581 raise SerialException('connection failed (reader thread died)')
Chris Liechti01587b12015-08-05 02:39:32 +0200582 data += self._read_buffer.get(True, self._timeout)
cliechti8099bed2009-08-01 23:59:18 +0000583 except Queue.Empty: # -> timeout
584 pass
585 return bytes(data)
586
587 def write(self, data):
cliechtieada4fd2013-07-31 16:26:07 +0000588 """\
589 Output the given string over the serial port. Can block if the
cliechti8099bed2009-08-01 23:59:18 +0000590 connection is blocked. May raise SerialException if the connection is
cliechtieada4fd2013-07-31 16:26:07 +0000591 closed.
592 """
cliechti8099bed2009-08-01 23:59:18 +0000593 if not self._isOpen: raise portNotOpenError
Chris Liechti01587b12015-08-05 02:39:32 +0200594 with self._write_lock:
cliechti81c54762009-08-03 23:53:27 +0000595 try:
cliechti38077122013-10-16 02:57:27 +0000596 self._socket.sendall(to_bytes(data).replace(IAC, IAC_DOUBLED))
Chris Liechti68340d72015-08-03 14:15:48 +0200597 except socket.error as e:
Chris Liechti142ae562015-08-23 01:11:06 +0200598 raise SerialException("connection failed (socket error): %s" % (e,))
cliechti8099bed2009-08-01 23:59:18 +0000599 return len(data)
600
601 def flushInput(self):
602 """Clear input buffer, discarding all that is in the buffer."""
603 if not self._isOpen: raise portNotOpenError
cliechti1ef7e3e2009-08-03 02:38:43 +0000604 self.rfc2217SendPurge(PURGE_RECEIVE_BUFFER)
cliechti8099bed2009-08-01 23:59:18 +0000605 # empty read buffer
606 while self._read_buffer.qsize():
607 self._read_buffer.get(False)
608
609 def flushOutput(self):
cliechtieada4fd2013-07-31 16:26:07 +0000610 """\
611 Clear output buffer, aborting the current output and
612 discarding all that is in the buffer.
613 """
cliechti8099bed2009-08-01 23:59:18 +0000614 if not self._isOpen: raise portNotOpenError
cliechti1ef7e3e2009-08-03 02:38:43 +0000615 self.rfc2217SendPurge(PURGE_TRANSMIT_BUFFER)
cliechti8099bed2009-08-01 23:59:18 +0000616
617 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000618 """\
619 Send break condition. Timed, returns to idle state after given
620 duration.
621 """
cliechti8099bed2009-08-01 23:59:18 +0000622 if not self._isOpen: raise portNotOpenError
623 self.setBreak(True)
624 time.sleep(duration)
625 self.setBreak(False)
626
627 def setBreak(self, level=True):
cliechtieada4fd2013-07-31 16:26:07 +0000628 """\
629 Set break: Controls TXD. When active, to transmitting is
630 possible.
631 """
cliechti8099bed2009-08-01 23:59:18 +0000632 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000633 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +0200634 self.logger.info('set BREAK to %s' % ('active' if level else 'inactive'))
cliechti8099bed2009-08-01 23:59:18 +0000635 if level:
cliechti1ef7e3e2009-08-03 02:38:43 +0000636 self.rfc2217SetControl(SET_CONTROL_BREAK_ON)
cliechti8099bed2009-08-01 23:59:18 +0000637 else:
cliechti1ef7e3e2009-08-03 02:38:43 +0000638 self.rfc2217SetControl(SET_CONTROL_BREAK_OFF)
cliechti8099bed2009-08-01 23:59:18 +0000639
640 def setRTS(self, level=True):
cliechti044d8662009-08-11 21:40:31 +0000641 """Set terminal status line: Request To Send."""
cliechti8099bed2009-08-01 23:59:18 +0000642 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000643 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +0200644 self.logger.info('set RTS to %s' % ('active' if level else 'inactive'))
cliechti8099bed2009-08-01 23:59:18 +0000645 if level:
cliechti1ef7e3e2009-08-03 02:38:43 +0000646 self.rfc2217SetControl(SET_CONTROL_RTS_ON)
cliechti8099bed2009-08-01 23:59:18 +0000647 else:
cliechti1ef7e3e2009-08-03 02:38:43 +0000648 self.rfc2217SetControl(SET_CONTROL_RTS_OFF)
cliechti8099bed2009-08-01 23:59:18 +0000649
650 def setDTR(self, level=True):
cliechti044d8662009-08-11 21:40:31 +0000651 """Set terminal status line: Data Terminal Ready."""
cliechti8099bed2009-08-01 23:59:18 +0000652 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000653 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +0200654 self.logger.info('set DTR to %s' % ('active' if level else 'inactive'))
cliechti8099bed2009-08-01 23:59:18 +0000655 if level:
cliechti1ef7e3e2009-08-03 02:38:43 +0000656 self.rfc2217SetControl(SET_CONTROL_DTR_ON)
cliechti8099bed2009-08-01 23:59:18 +0000657 else:
cliechti1ef7e3e2009-08-03 02:38:43 +0000658 self.rfc2217SetControl(SET_CONTROL_DTR_OFF)
cliechti8099bed2009-08-01 23:59:18 +0000659
660 def getCTS(self):
cliechti044d8662009-08-11 21:40:31 +0000661 """Read terminal status line: Clear To Send."""
cliechti8099bed2009-08-01 23:59:18 +0000662 if not self._isOpen: raise portNotOpenError
cliechti7cb78e82009-08-05 15:47:57 +0000663 return bool(self.getModemState() & MODEMSTATE_MASK_CTS)
cliechti8099bed2009-08-01 23:59:18 +0000664
665 def getDSR(self):
cliechti044d8662009-08-11 21:40:31 +0000666 """Read terminal status line: Data Set Ready."""
cliechti8099bed2009-08-01 23:59:18 +0000667 if not self._isOpen: raise portNotOpenError
cliechti7cb78e82009-08-05 15:47:57 +0000668 return bool(self.getModemState() & MODEMSTATE_MASK_DSR)
cliechti8099bed2009-08-01 23:59:18 +0000669
670 def getRI(self):
cliechti044d8662009-08-11 21:40:31 +0000671 """Read terminal status line: Ring Indicator."""
cliechti8099bed2009-08-01 23:59:18 +0000672 if not self._isOpen: raise portNotOpenError
cliechti7cb78e82009-08-05 15:47:57 +0000673 return bool(self.getModemState() & MODEMSTATE_MASK_RI)
cliechti8099bed2009-08-01 23:59:18 +0000674
675 def getCD(self):
cliechti044d8662009-08-11 21:40:31 +0000676 """Read terminal status line: Carrier Detect."""
cliechti8099bed2009-08-01 23:59:18 +0000677 if not self._isOpen: raise portNotOpenError
cliechti7cb78e82009-08-05 15:47:57 +0000678 return bool(self.getModemState() & MODEMSTATE_MASK_CD)
cliechti8099bed2009-08-01 23:59:18 +0000679
680 # - - - platform specific - - -
681 # None so far
682
683 # - - - RFC2217 specific - - -
684
cliechti1ef7e3e2009-08-03 02:38:43 +0000685 def _telnetReadLoop(self):
cliechti7d448562014-08-03 21:57:45 +0000686 """Read loop for the socket."""
cliechti8099bed2009-08-01 23:59:18 +0000687 mode = M_NORMAL
688 suboption = None
cliechti81c54762009-08-03 23:53:27 +0000689 try:
690 while self._socket is not None:
691 try:
692 data = self._socket.recv(1024)
693 except socket.timeout:
694 # just need to get out of recv form time to time to check if
695 # still alive
696 continue
Chris Liechti68340d72015-08-03 14:15:48 +0200697 except socket.error as e:
cliechti81c54762009-08-03 23:53:27 +0000698 # connection fails -> terminate loop
cliechticb20a4f2011-04-25 02:25:54 +0000699 if self.logger:
700 self.logger.debug("socket error in reader thread: %s" % (e,))
cliechti81c54762009-08-03 23:53:27 +0000701 break
cliechticb20a4f2011-04-25 02:25:54 +0000702 if not data: break # lost connection
Chris Liechtif99cd5c2015-08-13 22:54:16 +0200703 for byte in iterbytes(data):
cliechti81c54762009-08-03 23:53:27 +0000704 if mode == M_NORMAL:
705 # interpret as command or as data
706 if byte == IAC:
707 mode = M_IAC_SEEN
cliechti8099bed2009-08-01 23:59:18 +0000708 else:
cliechti81c54762009-08-03 23:53:27 +0000709 # store data in read buffer or sub option buffer
710 # depending on state
711 if suboption is not None:
Chris Liechti01587b12015-08-05 02:39:32 +0200712 suboption += byte
cliechti81c54762009-08-03 23:53:27 +0000713 else:
714 self._read_buffer.put(byte)
715 elif mode == M_IAC_SEEN:
716 if byte == IAC:
717 # interpret as command doubled -> insert character
718 # itself
cliechtif325c032009-12-25 16:09:49 +0000719 if suboption is not None:
Chris Liechti01587b12015-08-05 02:39:32 +0200720 suboption += IAC
cliechtif325c032009-12-25 16:09:49 +0000721 else:
722 self._read_buffer.put(IAC)
cliechti81c54762009-08-03 23:53:27 +0000723 mode = M_NORMAL
724 elif byte == SB:
725 # sub option start
726 suboption = bytearray()
727 mode = M_NORMAL
728 elif byte == SE:
729 # sub option end -> process it now
730 self._telnetProcessSubnegotiation(bytes(suboption))
731 suboption = None
732 mode = M_NORMAL
733 elif byte in (DO, DONT, WILL, WONT):
734 # negotiation
735 telnet_command = byte
736 mode = M_NEGOTIATE
737 else:
738 # other telnet commands
739 self._telnetProcessCommand(byte)
740 mode = M_NORMAL
741 elif mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following
742 self._telnetNegotiateOption(telnet_command, byte)
cliechti8099bed2009-08-01 23:59:18 +0000743 mode = M_NORMAL
cliechti81c54762009-08-03 23:53:27 +0000744 finally:
745 self._thread = None
cliechti6a300772009-08-12 02:28:56 +0000746 if self.logger:
747 self.logger.debug("read thread terminated")
cliechti8099bed2009-08-01 23:59:18 +0000748
749 # - incoming telnet commands and options
750
cliechti1ef7e3e2009-08-03 02:38:43 +0000751 def _telnetProcessCommand(self, command):
cliechti044d8662009-08-11 21:40:31 +0000752 """Process commands other than DO, DONT, WILL, WONT."""
cliechti1ef7e3e2009-08-03 02:38:43 +0000753 # Currently none. RFC2217 only uses negotiation and subnegotiation.
cliechti6a300772009-08-12 02:28:56 +0000754 if self.logger:
755 self.logger.warning("ignoring Telnet command: %r" % (command,))
cliechti8099bed2009-08-01 23:59:18 +0000756
cliechti1ef7e3e2009-08-03 02:38:43 +0000757 def _telnetNegotiateOption(self, command, option):
cliechti044d8662009-08-11 21:40:31 +0000758 """Process incoming DO, DONT, WILL, WONT."""
cliechti2b929b72009-08-02 23:49:02 +0000759 # check our registered telnet options and forward command to them
760 # they know themselves if they have to answer or not
cliechtiac205322009-08-02 20:40:21 +0000761 known = False
762 for item in self._telnet_options:
cliechti2b929b72009-08-02 23:49:02 +0000763 # can have more than one match! as some options are duplicated for
764 # 'us' and 'them'
cliechtiac205322009-08-02 20:40:21 +0000765 if item.option == option:
cliechti2b929b72009-08-02 23:49:02 +0000766 item.process_incoming(command)
cliechtiac205322009-08-02 20:40:21 +0000767 known = True
768 if not known:
769 # handle unknown options
770 # only answer to positive requests and deny them
771 if command == WILL or command == DO:
Chris Liechti142ae562015-08-23 01:11:06 +0200772 self.telnetSendOption((DONT if command == WILL else WONT), option)
cliechti6a300772009-08-12 02:28:56 +0000773 if self.logger:
774 self.logger.warning("rejected Telnet option: %r" % (option,))
cliechtiac205322009-08-02 20:40:21 +0000775
cliechti8099bed2009-08-01 23:59:18 +0000776
cliechti1ef7e3e2009-08-03 02:38:43 +0000777 def _telnetProcessSubnegotiation(self, suboption):
cliechti044d8662009-08-11 21:40:31 +0000778 """Process subnegotiation, the data between IAC SB and IAC SE."""
cliechti8099bed2009-08-01 23:59:18 +0000779 if suboption[0:1] == COM_PORT_OPTION:
780 if suboption[1:2] == SERVER_NOTIFY_LINESTATE and len(suboption) >= 3:
cliechti672d0292009-08-03 02:01:57 +0000781 self._linestate = ord(suboption[2:3]) # ensure it is a number
cliechti6a300772009-08-12 02:28:56 +0000782 if self.logger:
783 self.logger.info("NOTIFY_LINESTATE: %s" % self._linestate)
cliechti8099bed2009-08-01 23:59:18 +0000784 elif suboption[1:2] == SERVER_NOTIFY_MODEMSTATE and len(suboption) >= 3:
cliechti672d0292009-08-03 02:01:57 +0000785 self._modemstate = ord(suboption[2:3]) # ensure it is a number
cliechti6a300772009-08-12 02:28:56 +0000786 if self.logger:
787 self.logger.info("NOTIFY_MODEMSTATE: %s" % self._modemstate)
cliechti7cb78e82009-08-05 15:47:57 +0000788 # update time when we think that a poll would make sense
789 self._modemstate_expires = time.time() + 0.3
cliechti672d0292009-08-03 02:01:57 +0000790 elif suboption[1:2] == FLOWCONTROL_SUSPEND:
791 self._remote_suspend_flow = True
792 elif suboption[1:2] == FLOWCONTROL_RESUME:
793 self._remote_suspend_flow = False
cliechti8099bed2009-08-01 23:59:18 +0000794 else:
cliechti2b929b72009-08-02 23:49:02 +0000795 for item in self._rfc2217_options.values():
796 if item.ack_option == suboption[1:2]:
cliechti81c54762009-08-03 23:53:27 +0000797 #~ print "processing COM_PORT_OPTION: %r" % list(suboption[1:])
cliechti2b929b72009-08-02 23:49:02 +0000798 item.checkAnswer(bytes(suboption[2:]))
799 break
800 else:
cliechti6a300772009-08-12 02:28:56 +0000801 if self.logger:
802 self.logger.warning("ignoring COM_PORT_OPTION: %r" % (suboption,))
cliechti8099bed2009-08-01 23:59:18 +0000803 else:
cliechti6a300772009-08-12 02:28:56 +0000804 if self.logger:
805 self.logger.warning("ignoring subnegotiation: %r" % (suboption,))
cliechti8099bed2009-08-01 23:59:18 +0000806
807 # - outgoing telnet commands and options
808
cliechti81c54762009-08-03 23:53:27 +0000809 def _internal_raw_write(self, data):
cliechti044d8662009-08-11 21:40:31 +0000810 """internal socket write with no data escaping. used to send telnet stuff."""
Chris Liechti01587b12015-08-05 02:39:32 +0200811 with self._write_lock:
cliechti81c54762009-08-03 23:53:27 +0000812 self._socket.sendall(data)
cliechti81c54762009-08-03 23:53:27 +0000813
cliechti1ef7e3e2009-08-03 02:38:43 +0000814 def telnetSendOption(self, action, option):
cliechti044d8662009-08-11 21:40:31 +0000815 """Send DO, DONT, WILL, WONT."""
cliechti81c54762009-08-03 23:53:27 +0000816 self._internal_raw_write(to_bytes([IAC, action, option]))
cliechti8099bed2009-08-01 23:59:18 +0000817
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200818 def rfc2217SendSubnegotiation(self, option, value=b''):
cliechti044d8662009-08-11 21:40:31 +0000819 """Subnegotiation of RFC2217 parameters."""
cliechtif325c032009-12-25 16:09:49 +0000820 value = value.replace(IAC, IAC_DOUBLED)
cliechti81c54762009-08-03 23:53:27 +0000821 self._internal_raw_write(to_bytes([IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE]))
cliechti2b929b72009-08-02 23:49:02 +0000822
cliechti1ef7e3e2009-08-03 02:38:43 +0000823 def rfc2217SendPurge(self, value):
cliechti2b929b72009-08-02 23:49:02 +0000824 item = self._rfc2217_options['purge']
cliechti672d0292009-08-03 02:01:57 +0000825 item.set(value) # transmit desired purge type
cliechtidfe2d272009-08-10 22:19:41 +0000826 item.wait(self._network_timeout) # wait for acknowledge from the server
cliechti2b929b72009-08-02 23:49:02 +0000827
cliechti1ef7e3e2009-08-03 02:38:43 +0000828 def rfc2217SetControl(self, value):
cliechti81c54762009-08-03 23:53:27 +0000829 item = self._rfc2217_options['control']
cliechticb20a4f2011-04-25 02:25:54 +0000830 item.set(value) # transmit desired control type
cliechti81c54762009-08-03 23:53:27 +0000831 if self._ignore_set_control_answer:
832 # answers are ignored when option is set. compatibility mode for
cliechticb20a4f2011-04-25 02:25:54 +0000833 # servers that answer, but not the expected one... (or no answer
cliechti81c54762009-08-03 23:53:27 +0000834 # at all) i.e. sredird
835 time.sleep(0.1) # this helps getting the unit tests passed
836 else:
cliechtidfe2d272009-08-10 22:19:41 +0000837 item.wait(self._network_timeout) # wait for acknowledge from the server
cliechti8099bed2009-08-01 23:59:18 +0000838
cliechti1ef7e3e2009-08-03 02:38:43 +0000839 def rfc2217FlowServerReady(self):
cliechtieada4fd2013-07-31 16:26:07 +0000840 """\
841 check if server is ready to receive data. block for some time when
842 not.
843 """
cliechti672d0292009-08-03 02:01:57 +0000844 #~ if self._remote_suspend_flow:
845 #~ wait---
846
cliechti7cb78e82009-08-05 15:47:57 +0000847 def getModemState(self):
cliechtieada4fd2013-07-31 16:26:07 +0000848 """\
cliechti7d448562014-08-03 21:57:45 +0000849 get last modem state (cached value. If value is "old", request a new
850 one. This cache helps that we don't issue to many requests when e.g. all
851 status lines, one after the other is queried by the user (getCTS, getDSR
cliechtieada4fd2013-07-31 16:26:07 +0000852 etc.)
853 """
cliechti7cb78e82009-08-05 15:47:57 +0000854 # active modem state polling enabled? is the value fresh enough?
855 if self._poll_modem_state and self._modemstate_expires < time.time():
cliechti6a300772009-08-12 02:28:56 +0000856 if self.logger:
857 self.logger.debug('polling modem state')
cliechti7cb78e82009-08-05 15:47:57 +0000858 # when it is older, request an update
859 self.rfc2217SendSubnegotiation(NOTIFY_MODEMSTATE)
cliechtidfe2d272009-08-10 22:19:41 +0000860 timeout_time = time.time() + self._network_timeout
cliechti7cb78e82009-08-05 15:47:57 +0000861 while time.time() < timeout_time:
862 time.sleep(0.05) # prevent 100% CPU load
863 # when expiration time is updated, it means that there is a new
864 # value
865 if self._modemstate_expires > time.time():
866 break
Chris Liechti01587b12015-08-05 02:39:32 +0200867 else:
868 if self.logger:
869 self.logger.warning('poll for modem state failed')
cliechti7cb78e82009-08-05 15:47:57 +0000870 # even when there is a timeout, do not generate an error just
871 # return the last known value. this way we can support buggy
872 # servers that do not respond to polls, but send automatic
873 # updates.
874 if self._modemstate is not None:
cliechti6a300772009-08-12 02:28:56 +0000875 if self.logger:
876 self.logger.debug('using cached modem state')
cliechti7cb78e82009-08-05 15:47:57 +0000877 return self._modemstate
878 else:
879 # never received a notification from the server
cliechti8fb119c2009-08-05 23:39:45 +0000880 raise SerialException("remote sends no NOTIFY_MODEMSTATE")
cliechti8099bed2009-08-01 23:59:18 +0000881
cliechti5cc3eb12009-08-11 23:04:30 +0000882
cliechti595ed5b2009-08-10 01:43:32 +0000883#############################################################################
cliechti5cc3eb12009-08-11 23:04:30 +0000884# The following is code that helps implementing an RFC 2217 server.
cliechti8099bed2009-08-01 23:59:18 +0000885
cliechti8ccc2ff2009-08-05 12:44:46 +0000886class PortManager(object):
cliechtieada4fd2013-07-31 16:26:07 +0000887 """\
888 This class manages the state of Telnet and RFC 2217. It needs a serial
cliechticb20a4f2011-04-25 02:25:54 +0000889 instance and a connection to work with. Connection is expected to implement
cliechtieada4fd2013-07-31 16:26:07 +0000890 a (thread safe) write function, that writes the string to the network.
891 """
cliechti130d1f02009-08-04 02:10:58 +0000892
cliechti6a300772009-08-12 02:28:56 +0000893 def __init__(self, serial_port, connection, logger=None):
cliechti130d1f02009-08-04 02:10:58 +0000894 self.serial = serial_port
895 self.connection = connection
cliechti6a300772009-08-12 02:28:56 +0000896 self.logger = logger
cliechti86b593e2009-08-05 16:28:12 +0000897 self._client_is_rfc2217 = False
cliechti130d1f02009-08-04 02:10:58 +0000898
899 # filter state machine
900 self.mode = M_NORMAL
901 self.suboption = None
902 self.telnet_command = None
903
904 # states for modem/line control events
905 self.modemstate_mask = 255
906 self.last_modemstate = None
907 self.linstate_mask = 0
908
909 # all supported telnet options
910 self._telnet_options = [
911 TelnetOption(self, 'ECHO', ECHO, WILL, WONT, DO, DONT, REQUESTED),
912 TelnetOption(self, 'we-SGA', SGA, WILL, WONT, DO, DONT, REQUESTED),
913 TelnetOption(self, 'they-SGA', SGA, DO, DONT, WILL, WONT, INACTIVE),
914 TelnetOption(self, 'we-BINARY', BINARY, WILL, WONT, DO, DONT, INACTIVE),
915 TelnetOption(self, 'they-BINARY', BINARY, DO, DONT, WILL, WONT, REQUESTED),
cliechti86b593e2009-08-05 16:28:12 +0000916 TelnetOption(self, 'we-RFC2217', COM_PORT_OPTION, WILL, WONT, DO, DONT, REQUESTED, self._client_ok),
917 TelnetOption(self, 'they-RFC2217', COM_PORT_OPTION, DO, DONT, WILL, WONT, INACTIVE, self._client_ok),
cliechti130d1f02009-08-04 02:10:58 +0000918 ]
919
920 # negotiate Telnet/RFC2217 -> send initial requests
cliechti6a300772009-08-12 02:28:56 +0000921 if self.logger:
922 self.logger.debug("requesting initial Telnet/RFC 2217 options")
cliechti130d1f02009-08-04 02:10:58 +0000923 for option in self._telnet_options:
924 if option.state is REQUESTED:
925 self.telnetSendOption(option.send_yes, option.option)
926 # issue 1st modem state notification
cliechti86b593e2009-08-05 16:28:12 +0000927
928 def _client_ok(self):
cliechtieada4fd2013-07-31 16:26:07 +0000929 """\
cliechti7d448562014-08-03 21:57:45 +0000930 callback of telnet option. It gets called when option is activated.
931 This one here is used to detect when the client agrees on RFC 2217. A
cliechti86b593e2009-08-05 16:28:12 +0000932 flag is set so that other functions like check_modem_lines know if the
cliechti7d448562014-08-03 21:57:45 +0000933 client is OK.
cliechtieada4fd2013-07-31 16:26:07 +0000934 """
cliechti86b593e2009-08-05 16:28:12 +0000935 # The callback is used for we and they so if one party agrees, we're
936 # already happy. it seems not all servers do the negotiation correctly
937 # and i guess there are incorrect clients too.. so be happy if client
938 # answers one or the other positively.
939 self._client_is_rfc2217 = True
cliechti6a300772009-08-12 02:28:56 +0000940 if self.logger:
941 self.logger.info("client accepts RFC 2217")
cliechti8fb119c2009-08-05 23:39:45 +0000942 # this is to ensure that the client gets a notification, even if there
943 # was no change
944 self.check_modem_lines(force_notification=True)
cliechti130d1f02009-08-04 02:10:58 +0000945
946 # - outgoing telnet commands and options
947
948 def telnetSendOption(self, action, option):
cliechti044d8662009-08-11 21:40:31 +0000949 """Send DO, DONT, WILL, WONT."""
cliechti130d1f02009-08-04 02:10:58 +0000950 self.connection.write(to_bytes([IAC, action, option]))
951
Chris Liechtib4cda3a2015-08-08 17:12:08 +0200952 def rfc2217SendSubnegotiation(self, option, value=b''):
cliechti044d8662009-08-11 21:40:31 +0000953 """Subnegotiation of RFC 2217 parameters."""
cliechtif325c032009-12-25 16:09:49 +0000954 value = value.replace(IAC, IAC_DOUBLED)
cliechti130d1f02009-08-04 02:10:58 +0000955 self.connection.write(to_bytes([IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE]))
956
957 # - check modem lines, needs to be called periodically from user to
958 # establish polling
959
cliechti7cb78e82009-08-05 15:47:57 +0000960 def check_modem_lines(self, force_notification=False):
cliechti130d1f02009-08-04 02:10:58 +0000961 modemstate = (
Chris Liechti142ae562015-08-23 01:11:06 +0200962 (self.serial.getCTS() and MODEMSTATE_MASK_CTS) |
963 (self.serial.getDSR() and MODEMSTATE_MASK_DSR) |
964 (self.serial.getRI() and MODEMSTATE_MASK_RI) |
965 (self.serial.getCD() and MODEMSTATE_MASK_CD))
cliechti7cb78e82009-08-05 15:47:57 +0000966 # check what has changed
967 deltas = modemstate ^ (self.last_modemstate or 0) # when last is None -> 0
968 if deltas & MODEMSTATE_MASK_CTS:
969 modemstate |= MODEMSTATE_MASK_CTS_CHANGE
970 if deltas & MODEMSTATE_MASK_DSR:
971 modemstate |= MODEMSTATE_MASK_DSR_CHANGE
972 if deltas & MODEMSTATE_MASK_RI:
973 modemstate |= MODEMSTATE_MASK_RI_CHANGE
974 if deltas & MODEMSTATE_MASK_CD:
975 modemstate |= MODEMSTATE_MASK_CD_CHANGE
976 # if new state is different and the mask allows this change, send
cliechti86b593e2009-08-05 16:28:12 +0000977 # notification. suppress notifications when client is not rfc2217
cliechti7cb78e82009-08-05 15:47:57 +0000978 if modemstate != self.last_modemstate or force_notification:
cliechti8fb119c2009-08-05 23:39:45 +0000979 if (self._client_is_rfc2217 and (modemstate & self.modemstate_mask)) or force_notification:
cliechti7cb78e82009-08-05 15:47:57 +0000980 self.rfc2217SendSubnegotiation(
981 SERVER_NOTIFY_MODEMSTATE,
982 to_bytes([modemstate & self.modemstate_mask])
983 )
cliechti6a300772009-08-12 02:28:56 +0000984 if self.logger:
985 self.logger.info("NOTIFY_MODEMSTATE: %s" % (modemstate,))
cliechti7cb78e82009-08-05 15:47:57 +0000986 # save last state, but forget about deltas.
987 # otherwise it would also notify about changing deltas which is
988 # probably not very useful
989 self.last_modemstate = modemstate & 0xf0
cliechti130d1f02009-08-04 02:10:58 +0000990
cliechti32c10332009-08-05 13:23:43 +0000991 # - outgoing data escaping
992
993 def escape(self, data):
cliechtieada4fd2013-07-31 16:26:07 +0000994 """\
cliechti7d448562014-08-03 21:57:45 +0000995 This generator function is for the user. All outgoing data has to be
cliechticb20a4f2011-04-25 02:25:54 +0000996 properly escaped, so that no IAC character in the data stream messes up
997 the Telnet state machine in the server.
cliechti32c10332009-08-05 13:23:43 +0000998
999 socket.sendall(escape(data))
1000 """
1001 for byte in data:
1002 if byte == IAC:
1003 yield IAC
1004 yield IAC
1005 else:
1006 yield byte
1007
cliechti130d1f02009-08-04 02:10:58 +00001008 # - incoming data filter
1009
1010 def filter(self, data):
cliechtieada4fd2013-07-31 16:26:07 +00001011 """\
cliechti7d448562014-08-03 21:57:45 +00001012 Handle a bunch of incoming bytes. This is a generator. It will yield
cliechti044d8662009-08-11 21:40:31 +00001013 all characters not of interest for Telnet/RFC 2217.
cliechti130d1f02009-08-04 02:10:58 +00001014
1015 The idea is that the reader thread pushes data from the socket through
1016 this filter:
1017
1018 for byte in filter(socket.recv(1024)):
1019 # do things like CR/LF conversion/whatever
1020 # and write data to the serial port
1021 serial.write(byte)
1022
1023 (socket error handling code left as exercise for the reader)
1024 """
Chris Liechtif99cd5c2015-08-13 22:54:16 +02001025 for byte in iterbytes(data):
cliechti130d1f02009-08-04 02:10:58 +00001026 if self.mode == M_NORMAL:
1027 # interpret as command or as data
1028 if byte == IAC:
1029 self.mode = M_IAC_SEEN
1030 else:
1031 # store data in sub option buffer or pass it to our
1032 # consumer depending on state
1033 if self.suboption is not None:
Chris Liechti01587b12015-08-05 02:39:32 +02001034 self.suboption += byte
cliechti130d1f02009-08-04 02:10:58 +00001035 else:
1036 yield byte
1037 elif self.mode == M_IAC_SEEN:
1038 if byte == IAC:
1039 # interpret as command doubled -> insert character
1040 # itself
cliechtif325c032009-12-25 16:09:49 +00001041 if self.suboption is not None:
Chris Liechti01587b12015-08-05 02:39:32 +02001042 self.suboption += byte
cliechtif325c032009-12-25 16:09:49 +00001043 else:
1044 yield byte
cliechti130d1f02009-08-04 02:10:58 +00001045 self.mode = M_NORMAL
1046 elif byte == SB:
1047 # sub option start
1048 self.suboption = bytearray()
1049 self.mode = M_NORMAL
1050 elif byte == SE:
1051 # sub option end -> process it now
1052 self._telnetProcessSubnegotiation(bytes(self.suboption))
1053 self.suboption = None
1054 self.mode = M_NORMAL
1055 elif byte in (DO, DONT, WILL, WONT):
1056 # negotiation
1057 self.telnet_command = byte
1058 self.mode = M_NEGOTIATE
1059 else:
1060 # other telnet commands
1061 self._telnetProcessCommand(byte)
1062 self.mode = M_NORMAL
1063 elif self.mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following
1064 self._telnetNegotiateOption(self.telnet_command, byte)
1065 self.mode = M_NORMAL
1066
1067 # - incoming telnet commands and options
1068
1069 def _telnetProcessCommand(self, command):
cliechti044d8662009-08-11 21:40:31 +00001070 """Process commands other than DO, DONT, WILL, WONT."""
cliechti130d1f02009-08-04 02:10:58 +00001071 # Currently none. RFC2217 only uses negotiation and subnegotiation.
cliechti6a300772009-08-12 02:28:56 +00001072 if self.logger:
1073 self.logger.warning("ignoring Telnet command: %r" % (command,))
cliechti130d1f02009-08-04 02:10:58 +00001074
1075 def _telnetNegotiateOption(self, command, option):
cliechti044d8662009-08-11 21:40:31 +00001076 """Process incoming DO, DONT, WILL, WONT."""
cliechti130d1f02009-08-04 02:10:58 +00001077 # check our registered telnet options and forward command to them
1078 # they know themselves if they have to answer or not
1079 known = False
1080 for item in self._telnet_options:
1081 # can have more than one match! as some options are duplicated for
1082 # 'us' and 'them'
1083 if item.option == option:
1084 item.process_incoming(command)
1085 known = True
1086 if not known:
1087 # handle unknown options
1088 # only answer to positive requests and deny them
1089 if command == WILL or command == DO:
Chris Liechti142ae562015-08-23 01:11:06 +02001090 self.telnetSendOption((DONT if command == WILL else WONT), option)
cliechti6a300772009-08-12 02:28:56 +00001091 if self.logger:
1092 self.logger.warning("rejected Telnet option: %r" % (option,))
cliechti130d1f02009-08-04 02:10:58 +00001093
1094
1095 def _telnetProcessSubnegotiation(self, suboption):
cliechti044d8662009-08-11 21:40:31 +00001096 """Process subnegotiation, the data between IAC SB and IAC SE."""
cliechti130d1f02009-08-04 02:10:58 +00001097 if suboption[0:1] == COM_PORT_OPTION:
cliechti6a300772009-08-12 02:28:56 +00001098 if self.logger:
1099 self.logger.debug('received COM_PORT_OPTION: %r' % (suboption,))
cliechti130d1f02009-08-04 02:10:58 +00001100 if suboption[1:2] == SET_BAUDRATE:
1101 backup = self.serial.baudrate
1102 try:
Chris Liechti01587b12015-08-05 02:39:32 +02001103 (baudrate,) = struct.unpack(b"!I", suboption[2:6])
cliechtieada4fd2013-07-31 16:26:07 +00001104 if baudrate != 0:
1105 self.serial.baudrate = baudrate
Chris Liechtid2146002015-08-04 16:57:16 +02001106 except ValueError as e:
cliechti6a300772009-08-12 02:28:56 +00001107 if self.logger:
1108 self.logger.error("failed to set baud rate: %s" % (e,))
cliechti130d1f02009-08-04 02:10:58 +00001109 self.serial.baudrate = backup
cliechti5cc3eb12009-08-11 23:04:30 +00001110 else:
cliechti6a300772009-08-12 02:28:56 +00001111 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +02001112 self.logger.info("%s baud rate: %s" % ('set' if baudrate else 'get', self.serial.baudrate))
Chris Liechti01587b12015-08-05 02:39:32 +02001113 self.rfc2217SendSubnegotiation(SERVER_SET_BAUDRATE, struct.pack(b"!I", self.serial.baudrate))
cliechti130d1f02009-08-04 02:10:58 +00001114 elif suboption[1:2] == SET_DATASIZE:
1115 backup = self.serial.bytesize
1116 try:
Chris Liechti142ae562015-08-23 01:11:06 +02001117 (datasize,) = struct.unpack(b"!B", suboption[2:3])
cliechtieada4fd2013-07-31 16:26:07 +00001118 if datasize != 0:
1119 self.serial.bytesize = datasize
Chris Liechtid2146002015-08-04 16:57:16 +02001120 except ValueError as e:
cliechti6a300772009-08-12 02:28:56 +00001121 if self.logger:
1122 self.logger.error("failed to set data size: %s" % (e,))
cliechti130d1f02009-08-04 02:10:58 +00001123 self.serial.bytesize = backup
cliechti5cc3eb12009-08-11 23:04:30 +00001124 else:
cliechti6a300772009-08-12 02:28:56 +00001125 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +02001126 self.logger.info("%s data size: %s" % ('set' if datasize else 'get', self.serial.bytesize))
Chris Liechti01587b12015-08-05 02:39:32 +02001127 self.rfc2217SendSubnegotiation(SERVER_SET_DATASIZE, struct.pack(b"!B", self.serial.bytesize))
cliechti130d1f02009-08-04 02:10:58 +00001128 elif suboption[1:2] == SET_PARITY:
1129 backup = self.serial.parity
1130 try:
Chris Liechti01587b12015-08-05 02:39:32 +02001131 parity = struct.unpack(b"!B", suboption[2:3])[0]
cliechtieada4fd2013-07-31 16:26:07 +00001132 if parity != 0:
1133 self.serial.parity = RFC2217_REVERSE_PARITY_MAP[parity]
Chris Liechtid2146002015-08-04 16:57:16 +02001134 except ValueError as e:
cliechti6a300772009-08-12 02:28:56 +00001135 if self.logger:
1136 self.logger.error("failed to set parity: %s" % (e,))
cliechti130d1f02009-08-04 02:10:58 +00001137 self.serial.parity = backup
cliechti5cc3eb12009-08-11 23:04:30 +00001138 else:
cliechti6a300772009-08-12 02:28:56 +00001139 if self.logger:
Chris Liechti142ae562015-08-23 01:11:06 +02001140 self.logger.info("%s parity: %s" % ('set' if parity else 'get', self.serial.parity))
cliechti130d1f02009-08-04 02:10:58 +00001141 self.rfc2217SendSubnegotiation(
1142 SERVER_SET_PARITY,
Chris Liechtib4cda3a2015-08-08 17:12:08 +02001143 struct.pack(b"!B", RFC2217_PARITY_MAP[self.serial.parity])
cliechti130d1f02009-08-04 02:10:58 +00001144 )
1145 elif suboption[1:2] == SET_STOPSIZE:
1146 backup = self.serial.stopbits
1147 try:
Chris Liechti01587b12015-08-05 02:39:32 +02001148 stopbits = struct.unpack(b"!B", suboption[2:3])[0]
cliechtieada4fd2013-07-31 16:26:07 +00001149 if stopbits != 0:
1150 self.serial.stopbits = RFC2217_REVERSE_STOPBIT_MAP[stopbits]
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 stop bits: %s" % (e,))
cliechti130d1f02009-08-04 02:10:58 +00001154 self.serial.stopbits = 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 stop bits: %s" % ('set' if stopbits else 'get', self.serial.stopbits))
cliechti130d1f02009-08-04 02:10:58 +00001158 self.rfc2217SendSubnegotiation(
1159 SERVER_SET_STOPSIZE,
Chris Liechti01587b12015-08-05 02:39:32 +02001160 struct.pack(b"!B", RFC2217_STOPBIT_MAP[self.serial.stopbits])
cliechti130d1f02009-08-04 02:10:58 +00001161 )
1162 elif suboption[1:2] == SET_CONTROL:
1163 if suboption[2:3] == SET_CONTROL_REQ_FLOW_SETTING:
1164 if self.serial.xonxoff:
1165 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_SW_FLOW_CONTROL)
1166 elif self.serial.rtscts:
1167 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_HW_FLOW_CONTROL)
1168 else:
1169 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_NO_FLOW_CONTROL)
1170 elif suboption[2:3] == SET_CONTROL_USE_NO_FLOW_CONTROL:
1171 self.serial.xonxoff = False
1172 self.serial.rtscts = False
cliechti6a300772009-08-12 02:28:56 +00001173 if self.logger:
1174 self.logger.info("changed flow control to None")
cliechti130d1f02009-08-04 02:10:58 +00001175 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_NO_FLOW_CONTROL)
1176 elif suboption[2:3] == SET_CONTROL_USE_SW_FLOW_CONTROL:
1177 self.serial.xonxoff = True
cliechti6a300772009-08-12 02:28:56 +00001178 if self.logger:
1179 self.logger.info("changed flow control to XON/XOFF")
cliechti130d1f02009-08-04 02:10:58 +00001180 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_SW_FLOW_CONTROL)
1181 elif suboption[2:3] == SET_CONTROL_USE_HW_FLOW_CONTROL:
1182 self.serial.rtscts = True
cliechti6a300772009-08-12 02:28:56 +00001183 if self.logger:
1184 self.logger.info("changed flow control to RTS/CTS")
cliechti130d1f02009-08-04 02:10:58 +00001185 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_HW_FLOW_CONTROL)
1186 elif suboption[2:3] == SET_CONTROL_REQ_BREAK_STATE:
cliechti6a300772009-08-12 02:28:56 +00001187 if self.logger:
1188 self.logger.warning("requested break state - not implemented")
cliechti130d1f02009-08-04 02:10:58 +00001189 pass # XXX needs cached value
1190 elif suboption[2:3] == SET_CONTROL_BREAK_ON:
1191 self.serial.setBreak(True)
cliechti6a300772009-08-12 02:28:56 +00001192 if self.logger:
1193 self.logger.info("changed BREAK to active")
cliechti130d1f02009-08-04 02:10:58 +00001194 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_BREAK_ON)
1195 elif suboption[2:3] == SET_CONTROL_BREAK_OFF:
1196 self.serial.setBreak(False)
cliechti6a300772009-08-12 02:28:56 +00001197 if self.logger:
1198 self.logger.info("changed BREAK to inactive")
cliechti130d1f02009-08-04 02:10:58 +00001199 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_BREAK_OFF)
1200 elif suboption[2:3] == SET_CONTROL_REQ_DTR:
cliechti6a300772009-08-12 02:28:56 +00001201 if self.logger:
1202 self.logger.warning("requested DTR state - not implemented")
cliechti130d1f02009-08-04 02:10:58 +00001203 pass # XXX needs cached value
1204 elif suboption[2:3] == SET_CONTROL_DTR_ON:
1205 self.serial.setDTR(True)
cliechti6a300772009-08-12 02:28:56 +00001206 if self.logger:
1207 self.logger.info("changed DTR to active")
cliechti130d1f02009-08-04 02:10:58 +00001208 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_DTR_ON)
1209 elif suboption[2:3] == SET_CONTROL_DTR_OFF:
1210 self.serial.setDTR(False)
cliechti6a300772009-08-12 02:28:56 +00001211 if self.logger:
1212 self.logger.info("changed DTR to inactive")
cliechti130d1f02009-08-04 02:10:58 +00001213 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_DTR_OFF)
1214 elif suboption[2:3] == SET_CONTROL_REQ_RTS:
cliechti6a300772009-08-12 02:28:56 +00001215 if self.logger:
1216 self.logger.warning("requested RTS state - not implemented")
cliechti130d1f02009-08-04 02:10:58 +00001217 pass # XXX needs cached value
1218 #~ self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_ON)
1219 elif suboption[2:3] == SET_CONTROL_RTS_ON:
1220 self.serial.setRTS(True)
cliechti6a300772009-08-12 02:28:56 +00001221 if self.logger:
1222 self.logger.info("changed RTS to active")
cliechti130d1f02009-08-04 02:10:58 +00001223 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_ON)
1224 elif suboption[2:3] == SET_CONTROL_RTS_OFF:
1225 self.serial.setRTS(False)
cliechti6a300772009-08-12 02:28:56 +00001226 if self.logger:
1227 self.logger.info("changed RTS to inactive")
cliechti130d1f02009-08-04 02:10:58 +00001228 self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_OFF)
1229 #~ elif suboption[2:3] == SET_CONTROL_REQ_FLOW_SETTING_IN:
1230 #~ elif suboption[2:3] == SET_CONTROL_USE_NO_FLOW_CONTROL_IN:
1231 #~ elif suboption[2:3] == SET_CONTROL_USE_SW_FLOW_CONTOL_IN:
1232 #~ elif suboption[2:3] == SET_CONTROL_USE_HW_FLOW_CONTOL_IN:
1233 #~ elif suboption[2:3] == SET_CONTROL_USE_DCD_FLOW_CONTROL:
1234 #~ elif suboption[2:3] == SET_CONTROL_USE_DTR_FLOW_CONTROL:
1235 #~ elif suboption[2:3] == SET_CONTROL_USE_DSR_FLOW_CONTROL:
1236 elif suboption[1:2] == NOTIFY_LINESTATE:
cliechti7cb78e82009-08-05 15:47:57 +00001237 # client polls for current state
1238 self.rfc2217SendSubnegotiation(
Chris Liechti142ae562015-08-23 01:11:06 +02001239 SERVER_NOTIFY_LINESTATE,
1240 to_bytes([0])) # sorry, nothing like that implemented
cliechti130d1f02009-08-04 02:10:58 +00001241 elif suboption[1:2] == NOTIFY_MODEMSTATE:
cliechti6a300772009-08-12 02:28:56 +00001242 if self.logger:
1243 self.logger.info("request for modem state")
cliechti7cb78e82009-08-05 15:47:57 +00001244 # client polls for current state
1245 self.check_modem_lines(force_notification=True)
cliechti130d1f02009-08-04 02:10:58 +00001246 elif suboption[1:2] == FLOWCONTROL_SUSPEND:
cliechti6a300772009-08-12 02:28:56 +00001247 if self.logger:
1248 self.logger.info("suspend")
cliechti130d1f02009-08-04 02:10:58 +00001249 self._remote_suspend_flow = True
1250 elif suboption[1:2] == FLOWCONTROL_RESUME:
cliechti6a300772009-08-12 02:28:56 +00001251 if self.logger:
1252 self.logger.info("resume")
cliechti130d1f02009-08-04 02:10:58 +00001253 self._remote_suspend_flow = False
1254 elif suboption[1:2] == SET_LINESTATE_MASK:
1255 self.linstate_mask = ord(suboption[2:3]) # ensure it is a number
cliechti6a300772009-08-12 02:28:56 +00001256 if self.logger:
cliechtif325c032009-12-25 16:09:49 +00001257 self.logger.info("line state mask: 0x%02x" % (self.linstate_mask,))
cliechti130d1f02009-08-04 02:10:58 +00001258 elif suboption[1:2] == SET_MODEMSTATE_MASK:
1259 self.modemstate_mask = ord(suboption[2:3]) # ensure it is a number
cliechti6a300772009-08-12 02:28:56 +00001260 if self.logger:
cliechtif325c032009-12-25 16:09:49 +00001261 self.logger.info("modem state mask: 0x%02x" % (self.modemstate_mask,))
cliechti130d1f02009-08-04 02:10:58 +00001262 elif suboption[1:2] == PURGE_DATA:
1263 if suboption[2:3] == PURGE_RECEIVE_BUFFER:
1264 self.serial.flushInput()
cliechti6a300772009-08-12 02:28:56 +00001265 if self.logger:
1266 self.logger.info("purge in")
cliechti130d1f02009-08-04 02:10:58 +00001267 self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_RECEIVE_BUFFER)
1268 elif suboption[2:3] == PURGE_TRANSMIT_BUFFER:
1269 self.serial.flushOutput()
cliechti6a300772009-08-12 02:28:56 +00001270 if self.logger:
1271 self.logger.info("purge out")
cliechti130d1f02009-08-04 02:10:58 +00001272 self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_TRANSMIT_BUFFER)
1273 elif suboption[2:3] == PURGE_BOTH_BUFFERS:
1274 self.serial.flushInput()
1275 self.serial.flushOutput()
cliechti6a300772009-08-12 02:28:56 +00001276 if self.logger:
1277 self.logger.info("purge both")
cliechti130d1f02009-08-04 02:10:58 +00001278 self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_BOTH_BUFFERS)
1279 else:
cliechti6a300772009-08-12 02:28:56 +00001280 if self.logger:
1281 self.logger.error("undefined PURGE_DATA: %r" % list(suboption[2:]))
cliechti130d1f02009-08-04 02:10:58 +00001282 else:
cliechti6a300772009-08-12 02:28:56 +00001283 if self.logger:
1284 self.logger.error("undefined COM_PORT_OPTION: %r" % list(suboption[1:]))
cliechti130d1f02009-08-04 02:10:58 +00001285 else:
cliechti6a300772009-08-12 02:28:56 +00001286 if self.logger:
1287 self.logger.warning("unknown subnegotiation: %r" % (suboption,))
cliechti130d1f02009-08-04 02:10:58 +00001288
1289
1290# simple client test
cliechti8099bed2009-08-01 23:59:18 +00001291if __name__ == '__main__':
1292 import sys
1293 s = Serial('rfc2217://localhost:7000', 115200)
1294 sys.stdout.write('%s\n' % s)
1295
cliechti2b929b72009-08-02 23:49:02 +00001296 #~ s.baudrate = 1898
1297
cliechti8099bed2009-08-01 23:59:18 +00001298 sys.stdout.write("write...\n")
Chris Liechtib4cda3a2015-08-08 17:12:08 +02001299 s.write(b"hello\n")
cliechti8099bed2009-08-01 23:59:18 +00001300 s.flush()
cliechti8099bed2009-08-01 23:59:18 +00001301 sys.stdout.write("read: %s\n" % s.read(5))
1302
1303 #~ s.baudrate = 19200
1304 #~ s.databits = 7
1305 s.close()