1 # -*- coding: iso-8859-1 -*-
\r
3 ##########################################################################
\r
4 # USPP Library (Universal Serial Port Python Library)
\r
6 # Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
\r
8 # This library is free software; you can redistribute it and/or
\r
9 # modify it under the terms of the GNU Lesser General Public
\r
10 # License as published by the Free Software Foundation; either
\r
11 # version 2.1 of the License, or (at your option) any later version.
\r
13 # This library is distributed in the hope that it will be useful,
\r
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
\r
16 # Lesser General Public License for more details.
\r
18 # You should have received a copy of the GNU Lesser General Public
\r
19 # License along with this library; if not, write to the Free Software
\r
20 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
\r
21 ##########################################################################
\r
23 #------------------------------------------------------------------------
\r
24 # Project: USPP Library (Universal Serial Port Python Library)
\r
25 # Name: SerialPort_linux.py
\r
26 # Purpose: Handle low level access to serial port in linux.
\r
28 # Author: Isaac Barona Martinez <ibarona@gmail.com>
\r
29 # Copyright: (c) 2006 by Isaac Barona MartÃnez
\r
32 # Created: 26 June 2001
\r
34 # 20 January 2002 : Damien Geranton <dgeranton@voila.fr>
\r
35 # - NCCS worry fixed. We must not use TERMIOS
\r
36 # - inWaiting call fixed.
\r
37 # 09 Sept 2005: Douglas Jones <dfj23@drexel.edu>
\r
38 # - readline method.
\r
40 #-------------------------------------------------------------------------
\r
43 SerialPort_linux.py - Handle low level access to serial port in linux.
\r
45 See also uspp module docstring.
\r
51 from termios import *
\r
58 class SerialPortException(exceptions.Exception):
\r
59 """Exception raise in the SerialPort methods"""
\r
60 def __init__(self, args=None):
\r
65 """Encapsulate methods for accesing to a serial port."""
\r
80 buf = array.array('h', '\000'*4)
\r
82 def __init__(self, dev, timeout=None, speed=None, mode='232', params=None):
\r
83 """Open the serial port named by the string 'dev'
\r
85 'dev' can be any of the following strings: '/dev/ttyS0', '/dev/ttyS1',
\r
86 ..., '/dev/ttySX' or '/dev/cua0', '/dev/cua1', ..., '/dev/cuaX'.
\r
88 'timeout' specifies the inter-byte timeout or first byte timeout
\r
89 (in miliseconds) for all subsequent reads on SerialPort.
\r
90 If we specify None time-outs are not used for reading operations
\r
92 If 'timeout' is 0 then reading operations are non-blocking. It
\r
93 specifies that the reading operation is to return inmediately
\r
94 with the bytes that have already been received, even if
\r
95 no bytes have been received.
\r
97 'speed' is an integer that specifies the input and output baud rate to
\r
98 use. Possible values are: 110, 300, 600, 1200, 2400, 4800, 9600,
\r
99 19200, 38400, 57600 and 115200.
\r
100 If None a default speed of 9600 bps is selected.
\r
102 'mode' specifies if we are using RS-232 or RS-485. The RS-485 mode
\r
103 is half duplex and use the RTS signal to indicate the
\r
104 direction of the communication (transmit or recive).
\r
105 Default to RS232 mode (at moment, only the RS-232 mode is
\r
108 'params' is a list that specifies properties of the serial
\r
110 If params=None it uses default values for the number of bits
\r
111 per byte (8), the parity (NOPARITY) and the number of stop bits (1)
\r
112 else params is the termios package mode array to use for
\r
116 self.__devName, self.__timeout, self.__speed=dev, timeout, speed
\r
118 self.__params=params
\r
120 self.__handle=os.open(dev, os.O_RDWR)
\r
122 raise SerialPortException('Unable to open port')
\r
127 """Close the serial port and restore its initial configuration
\r
129 To close the serial port we have to do explicity: del s
\r
130 (where s is an instance of SerialPort)
\r
133 tcsetattr(self.__handle, TCSANOW, self.__oldmode)
\r
136 os.close(self.__handle)
\r
138 raise SerialPortException('Unable to close port')
\r
141 def __configure(self):
\r
142 """Configure the serial port.
\r
144 Private method called in the class constructor that configure the
\r
145 serial port with the characteristics given in the constructor.
\r
147 if not self.__speed:
\r
150 # Save the initial port configuration
\r
151 self.__oldmode=tcgetattr(self.__handle)
\r
152 if not self.__params:
\r
153 # self.__params is a list of attributes of the file descriptor
\r
154 # self.__handle as follows:
\r
155 # [c_iflag, c_oflag, c_cflag, c_lflag, c_ispeed, c_ospeed, cc]
\r
156 # where cc is a list of the tty special characters.
\r
159 self.__params.append(IGNPAR)
\r
161 self.__params.append(0)
\r
163 self.__params.append(CS8|CLOCAL|CREAD)
\r
165 self.__params.append(0)
\r
167 self.__params.append(SerialPort.BaudRatesDic[self.__speed])
\r
169 self.__params.append(SerialPort.BaudRatesDic[self.__speed])
\r
171 if self.__timeout==None:
\r
172 # A reading is only complete when VMIN characters have
\r
173 # been received (blocking reading)
\r
176 elif self.__timeout==0:
\r
177 # Non-blocking reading. The reading operation returns
\r
178 # inmeditately, returning the characters waiting to
\r
183 # Time-out reading. For a reading to be correct
\r
184 # a character must be recieved in VTIME*100 seconds.
\r
186 cc[VTIME]=self.__timeout/100
\r
187 self.__params.append(cc) # c_cc
\r
189 tcsetattr(self.__handle, TCSANOW, self.__params)
\r
193 """Return the file descriptor for opened device.
\r
195 This information can be used for example with the
\r
198 return self.__handle
\r
202 """Read 1 byte from the serial port.
\r
204 Generate an exception if no byte is read and self.timeout!=0
\r
205 because a timeout has expired.
\r
207 byte = os.read(self.__handle, 1)
\r
208 if len(byte)==0 and self.__timeout!=0: # Time-out
\r
209 raise SerialPortException('Timeout')
\r
214 def read(self, num=1):
\r
215 """Read num bytes from the serial port.
\r
217 Uses the private method __read1 to read num bytes. If an exception
\r
218 is generated in any of the calls to __read1 the exception is reraised.
\r
221 for i in range(num):
\r
222 s=s+SerialPort.__read1(self)
\r
227 def readline(self):
\r
228 """Read a line from the serial port. Returns input once a '\n'
\r
229 character is found.
\r
230 Douglas Jones (dfj23@drexel.edu) 09/09/2005.
\r
234 while not '\n' in s:
\r
235 s = s+SerialPort.__read1(self)
\r
240 def write(self, s):
\r
241 """Write the string s to the serial port"""
\r
243 os.write(self.__handle, s)
\r
246 def inWaiting(self):
\r
247 """Returns the number of bytes waiting to be read"""
\r
248 data = struct.pack("L", 0)
\r
249 data=fcntl.ioctl(self.__handle, TIOCINQ, data)
\r
250 return struct.unpack("L", data)[0]
\r
252 def outWaiting(self):
\r
253 """Returns the number of bytes waiting to be write
\r
254 mod. by J.Grauheding
\r
255 result needs some finetunning
\r
257 rbuf=fcntl.ioctl(self.__handle, TIOCOUTQ, self.buf)
\r
261 """Returns the status of the UART LSR Register
\r
264 rbuf=fcntl.ioctl(self.__handle, TIOCSERGETLSR, self.buf)
\r
265 return ord(rbuf[0])
\r
267 def get_temt(self):
\r
268 """Returns the Tranmitterbuffer Empty Bit of LSR Register
\r
270 test result against TIOCSER_TEMT
\r
272 rbuf=fcntl.ioctl(self.__handle, TIOCSERGETLSR, self.buf)
\r
273 return ord(rbuf[0]) & TIOSER_TEMT
\r
277 """Discards all bytes from the output or input buffer"""
\r
278 tcflush(self.__handle, TCIOFLUSH)
\r
281 """ J.Grauheding """
\r
282 rbuf = fcntl.ioctl(self.__handle, TIOCMGET, SerialPort.buf)
\r
283 SerialPort.buf[1] = ord(rbuf[3]) | TIOCM_RTS
\r
284 rbuf = fcntl.ioctl(self.__handle, TIOCMSET, SerialPort.buf)
\r
288 """ J.Grauheding """
\r
289 rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
\r
290 self.buf[1]=ord(rbuf[3]) & ~TIOCM_RTS
\r
291 rbuf = fcntl.ioctl(self.__handle, TIOCMSET, self.buf)
\r
295 """ J.Grauheding """
\r
296 rbuf = fcntl.ioctl(self.__handle, TIOCMGET, SerialPort.buf)
\r
297 SerialPort.buf[1] = ord(rbuf[3]) | TIOCM_DTR
\r
298 rbuf = fcntl.ioctl(self.__handle, TIOCMSET, SerialPort.buf)
\r
302 """ J.Grauheding """
\r
303 rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
\r
304 self.buf[1]=ord(rbuf[3]) & ~TIOCM_DTR
\r
305 rbuf = fcntl.ioctl(self.__handle, TIOCMSET, self.buf)
\r
309 """ J.Grauheding """
\r
310 rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
\r
311 return ord(rbuf[3]) & TIOCM_CTS
\r
314 """ J.Grauheding """
\r
315 rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
\r
316 return ord(rbuf[3]) & TIOCM_CAR
\r
319 """ J.Grauheding """
\r
320 rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
\r
321 return ord(rbuf[2]) & (TIOCM_DSR>>8)
\r
324 """ J.Grauheding """
\r
325 rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
\r
326 return ord(rbuf[3]) & TIOCM_RNG
\r