~ubuntu-branches/ubuntu/quantal/pyserial/quantal

« back to all changes in this revision

Viewing changes to serial/serialjava.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2008-06-24 19:14:57 UTC
  • mfrom: (3.1.4 lenny)
  • Revision ID: james.westby@ubuntu.com-20080624191457-l7snsahtf9ngtuti
Tags: 2.3-1
* New upstream version.
* Update watch file. Closes: #450106.
* Mention the upstream name in the package description. Closes: #459590.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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>
7
 
# this is distributed under a free software license, see license.txt
8
 
 
9
 
import javax.comm
10
 
from serialutil import *
11
 
 
12
 
VERSION = "$Revision: 1.8 $".split()[1]     #extract CVS version
13
 
 
14
 
 
15
 
def device(portnumber):
16
 
    """Turn a port number into a device name"""
17
 
    enum = javax.comm.CommPortIdentifier.getPortIdentifiers()
18
 
    ports = []
19
 
    while enum.hasMoreElements():
20
 
        el = enum.nextElement()
21
 
        if el.getPortType() == javax.comm.CommPortIdentifier.PORT_SERIAL:
22
 
            ports.append(el)
23
 
    return ports[portnumber].getName()
24
 
 
25
 
class Serial(SerialBase):
26
 
    """Serial port class, implemented with javax.comm and thus usable with
27
 
       jython and the appropriate java extension."""
28
 
    
29
 
    def open(self):
30
 
        """Open port with current settings. This may throw a SerialException
31
 
           if the port cannot be opened."""
32
 
        if self._port is None:
33
 
            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)
36
 
        else:
37
 
            portId = javax.comm.CommPortIdentifier.getPortIdentifier(device(self._port))     #numbers are transformed to a comportid obj
38
 
        try:
39
 
            self.sPort = portId.open("python serial module", 10)
40
 
        except Exception, msg:
41
 
            self.sPort = None
42
 
            raise SerialException("Could not open port: %s" % msg)
43
 
        self._reconfigurePort()
44
 
        self._instream = self.sPort.getInputStream()
45
 
        self._outstream = self.sPort.getOutputStream()
46
 
        self._isOpen = True
47
 
 
48
 
    def _reconfigurePort(self):
49
 
        """Set commuication parameters on opened port."""
50
 
        if not self.sPort:
51
 
            raise SerialException("Can only operate on a valid port handle")
52
 
        
53
 
        self.sPort.enableReceiveTimeout(30)
54
 
        if self._bytesize == FIVEBITS:
55
 
            jdatabits = javax.comm.SerialPort.DATABITS_5
56
 
        elif self._bytesize == SIXBITS:
57
 
            jdatabits = javax.comm.SerialPort.DATABITS_6
58
 
        elif self._bytesize == SEVENBITS:
59
 
            jdatabits = javax.comm.SerialPort.DATABITS_7
60
 
        elif self._bytesize == EIGHTBITS:
61
 
            jdatabits = javax.comm.SerialPort.DATABITS_8
62
 
        else:
63
 
            raise ValueError("unsupported bytesize: %r" % self._bytesize)
64
 
        
65
 
        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
69
 
        elif self._stopbits == STOPBITS_TWO:
70
 
            jstopbits = javax.comm.SerialPort.STOPBITS_2
71
 
        else:
72
 
            raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
73
 
 
74
 
        if self._parity == PARITY_NONE:
75
 
            jparity = javax.comm.SerialPort.PARITY_NONE
76
 
        elif self._parity == PARITY_EVEN:
77
 
            jparity = javax.comm.SerialPort.PARITY_EVEN
78
 
        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
84
 
        else:
85
 
            raise ValueError("unsupported parity type: %r" % self._parity)
86
 
 
87
 
        jflowin = jflowout = 0
88
 
        if self._rtscts:
89
 
            jflowin  |=  javax.comm.SerialPort.FLOWCONTROL_RTSCTS_IN
