~ubuntu-branches/ubuntu/utopic/pyserial/utopic

« back to all changes in this revision

Viewing changes to serial/serialjava.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2011-01-25 07:59:17 UTC
  • mfrom: (3.1.5 experimental)
  • Revision ID: james.westby@ubuntu.com-20110125075917-m132a8pxfff5a7sf
Tags: 2.5-1
* New upstream version. Closes: #520618.
* Build a python3-serial package.
* Don't use string exception in miniterm.py. Closes: #585328.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!jython
2
 
#Python Serial Port Extension for Win32, Linux, BSD, Jython
3
 
#module for serial IO for Jython and JavaComm
4
 
#see __init__.py
5
 
#
6
 
#(C) 2002-2003 Chris Liechti <cliechti@gmx.net>
 
2
#
 
3
# Python Serial Port Extension for Win32, Linux, BSD, Jython
 
4
# module for serial IO for Jython and JavaComm
 
5
# see __init__.py
 
6
#
 
7
# (C) 2002-2008 Chris Liechti <cliechti@gmx.net>
7
8
# this is distributed under a free software license, see license.txt
8
9
 
9
 
import javax.comm
10
10
from serialutil import *
11
11
 
12
 
VERSION = "$Revision: 1.10 $".split()[1]     #extract CVS version
 
12
def my_import(name):
 
13
    mod = __import__(name)
 
14
    components = name.split('.')
 
15
    for comp in components[1:]:
 
16
        mod = getattr(mod, comp)
 
17
    return mod
 
18
 
 
19
 
 
20
def detect_java_comm(names):
 
21
    """try given list of modules and return that imports"""
 
22
    for name in names:
 
23
        try:
 
24
            mod = my_import(name)
 
25
            mod.SerialPort
 
26
            return mod
 
27
        except (ImportError, AttributeError):
 
28
            pass
 
29
    raise ImportError("No Java Communications API implementation found")
 
30
 
 
31
 
 
32
# Java Communications API implementations
 
33
# http://mho.republika.pl/java/comm/
 
34
 
 
35
comm = detect_java_comm([
 
36
    'javax.comm', # Sun/IBM
 
37
    'gnu.io',     # RXTX
 
38
])
13
39
 
14
40
 
15
41
def device(portnumber):
16
42
    """Turn a port number into a device name"""
17
 
    enum = javax.comm.CommPortIdentifier.getPortIdentifiers()
 
43
    enum = comm.CommPortIdentifier.getPortIdentifiers()
18
44
    ports = []
19
45
    while enum.hasMoreElements():
20
46
        el = enum.nextElement()
21
 
        if el.getPortType() == javax.comm.CommPortIdentifier.PORT_SERIAL:
 
47
        if el.getPortType() == comm.CommPortIdentifier.PORT_SERIAL:
22
48
            ports.append(el)
23
49
    return ports[portnumber].getName()
24
50
 
25
 
class Serial(SerialBase):
26
 
    """Serial port class, implemented with javax.comm and thus usable with
27
 
       jython and the appropriate java extension."""
28
 
    
 
51
 
 
52
class JavaSerial(SerialBase):
 
53
    """Serial port class, implemented with Java Communications API and
 
54
       thus usable with jython and the appropriate java extension."""
 
55
 
29
56
    def open(self):
30
57
        """Open port with current settings. This may throw a SerialException
31
58
           if the port cannot be opened."""
32
59
        if self._port is None:
33
60
            raise SerialException("Port must be configured before it can be used.")
34
 
        if type(self._port) == type(''):      #strings are taken directly
35
 
            portId = javax.comm.CommPortIdentifier.getPortIdentifier(self._port)
 
61
        if type(self._port) == type(''):      # strings are taken directly
 
62
            portId = comm.CommPortIdentifier.getPortIdentifier(self._port)
36
63
        else:
37
 
            portId = javax.comm.CommPortIdentifier.getPortIdentifier(device(self._port))     #numbers are transformed to a comportid obj
 
64
            portId = comm.CommPortIdentifier.getPortIdentifier(device(self._port))     # numbers are transformed to a comport id obj
38
65
        try:
39
66
            self.sPort = portId.open("python serial module", 10)
40
67
        except Exception, msg:
46
73
        self._isOpen = True
47
74
 
48
75
    def _reconfigurePort(self):
