blob: 2b63c0d9ca85c3a4d0fae86ae6b183b976c9696f [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>
cliechtiab90e072009-08-06 01:44:34 +000014# this is distributed under a free software license, see license.txt
15#
16# URL format: socket://<host>:<port>[/option[/option...]]
17# options:
18# - "debug" print diagnostic messages
19
cliechti2a6d5332011-03-04 02:08:32 +000020from serial.serialutil import *
cliechtiab90e072009-08-06 01:44:34 +000021import time
cliechtiab90e072009-08-06 01:44:34 +000022import socket
cliechti77e088a2014-08-04 10:29:24 +000023import select
cliechtic64ba692009-08-12 00:32:47 +000024import logging
Chris Liechtia4222112015-08-07 01:03:12 +020025import urlparse
cliechtic64ba692009-08-12 00:32:47 +000026
27# map log level names to constants. used in fromURL()
28LOGGER_LEVELS = {
29 'debug': logging.DEBUG,
30 'info': logging.INFO,
31 'warning': logging.WARNING,
32 'error': logging.ERROR,
33 }
34
cliechti5d66a952013-10-11 02:27:30 +000035POLL_TIMEOUT = 2
cliechtiab90e072009-08-06 01:44:34 +000036
Chris Liechtief6b7b42015-08-06 22:19:26 +020037class Serial(SerialBase):
cliechtiab90e072009-08-06 01:44:34 +000038 """Serial port implementation for plain sockets."""
39
40 BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
41 9600, 19200, 38400, 57600, 115200)
42
43 def open(self):
cliechti7d448562014-08-03 21:57:45 +000044 """\
45 Open port with current settings. This may throw a SerialException
46 if the port cannot be opened.
47 """
cliechti6a300772009-08-12 02:28:56 +000048 self.logger = None
cliechtiab90e072009-08-06 01:44:34 +000049 if self._port is None:
50 raise SerialException("Port must be configured before it can be used.")
cliechti8f69e702011-03-19 00:22:32 +000051 if self._isOpen:
52 raise SerialException("Port is already open.")
cliechtiab90e072009-08-06 01:44:34 +000053 try:
cliechti5d66a952013-10-11 02:27:30 +000054 # XXX in future replace with create_connection (py >=2.6)
Chris Liechtia4222112015-08-07 01:03:12 +020055 self._socket = socket.create_connection(self.fromURL(self.portstr))
Chris Liechti68340d72015-08-03 14:15:48 +020056 except Exception as msg:
cliechtiab90e072009-08-06 01:44:34 +000057 self._socket = None
58 raise SerialException("Could not open port %s: %s" % (self.portstr, msg))
59
cliechti5d66a952013-10-11 02:27:30 +000060 self._socket.settimeout(POLL_TIMEOUT) # used for write timeout support :/
cliechtiab90e072009-08-06 01:44:34 +000061
62 # not that there anything to configure...
63 self._reconfigurePort()
64 # all things set up get, now a clean start
65 self._isOpen = True
66 if not self._rtscts:
67 self.setRTS(True)
68 self.setDTR(True)
69 self.flushInput()
70 self.flushOutput()
71
72 def _reconfigurePort(self):
cliechti7d448562014-08-03 21:57:45 +000073 """\
74 Set communication parameters on opened port. For the socket://
75 protocol all settings are ignored!
76 """
cliechtiab90e072009-08-06 01:44:34 +000077 if self._socket is None:
78 raise SerialException("Can only operate on open ports")
cliechti6a300772009-08-12 02:28:56 +000079 if self.logger:
80 self.logger.info('ignored port configuration change')
cliechtiab90e072009-08-06 01:44:34 +000081
82 def close(self):
83 """Close port"""
84 if self._isOpen:
85 if self._socket:
86 try:
87 self._socket.shutdown(socket.SHUT_RDWR)
88 self._socket.close()
89 except:
90 # ignore errors.
91 pass
92 self._socket = None
cliechtiab90e072009-08-06 01:44:34 +000093 self._isOpen = False
94 # in case of quick reconnects, give the server some time
95 time.sleep(0.3)
96
97 def makeDeviceName(self, port):
98 raise SerialException("there is no sensible way to turn numbers into URLs")
99
100 def fromURL(self, url):
101 """extract host and port from an URL string"""
Chris Liechtia4222112015-08-07 01:03:12 +0200102 parts = urlparse.urlsplit(url)
103 if parts.scheme.lower() != "socket":
104 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 +0000105 try:
Chris Liechtia4222112015-08-07 01:03:12 +0200106 # process options now, directly altering self
107 for option in parts.path.lower().split('/'):
108 if '=' in option:
109 option, value = option.split('=', 1)
110 else:
111 value = None
112 if not option:
113 pass
114 elif option == 'logging':
115 logging.basicConfig() # XXX is that good to call it here?
116 self.logger = logging.getLogger('pySerial.socket')
117 self.logger.setLevel(LOGGER_LEVELS[value])
118 self.logger.debug('enabled logging')
119 else:
120 raise ValueError('unknown option: %r' % (option,))
cliechtiab90e072009-08-06 01:44:34 +0000121 # get host and port
Chris Liechtia4222112015-08-07 01:03:12 +0200122 host, port = parts.hostname, parts.port
cliechtiab90e072009-08-06 01:44:34 +0000123 if not 0 <= port < 65536: raise ValueError("port not in range 0...65535")
Chris Liechti68340d72015-08-03 14:15:48 +0200124 except ValueError as e:
Chris Liechtia4222112015-08-07 01:03:12 +0200125 raise SerialException('expected a string in the form "socket://<host>:<port>[/option[/option...]]": %s' % e)
cliechtiab90e072009-08-06 01:44:34 +0000126 return (host, port)
127
128 # - - - - - - - - - - - - - - - - - - - - - - - -
129
130 def inWaiting(self):
131 """Return the number of characters currently in the input buffer."""
132 if not self._isOpen: raise portNotOpenError
cliechti77e088a2014-08-04 10:29:24 +0000133 # Poll the socket to see if it is ready for reading.
134 # If ready, at least one byte will be to read.
135 lr, lw, lx = select.select([self._socket], [], [], 0)
136 return len(lr)
cliechtiab90e072009-08-06 01:44:34 +0000137
138 def read(self, size=1):
cliechti7d448562014-08-03 21:57:45 +0000139 """\
140 Read size bytes from the serial port. If a timeout is set it may
cliechtiab90e072009-08-06 01:44:34 +0000141 return less characters as requested. With no timeout it will block
cliechti7d448562014-08-03 21:57:45 +0000142 until the requested number of bytes is read.
143 """
cliechtiab90e072009-08-06 01:44:34 +0000144 if not self._isOpen: raise portNotOpenError
145 data = bytearray()
cliechti20e1fae2013-05-31 01:33:12 +0000146 if self._timeout is not None:
147 timeout = time.time() + self._timeout
148 else:
149 timeout = None
Chris Liechti069d32a2015-08-05 03:21:38 +0200150 while len(data) < size:
cliechtiab90e072009-08-06 01:44:34 +0000151 try:
152 # an implementation with internal buffer would be better
153 # performing...
cliechtifee4e962013-05-31 00:55:43 +0000154 block = self._socket.recv(size - len(data))
155 if block:
cliechti5d66a952013-10-11 02:27:30 +0000156 data.extend(block)
157 else:
158 # no data -> EOF (connection probably closed)
159 break
cliechtiab90e072009-08-06 01:44:34 +0000160 except socket.timeout:
cliechti5d66a952013-10-11 02:27:30 +0000161 # just need to get out of recv from time to time to check if
cliechtiab90e072009-08-06 01:44:34 +0000162 # still alive
163 continue
Chris Liechti68340d72015-08-03 14:15:48 +0200164 except socket.error as e:
cliechtiab90e072009-08-06 01:44:34 +0000165 # connection fails -> terminate loop
166 raise SerialException('connection failed (%s)' % e)
Chris Liechti069d32a2015-08-05 03:21:38 +0200167 if timeout is not None and time.time() > timeout:
168 break
cliechtiab90e072009-08-06 01:44:34 +0000169 return bytes(data)
170
171 def write(self, data):
cliechti7d448562014-08-03 21:57:45 +0000172 """\
173 Output the given string over the serial port. Can block if the
cliechtiab90e072009-08-06 01:44:34 +0000174 connection is blocked. May raise SerialException if the connection is
cliechti7d448562014-08-03 21:57:45 +0000175 closed.
176 """
cliechtiab90e072009-08-06 01:44:34 +0000177 if not self._isOpen: raise portNotOpenError
178 try:
cliechti38077122013-10-16 02:57:27 +0000179 self._socket.sendall(to_bytes(data))
Chris Liechti68340d72015-08-03 14:15:48 +0200180 except socket.error as e:
cliechti5d66a952013-10-11 02:27:30 +0000181 # XXX what exception if socket connection fails
182 raise SerialException("socket connection failed: %s" % e)
cliechtiab90e072009-08-06 01:44:34 +0000183 return len(data)
184
185 def flushInput(self):
186 """Clear input buffer, discarding all that is in the buffer."""
187 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000188 if self.logger:
189 self.logger.info('ignored flushInput')
cliechtiab90e072009-08-06 01:44:34 +0000190
191 def flushOutput(self):
cliechti7d448562014-08-03 21:57:45 +0000192 """\
193 Clear output buffer, aborting the current output and
194 discarding all that is in the buffer.
195 """
cliechtiab90e072009-08-06 01:44:34 +0000196 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000197 if self.logger:
198 self.logger.info('ignored flushOutput')
cliechtiab90e072009-08-06 01:44:34 +0000199
200 def sendBreak(self, duration=0.25):
cliechti7d448562014-08-03 21:57:45 +0000201 """\
202 Send break condition. Timed, returns to idle state after given
203 duration.
204 """
cliechtiab90e072009-08-06 01:44:34 +0000205 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000206 if self.logger:
207 self.logger.info('ignored sendBreak(%r)' % (duration,))
cliechtiab90e072009-08-06 01:44:34 +0000208
209 def setBreak(self, level=True):
210 """Set break: Controls TXD. When active, to transmitting is
211 possible."""
212 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000213 if self.logger:
214 self.logger.info('ignored setBreak(%r)' % (level,))
cliechtiab90e072009-08-06 01:44:34 +0000215
216 def setRTS(self, level=True):
217 """Set terminal status line: Request To Send"""
218 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000219 if self.logger:
220 self.logger.info('ignored setRTS(%r)' % (level,))
cliechtiab90e072009-08-06 01:44:34 +0000221
222 def setDTR(self, level=True):
223 """Set terminal status line: Data Terminal Ready"""
224 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000225 if self.logger:
226 self.logger.info('ignored setDTR(%r)' % (level,))
cliechtiab90e072009-08-06 01:44:34 +0000227
228 def getCTS(self):
229 """Read terminal status line: Clear To Send"""
230 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000231 if self.logger:
232 self.logger.info('returning dummy for getCTS()')
cliechtiab90e072009-08-06 01:44:34 +0000233 return True
234
235 def getDSR(self):
236 """Read terminal status line: Data Set Ready"""
237 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000238 if self.logger:
239 self.logger.info('returning dummy for getDSR()')
cliechtiab90e072009-08-06 01:44:34 +0000240 return True
241
242 def getRI(self):
243 """Read terminal status line: Ring Indicator"""
244 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000245 if self.logger:
246 self.logger.info('returning dummy for getRI()')
cliechtiab90e072009-08-06 01:44:34 +0000247 return False
248
249 def getCD(self):
250 """Read terminal status line: Carrier Detect"""
251 if not self._isOpen: raise portNotOpenError
cliechti6a300772009-08-12 02:28:56 +0000252 if self.logger:
253 self.logger.info('returning dummy for getCD()')
cliechtiab90e072009-08-06 01:44:34 +0000254 return True
255
256 # - - - platform specific - - -
cliechtib869edb2014-07-31 22:13:19 +0000257
258 # works on Linux and probably all the other POSIX systems
259 def fileno(self):
260 """Get the file handle of the underlying socket for use with select"""
261 return self._socket.fileno()
cliechtiab90e072009-08-06 01:44:34 +0000262
263
Chris Liechtief6b7b42015-08-06 22:19:26 +0200264#
cliechtiab90e072009-08-06 01:44:34 +0000265# simple client test
266if __name__ == '__main__':
267 import sys
268 s = Serial('socket://localhost:7000')
269 sys.stdout.write('%s\n' % s)
270
271 sys.stdout.write("write...\n")
272 s.write("hello\n")
273 s.flush()
274 sys.stdout.write("read: %s\n" % s.read(5))
275
276 s.close()