90
 
            jflowout |=  javax.comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
91
 
        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)
96
 
        self.sPort.setFlowControlMode(jflowin | jflowout)
97
 
        
98
 
        if self._timeout >= 0:
99
 
            self.sPort.enableReceiveTimeout(self._timeout*1000)
100
 
        else:
101
 
            self.sPort.disableReceiveTimeout()
102
 
 
103
 
    def close(self):
104
 
        """Close port"""
105
 
        if self._isOpen:
106
 
            if self.sPort:
107
 
                self._instream.close()
108
 
                self._outstream.close()
109
 
                self.sPort.close()
110
 
                self.sPort = None
111
 
            self._isOpen = False
112
 
 
113
 
    def makeDeviceName(self, port):
114
 
        return device(port)
115
 
 
116
 
    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
117
 
 
118
 
    def inWaiting(self):
119
 
        """Return the number of characters currently in the input buffer."""
120
 
        if not self.sPort: raise portNotOpenError
121
 
        return self._instream.available()
122
 
 
123
 
    def read(self, size=1):
124
 
        """Read size bytes from the serial port. If a timeout is set it may
125
 
           return less characters as requested. With no timeout it will block
126
 
           until the requested number of bytes is read."""
127
 
        if not self.sPort: raise portNotOpenError
128
 
        read = ''
129
 
        if size > 0:
130
 
            while len(read) < size:
131
 
                x = self._instream.read()
132
 
                if x == -1:
133
 
                    if self.timeout >= 0:
134
 
                        break
135
 
                else:
136
 
                    read = read + chr(x)
137
 
        return read
138
 
 
139
 
    def write(self, data):
140
 
        """Output the given string over the serial port."""
141
 
        if not self.sPort: raise portNotOpenError
142
 
        self._outstream.write(data)
143
 
 
144
 
    def flushInput(self):
145
 
        """Clear input buffer, discarding all that is in the buffer."""
146
 
        if not self.sPort: raise portNotOpenError
147
 
        self._instream.skip(self._instream.available())
148
 
 
149
 
    def flushOutput(self):
150
 
        """Clear output buffer, aborting the current output and
151
 
        discarding all that is in the buffer."""
152
 
        if not self.sPort: raise portNotOpenError
153
 
        self._outstream.flush()
154
 
 
155
 
    def sendBreak(self):
156
 
        """Send break condition."""
157
 
        if not self.sPort: raise portNotOpenError
158
 
        self.sPort.sendBreak()
159
 
 
160
 
    def setRTS(self,on=1):
161
 
        """Set terminal status line: Request To Send"""
162
 
        if not self.sPort: raise portNotOpenError
163
 
        self.sPort.setRTS(on)
164
 
        
165
 
    def setDTR(self,on=1):
166
 
        """Set terminal status line: Data Terminal Ready"""
167
 
        if not self.sPort: raise portNotOpenError
168
 
        self.sPort.setDTR(on)
169
 
 
170
 
    def getCTS(self):
171
 
        """Read terminal status line: Clear To Send"""
172
 
        if not self.sPort: raise portNotOpenError
173
 
        self.sPort.isCTS()
174
 
 
175
 
    def getDSR(self):
176
 
        """Read terminal status line: Data Set Ready"""
177
 
        if not self.sPort: raise portNotOpenError
178
 
        self.sPort.isDSR()
179
 
 
180
 
    def getRI(self):
181
 
        """Read terminal status line: Ring Indicator"""
182
 
        if not self.sPort: raise portNotOpenError
183
 
        self.sPort.isRI()
184
 
 
185
 
    def getCD(self):
186
 
        """Read terminal status line: Carrier Detect"""
187
 
        if not self.sPort: raise portNotOpenError
188
 
        self.sPort.isCD()
189
 
 
190
 
 
191
 
 
192
 
if __name__ == '__main__':
193
 
    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
 
               )
202
 
    s.setRTS(1)
203
 
    s.setDTR(1)
