blob: ac6bd68b5a9e5866c37bd6f1e6c68f9430768834 [file] [log] [blame]
cliechti0d6029a2008-06-21 01:28:46 +00001#! python
2#Python Serial Port Extension for Win32, Linux, BSD, Jython and .NET/Mono
3#serial driver for .NET/Mono (IronPython), .NET >= 2
4#see __init__.py
5#
6#(C) 2008 Chris Liechti <cliechti@gmx.net>
7# this is distributed under a free software license, see license.txt
8
9import System.IO.Ports
10from serialutil import *
11
12def device(portnum):
13 """Turn a port number into a device name"""
14 return System.IO.Ports.SerialPort.GetPortNames()[portnum]
15
16class Serial(SerialBase):
17 """Serial port implemenation for .NET/Mono."""
18
19 BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
20 19200,38400,57600,115200)
21
22 def open(self):
23 """Open port with current settings. This may throw a SerialException
24 if the port cannot be opened."""
25 if self._port is None:
26 raise SerialException("Port must be configured before it can be used.")
27 self._port_handle = None
28 try:
29 self._port_handle = System.IO.Ports.SerialPort(self.portstr)
30 except Exception, msg:
31 raise SerialException("could not open port %s: %s" % (self.portstr, msg))
32
33 self._reconfigurePort()
34 self._port_handle.Open()
35 self._isOpen = True
36
37 def _reconfigurePort(self):
38 """Set commuication parameters on opened port."""
39 if not self._port_handle:
40 raise SerialException("Can only operate on a valid port handle")
41
42 self.ReceivedBytesThreshold = 1
43
44 if self._timeout is None:
45 self._port_handle.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
46 else:
47 self._port_handle.ReadTimeout = int(self._timeout*1000)
48
49 # if self._timeout != 0 and self._interCharTimeout is not None:
50 # timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
51
52 if self._writeTimeout is None:
53 pass
54 else:
55 self._port_handle.WriteTimeout = int(self._writeTimeout*1000)
56
57
58 # Setup the connection info.
59 self._port_handle.BaudRate = self._baudrate
60
61 if self._bytesize == FIVEBITS:
62 self._port_handle.DataBits = 5
63 elif self._bytesize == SIXBITS:
64 self._port_handle.DataBits = 6
65 elif self._bytesize == SEVENBITS:
66 self._port_handle.DataBits = 7
67 elif self._bytesize == EIGHTBITS:
68 self._port_handle.DataBits = 8
69 else:
70 raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
71
72 if self._parity == PARITY_NONE:
73 self._port_handle.Parity = System.IO.Ports.Parity.None
74 elif self._parity == PARITY_EVEN:
75 self._port_handle.Parity = System.IO.Ports.Parity.Even
76 elif self._parity == PARITY_ODD:
77 self._port_handle.Parity = System.IO.Ports.Parity.Odd
78 elif self._parity == PARITY_MARK:
79 self._port_handle.Parity = System.IO.Ports.Parity.Mark
80 elif self._parity == PARITY_SPACE:
81 self._port_handle.Parity = System.IO.Ports.Parity.Space
82 else:
83 raise ValueError("Unsupported parity mode: %r" % self._parity)
84
85 if self._stopbits == STOPBITS_ONE:
86 self._port_handle.StopBits = System.IO.Ports.StopBits.One
87 elif self._stopbits == STOPBITS_TWO:
88 self._port_handle.StopBits = System.IO.Ports.StopBits.Two
89 else:
90 raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
91
92 if self._rtscts and self._xonxoff:
93 self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff
94 elif self._rtscts:
95 self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSend
96 elif self._xonxoff:
97 self._port_handle.Handshake = System.IO.Ports.Handshake.XOnXOff
98 else:
99 self._port_handle.Handshake = System.IO.Ports.Handshake.None
100
101 #~ def __del__(self):
102 #~ self.close()
103
104 def close(self):
105 """Close port"""
106 if self._isOpen:
107 if self._port_handle:
108 try:
109 self.Close()
110 except System.IO.Ports.InvalidOperationException:
111 # ignore errors. can happen for unplugged USB serial devices
112 pass
113 self._port_handle = None
114 self._isOpen = False
115
116 def makeDeviceName(self, port):
117 return device(port)
118
119 # - - - - - - - - - - - - - - - - - - - - - - - -
120
121 def inWaiting(self):
122 """Return the number of characters currently in the input buffer."""
123 if not self._port_handle: raise portNotOpenError
124 return self._port_handle.BytesToRead
125
126 def read(self, size=1):
127 """Read size bytes from the serial port. If a timeout is set it may
128 return less characters as requested. With no timeout it will block
129 until the requested number of bytes is read."""
130 if not self._port_handle: raise portNotOpenError
131 data = []
132 while size:
133 data.append(self._port_handle.ReadByte())
134 size -= 1
135 return ''.join(data)
136
137 def write(self, data):
138 """Output the given string over the serial port."""
139 if not self._port_handle: raise portNotOpenError
140 if not isinstance(data, str):
141 raise TypeError('expected str, got %s' % type(data))
142 self._port_handle.Write(data)
143
144 def flushInput(self):
145 """Clear input buffer, discarding all that is in the buffer."""
146 if not self._port_handle: raise portNotOpenError
147 self._port_handle.DiscardInBuffer()
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._port_handle: raise portNotOpenError
153 self._port_handle.DiscardOutBuffer()
154
155 def sendBreak(self, duration=0.25):
156 """Send break condition. Timed, returns to idle state after given duration."""
157 if not self._port_handle: raise portNotOpenError
158 import time
159 self._port_handle.BreakState = True
160 time.sleep(duration)
161 self._port_handle.BreakState = False
162
163 def setBreak(self, level=1):
164 """Set break: Controls TXD. When active, to transmitting is possible."""
165 if not self._port_handle: raise portNotOpenError
166 self._port_handle.BreakState = level
167
168 def setRTS(self, level=1):
169 """Set terminal status line: Request To Send"""
170 if not self._port_handle: raise portNotOpenError
171 self._port_handle.RtsEnable = level
172
173 def setDTR(self, level=1):
174 """Set terminal status line: Data Terminal Ready"""
175 if not self._port_handle: raise portNotOpenError
176 self._port_handle.DtrEnable = level
177
178 def getCTS(self):
179 """Read terminal status line: Clear To Send"""
180 if not self._port_handle: raise portNotOpenError
181 return self._port_handle.CtsHolding
182
183 def getDSR(self):
184 """Read terminal status line: Data Set Ready"""
185 if not self._port_handle: raise portNotOpenError
186 return self._port_handle.DsrHolding
187
188 #~ def getRI(self):
189 #~ """Read terminal status line: Ring Indicator"""
190 #~ if not self._port_handle: raise portNotOpenError
191 #~ return self._port_handle.XXX
192
193 def getCD(self):
194 """Read terminal status line: Carrier Detect"""
195 if not self._port_handle: raise portNotOpenError
196 return self._port_handle.CDHolding
197
198 # - - platform specific - - - -
199
200#Nur Testfunktion!!
201if __name__ == '__main__':
202 s = Serial(0)
203 print s
204
205 s = Serial()
206 print s
207
208
209 s.baudrate = 19200
210 s.databits = 7
211 s.close()
212 s.port = 0
213 s.open()
214 print s
215