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_darwin.py] - Blame information for rev 53

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

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