204
 
    s.flushInput()
205
 
    s.flushOutput()
206
 
    s.write('hello')
207
 
    print repr(s.read(5))
208
 
    print s.inWaiting()
209
 
    del s
210
 
 
211
 
 
212
 
 
 
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>
 
7
# this is distributed under a free software license, see license.txt
 
8
 
 
9
import javax.comm
 
10
from serialutil import *
 
11
 
 
12
VERSION = "$Revision: 1.10 $".split()[1]     #extract CVS version
 
13
 
 
14
 
 
15
def device(portnumber):
 
16
    """Turn a port number into a device name"""
 
17
    enum = javax.comm.CommPortIdentifier.getPortIdentifiers()
 
18
    ports = []
 
19
    while enum.hasMoreElements():
 
20
        el = enum.nextElement()
 
21
        if el.getPortType() == javax.comm.CommPortIdentifier.PORT_SERIAL:
 
22
            ports.append(el)
 
23
    return ports[portnumber].getName()
 
24
 
 
25
class Serial(SerialBase):
 
26
    """Serial port class, implemented with javax.comm and thus usable with
 
27
       jython and the appropriate java extension."""
 
28
    
 
29
    def open(self):
 
30
        """Open port with current settings. This may throw a SerialException
 
31
           if the port cannot be opened."""
 
32
        if self._port is None:
 
33
            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)
 
36
        else:
 
37
            portId = javax.comm.CommPortIdentifier.getPortIdentifier(device(self._port))     #numbers are transformed to a comportid obj
 
38
        try:
 
39
            self.sPort = portId.open("python serial module", 10)
 
40
        except Exception, msg:
 
41
            self.sPort = None
 
42
            raise SerialException("Could not open port: %s" % msg)
 
43
        self._reconfigurePort()
 
44
        self._instream = self.sPort.getInputStream()
 
45
        self._outstream = self.sPort.getOutputStream()
 
46
        self._isOpen = True
 
47
 
 
48
    def _reconfigurePort(self):
 
49
        """Set commuication parameters on opened port."""
 
50
        if not self.sPort:
 
51
            raise SerialException("Can only operate on a valid port handle")
 
52
        
 
53
        self.sPort.enableReceiveTimeout(30)
 
54
        if self._bytesize == FIVEBITS:
 
55
            jdatabits = javax.comm.SerialPort.DATABITS_5
 
56
        elif self._bytesize == SIXBITS:
 
57
            jdatabits = javax.comm.SerialPort.DATABITS_6
 
58
        elif self._bytesize == SEVENBITS:
 
59
            jdatabits = javax.comm.SerialPort.DATABITS_7
 
60
        elif self._bytesize == EIGHTBITS:
 
61
            jdatabits = javax.comm.SerialPort.DATABITS_8
 
62
        else:
 
63
            raise ValueError("unsupported bytesize: %r" % self._bytesize)
 
64
        
 
65
        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
 
69
        elif self._stopbits == STOPBITS_TWO:
 
70
            jstopbits = javax.comm.SerialPort.STOPBITS_2
 
71
        else:
 
72
            raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
 
73
 
 
74
        if self._parity == PARITY_NONE:
 
75
            jparity = javax.comm.SerialPort.PARITY_NONE
 
76
        elif self._parity == PARITY_EVEN:
 
77
            jparity = javax.comm.SerialPort.PARITY_EVEN
 
78
        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
 
84
        else:
 
85
            raise ValueError("unsupported parity type: %r" % self._parity)
 
86
 
 
87
        jflowin = jflowout = 0
 
88
        if self._rtscts:
 
89
            jflowin  |=  javax.comm.SerialPort.FLOWCONTROL_RTSCTS_IN
 
90
            jflowout |=  javax.comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
 
91
        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)
 
96
        self.sPort.setFlowControlMode(jflowin | jflowout)
 
97
        
 
98
        if self._timeout >= 0:
 
99
            self.sPort.enableReceiveTimeout(self._timeout*1000)
 
