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_win.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_win.py
26
# Purpose:   Handle low level access to serial port in windows.
27
#
28
# Author:    Isaac Barona Martinez <ibarona@gmail.com>
29
# Copyright: (c) 2001 by Isaac Barona Martínez
30
# Licence:   LGPL
31
#
32
# Created:   26 June 2001
33
# History:
34
# 20 January 2002 : Damien Géranton <dgeranton@voila.fr>
35
#  Bug fix for Win2000, the file must not be open with
36
#  FILE_FLAG_OVERLAPPED
37
#
38
#-------------------------------------------------------------------------
39
 
40
"""
41
SerialPort_win.py - Handle low level access to serial port in windows.
42
 
43
See also uspp module docstring.
44
 
45
"""
46 17 nuubik
 
47 2 nuubik
from win32file import *
48
from win32event import *
49
import win32con
50
import exceptions
51
 
52
class SerialPortException(exceptions.Exception):
53
    """Exception raise in the SerialPort methods"""
54
    def __init__(self, args=None):
55
        self.args=args
56 17 nuubik
    def __str__(self):
57
        return repr(self.args)
58 2 nuubik
 
59
class SerialPort:
60
    """Encapsulate methods for accesing to a serial port."""
61
 
62
    BaudRatesDic={110: CBR_110,
63
                  300: CBR_300,
64
                  600: CBR_600,
65
                  1200: CBR_1200,
66
                  2400: CBR_2400,
67
                  4800: CBR_4800,
68
                  9600: CBR_9600,
69
                  19200: CBR_19200,
70
                  38400: CBR_38400,
71
                  57600: CBR_57600,
72
                  115200: CBR_115200
73
                  }
74
 
75
    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
76
        """Open the serial port named by the string 'dev'
77
 
78
        'dev' can be any of the following strings: 'COM1', 'COM2', ... 'COMX'
79
 
80
        'timeout' specifies the inter-byte timeout or first byte timeout
81
        (in miliseconds) for all subsequent reads on SerialPort.
82
        If we specify None time-outs are not used for reading operations
83
        (blocking reading).
84
        If 'timeout' is 0 then reading operations are non-blocking. It
85
        specifies that the reading operation is to return inmediately
86
        with the bytes that have already been received, even if
87
        no bytes have been received.
88
 
89
        'speed' is an integer that specifies the input and output baud rate to
90
        use. Possible values are: 110, 300, 600, 1200, 2400, 4800, 9600,
91
        19200, 38400, 57600 and 115200.
92
        If None a default speed of 9600 bps is selected.
93
 
94
        'mode' specifies if we are using RS-232 or RS-485. The RS-485 mode
95
        is half duplex and use the RTS signal to indicate the
96
        direction of the communication (transmit or recive).
97
        Default to RS232 mode (at moment, only the RS-232 mode is
98
        implemented).
99
 
100
        'params' is a list that specifies properties of the serial
101
        communication.
102
        If params=None it uses default values for the number of bits
103
        per byte (8), the parity (NOPARITY) and the number of stop bits (1)
104
        else params must be a list with three items setting up the
105
        these values in this order.
106
 
107
        """
108 17 nuubik
 
109 2 nuubik
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
110
        self.__mode=mode
111
        self.__params=params
112 9 nuubik
        self.__speed = 0
113
        self.__reopen = 0
114
        while 1:
115
            try:
116
                self.__handle=CreateFile (dev,
117
                win32con.GENERIC_READ|win32con.GENERIC_WRITE,
118
                0, # exclusive access
119
                None, # no security
120
                win32con.OPEN_EXISTING,
121
                win32con.FILE_ATTRIBUTE_NORMAL,
122
                None)
123
                break
124 2 nuubik
 
125 9 nuubik
            except:
126
                n=0
127
                while (n < 2000000):
128
                    n += 1;
129
                self.__reopen = self.__reopen + 1
130
            if self.__reopen > 32:
131
                print "Port does not exist..."
132 17 nuubik
                raise SerialPortException('Port does not exist...')
133
                break
134
                #sys.exit()
135 2 nuubik
        self.__configure()
136
 
137
    def __del__(self):
