2
#Python Serial Port Extension for Win32, Linux, BSD, Jython
3
#module for serial IO for Jython and JavaComm
6
#(C) 2002-2003 Chris Liechti <cliechti@gmx.net>
7
# this is distributed under a free software license, see license.txt
10
from serialutil import *
12
VERSION = "$Revision: 1.8 $".split()[1] #extract CVS version
15
def device(portnumber):
16
"""Turn a port number into a device name"""
17
enum = javax.comm.CommPortIdentifier.getPortIdentifiers()
19
while enum.hasMoreElements():
20
el = enum.nextElement()
21
if el.getPortType() == javax.comm.CommPortIdentifier.PORT_SERIAL:
23
return ports[portnumber].getName()
25
class Serial(SerialBase):
26
"""Serial port class, implemented with javax.comm and thus usable with
27
jython and the appropriate java extension."""
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)
37
portId = javax.comm.CommPortIdentifier.getPortIdentifier(device(self._port)) #numbers are transformed to a comportid obj
39
self.sPort = portId.open("python serial module", 10)
40
except Exception, msg:
42
raise SerialException("Could not open port: %s" % msg)
43
self._reconfigurePort()
44
self._instream = self.sPort.getInputStream()
45
self._outstream = self.sPort.getOutputStream()
48
def _reconfigurePort(self):
49
"""Set commuication parameters on opened port."""
51
raise SerialException("Can only operate on a valid port handle")
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
63
raise ValueError("unsupported bytesize: %r" % self._bytesize)
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
72
raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
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
85
raise ValueError("unsupported parity type: %r" % self._parity)
87
jflowin = jflowout = 0
89
jflowin |= javax.comm.SerialPort.FLOWCONTROL_RTSCTS_IN
90
jflowout |= javax.comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
92
jflowin |= javax.comm.SerialPort.FLOWCONTROL_XONXOFF_IN
93
jflowout |= javax.comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
95
self.sPort.setSerialPortParams(baudrate, jdatabits, jstopbits, jparity)
96
self.sPort.setFlowControlMode(jflowin | jflowout)
98
if self._timeout >= 0:
99
self.sPort.enableReceiveTimeout(self._timeout*1000)
101
self.sPort.disableReceiveTimeout()
107
self._instream.close()
108
self._outstream.close()
113
def makeDeviceName(self, port):
116
# - - - - - - - - - - - - - - - - - - - - - - - -
119
"""Return the number of characters currently in the input buffer."""
120
if not self.sPort: raise portNotOpenError
121
return self._instream.available()
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
130
while len(read) < size:
131
x = self._instream.read()
133
if self.timeout >= 0:
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)
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())
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()
156
"""Send break condition."""
157
if not self.sPort: raise portNotOpenError
158
self.sPort.sendBreak()
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)
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)
171
"""Read terminal status line: Clear To Send"""
172
if not self.sPort: raise portNotOpenError
176
"""Read terminal status line: Data Set Ready"""
177
if not self.sPort: raise portNotOpenError
181
"""Read terminal status line: Ring Indicator"""
182
if not self.sPort: raise portNotOpenError
186
"""Read terminal status line: Carrier Detect"""
187
if not self.sPort: raise portNotOpenError
192
if __name__ == '__main__':
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
207
print repr(s.read(5))
2
#Python Serial Port Extension for Win32, Linux, BSD, Jython
3
#module for serial IO for Jython and JavaComm
6
#(C) 2002-2003 Chris Liechti <cliechti@gmx.net>
7
# this is distributed under a free software license, see license.txt
10
from serialutil import *
12
VERSION = "$Revision: 1.10 $".split()[1] #extract CVS version
15
def device(portnumber):
16
"""Turn a port number into a device name"""
17
enum = javax.comm.CommPortIdentifier.getPortIdentifiers()
19
while enum.hasMoreElements():
20
el = enum.nextElement()
21
if el.getPortType() == javax.comm.CommPortIdentifier.PORT_SERIAL:
23
return ports[portnumber].getName()
25
class Serial(SerialBase):
26
"""Serial port class, implemented with javax.comm and thus usable with
27
jython and the appropriate java extension."""
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)
37
portId = javax.comm.CommPortIdentifier.getPortIdentifier(device(self._port)) #numbers are transformed to a comportid obj
39
self.sPort = portId.open("python serial module", 10)
40
except Exception, msg:
42
raise SerialException("Could not open port: %s" % msg)
43
self._reconfigurePort()
44
self._instream = self.sPort.getInputStream()
45
self._outstream = self.sPort.getOutputStream()
48
def _reconfigurePort(self):
49
"""Set commuication parameters on opened port."""
51
raise SerialException("Can only operate on a valid port handle")
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
63
raise ValueError("unsupported bytesize: %r" % self._bytesize)
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
72
raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
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
85
raise ValueError("unsupported parity type: %r" % self._parity)
87
jflowin = jflowout = 0
89
jflowin |= javax.comm.SerialPort.FLOWCONTROL_RTSCTS_IN
90
jflowout |= javax.comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
92
jflowin |= javax.comm.SerialPort.FLOWCONTROL_XONXOFF_IN
93
jflowout |= javax.comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
95
self.sPort.setSerialPortParams(baudrate, jdatabits, jstopbits, jparity)
96
self.sPort.setFlowControlMode(jflowin | jflowout)
98
if self._timeout >= 0:
99
self.sPort.enableReceiveTimeout(self._timeout*1000)
101
self.sPort.disableReceiveTimeout()
107
self._instream.close()
108
self._outstream.close()
113
def makeDeviceName(self, port):
116
# - - - - - - - - - - - - - - - - - - - - - - - -
119
"""Return the number of characters currently in the input buffer."""
120
if not self.sPort: raise portNotOpenError
121
return self._instream.available()
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
130
while len(read) < size:
131
x = self._instream.read()
133
if self.timeout >= 0:
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)
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())
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()
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)
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)
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)
171
"""Read terminal status line: Clear To Send"""
172
if not self.sPort: raise portNotOpenError
176
"""Read terminal status line: Data Set Ready"""
177
if not self.sPort: raise portNotOpenError
181
"""Read terminal status line: Ring Indicator"""
182
if not self.sPort: raise portNotOpenError
186
"""Read terminal status line: Carrier Detect"""
187
if not self.sPort: raise portNotOpenError
192
if __name__ == '__main__':
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
207
print repr(s.read(5))