make: check if git is available before calculate version
[pyfrprog.git] / SerialPort_linux.py
1 # -*- coding: iso-8859-1 -*-\r
2 \r
3 ##########################################################################\r
4 # USPP Library (Universal Serial Port Python Library)\r
5 #\r
6 # Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>\r
7\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
12\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
17 \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
22 \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
27 #\r
28 # Author:    Isaac Barona Martinez <ibarona@gmail.com>\r
29 # Copyright: (c) 2006 by Isaac Barona Martínez\r
30 # Licence:   LGPL\r
31 #\r
32 # Created:   26 June 2001\r
33 # History:\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
39 #\r
40 #-------------------------------------------------------------------------\r
41 \r
42 """\r
43 SerialPort_linux.py - Handle low level access to serial port in linux.\r
44 \r
45 See also uspp module docstring.\r
46 \r
47 \r
48 """\r
49 \r
50 import os\r
51 from termios import *\r
52 import fcntl\r
53 import exceptions\r
54 import struct\r
55 import array\r
56 \r
57 \r
58 class SerialPortException(exceptions.Exception):\r
59     """Exception raise in the SerialPort methods"""\r
60     def __init__(self, args=None):\r
61         self.args=args\r
62 \r
63 \r
64 class SerialPort:\r
65     """Encapsulate methods for accesing to a serial port."""\r
66 \r
67     BaudRatesDic={\r
68         110: B110,\r
69         300: B300,\r
70         600: B600,\r
71         1200: B1200,\r
72         2400: B2400,\r
73         4800: B4800, \r
74         9600: B9600,\r
75         19200: B19200,\r
76         38400: B38400,\r
77         57600: B57600,\r
78         115200: B115200\r
79         }\r
80     buf = array.array('h', '\000'*4)\r
81 \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
84 \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
87         \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
91         (blocking reading).\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
96         \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
101         \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
106         implemented).\r
107 \r
108         'params' is a list that specifies properties of the serial \r
109         communication.\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
113         initialization.\r
114 \r
115         """\r
116         self.__devName, self.__timeout, self.__speed=dev, timeout, speed\r
117         self.__mode=mode\r
118         self.__params=params\r
119         try:\r
120                 self.__handle=os.open(dev, os.O_RDWR)\r
121         except:\r
122             raise SerialPortException('Unable to open port')\r
123 \r
124         self.__configure()\r
125 \r
126     def __del__(self):\r
127         """Close the serial port and restore its initial configuration\r
128         \r
129         To close the serial port we have to do explicity: del s\r
130         (where s is an instance of SerialPort)\r
131         """\r
132         \r
133         tcsetattr(self.__handle, TCSANOW, self.__oldmode)\r
134         \r
135         try:\r
136             os.close(self.__handle)\r
137         except IOError:\r
138             raise SerialPortException('Unable to close port')\r
139 \r
140 \r
141     def __configure(self):\r
142         """Configure the serial port.\r
143 \r
144         Private method called in the class constructor that configure the \r
145         serial port with the characteristics given in the constructor.\r
146         """\r
147         if not self.__speed:\r
148             self.__speed=9600\r
149         \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
157             self.__params=[]\r
158             # c_iflag\r
159             self.__params.append(IGNPAR)           \r
160             # c_oflag\r
161             self.__params.append(0)                \r
162             # c_cflag\r
163             self.__params.append(CS8|CLOCAL|CREAD) \r
164             # c_lflag\r
165             self.__params.append(0)                \r
166             # c_ispeed\r
167             self.__params.append(SerialPort.BaudRatesDic[self.__speed]) \r
168             # c_ospeed\r
169             self.__params.append(SerialPort.BaudRatesDic[self.__speed]) \r
170             cc=[0]*NCCS\r
171         if self.__timeout==None:\r
172             # A reading is only complete when VMIN characters have\r
173             # been received (blocking reading)\r
174             cc[VMIN]=1\r
175             cc[VTIME]=0\r
176         elif self.__timeout==0:\r
177             # Non-blocking reading. The reading operation returns\r
178             # inmeditately, returning the characters waiting to \r
179             # be read.\r
180             cc[VMIN]=0\r
181             cc[VTIME]=0\r
182         else:\r
183             # Time-out reading. For a reading to be correct\r
184             # a character must be recieved in VTIME*100 seconds.\r
185             cc[VMIN]=0\r
186             cc[VTIME]=self.__timeout/100\r
187         self.__params.append(cc)               # c_cc\r
188         \r
189         tcsetattr(self.__handle, TCSANOW, self.__params)\r
190     \r
191 \r
192     def fileno(self):\r
193         """Return the file descriptor for opened device.\r
194 \r
195         This information can be used for example with the \r
196         select funcion.\r
197         """\r
198         return self.__handle\r
199 \r
200 \r
201     def __read1(self):\r
202         """Read 1 byte from the serial port.\r
203 \r
204         Generate an exception if no byte is read and self.timeout!=0 \r
205         because a timeout has expired.\r
206         """\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
210         else:\r
211             return byte\r
212             \r
213 \r
214     def read(self, num=1):\r
215         """Read num bytes from the serial port.\r
216 \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
219         """\r
220         s=''\r
221         for i in range(num):\r
222             s=s+SerialPort.__read1(self)\r
223         \r
224         return s\r
225 \r
226 \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
231         """\r
232 \r
233         s = ''\r
234         while not '\n' in s:\r
235             s = s+SerialPort.__read1(self)\r
236 \r
237         return s \r
238 \r
239         \r
240     def write(self, s):\r
241         """Write the string s to the serial port"""\r
242 \r
243         os.write(self.__handle, s)\r
244 \r
245         \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
251 \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
256         """\r
257         rbuf=fcntl.ioctl(self.__handle, TIOCOUTQ, self.buf)\r
258         return rbuf\r
259 \r
260     def getlsr(self):\r
261         """Returns the status of the UART LSR Register\r
262         J.Grauheding\r
263         """\r
264         rbuf=fcntl.ioctl(self.__handle, TIOCSERGETLSR, self.buf)\r
265         return ord(rbuf[0])\r
266 \r
267     def get_temt(self):\r
268         """Returns the Tranmitterbuffer Empty Bit of LSR Register\r
269         J.Grauheding\r
270         test result against TIOCSER_TEMT\r
271         """\r
272         rbuf=fcntl.ioctl(self.__handle, TIOCSERGETLSR, self.buf)\r
273         return ord(rbuf[0]) & TIOSER_TEMT\r
274 \r
275 \r
276     def flush(self):\r
277         """Discards all bytes from the output or input buffer"""\r
278         tcflush(self.__handle, TCIOFLUSH)\r
279 \r
280     def rts_on(self):\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
285         return rbuf\r
286 \r
287     def rts_off(self):\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
292         return rbuf\r
293 \r
294     def dtr_on(self):\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
299         return rbuf\r
300 \r
301     def dtr_off(self):\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
306         return rbuf\r
307 \r
308     def cts(self):\r
309         """ J.Grauheding """\r
310         rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)\r
311         return ord(rbuf[3]) & TIOCM_CTS\r
312 \r
313     def cd(self):\r
314         """ J.Grauheding """\r
315         rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)\r
316         return ord(rbuf[3]) & TIOCM_CAR\r
317 \r
318     def dsr(self):\r
319         """ J.Grauheding """\r
320         rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)\r
321         return ord(rbuf[2]) & (TIOCM_DSR>>8)\r
322 \r
323     def ri(self):\r
324         """ J.Grauheding """\r
325         rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)\r
326         return ord(rbuf[3]) & TIOCM_RNG\r
327 \r
328         \r
329 \r