rfc2217.py 57 KB

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