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>
3
# Python Serial Port Extension for Win32, Linux, BSD, Jython
4
# module for serial IO for Jython and JavaComm
7
# (C) 2002-2008 Chris Liechti <cliechti@gmx.net>
7
8
# this is distributed under a free software license, see license.txt
10
10
from serialutil import *
12
VERSION = "$Revision: 1.10 $".split()[1] #extract CVS version
13
mod = __import__(name)
14
components = name.split('.')
15
for comp in components[1:]:
16
mod = getattr(mod, comp)
20
def detect_java_comm(names):
21
"""try given list of modules and return that imports"""
27
except (ImportError, AttributeError):
29
raise ImportError("No Java Communications API implementation found")
32
# Java Communications API implementations
33
# http://mho.republika.pl/java/comm/
35
comm = detect_java_comm([
36
'javax.comm', # Sun/IBM
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()
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:
23
49
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."""
52
class JavaSerial(SerialBase):
53
"""Serial port class, implemented with Java Communications API and
54
thus usable with jython and the appropriate java extension."""
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)
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
39
66
self.sPort = portId.open("python serial module", 10)
40
67
except Exception, msg:
46
73
self._isOpen = True
48
75
def _reconfigurePort(self):
49
"""Set commuication parameters on opened port."""
76
"""Set communication parameters on opened port."""
51
78
raise SerialException("Can only operate on a valid port handle")
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
63
90
raise ValueError("unsupported bytesize: %r" % self._bytesize)
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
72
99
raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
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
85
112
raise ValueError("unsupported parity type: %r" % self._parity)
87
114
jflowin = jflowout = 0
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
92
jflowin |= javax.comm.SerialPort.FLOWCONTROL_XONXOFF_IN
93
jflowout |= javax.comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
95
self.sPort.setSerialPortParams(baudrate, jdatabits, jstopbits, jparity)
119
jflowin |= comm.SerialPort.FLOWCONTROL_XONXOFF_IN
120
jflowout |= comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
122
self.sPort.setSerialPortParams(self._baudrate, jdatabits, jstopbits, jparity)
96
123
self.sPort.setFlowControlMode(jflowin | jflowout)
98
125
if self._timeout >= 0:
99
126
self.sPort.enableReceiveTimeout(self._timeout*1000)
153
183
self._outstream.flush()
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)
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.")
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)
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()
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
232
# classic version with our own file-like emulation
233
class Serial(JavaSerial, FileLike):
237
class Serial(JavaSerial, io.RawIOBase):
192
241
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
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
207
print repr(s.read(5))
256
sys.stdio.write('%r\n' % s.read(5))
257
sys.stdio.write('%s\n' % s.inWaiting())