49
 
        """Set commuication parameters on opened port."""
 
76
        """Set communication parameters on opened port."""
50
77
        if not self.sPort:
51
78
            raise SerialException("Can only operate on a valid port handle")
52
 
        
 
79
 
53
80
        self.sPort.enableReceiveTimeout(30)
54
81
        if self._bytesize == FIVEBITS:
55
 
            jdatabits = javax.comm.SerialPort.DATABITS_5
 
82
            jdatabits = comm.SerialPort.DATABITS_5
56
83
        elif self._bytesize == SIXBITS:
57
 
            jdatabits = javax.comm.SerialPort.DATABITS_6
 
84
            jdatabits = comm.SerialPort.DATABITS_6
58
85
        elif self._bytesize == SEVENBITS:
59
 
            jdatabits = javax.comm.SerialPort.DATABITS_7
 
86
            jdatabits = comm.SerialPort.DATABITS_7
60
87
        elif self._bytesize == EIGHTBITS:
61
 
            jdatabits = javax.comm.SerialPort.DATABITS_8
 
88
            jdatabits = comm.SerialPort.DATABITS_8
62
89
        else:
63
90
            raise ValueError("unsupported bytesize: %r" % self._bytesize)
64
 
        
 
91
 
65
92
        if self._stopbits == STOPBITS_ONE:
66
 
            jstopbits = javax.comm.SerialPort.STOPBITS_1
67
 
        elif stopbits == STOPBITS_ONE_HALVE:
68
 
            self._jstopbits = javax.comm.SerialPort.STOPBITS_1_5
 
93
            jstopbits = comm.SerialPort.STOPBITS_1
 
94
        elif stopbits == STOPBITS_ONE_POINT_FIVE:
 
95
            self._jstopbits = comm.SerialPort.STOPBITS_1_5
69
96
        elif self._stopbits == STOPBITS_TWO:
70
 
            jstopbits = javax.comm.SerialPort.STOPBITS_2
 
97
            jstopbits = comm.SerialPort.STOPBITS_2
71
98
        else:
72
99
            raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
73
100
 
74
101
        if self._parity == PARITY_NONE:
75
 
            jparity = javax.comm.SerialPort.PARITY_NONE
 
102
            jparity = comm.SerialPort.PARITY_NONE
76
103
        elif self._parity == PARITY_EVEN:
77
 
            jparity = javax.comm.SerialPort.PARITY_EVEN
 
104
            jparity = comm.SerialPort.PARITY_EVEN
78
105
        elif self._parity == PARITY_ODD:
79
 
            jparity = javax.comm.SerialPort.PARITY_ODD
80
 
        #~ elif self._parity == PARITY_MARK:
81
 
            #~ jparity = javax.comm.SerialPort.PARITY_MARK
82
 
        #~ elif self._parity == PARITY_SPACE:
83
 
            #~ jparity = javax.comm.SerialPort.PARITY_SPACE
 
106
            jparity = comm.SerialPort.PARITY_ODD
 
107
        elif self._parity == PARITY_MARK:
 
108
            jparity = comm.SerialPort.PARITY_MARK
 
109
        elif self._parity == PARITY_SPACE:
 
110
            jparity = comm.SerialPort.PARITY_SPACE
84
111
        else:
85
112
            raise ValueError("unsupported parity type: %r" % self._parity)
86
113
 
87
114
        jflowin = jflowout = 0
88
115
        if self._rtscts:
89
 
            jflowin  |=  javax.comm.SerialPort.FLOWCONTROL_RTSCTS_IN
90
 
            jflowout |=  javax.comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
 
116
            jflowin  |=  comm.SerialPort.FLOWCONTROL_RTSCTS_IN
 
117
            jflowout |=  comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
91
118
        if self._xonxoff:
92
 
            jflowin  |=  javax.comm.SerialPort.FLOWCONTROL_XONXOFF_IN
93
 
            jflowout |=  javax.comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
94
 
        
95
 
        self.sPort.setSerialPortParams(baudrate, jdatabits, jstopbits, jparity)
 
119
            jflowin  |=  comm.SerialPort.FLOWCONTROL_XONXOFF_IN
 
120
            jflowout |=  comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
 
121
 
 
122
        self.sPort.setSerialPortParams(self._baudrate, jdatabits, jstopbits, jparity)