100
        else:
 
101
            self.sPort.disableReceiveTimeout()
 
102
 
 
103
    def close(self):
 
104
        """Close port"""
 
105
        if self._isOpen:
 
106
            if self.sPort:
 
107
                self._instream.close()
 
108
                self._outstream.close()
 
109
                self.sPort.close()
 
110
                self.sPort = None
 
111
            self._isOpen = False
 
112
 
 
113
    def makeDeviceName(self, port):
 
114
        return device(port)
 
115
 
 
116
    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
 
117
 
 
118
    def inWaiting(self):
 
119
        """Return the number of characters currently in the input buffer."""
 
120
        if not self.sPort: raise portNotOpenError
 
121
        return self._instream.available()
 
122
 
 
123
    def read(self, size=1):
 
124
        """Read size bytes from the serial port. If a timeout is set it may
 
125
           return less characters as requested. With no timeout it will block
 
126
           until the requested number of bytes is read."""
 
127
        if not self.sPort: raise portNotOpenError
 
128
        read = ''
 
129
        if size > 0:
 
130
            while len(read) < size:
 
131
                x = self._instream.read()
 
132
                if x == -1:
 
133
                    if self.timeout >= 0:
 
134
                        break
 
135
                else:
 
136
                    read = read + chr(x)
 
137
        return read
 
138
 
 
139
    def write(self, data):
 
140
        """Output the given string over the serial port."""
 
141
        if not self.sPort: raise portNotOpenError
 
142
        self._outstream.write(data)
 
143
 
 
144
    def flushInput(self):
 
145
        """Clear input buffer, discarding all that is in the buffer."""
 
146
        if not self.sPort: raise portNotOpenError
 
147
        self._instream.skip(self._instream.available())
 
148
 
 
149
    def flushOutput(self):
 
150
        """Clear output buffer, aborting the current output and
 
151
        discarding all that is in the buffer."""
 
152
        if not self.sPort: raise portNotOpenError
 
153
        self._outstream.flush()
 
154
 
 
155
    def sendBreak(self, duration=0.25):
 
156
        """Send break condition."""
 
157
        if not self.sPort: raise portNotOpenError
 
158
        self.sPort.sendBreak(duration*1000.0)
 
159
 
 
160
    def setRTS(self, level=1):
 
161
        """Set terminal status line: Request To Send"""
 
162
        if not self.sPort: raise portNotOpenError
 
163
        self.sPort.setRTS(level)
 
164
        
 
165
    def setDTR(self, level=1):
 
166
        """Set terminal status line: Data Terminal Ready"""
 
167
        if not self.sPort: raise portNotOpenError
 
168
        self.sPort.setDTR(level)
 
169
 
 
170
    def getCTS(self):
 
171
        """Read terminal status line: Clear To Send"""
 
172
        if not self.sPort: raise portNotOpenError
 
173
        self.sPort.isCTS()
 
174
 
 
175
    def getDSR(self):
 
176
        """Read terminal status line: Data Set Ready"""
 
177
        if not self.sPort: raise portNotOpenError
 
178
        self.sPort.isDSR()
 
179
 
 
180
    def getRI(self):
 
181
        """Read terminal status line: Ring Indicator"""
 
182
        if not self.sPort: raise portNotOpenError
 
183
        self.sPort.isRI()
 
184
 
 
185
    def getCD(self):
 
186
        """Read terminal status line: Carrier Detect"""
 
187
        if not self.sPort: raise portNotOpenError
 
188
        self.sPort.isCD()
 
189
 
 
190
 
 
191
 
 
192
if __name__ == '__main__':
 
193
    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
               )
 
202
    s.setRTS(1)
 
203
    s.setDTR(1)
 
204
    s.flushInput()
 
205
    s.flushOutput()
 
206
    s.write('hello')
 
207
    print repr(s.read(5))
 
208
    print s.inWaiting()
 
209
    del s
 
210
 
 
211