blob: 4fe188dc1e6a0b8eb9bd86b2dd621b4294912bb7 [file] [log] [blame]
cliechtiab90e072009-08-06 01:44:34 +00001#! python
2#
3# Python Serial Port Extension for Win32, Linux, BSD, Jython
4# see __init__.py
5#
6# This module implements a simple socket based client.
7# It does not support changing any port parameters and will silently ignore any
8# requests to do so.
9#
10# The purpose of this module is that applications using pySerial can connect to
11# TCP/IP to serial port converters that do not support RFC 2217.
12#
Chris Liechtia4222112015-08-07 01:03:12 +020013# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
Chris Liechtifbdd8a02015-08-09 02:37:45 +020014#
15# SPDX-License-Identifier: BSD-3-Clause
cliechtiab90e072009-08-06 01:44:34 +000016#
17# URL format: socket://<host>:<port>[/option[/option...]]
18# options:
19# - "debug" print diagnostic messages
20
cliechtic64ba692009-08-12 00:32:47 +000021import logging
Chris Liechtifbdd8a02015-08-09 02:37:45 +020022import select
23import socket
24import time
Chris Liechtic4bca9e2015-08-07 14:40:41 +020025try:
26 import urlparse
27except ImportError:
28 import urllib.parse as urlparse
cliechtic64ba692009-08-12 00:32:47 +000029
Chris Liechtifbdd8a02015-08-09 02:37:45 +020030from serial.serialutil import *
31
cliechtic64ba692009-08-12 00:32:47 +000032# map log level names to constants. used in fromURL()
33LOGGER_LEVELS = {
Chris Liechtic4bca9e2015-08-07 14:40:41 +020034 'debug': logging.DEBUG,
35 'info': logging.INFO,
36 'warning': logging.WARNING,
37 'error': logging.ERROR,
38 }
cliechtic64ba692009-08-12 00:32:47 +000039
cliechti5d66a952013-10-11 02:27:30 +000040POLL_TIMEOUT = 2
cliechtiab90e072009-08-06 01:44:34 +000041
Chris Liechtief6b7b42015-08-06 22:19:26 +020042class Serial(SerialBase):
cliechtiab90e072009-08-06 01:44:34 +000043 """Serial port implementation for plain sockets."""
44
45 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
46 9600, 19200, 38400, 57600, 115200)
47
48 def open(self):
cliechti7d448562014-08-03 21:57:45 +000049 """\
50 Open port with current settings. This may throw a SerialException
51 if the port cannot be opened.
52 """
cliechti6a300772009-08-12 02:28:56 +000053 self.logger = None
cliechtiab90e072009-08-06 01:44:34 +000054 if self._port is None:
55 raise SerialException("Port must be configured before it can be used.")
cliechti8f69e702011-03-19 00:22:32 +000056 if self._isOpen:
57 raise SerialException("Port is already open.")
cliechtiab90e072009-08-06 01:44:34 +000058 try:
Chris Liechtia4222112015-08-07 01:03:12 +020059 self._socket = socket.create_connection(self.fromURL(self.portstr))
Chris Liechti68340d72015-08-03 14:15:48 +020060 except Exception as msg:
cliechtiab90e072009-08-06 01:44:34 +000061 self._socket = None
62 raise SerialException("Could not open port %s: %s" % (self.portstr, msg))
63
cliechti5d66a952013-10-11 02:27:30 +000064 self._socket.settimeout(POLL_TIMEOUT) # used for write timeout support :/
cliechtiab90e072009-08-06 01:44:34 +000065
66 # not that there anything to configure...
67 self._reconfigurePort()
68 # all things set up get, now a clean start
69 self._isOpen = True
70 if not self._rtscts:
71 self.setRTS(True)
72 self.setDTR(True)
73 self.flushInput()
74 self.flushOutput()
75
76 def _reconfigurePort(self):
cliechti7d448562014-08-03 21:57:45 +000077 """\
78 Set communication parameters on opened port. For the socket://
79 protocol all settings are ignored!
80 """
cliechtiab90e072009-08-06 01:44:34 +000081 if self._socket is None:
82 raise SerialException("Can only operate on open ports")
cliechti6a300772009-08-12 02:28:56 +000083 if self.logger:
84 self.logger.info('ignored port configuration change')
cliechtiab90e072009-08-06 01:44:34 +000085
86 def close(self):
87 """Close port"""
88 if self._isOpen:
89 if self._socket:
90 try:
91 self._socket.shutdown(socket.SHUT_RDWR)
92 self._socket.close()
93 except:
94 # ignore errors.
95 pass
96 self._socket = None
cliechtiab90e072009-08-06 01:44:34 +000097 self._isOpen = False
98 # in case of quick reconnects, give the server some time
99 time.sleep(0.3)
100
101 def makeDeviceName(self, port):
102 raise SerialException("there is no sensible way to turn numbers into URLs")
103
104 def fromURL(self, url):
105 """extract host and port from an URL string"""
Chris Liechtia4222112015-08-07 01:03:12 +0200106 parts = urlparse.urlsplit(url)
107 if parts.scheme.lower() != "socket":
108 raise SerialException('expected a string in the form "socket://<host>:<port>[/option[/option...]]": not starting with socket:// (%r)' % (parts.scheme,))
cliechtiab90e072009-08-06 01:44:34 +0000109 try:
Chris Liechtia4222112015-08-07 01:03:12 +0200110 # process options now, directly altering self
111 for option in parts.path.lower().split('/'):
112 if '=' in option:
113 option, value = option.split('=', 1)
114 else:
115 value = None
116 if not option:
117 pass
118 elif option == 'logging':
119 logging.basicConfig() # XXX is that good to call it here?
120 self.logger = logging.getLogger('pySerial.socket')
121 self.logger.setLevel(LOGGER_LEVELS[value])
122 self.logger.debug('enabled logging')
123 else:
124 raise ValueError('unknown option: %r' % (option,))
cliechtiab90e072009-08-06 01:44:34 +0000125 # get host and port
Chris Liechtia4222112015-08-07 01:03:12 +0200126 host, port = parts.hostname, parts.port
cliechtiab90e072009-08-06 01:44:34 +0000127 if not 0 <= port < 65536: raise ValueError("port not in range 0...65535")
Chris Liechti68340d72015-08-03 14:15:48 +0200128 except ValueError as e:
Chris Liechtia4222112015-08-07 01:03:12 +0200129 raise SerialException('expected a string in the form "socket://<host>:<port>[/option[/option...]]": %s' % e)
cliechtiab90e072009-08-06 01:44:34 +0000130 return (host, port)
131
132 # - - - - - - - - - - - - - - - - - - - - - - - -
133
134 def inWaiting(self):
135 """Return the number of characters currently in the input buffer."""
136 if not self._isOpen: raise portNotOpenError
cliechti77e088a2014-08-04 10:29:24 +0000137 # Poll the socket to see if it is ready for reading.
138 # If ready, at least one byte will be to read.
139 lr, lw, lx = select.select([self._socket], [], [], 0)
140 return len(lr)
cliechtiab90e072009-08-06 01:44:34 +0000141
142 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000143 """\
144 Read size bytes from the serial port. If a timeout is set it may
cliechtiab90e072009-08-06 01:44:34 +0000145 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000146 until the requested number of bytes is read.
147 """
cliechtiab90e072009-08-06 01:44:34 +0000148 if not self._isOpen: raise portNotOpenError
149 data = bytearray()
cliechti20e1fae2013-05-31 01:33:12 +0000150 if self._timeout is not None:
151 timeout = time.time() + self._timeout
152 else:
153 timeout = None
Chris Liechti069d32a2015-08-05 03:21:38 +0200154 while len(data) < size:
cliechtiab90e072009-08-06 01:44:34 +0000155 try:
156 # an implementation with internal buffer would be better
157 # performing...
cliechtifee4e962013-05-31 00:55:43 +0000158 block = self._socket.recv(size - len(data))
159 if block:
cliechti5d66a952013-10-11 02:27:30 +0000160 data.extend(block)
161 else:
162 # no data -> EOF (connection probably closed)
163 break
cliechtiab90e072009-08-06 01:44:34 +0000164 except socket.timeout:
cliechti5d66a952013-10-11 02:27:30 +0000165 # just need to get out of recv from time to time to check if
cliechtiab90e072009-08-06 01:44:34 +0000166 # still alive
167 continue
Chris Liechti68340d72015-08-03 14:15:48 +0200168 except socket.error as e:
cliechtiab90e072009-08-06 01:44:34 +0000169 # connection fails -> terminate loop
170 raise SerialException('connection failed (%s)' % e)
Chris Liechti069d32a2015-08-05 03:21:38 +0200171 if timeout is not None and time.time() > timeout:
172 break
cliechtiab90e072009-08-06 01:44:34 +0000173 return bytes(data)
174
175 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000176 """\
177 Output the given string over the serial port. Can block if the
cliechtiab90e072009-08-06 01:44:34 +0000178 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000179 closed.
180 """
cliechtiab90e072009-08-06 01:44:34 +0000181 if not self._isOpen: raise portNotOpenError
182 try:
cliechti38077122013-10-16 02:57:27 +0000183 self._socket.sendall(to_bytes(data))
Chris Liechti68340d72015-08-03 14:15:48 +0200184 except socket.error as e:
cliechti5d66a952013-10-11 02:27:30 +0000185 # XXX what exception if socket connection fails
186 raise SerialException("socket connection failed: %s" % e)
cliechtiab90e072009-08-06 01:44:34 +0000187 return len(data)
188
189 def flushInput(self):
190 """Clear input buffer, discarding all that is in the buffer."""
191 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000192 if self.logger:
193 self.logger.info('ignored flushInput')
cliechtiab90e072009-08-06 01:44:34 +0000194
195 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000196 """\
197 Clear output buffer, aborting the current output and
198 discarding all that is in the buffer.
199 """
cliechtiab90e072009-08-06 01:44:34 +0000200 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000201 if self.logger:
202 self.logger.info('ignored flushOutput')
cliechtiab90e072009-08-06 01:44:34 +0000203
204 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000205 """\
206 Send break condition. Timed, returns to idle state after given
207 duration.
208 """
cliechtiab90e072009-08-06 01:44:34 +0000209 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000210 if self.logger:
211 self.logger.info('ignored sendBreak(%r)' % (duration,))
cliechtiab90e072009-08-06 01:44:34 +0000212
213 def setBreak(self, level=True):
214 """Set break: Controls TXD. When active, to transmitting is
215 possible."""
216 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000217 if self.logger:
218 self.logger.info('ignored setBreak(%r)' % (level,))
cliechtiab90e072009-08-06 01:44:34 +0000219
220 def setRTS(self, level=True):
221 """Set terminal status line: Request To Send"""
222 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000223 if self.logger:
224 self.logger.info('ignored setRTS(%r)' % (level,))
cliechtiab90e072009-08-06 01:44:34 +0000225
226 def setDTR(self, level=True):
227 """Set terminal status line: Data Terminal Ready"""
228 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000229 if self.logger:
230 self.logger.info('ignored setDTR(%r)' % (level,))
cliechtiab90e072009-08-06 01:44:34 +0000231
232 def getCTS(self):
233 """Read terminal status line: Clear To Send"""
234 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000235 if self.logger:
236 self.logger.info('returning dummy for getCTS()')
cliechtiab90e072009-08-06 01:44:34 +0000237 return True
238
239 def getDSR(self):
240 """Read terminal status line: Data Set Ready"""
241 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000242 if self.logger:
243 self.logger.info('returning dummy for getDSR()')
cliechtiab90e072009-08-06 01:44:34 +0000244 return True
245
246 def getRI(self):
247 """Read terminal status line: Ring Indicator"""
248 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000249 if self.logger:
250 self.logger.info('returning dummy for getRI()')
cliechtiab90e072009-08-06 01:44:34 +0000251 return False
252
253 def getCD(self):
254 """Read terminal status line: Carrier Detect"""
255 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000256 if self.logger:
257 self.logger.info('returning dummy for getCD()')
cliechtiab90e072009-08-06 01:44:34 +0000258 return True
259
260 # - - - platform specific - - -
cliechtib869edb2014-07-31 22:13:19 +0000261
262 # works on Linux and probably all the other POSIX systems
263 def fileno(self):
264 """Get the file handle of the underlying socket for use with select"""
265 return self._socket.fileno()
cliechtiab90e072009-08-06 01:44:34 +0000266
267
Chris Liechtief6b7b42015-08-06 22:19:26 +0200268#
cliechtiab90e072009-08-06 01:44:34 +0000269# simple client test
270if __name__ == '__main__':
271 import sys
272 s = Serial('socket://localhost:7000')
273 sys.stdout.write('%s\n' % s)
274
275 sys.stdout.write("write...\n")
Chris Liechtifbdd8a02015-08-09 02:37:45 +0200276 s.write(b"hello\n")
cliechtiab90e072009-08-06 01:44:34 +0000277 s.flush()
278 sys.stdout.write("read: %s\n" % s.read(5))
279
280 s.close()