OpenCores
URL https://opencores.org/ocsvn/usb_dongle_fpga/usb_dongle_fpga/trunk

Subversion Repositories usb_dongle_fpga

[/] [usb_dongle_fpga/] [tags/] [version_1_4/] [sw/] [Uspp/] [SerialPort_linux.py] - Blame information for rev 53

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 17 nuubik
# -*- coding: ISO-8859-1 -*-
2 2 nuubik
 
3
##########################################################################
4
# USPP Library (Universal Serial Port Python Library)
5
#
6
# Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
7
# 
8
# This library is free software; you can redistribute it and/or
9
# modify it under the terms of the GNU Lesser General Public
10
# License as published by the Free Software Foundation; either
11
# version 2.1 of the License, or (at your option) any later version.
12
# 
13
# This library is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
# Lesser General Public License for more details.
17
 
18
# You should have received a copy of the GNU Lesser General Public
19
# License along with this library; if not, write to the Free Software
20
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21
##########################################################################
22
 
23
#------------------------------------------------------------------------
24
# Project:   USPP Library (Universal Serial Port Python Library)
25
# Name:      SerialPort_linux.py
26
# Purpose:   Handle low level access to serial port in linux.
27
#
28
# Author:    Isaac Barona Martinez <ibarona@gmail.com>
29
# Copyright: (c) 2006 by Isaac Barona Martínez
30
# Licence:   LGPL
31
#
32
# Created:   26 June 2001
33
# History:
34
# 20 January 2002 : Damien Geranton <dgeranton@voila.fr>
35
#  - NCCS worry fixed. We must not use TERMIOS
36
#  - inWaiting call fixed.
37
# 09 Sept 2005: Douglas Jones <dfj23@drexel.edu>
38
#  - readline method.
39
#
40
#-------------------------------------------------------------------------
41
 
42
"""
43
SerialPort_linux.py - Handle low level access to serial port in linux.
44
 
45
See also uspp module docstring.
46
 
47
 
48
"""
49
 
50
import os
51
from termios import *
52
from struct import *
53
import fcntl
54
import exceptions
55
import struct
56
import array
57
import time
58
 
59
 
60
class SerialPortException(exceptions.Exception):
61
    """Exception raise in the SerialPort methods"""
62
    def __init__(self, args=None):
63
        self.args=args
64 17 nuubik
    def __str__(self):
65
        return repr(self.args)
66 2 nuubik
 
67
class SerialPort:
68
    """Encapsulate methods for accesing to a serial port."""
69
 
70
    BaudRatesDic={
71
        110: B110,
72
        300: B300,
73
        600: B600,
74
        1200: B1200,
75
        2400: B2400,
76
        4800: B4800,
77
        9600: B9600,
78
        19200: B19200,
79
        38400: B38400,
80
        57600: B57600,
81
        115200: B115200
82
        }
83
    buf = array.array('h', '\000'*4)
84
 
85
    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
86
        """Open the serial port named by the string 'dev'
87
 
88
        'dev' can be any of the following strings: '/dev/ttyS0', '/dev/ttyS1',
89
        ..., '/dev/ttySX' or '/dev/cua0', '/dev/cua1', ..., '/dev/cuaX'.
90
 
91
        'timeout' specifies the inter-byte timeout or first byte timeout
92
        (in miliseconds) for all subsequent reads on SerialPort.
93
        If we specify None time-outs are not used for reading operations
94
        (blocking reading).
95
        If 'timeout' is 0 then reading operations are non-blocking. It
96
        specifies that the reading operation is to return inmediately
97
        with the bytes that have already been received, even if
98
        no bytes have been received.
99
 
100
        'speed' is an integer that specifies the input and output baud rate to
101
        use. Possible values are: 110, 300, 600, 1200, 2400, 4800, 9600,
102
        19200, 38400, 57600 and 115200.
103
        If None a default speed of 9600 bps is selected.
104
 
105
        'mode' specifies if we are using RS-232 or RS-485. The RS-485 mode
106
        is half duplex and use the RTS signal to indicate the
107
        direction of the communication (transmit or recive).
108
        Default to RS232 mode (at moment, only the RS-232 mode is
109
        implemented).
110
 
111
        'params' is a list that specifies properties of the serial
112
        communication.
113
        If params=None it uses default values for the number of bits
114
        per byte (8), the parity (NOPARITY) and the number of stop bits (1)
115
        else params is the termios package mode array to use for
116
        initialization.
117
 
118
        """