96
123
        self.sPort.setFlowControlMode(jflowin | jflowout)
97
 
        
 
124
 
98
125
        if self._timeout >= 0:
99
126
            self.sPort.enableReceiveTimeout(self._timeout*1000)
100
127
        else:
125
152
           return less characters as requested. With no timeout it will block
126
153
           until the requested number of bytes is read."""
127
154
        if not self.sPort: raise portNotOpenError
128
 
        read = ''
 
155
        read = bytearray()
129
156
        if size > 0:
130
157
            while len(read) < size:
131
158
                x = self._instream.read()
133
160
                    if self.timeout >= 0:
134
161
                        break
135
162
                else:
136
 
                    read = read + chr(x)
137
 
        return read
 
163
                    read.append(x)
 
164
        return bytes(read)
138
165
 
139
166
    def write(self, data):
140
167
        """Output the given string over the serial port."""
141
168
        if not self.sPort: raise portNotOpenError
 
169
        if not isinstance(data, (bytes, bytearray)):
 
170
            raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
142
171
        self._outstream.write(data)
 
172
        return len(data)
143
173
 
144
174
    def flushInput(self):
145
175
        """Clear input buffer, discarding all that is in the buffer."""
153
183
        self._outstream.flush()
154
184
 
155
185
    def sendBreak(self, duration=0.25):
156
 
        """Send break condition."""
 
186
        """Send break condition. Timed, returns to idle state after given duration."""
157
187
        if not self.sPort: raise portNotOpenError
158
188
        self.sPort.sendBreak(duration*1000.0)
159
189
 
 
190
    def setBreak(self, level=1):
 
191
        """Set break: Controls TXD. When active, to transmitting is possible."""
 
192
        if self.fd is None: raise portNotOpenError
 
193
        raise SerialException("The setBreak function is not implemented in java.")
 
194
 
160
195
    def setRTS(self, level=1):
161
196
        """Set terminal status line: Request To Send"""
162
197
        if not self.sPort: raise portNotOpenError
163
198
        self.sPort.setRTS(level)
164
 
        
 
199
 
165
200
    def setDTR(self, level=1):
166
201
        """Set terminal status line: Data Terminal Ready"""
167
202
        if not self.sPort: raise portNotOpenError
188
223
        self.sPort.isCD()
189
224
 
190
225
 
 
226
# assemble Serial class with the platform specific implementation and the base
 
227
# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
 
228
# library, derive from io.RawIOBase
 
229
try:
 
230
    import io
 
231
except ImportError:
 
232
    # classic version with our own file-like emulation
 
233
    class Serial(JavaSerial, FileLike):
 
234
        pass
 
235
else:
 
236
    # io library present
 
237
    class Serial(JavaSerial, io.RawIOBase):
 
238
        pass
 
239
 
191
240
 
192
241
if __name__ == '__main__':
193
242
    s = Serial(0,
194
 
                 baudrate=19200,        #baudrate
195
 
                 bytesize=EIGHTBITS,    #number of databits
196
 
                 parity=PARITY_EVEN,    #enable parity checking
197
 
                 stopbits=STOPBITS_ONE, #number of stopbits
198
 
                 timeout=3,             #set a timeout value, None for waiting forever
199
 
                 xonxoff=0,             #enable software flow control
200
 
                 rtscts=0,              #enable RTS/CTS flow control
201
 
               )
 
243
         baudrate=19200,        # baudrate
 
244
         bytesize=EIGHTBITS,    # number of databits
 
245
         parity=PARITY_EVEN,    # enable parity checking
 
246
         stopbits=STOPBITS_ONE, # number of stopbits
 
247
         timeout=3,             # set a timeout value, None for waiting forever
 
248
         xonxoff=0,             # enable software flow control
 
249
         rtscts=0,              # enable RTS/CTS flow control
 
250
    )
202
251
    s.setRTS(1)
203
252
    s.setDTR(1)
204
253
    s.flushInput()
205
254
    s.flushOutput()
206
255
    s.write('hello')
207
 
    print repr(s.read(5))
208
 
    print s.inWaiting()
 
256
    sys.stdio.write('%r\n' % s.read(5))
 
257
    sys.stdio.write('%s\n' % s.inWaiting())
209
258
    del s
210
259
 
211
260