138
        """Close the serial port
139
 
140
        To close the serial port we have to do explicity: del s
141
        (where s is an instance of SerialPort)
142
        """
143 9 nuubik
        if self.__speed:
144
            try:
145
                CloseHandle(self.__handle)
146
            except:
147
                raise SerialPortException('Unable to close port')
148 2 nuubik
 
149
 
150
 
151
 
152
    def __configure(self):
153
        """Configure the serial port.
154
 
155
        Private method called in the class constructor that configure the
156
        serial port with the characteristics given in the constructor.
157
        """
158
        if not self.__speed:
159
            self.__speed=115200
160
        # Tell the port we want a notification on each char
161
        SetCommMask(self.__handle, EV_RXCHAR)
162
        # Setup a 4k buffer
163
        SetupComm(self.__handle, 4096, 4096)
164
        # Remove anything that was there
165
        PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
166
                  PURGE_RXCLEAR)
167
 
168
        # Setup the timeouts parameters for the port
169
        # timeouts is a tuple with the following items:
170
        # [0] int : ReadIntervalTimeout
171
        # [1] int : ReadTotalTimeoutMultiplier
172
        # [2] int : ReadTotalTimeoutConstant
173
        # [3] int : WriteTotalTimeoutMultiplier
174
        # [4] int : WriteTotalTimeoutConstant
175
 
176
        if self.__timeout==None:
177
            timeouts= 0, 0, 0, 0, 0
178
        elif self.__timeout==0:
179
            timeouts = win32con.MAXDWORD, 0, 0, 0, 1000
180
        else:
181
            timeouts= self.__timeout, 0, self.__timeout, 0 , 1000
182
        SetCommTimeouts(self.__handle, timeouts)
183
 
184
        # Setup the connection info
185
        dcb=GetCommState(self.__handle)
186
        dcb.BaudRate=SerialPort.BaudRatesDic[self.__speed]
187
        if not self.__params:
188
            dcb.ByteSize=8
189
            dcb.Parity=NOPARITY
190
            dcb.StopBits=ONESTOPBIT
191
        else:
192
            dcb.ByteSize, dcb.Parity, dcb.StopBits=self.__params
193
        SetCommState(self.__handle, dcb)
194
 
195
 
196
    def fileno(self):
197
        """Return the file descriptor for opened device.
198
 
199
        This information can be used for example with the
200
        select function.
201
        """
202
        return self.__handle
203
 
204
 
205
    def read(self, num=1):
206
        """Read num bytes from the serial port.
207
 
208
        If self.__timeout!=0 and != None and the number of read bytes is less
209
        than num an exception is generated because a timeout has expired.
210
        If self.__timeout==0 read is non-blocking and inmediately returns
211
        up to num bytes that have previously been received.
212
        """
213
 
214
        (Br, buff) = ReadFile(self.__handle, num)
215
        if len(buff)<>num and self.__timeout!=0: # Time-out  
216
            raise SerialPortException('Timeout')
217
        else:
218
            return buff
219
 
220
 
221
    def readline(self):
222
        """Read a line from the serial port.  Returns input once a '\n'
223
        character is found.
224
 
225
        """
226
 
227
        s = ''
228
        while not '\n' in s:
229 17 nuubik
            s = s+SerialPort.read(self,1)
230 2 nuubik
 
231
        return s
232
 
233
 
234
    def write(self, s):
235
        """Write the string s to the serial port"""
236
        overlapped=OVERLAPPED()
237
        overlapped.hEvent=CreateEvent(None, 0,0, None)
238
        WriteFile(self.__handle, s, overlapped)
239
        # Wait for the write to complete
240 17 nuubik
        WaitForSingleObject(overlapped.hEvent, INFINITE)
241 2 nuubik
 
242
    def inWaiting(self):
243
        """Returns the number of bytes waiting to be read"""
244
        flags, comstat = ClearCommError(self.__handle)
245
        return comstat.cbInQue
246
 
247
    def flush(self):
248
        """Discards all bytes from the output or input buffer"""
249
        PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
250
                  PURGE_RXCLEAR)
251
 
252
 
253
 
254
 
255
 

powered by: WebSVN 2.1.0

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