119 17 nuubik
 
120 2 nuubik
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
121
        self.__mode=mode
122
        self.__params=params
123 9 nuubik
        self.__speed = 0
124
        self.__reopen = 0
125
        while 1:
126
            try:
127
                self.__handle=os.open(dev, os.O_RDWR)
128
                break
129
 
130
            except:
131
                n=0
132
                while (n < 2000000):
133
                    n += 1;
134
                self.__reopen = self.__reopen + 1
135
            if self.__reopen > 32:
136
                print "Port does not exist..."
137 17 nuubik
                raise SerialPortException('Port does not exist...')
138
                break
139 2 nuubik
 
140
        self.__configure()
141
 
142
    def __del__(self):
143
        """Close the serial port and restore its initial configuration
144
 
145
        To close the serial port we have to do explicity: del s
146
        (where s is an instance of SerialPort)
147
        """
148 9 nuubik
        if self.__speed:
149
            tcsetattr(self.__handle, TCSANOW, self.__oldmode)
150
            try:
151
                os.close(self.__handle)
152
            except IOError:
153
                raise SerialPortException('Unable to close port')
154 2 nuubik
 
155
 
156
    def __configure(self):
157
        """Configure the serial port.
158
 
159
        Private method called in the class constructor that configure the
160
        serial port with the characteristics given in the constructor.
161
        """
162
        if not self.__speed:
163
            self.__speed=115200
164
 
165
        # Save the initial port configuration
166
        self.__oldmode=tcgetattr(self.__handle)
167
        if not self.__params:
168
            # self.__params is a list of attributes of the file descriptor
169
            # self.__handle as follows:
170
            # [c_iflag, c_oflag, c_cflag, c_lflag, c_ispeed, c_ospeed, cc]
171
            # where cc is a list of the tty special characters.
172
            self.__params=[]
173
            # c_iflag
174
            self.__params.append(IGNPAR)
175
            # c_oflag
176
            self.__params.append(0)
177
            # c_cflag
178
            self.__params.append(CS8|CLOCAL|CREAD)
179
            # c_lflag
180
            self.__params.append(0)
181
            # c_ispeed
182
            self.__params.append(SerialPort.BaudRatesDic[self.__speed])
183
            # c_ospeed
184
            self.__params.append(SerialPort.BaudRatesDic[self.__speed])
185
            cc=[0]*NCCS
186
        if self.__timeout==None:
187
            # A reading is only complete when VMIN characters have
188
            # been received (blocking reading)
189
            cc[VMIN]=1
190
            cc[VTIME]=0
191
        elif self.__timeout==0:
192
            # Non-blocking reading. The reading operation returns
193
            # inmeditately, returning the characters waiting to 
194
            # be read.
195
            cc[VMIN]=0
196
            cc[VTIME]=0
197
        else:
198
            # Time-out reading. For a reading to be correct
199
            # a character must be recieved in VTIME*100 seconds.
200
            cc[VMIN]=0
201
            cc[VTIME]=self.__timeout/100
202
        self.__params.append(cc)               # c_cc
203
 
204
        tcsetattr(self.__handle, TCSANOW, self.__params)
205
 
206
 
207
    def fileno(self):
208
        """Return the file descriptor for opened device.
209
 
210
        This information can be used for example with the
211
        select funcion.
212
        """
213
        return self.__handle
214
 
215
 
216
    def __read1(self):
217
        """Read 1 byte from the serial port.
218
 
219
        Generate an exception if no byte is read and self.timeout!=0
220
        because a timeout has expired.
221
        """
222
        byte = os.read(self.__handle, 1)
223
        if len(byte)==0 and self.__timeout!=0: # Time-out
224
            raise SerialPortException('Timeout')
225
        else:
226
            return byte
227
 
228
 
229
    def read(self, num=1):
230
        """Read num bytes from the serial port.
231
 
232
        Uses the private method __read1 to read num bytes. If an exception
233
        is generated in any of the calls to __read1 the exception is reraised.
234
        """
235
        s=''
236
        for i in range(num):
237
            s=s+SerialPort.__read1(self)
238
 
239
        return s
240
 
241
 
242
    def readline(self):
243
        """Read a line from the serial port.  Returns input once a '\n'
244
        character is found.
245
        Douglas Jones (dfj23@drexel.edu) 09/09/2005.
246
        """
247
 
248
        s = ''
249
        while not '\n' in s:
250
            s = s+SerialPort.__read1(self)
251
 
252
        return s
253
 
254
 
255
    def write(self, s):
256
        """Write the string s to the serial port"""
257
 
258
        os.write(self.__handle, s)
259
 
260
    def inWaiting(self):
261
        """Returns the number of bytes waiting to be read"""
262
        data = struct.pack("L", 0)
263
        data=fcntl.ioctl(self.__handle, TIOCINQ, data)
264
        return struct.unpack("L", data)[0]
265
 
266
    def outWaiting(self):
267
        """Returns the number of bytes waiting to be write
268
        mod. by J.Grauheding
269
        result needs some finetunning
270
        """
271
        rbuf=fcntl.ioctl(self.__handle, TIOCOUTQ, self.buf)
272
        return rbuf
273
 
274
    def getlsr(self):
275
        """Returns the status of the UART LSR Register
276
        J.Grauheding
277
        """
278
        rbuf=fcntl.ioctl(self.__handle, TIOCSERGETLSR, self.buf)
279
        return ord(rbuf[0])
280
 
281
    def get_temt(self):
282
        """Returns the Tranmitterbuffer Empty Bit of LSR Register
283
        J.Grauheding
284
        test result against TIOCSER_TEMT
285
        """
286
        rbuf=fcntl.ioctl(self.__handle, TIOCSERGETLSR, self.buf)
287
        return ord(rbuf[0]) & TIOSER_TEMT
288
 
289
 
290
    def flush(self):
291
        """Discards all bytes from the output or input buffer"""
292
        tcflush(self.__handle, TCIOFLUSH)
293
 
294
    def rts_on(self):
295
        """ J.Grauheding """
296
        rbuf = fcntl.ioctl(self.__handle, TIOCMGET, SerialPort.buf)
297
        SerialPort.buf[1] = ord(rbuf[3]) | TIOCM_RTS
298
        rbuf = fcntl.ioctl(self.__handle, TIOCMSET, SerialPort.buf)
299
        return rbuf
300
 
301
    def rts_off(self):
302
        """ J.Grauheding """
303
        rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
304
        self.buf[1]=ord(rbuf[3]) & ~TIOCM_RTS
305
        rbuf = fcntl.ioctl(self.__handle, TIOCMSET, self.buf)
306
        return rbuf
307
 
308
    def dtr_on(self):
309
        """ J.Grauheding """
310
        rbuf = fcntl.ioctl(self.__handle, TIOCMGET, SerialPort.buf)
311
        SerialPort.buf[1] = ord(rbuf[3]) | TIOCM_DTR
312
        rbuf = fcntl.ioctl(self.__handle, TIOCMSET, SerialPort.buf)
313
        return rbuf
314
 
315
    def dtr_off(self):
316
        """ J.Grauheding """
317
        rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
318
        self.buf[1]=ord(rbuf[3]) & ~TIOCM_DTR
319
        rbuf = fcntl.ioctl(self.__handle, TIOCMSET, self.buf)
320
        return rbuf
321
 
322
    def cts(self):
323
        """ J.Grauheding """
324
        rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
325
        return ord(rbuf[3]) & TIOCM_CTS
326
 
327
    def cd(self):
328
        """ J.Grauheding """
329
        rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
330
        return ord(rbuf[3]) & TIOCM_CAR
331
 
332
    def dsr(self):
333
        """ J.Grauheding """
334
        rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
335
        return ord(rbuf[2]) & (TIOCM_DSR>>8)
336
 
337
    def ri(self):
338
        """ J.Grauheding """
339
        rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
340
        return ord(rbuf[3]) & TIOCM_RNG
341
 
342
 
343
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.