summaryrefslogtreecommitdiff
path: root/maximus/python/lib
diff options
context:
space:
mode:
authorburet2008-04-07 09:37:26 +0000
committerburet2008-04-07 09:37:26 +0000
commit21d7eaaefe8407228967b36ec063d0e1d47d2578 (patch)
treea869953f41f68496cbd5319a7637f342ac9a93b9 /maximus/python/lib
parentef2e6189aa58270a03ff47a522d9c40ea85dd37a (diff)
Maximus V3:
- Develop a Python library for function call on proto. - For the moment, integrate 2 Python libraries for RS-232. Choice will be done after more tests. git-svn-id: svn+ssh://pessac/svn/cesar/trunk@1766 017c9cb6-072f-447c-8318-d5b54f68fe89
Diffstat (limited to 'maximus/python/lib')
-rw-r--r--maximus/python/lib/proto/fcall.py349
-rw-r--r--maximus/python/lib/proto/pyserial/CHANGES.txt171
-rw-r--r--maximus/python/lib/proto/pyserial/LICENSE.txt61
-rw-r--r--maximus/python/lib/proto/pyserial/PKG-INFO21
-rw-r--r--maximus/python/lib/proto/pyserial/README.txt244
-rw-r--r--maximus/python/lib/proto/pyserial/examples/enhancedserial.py62
-rw-r--r--maximus/python/lib/proto/pyserial/examples/miniterm.py165
-rw-r--r--maximus/python/lib/proto/pyserial/examples/scan.py27
-rw-r--r--maximus/python/lib/proto/pyserial/examples/setup_demo.py35
-rw-r--r--maximus/python/lib/proto/pyserial/examples/tcp_serial_redirect.py150
-rw-r--r--maximus/python/lib/proto/pyserial/examples/test.py186
-rw-r--r--maximus/python/lib/proto/pyserial/examples/test_advanced.py164
-rw-r--r--maximus/python/lib/proto/pyserial/examples/test_high_load.py67
-rw-r--r--maximus/python/lib/proto/pyserial/examples/wxSerialConfigDialog.py259
-rw-r--r--maximus/python/lib/proto/pyserial/examples/wxSerialConfigDialog.wxg262
-rw-r--r--maximus/python/lib/proto/pyserial/examples/wxTerminal.py332
-rw-r--r--maximus/python/lib/proto/pyserial/examples/wxTerminal.wxg127
-rw-r--r--maximus/python/lib/proto/pyserial/serial/__init__.py20
-rw-r--r--maximus/python/lib/proto/pyserial/serial/serialjava.py212
-rw-r--r--maximus/python/lib/proto/pyserial/serial/serialposix.py406
-rw-r--r--maximus/python/lib/proto/pyserial/serial/serialutil.py366
-rw-r--r--maximus/python/lib/proto/pyserial/serial/serialwin32.py314
-rw-r--r--maximus/python/lib/proto/pyserial/setup.py38
-rw-r--r--maximus/python/lib/proto/uspp/AUTHORS4
-rw-r--r--maximus/python/lib/proto/uspp/Copyright21
-rw-r--r--maximus/python/lib/proto/uspp/Readme190
-rw-r--r--maximus/python/lib/proto/uspp/Readme_es199
-rw-r--r--maximus/python/lib/proto/uspp/SerialPort_darwin.py326
-rw-r--r--maximus/python/lib/proto/uspp/SerialPort_linux.py329
-rw-r--r--maximus/python/lib/proto/uspp/SerialPort_win.py239
-rw-r--r--maximus/python/lib/proto/uspp/lesser.txt504
-rw-r--r--maximus/python/lib/proto/uspp/uspp.htm635
-rw-r--r--maximus/python/lib/proto/uspp/uspp.py193
-rw-r--r--maximus/python/lib/proto/uspp/uspp_es.htm629
34 files changed, 7307 insertions, 0 deletions
diff --git a/maximus/python/lib/proto/fcall.py b/maximus/python/lib/proto/fcall.py
new file mode 100644
index 0000000000..8b87c3d07d
--- /dev/null
+++ b/maximus/python/lib/proto/fcall.py
@@ -0,0 +1,349 @@
+#! usr/bin/env python
+
+#print __name__
+
+SERIAL = 'PYSERIAL'
+#SERIAL = 'USPP'
+
+import sys
+base = '../../../../'
+utils = 'maximus/python/maximus/utils'
+path = __file__[:__file__.find(".py") - len(__name__)] + base + utils
+sys.path.append(path)
+if SERIAL == 'PYSERIAL':
+ serial = 'maximus/python/lib/proto/pyserial'
+elif SERIAL == 'USPP':
+ serial = 'maximus/python/lib/proto/uspp'
+path = __file__[:__file__.find(".py") - len(__name__)] + base + serial
+sys.path.append(path)
+
+from exception import *
+from format import *
+if SERIAL == 'PYSERIAL':
+ import serial
+elif SERIAL == 'USPP':
+ from uspp import *
+
+# Constants from 'maximus/common/types/sci_types.h'
+SCI_MSG_MAGIC = 'MAXI'
+SCI_MSG_VERSION = 0x03
+SCI_MSG_ID_STATION = 0x8000
+SCI_MSG_TYPE_FUNCTION_CALL = 0x02
+SCI_MSG_TYPE_STATION_LOG = 0x06
+SCI_MSG_FLAG_RESP = 0x0001
+SIZE_OF_SCI_MSG_HEADER = 24 # in octets
+
+# Constants from 'maximus/common/types/functioncall_types.h'
+FUNCTION_CALL_VERSION = 0x03
+FUNCTION_CALL_FLAG_FAILED = 0x01
+FUNCTION_CALL_TYPE_REQ = 0x01
+FUNCTION_CALL_TYPE_RSP = 0x02
+SIZE_OF_FUNCTION_CALL_HEADER = 8 # in octets
+
+class Param:
+
+ def __init__(self, name, length, value):
+ self.__name = name
+ self.__length = hton16(length)
+ self.__value = value
+
+ def get_name(self):
+ return self.__name
+
+ def get_value(self):
+ return self.__value
+
+ def get(self):
+ return self.__name + '\0' + self.__length + self.__value
+
+class Fcall:
+ __msg_id = 1
+
+ tty = None
+ for i in range (1, len(sys.argv)):
+ if sys.argv[i] == '-r' or sys.argv[i] == '--rs-232':
+ if i+1 < len(sys.argv):
+ tty = sys.argv[i+1]
+ break
+
+ if SERIAL == 'PYSERIAL':
+ if tty is None:
+ # Open port 0 at "9600,8,N,1", 1s timeout
+ __tty = serial.Serial(0, timeout=1) # open first serial port
+ # Check which port was really used
+ print "Using port:", __tty.portstr
+ else:
+ # Open named port at "9600,8,N,1", 1s timeout
+ __tty = serial.Serial(tty, timeout=1)
+ if not __tty.isOpen():
+ raise Error("Cannot open serial port!")
+ elif SERIAL == 'USPP':
+ if tty is None:
+ tty = '/dev/ttyS0'
+ # Opens RS-232 at 9600 bps and with a read timeout of 1 second
+ __tty = SerialPort(tty, 1000, 9600)
+
+ def __init__(self, name):
+ self.__name = name
+ self.__param_list = []
+ self.__user_cb = None
+
+ def add_param(self, name, value=None):
+ if value is None:
+ value = ''
+ self.__param_list.append(Param(name, len(value), value))
+ return self
+
+ def add_param_bool(self, name, value):
+ self.__param_list.append(Param(name, SIZE_OF_U8, hton8(value)))
+ return self
+
+ def add_param_uchar(self, name, value):
+ self.__param_list.append(Param(name, SIZE_OF_U8, hton8(value)))
+ return self
+
+ def add_param_ushort(self, name, value):
+ self.__param_list.append(Param(name, SIZE_OF_U16, hton16(value)))
+ return self
+
+ def add_param_ulong(self, name, value):
+ self.__param_list.append(Param(name, SIZE_OF_U32, hton32(value)))
+ return self
+
+ def add_param_n_u8(self, name, tuple):
+ value = ''
+ for t in tuple:
+ value += hton8(t)
+ self.__param_list.append(Param(name, SIZE_OF_U8 * len(value), value))
+ return self
+
+ def add_param_n_u16(self, name, tuple):
+ value = ''
+ for t in tuple:
+ value += hton16(t)
+ self.__param_list.append(Param(name, SIZE_OF_U16 * len(value), value))
+ return self
+
+ def add_param_n_u32(self, name, tuple):
+ value = ''
+ for t in tuple:
+ value += hton32(t)
+ self.__param_list.append(Param(name, SIZE_OF_U32 * len(value), value))
+ return self
+
+ def remove_param(self, name):
+ for i in range (0, len(self.__param_list)):
+ if self.__param_list[i].get_name() == name:
+ self.__param_list.pop(i)
+ break
+ return self
+
+ def set_cb(self, user_cb):
+ self.__user_cb = user_cb
+ return self
+
+ def remove_cb(self):
+ self.__user_cb = None
+ return self
+
+ def set_sta(self, sta):
+ return self
+
+ def send_async(self, sta=None):
+ self.__write()
+ self.__read()
+ if self.__user_cb is not None:
+ self.__user_cb(self)
+
+ def send(self, sta=None):
+ self.__write()
+ return self.__read()
+
+ def is_param(self, name):
+ found = False
+ for l in self.__param_list:
+ if l.get_name() == name:
+ found = True
+ return found
+
+ def bind_param(self, name):
+ param = None
+ for l in self.__param_list:
+ if l.get_name() == name:
+ param = l.get_value()
+ break
+ return param
+
+ def bind_param_string(self, name):
+ param = None
+ for l in self.__param_list:
+ if l.get_name() == name:
+ param = l.get_value()
+ if param[len(param)-1] == '\0':
+ param = param[:-1]
+ break
+ return param
+
+ def bind_param_bool(self, name):
+ param = None
+ for l in self.__param_list:
+ if l.get_name() == name:
+ param = ntoh8(l.get_value())
+ break
+ return param
+
+ def bind_param_ushort(self, name):
+ param = None
+ for l in self.__param_list:
+ if l.get_name() == name:
+ param = ntoh16(l.get_value())
+ break
+ return param
+
+ def bind_param_ulong(self, name):
+ param = None
+ for l in self.__param_list:
+ if l.get_name() == name:
+ param = ntoh32(l.get_value())
+ break
+ return param
+
+ def __get(self):
+ if self.__class__.__msg_id < 0x7FFF:
+ self.__class__.__msg_id += 1
+ else:
+ self.__class__.__msg_id = 0x0001
+
+ # FCALL data
+ fcall_data = self.__name + '\0'
+ for l in self.__param_list:
+ fcall_data += l.get()
+
+ # FCALL header
+ # uint8_t version
+ # uint8_t type
+ # uint16_t msg_id
+ # uint8_t param_nb
+ # uint8_t flags
+ # uint16_t reserved
+ fcall_hdr = hton8(FUNCTION_CALL_VERSION)\
+ + hton8(FUNCTION_CALL_TYPE_REQ)\
+ + hton16(self.__class__.__msg_id)\
+ + hton8(len(self.__param_list))\
+ + hton8(0)\
+ + hton16(0)
+
+ # SCI header
+ # uint32_t magic_id
+ # uint8_t version
+ # uint8_t type
+ # uint16_t length
+ # uint16_t station_id
+ # uint16_t msg_id
+ # uint32_t netclock_high
+ # uint32_t netclock_low
+ # uint16_t flags
+ # uint16_t reserved
+ sci_hdr = SCI_MSG_MAGIC\
+ + hton8(SCI_MSG_VERSION)\
+ + hton8(SCI_MSG_TYPE_FUNCTION_CALL)\
+ + hton16(len(fcall_hdr + fcall_data))\
+ + hton16(0)\
+ + hton16(self.__class__.__msg_id)\
+ + hton32(0)\
+ + hton32(0)\
+ + hton16(0)\
+ + hton16(0)
+
+ return sci_hdr + fcall_hdr + fcall_data
+
+ def __write(self):
+ # Writes a string to the RS-232 port
+ self.__class__.__tty.write(self.__get())
+
+ def __read(self):
+ fcall = None
+
+ # SCI header
+ sci_hdr = self.__class__.__tty.read(SIZE_OF_SCI_MSG_HEADER) # read up to 24 bytes (timeout)
+ if sci_hdr[0:4] != SCI_MSG_MAGIC: # uint32_t magic_id
+ print "SCI header:"
+ print "magic id =", hex(ntoh32(sci_hdr[0:4]))
+ print "version =", hex(ntoh8(sci_hdr[4]))
+ print "type =", hex(ntoh8(sci_hdr[5]))
+ print "length =", hex(ntoh16(sci_hdr[6:8]))
+ print "station id =", hex(ntoh16(sci_hdr[8:10]))
+ print "msg id =", hex(ntoh16(sci_hdr[10:12]))
+ print "netclock high =", hex(ntoh32(sci_hdr[12:16]))
+ print "netclock low =", hex(ntoh32(sci_hdr[16:20]))
+ print "flags =", hex(ntoh16(sci_hdr[20:22]))
+ print "reserved =", hex(ntoh16(sci_hdr[22:24]))
+ raise Error("SCI header: bad magic id! (" + sci_hdr[0:4] + ")")
+ if ntoh8(sci_hdr[4]) != SCI_MSG_VERSION: # uint8_t version
+ raise Error("SCI header: bad version! (" + hex(ntoh8(sci_hdr[4])) + ")")
+ if ntoh8(sci_hdr[5]) == SCI_MSG_TYPE_FUNCTION_CALL: # uint8_t type
+ length = ntoh16(sci_hdr[6:8]) # uint16_t length
+
+ # FCALL header
+ fcall_hdr = self.__class__.__tty.read(SIZE_OF_FUNCTION_CALL_HEADER) # read up to 8 bytes (timeout)
+ if ntoh8(fcall_hdr[0]) != FUNCTION_CALL_VERSION: # uint8_t version
+ raise Error("FCALL header: bad version! (" + hex(ntoh8(fcall_hdr[0])) + ")")
+ if ntoh8(fcall_hdr[1]) != FUNCTION_CALL_TYPE_RSP: # uint8_t type
+ raise Error("FCALL header: bad type! (" + hex(ntoh8(fcall_hdr[1])) + ")")
+ ntoh16(fcall_hdr[2:4]) # uint16_t msg_id
+ param_nb = ntoh8(fcall_hdr[4]) # uint8_t param_nb
+ if ntoh8(fcall_hdr[5]) >= FUNCTION_CALL_FLAG_FAILED: # uint8_t flags
+ raise Error("FCALL header: flag failed! (" + hex(ntoh8(fcall_hdr[5])) + ")")
+ length -= SIZE_OF_FUNCTION_CALL_HEADER
+
+ # FCALL data
+ name = self.__read_name()
+ fcall = Fcall(name)
+ length -= len(name) + 1
+ for n in range(0, param_nb):
+ param_name = self.__read_param_name()
+ param_length = self.__read_param_length()
+ param_value = self.__read_param_value(param_length)
+ fcall.__param_list.append(Param(param_name, param_length, param_value))
+ length -= len(param_name) + 1 + SIZE_OF_U16 + param_length
+
+ if length != 0:
+ raise Error("length = " + str(length))
+
+ elif ntoh8(sci_hdr[5]) == SCI_MSG_TYPE_STATION_LOG: # uint8_t type
+ print self.__class__.__tty.readline() # read a '\n' terminated line
+ else:
+ raise Error("SCI header: bad type! (" + hex(ntoh8(sci_hdr[5])) + ")")
+
+ ntoh16(sci_hdr[8:10]) # uint16_t station_id
+ if ntoh16(sci_hdr[10:12]) < SCI_MSG_ID_STATION: # uint16_t msg_id
+ raise Error("SCI header: bad msg id! (" + hex(ntoh16(sci_hdr[10:12])) + ")")
+ ntoh32(sci_hdr[12:16]) # uint32_t netclock_high
+ ntoh32(sci_hdr[16:20]) # uint32_t netclock_low
+ if ntoh16(sci_hdr[20:22]) != SCI_MSG_FLAG_RESP: # uint16_t flags
+ raise Error("SCI header: bad flags! (" + hex(ntoh16(sci_hdr[20:22])) + ")")
+
+ return fcall
+
+ def __read_name(self):
+ name = ''
+ c = self.__class__.__tty.read() # read one byte
+ while c != '\0':
+ name += c
+ c = self.__class__.__tty.read() # read one byte
+ return name
+
+ def __read_param_name(self):
+ return self.__read_name()
+
+ def __read_param_length(self):
+ return ntoh16(self.__class__.__tty.read(2))
+
+ def __read_param_value(self, length):
+ return self.__class__.__tty.read(length)
+
+def create_fcall(name):
+ return Fcall(name)
+
+def create_probe():
+ return Fcall('probe')
diff --git a/maximus/python/lib/proto/pyserial/CHANGES.txt b/maximus/python/lib/proto/pyserial/CHANGES.txt
new file mode 100644
index 0000000000..cc2c0faace
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/CHANGES.txt
@@ -0,0 +1,171 @@
+Version 1.0 13 Feb 2002
+ First public release.
+ Split from the pybsl application (see mspgcc.sourceforge.net)
+
+ New Features:
+ - Added Jython support
+
+Version 1.1 14 Feb 2002
+ Bugfixes:
+ - Win32, when not specifying a timeout
+ - Typos in the Docs
+
+ New Features:
+ - added serialutil which provides a base class for the Serial
+ objects.
+
+ - readline, readlines, writelines and flush are now supported
+ see README.txt for deatils.
+
+Version 1.11 14 Feb 2002
+ Same as 1.1 but added missing files.
+
+Version 1.12 18 Feb 2002
+ Removed unneded constants to fix RH7.x problems.
+
+Version 1.13 09 Apr 2002
+ Added alternate way for enabling rtscts (CNEW_RTSCTS is tried too)
+ If port opening fails, a SerialException is raised on all platforms
+
+Version 1.14 29 May 2002
+ Added examples to archive
+ Added non-blocking mode for timeout=0 (tnx Mat Martineau)
+
+ Bugfixes:
+ - win32 does now return the remaining characters on timeout
+
+Version 1.15 04 Jun 2002
+ Bugfixes (win32):
+ - removed debug messages
+ - compatibility to win9x improved
+
+Version 1.16 02 Jul 2002
+ Added implementation of RI and corrected RTS/CTS on Win32
+
+Version 1.17 03 Jul 2002
+ Silly mix of two versions in win32 code corrected
+
+Version 1.18 06 Dec 2002
+ Bugfixes (general):
+ - remove the mapping of flush to the destructive flushOutput as
+ this is not the expected behaviour.
+ - readline: EOL character for lines can be chosen idea by
+ John Florian.
+ Bugfixes (posix):
+ - cygwin port numbering fixed
+ - test each and every constant for it's existence in termios module,
+ use default if not existent (fix for Bug item #640214)
+ - wrong exception on nonexitstent ports with /dev file. bug report
+ by Louis Cordier
+ Bugfixes (win32):
+ - RTS/CTS handling as sugested in Bug #635072
+ - bugfix of timeouts brought up by Markus Hoffrogge
+
+Version 1.19 19 Mar 2003
+ Bugfixes (posix):
+ - removed dgux entry which actualy had a wrong comment and is
+ probably not in use anywhere.
+ Bugfixes (win32):
+ - added int() conversion, [Bug 702120]
+ - remove code to set control lines in close methond of win32
+ version. [Bug 669625]
+
+Version 1.20 28 Aug 2003
+ Added serial.device() for all platforms
+ Bugfixes (win32):
+ - don't recreate opverlaped structures and events on each
+ read/write.
+ - don't set unneded event masks.
+ - dont use DOS device names for ports > 9.
+ - remove send timeout (its not used in the linux impl. anyway).
+
+
+Version 1.21 30 sep 2003
+ Bugfixes (win32):
+ - name for COM10 was not built correctly, found by Norm Davis.
+ Bugfixes (examples):
+ - small change in miniterm.py that should mage it run on cygwin,
+ [Bug 809904] submitted by Rolf Campbell.
+
+Version 2.0b1 1 Oct 2003
+ Transition to the 2.0 series:
+ - New implementation only supports Python 2.2+, backwards compatibility
+ should be maintained almost everywhere.
+ The OS handles (like the hComPort or fd attribute) were prefixed with an
+ underscore. The different names stay, as anyone that uses one of these
+ has to write platform specific code anyway.
+ - Common base class serialutil.SerialBase for all implementations.
+ - PARITY_NONE, PARITY_EVEN, PARITY_ODD constants changed and all these
+ constants moved to serialutil.py (still available as serial.PARITY_NONE
+ etc. and they should be used that way)
+ - Added serial.PARITY_NAMES (implemented in serialutil.PARITY_NAMES).
+ This dictionary can be used to convert parity constants to meaningful
+ strings.
+ - Each Serial class and instance has a list of supported values:
+ BAUDRATES, BYTESIZES, PARITIES, STOPBITS
+ (i.e. serial.Serial.BAUDRATES or s = serial.Serial; s.BAUDRATES)
+ these values can be used to fill in value sin GUI dialogs etc.
+ - Creating a Serial() object without port spec returns an unconfigured,
+ closed port. Useful if a GUI dialog should take a port and configure
+ it.
+ - New methods for serial.Serial instances: open(), isOpen()
+ - A port can be opened and closed as many times as desired.
+ - Instances of serial.Serial have baudrate, bytesize, timeout etc.
+ attributes implemented as properties, all can be set while the port is
+ opened. It will then be reconfigured.
+ - Improved __doc__'s.
+ - New test_advanced.py for the property setting/getting testing.
+ - Small bugfix on posix with get* methods (return value should be true a
+ boolean).
+ - added a __repr__ that returns a meaningful string will all the serial
+ setting, easy for debugging.
+ - The serialposix module does not throw an exception on unsupported
+ platforms, the message is still printed. The idea that it may still
+ work even if the platform itself s not known, it simply tries to do
+ the posix stuff anyway (It's likely that opening ports by number
+ fails, but by name it should work).
+
+Version 2.0b2 4 Oct 2003
+ - Added serial port configuration dialog for wxPython to the examples.
+ - Added terminal application for wxPython with wxGlade design file
+ to the examples.
+ - Jython support is currenty broken as Jython does not have a Python 2.2
+ compatible release out yet
+
+Version 2.0 6 Nov 2003
+ - Fixes setup.py for older distutils
+
+Version 2.1 28 Jul 2004
+ Bugfixes:
+ - Fix XON/XOFF values [Bug 975250]
+ Bugfixes (posix):
+ - fd == 0 fix from Vsevolod Lobko
+ - netbsd fixes from Erik Lindgren
+ - Dynamicaly lookup baudrates and some cleanups
+ Bugfixes (examples):
+ - CRLF handling of miniterm.py should be more consistent on Win32
+ and others. Added LF only command line option
+ - Mutithreading fixes to wxTerminal.py (helps with wxGTK)
+ - Small change for wxPython 2.5 in wxSerialConfigDialog.py [Bug 994856]
+
+ New Features:
+ - Implement write timeouts ('writeTimeout' parameter)
+
+
+Version 2.2 31 Jul 2005
+ Bugfixes:
+ - [Bug 1014227]: property <del> broken
+ - [Bug 1105687]: serial_tcp_example.py: --localport option
+ - [Bug 1106313]: device (port) strings cannot be unicode
+ Bugfixes (posix):
+ - [Patch 1043436] Fix for [Bug 1043420] (OSError: EAGAIN)
+ - [Patch 1102700] fileno() added
+ - ensure disbaled PARMRK
+ Bugfixes (win32):
+ - [Patch 983106]: keep RTS/CTS state on port setting changes
+
+ New Features:
+ - dsrdtr setting to enable/disable DSR/DTR flow control independently
+ from the rtscts setting. (Currenly Win32 only, ignored on other
+ platforms)
+
diff --git a/maximus/python/lib/proto/pyserial/LICENSE.txt b/maximus/python/lib/proto/pyserial/LICENSE.txt
new file mode 100644
index 0000000000..694e98a79d
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/LICENSE.txt
@@ -0,0 +1,61 @@
+Copyright (c) 2001-2004 Chris Liechti <cliechti@gmx.net>;
+All Rights Reserved.
+
+This is the Python license. In short, you can use this product in
+commercial and non-commercial applications, modify it, redistribute it.
+A notification to the author when you use and/or modify it is welcome.
+
+
+TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING THIS SOFTWARE
+===================================================================
+
+LICENSE AGREEMENT
+-----------------
+
+1. This LICENSE AGREEMENT is between the copyright holder of this
+product, and the Individual or Organization ("Licensee") accessing
+and otherwise using this product in source or binary form and its
+associated documentation.
+
+2. Subject to the terms and conditions of this License Agreement,
+the copyright holder hereby grants Licensee a nonexclusive,
+royalty-free, world-wide license to reproduce, analyze, test,
+perform and/or display publicly, prepare derivative works, distribute,
+and otherwise use this product alone or in any derivative version,
+provided, however, that copyright holders License Agreement and
+copyright holders notice of copyright are retained in this product
+alone or in any derivative version prepared by Licensee.
+
+3. In the event Licensee prepares a derivative work that is based on
+or incorporates this product or any part thereof, and wants to make
+the derivative work available to others as provided herein, then
+Licensee hereby agrees to include in any such work a brief summary of
+the changes made to this product.
+
+4. The copyright holder is making this product available to Licensee on
+an "AS IS" basis. THE COPYRIGHT HOLDER MAKES NO REPRESENTATIONS OR
+WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION,
+THE COPYRIGHT HOLDER MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
+WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR
+THAT THE USE OF THIS PRODUCT WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
+
+5. THE COPYRIGHT HOLDER SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER
+USERS OF THIS PRODUCT FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL
+DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE
+USING THIS PRODUCT, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE
+POSSIBILITY THEREOF.
+
+6. This License Agreement will automatically terminate upon a material
+breach of its terms and conditions.
+
+7. Nothing in this License Agreement shall be deemed to create any
+relationship of agency, partnership, or joint venture between the
+copyright holder and Licensee. This License Agreement does not grant
+permission to use trademarks or trade names from the copyright holder
+in a trademark sense to endorse or promote products or services of
+Licensee, or any third party.
+
+8. By copying, installing or otherwise using this product, Licensee
+agrees to be bound by the terms and conditions of this License
+Agreement.
+
diff --git a/maximus/python/lib/proto/pyserial/PKG-INFO b/maximus/python/lib/proto/pyserial/PKG-INFO
new file mode 100644
index 0000000000..575389e3e7
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/PKG-INFO
@@ -0,0 +1,21 @@
+Metadata-Version: 1.0
+Name: pyserial
+Version: 2.2
+Summary: Python Serial Port Extension
+Home-page: http://pyserial.sourceforge.net/
+Author: Chris Liechti
+Author-email: cliechti@gmx.net
+License: Python
+Description: Python Serial Port Extension for Win32, Linux, BSD, Jython
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: End Users/Desktop
+Classifier: License :: OSI Approved :: Python Software Foundation License
+Classifier: Natural Language :: English
+Classifier: Operating System :: POSIX
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Programming Language :: Python
+Classifier: Topic :: Communications
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: Terminals :: Serial
diff --git a/maximus/python/lib/proto/pyserial/README.txt b/maximus/python/lib/proto/pyserial/README.txt
new file mode 100644
index 0000000000..2dfa443ba7
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/README.txt
@@ -0,0 +1,244 @@
+pySerial
+--------
+This module capsulates the access for the serial port. It provides backends
+for standard Python running on Windows, Linux, BSD (possibly any POSIX
+compilant system) and Jython. The module named "serial" automaticaly selects
+the appropriate backend.
+
+It is released under a free software license, see LICENSE.txt for more
+details.
+
+Project Homepage: pyserial.sourceforge.net
+(C) 2001-2004 Chris Liechti <cliechti@gmx.net>
+
+
+Features
+--------
+- same class based interface on all supported platforms
+- access to the port settings trough Python 2.2 properties
+- port numbering starts at zero, no need to know the platform dependant port
+ name in the user program
+- port name can be specified if access through numbering is inappropriate
+- support for different bytesizes, stopbits, parity and flow control
+ with RTS/CTS and/or Xon/Xoff
+- working with or without receive timeout, blocking or non-blocking
+- file like API with "read" and "write" ("readline" etc. also supported)
+- The files in this package are 100% pure Python.
+ They depend on non standard but common packages on Windows (win32all) and
+ Jython (JavaComm). POSIX (Linux, BSD) uses only modules from the standard
+ Python distribution)
+- The port is set up for binary transmission. No NULL byte stripping, CR-LF
+ translation etc. (which are many times enabled for POSIX.) This makes this
+ module universally useful.
+
+
+Requirements
+------------
+- Python 2.2 or newer
+- win32all extensions on Windows
+- "Java Communications" (JavaComm) extension for Java/Jython
+
+
+Installation
+------------
+Extract files from the archive, open a shell/console in that directory and
+let Distutils do the rest: "python setup.py install"
+
+The files get installed in the "Lib/site-packages" directory.
+
+There is also a Windows installer, but for developers it may be interesting
+to get the source archive anyway, because it contains examples and the readme.
+
+Do also have a look at the example files in the examples directory in the
+source distribution or online in CVS repository.
+
+Serial to USB adapters
+----------------------
+Such adapters are reported to work under Mac OSX and Windows. They are
+mapped to a normal COM port under Windows, but on Mac OSX and other platforms
+they have special device names.
+
+Mac OSX: "/dev/[cu|tty].USA<adaptername><USB-part>P<serial-port>.1"
+ e.g. "/dev/cu.USA19QW11P1.1"
+
+Linux: "/dev/usb/ttyUSB[n]" or "/dev/ttyUSB[n]"
+ first for for RedHat, second form for Debian.
+ e.g. "/dev/usb/ttyUSB0"
+
+Either use these names for the serial ports or create a link to the common device
+names like "ln -s /dev/cu.USA19QW11P1.1 /dev/cuaa0" or "ln -s /dev/usb/ttyUSB0
+/dev/ttyS4" etc.
+
+But be aware that the (USB) device file disappears as soon as you unplug the USB
+adapter.
+
+
+Short introduction
+------------------
+Open port 0 at "9600,8,N,1", no timeout
+>>> import serial
+>>> ser = serial.Serial(0) #open first serial port
+>>> print ser.portstr #check which port was realy used
+>>> ser.write("hello") #write a string
+>>> ser.close() #close port
+
+Open named port at "19200,8,N,1", 1s timeout
+>>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)
+>>> x = ser.read() #read one byte
+>>> s = ser.read(10) #read up to ten bytes (timeout)
+>>> line = ser.readline() #read a '\n' terminated line
+>>> ser.close()
+
+Open second port at "38400,8,E,1", non blocking HW handshaking
+>>> ser = serial.Serial(1, 38400, timeout=0,
+... parity=serial.PARITY_EVEN, rtscts=1)
+>>> s = ser.read(100) #read up to one hunded bytes
+... #or as much is in the buffer
+
+Get a Serial instance and configure/open it later
+>>> ser = serial.Serial()
+>>> ser.baudrate = 19200
+>>> ser.port = 0
+>>> ser
+Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8,
+parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
+>>> ser.open()
+>>> ser.isOpen()
+True
+>>> ser.close()
+>>> ser.isOpen()
+False
+
+Be carefully when using "readline". Do specify a timeout when
+opening the serial port otherwise it could block forever if
+no newline character is received. Also note that "readlines" only
+works with a timeout. "readlines" depends on having a timeout
+and interprets that as EOF (end of file). It raises an exception
+if the port is not opened correctly.
+
+
+Parameters for the Serial class
+-------------------------------
+ser = serial.Serial(
+ port=None, #number of device, numbering starts at
+ #zero. if everything fails, the user
+ #can specify a device string, note
+ #that this isn't portable anymore
+ #if no port is specified an unconfigured
+ #an closed serial port object is created
+ baudrate=9600, #baudrate
+ bytesize=EIGHTBITS, #number of databits
+ parity=PARITY_NONE, #enable parity checking
+ stopbits=STOPBITS_ONE, #number of stopbits
+ timeout=None, #set a timeout value, None to wait forever
+ xonxoff=0, #enable software flow control
+ rtscts=0, #enable RTS/CTS flow control
+ writeTimeout=None, #set a timeout for writes
+)
+
+The port is immediately opened on object creation, if a port is given.
+It is not opened if port is None.
+
+Options for read timeout:
+timeout=None #wait forever
+timeout=0 #non-blocking mode (return immediately on read)
+timeout=x #set timeout to x seconds (float allowed)
+
+Options for write timeout:
+writeTimeout=x #will rise a SerialTimeoutException if the data
+ #cannot be sent in x seconds
+
+Methods of Serial instances
+---------------------------
+open() #open port
+close() #close port immediately
+setBaudrate(baudrate) #change baudarte on an open port
+inWaiting() #return the number of chars in the receive buffer
+read(size=1) #read "size" characters
+write(s) #write the string s to the port
+flushInput() #flush input buffer, discarding all it's contents
+flushOutput() #flush output buffer, abort output
+sendBreak() #send break condition
+setRTS(level=1) #set RTS line to specified logic level
+setDTR(level=1) #set DTR line to specified logic level
+getCTS() #return the state of the CTS line
+getDSR() #return the state of the DSR line
+getRI() #return the state of the RI line
+getCD() #return the state of the CD line
+
+Attributes of Serial instances
+------------------------------
+Read Only:
+portstr #device name
+BAUDRATES #list of valid baudrates
+BYTESIZES #list of valid byte sizes
+PARITIES #list of valid parities
+STOPBITS #list of valid stop bit widths
+
+New values can be assigned to the following attribues, the port
+will be reconfigured, even if it's opened at that time (port will be
+closed and reopened to apply the changes):
+port #port name/number as set by the user
+baudrate #current baudrate setting
+bytesize #bytesize in bits
+parity #parity setting
+stopbits #stop bit with (1,2)
+timeout #read timeout setting
+xonxoff #if Xon/Xoff flow control is enabled
+rtscts #if hardware flow control is enabled
+writeTimeout #write timeout setting
+
+These attribues also have corresponding getX and setXX methods.
+
+Exceptions
+----------
+serial.SerialException
+
+Constants
+---------
+parity:
+ serial.PARITY_NONE
+ serial.PARITY_EVEN
+ serial.PARITY_ODD
+stopbits:
+ serial.STOPBITS_ONE
+ serial.STOPBITS_TWO
+bytesize:
+ serial.FIVEBITS
+ serial.SIXBITS
+ serial.SEVENBITS
+ serial.EIGHTBITS
+
+Xon/Xoff characters:
+ serial.XON
+ serial.XOFF
+
+Tips & Tricks
+-------------
+- Some protocols need CR LF ("\r\n") as line terminator, not just LF ("\n").
+ Telephone modems with the AT command set are an example of this behaviour.
+
+- Scanning for available serial ports is possible with more or less success on
+ some platforms. Look at the tools from Roger Binns:
+ http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/bitpim/comscan/
+
+- When packaging a project with py2exe, it will likely print a warning about
+ missing modules 'javax.comm'. This warning is uncritical as the module is
+ used in the Jython implementation that is not used but packaged.
+
+ It can be avoided with:
+ setup(...
+ options = {'py2exe': {'excludes': ['javax.comm']}})
+
+ See also setup_demo.py in the examples.
+
+
+References
+----------
+- Python: http://www.python.org
+- Jython: http://www.jython.org
+- win32all: http://starship.python.net/crew/mhammond/
+ and http://www.activestate.com/Products/ActivePython/win32all.html
+- Java@IBM http://www-106.ibm.com/developerworks/java/jdk/
+ (JavaComm links are on the download page for the respective platform jdk)
+- Java@SUN http://java.sun.com/products/
diff --git a/maximus/python/lib/proto/pyserial/examples/enhancedserial.py b/maximus/python/lib/proto/pyserial/examples/enhancedserial.py
new file mode 100644
index 0000000000..7ca8b6f40e
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/enhancedserial.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+"""Enhanced Serial Port class
+part of pyserial (http://pyserial.sf.net) (C)2002 cliechti@gmx.net
+
+another implementation of the readline and readlines method.
+this one should be more efficient because a bunch of characters are read
+on each access, but the drawback is that a timeout must be specified to
+make it work (enforced by the class __init__).
+
+this class could be enhanced with a read_until() method and more
+like found in the telnetlib.
+"""
+
+from serial import Serial
+
+class EnhancedSerial(Serial):
+ def __init__(self, *args, **kwargs):
+ #ensure that a reasonable timeout is set
+ timeout = kwargs.get('timeout',0.1)
+ if timeout < 0.01: timeout = 0.1
+ kwargs['timeout'] = timeout
+ Serial.__init__(self, *args, **kwargs)
+ self.buf = ''
+
+ def readline(self, maxsize=None, timeout=1):
+ """maxsize is ignored, timeout in seconds is the max time that is way for a complete line"""
+ tries = 0
+ while 1:
+ self.buf += self.read(512)
+ pos = self.buf.find('\n')
+ if pos >= 0:
+ line, self.buf = self.buf[:pos+1], self.buf[pos+1:]
+ return line
+ tries += 1
+ if tries * self.timeout > timeout:
+ break
+ line, self.buf = self.buf, ''
+ return line
+
+ def readlines(self, sizehint=None, timeout=1):
+ """read all lines that are available. abort after timout
+ when no more data arrives."""
+ lines = []
+ while 1:
+ line = self.readline(timeout=timeout)
+ if line:
+ lines.append(line)
+ if not line or line[-1:] != '\n':
+ break
+ return lines
+
+if __name__=='__main__':
+ #do some simple tests with a Loopback HW (see test.py for details)
+ PORT = 0
+ #test, only with Loopback HW (shortcut RX/TX pins (3+4 on DSUB 9 and 25) )
+ s = EnhancedSerial(PORT)
+ #write out some test data lines
+ s.write('\n'.join("hello how are you".split()))
+ #and read them back
+ print s.readlines()
+ #this one should print an empty list
+ print s.readlines(timeout=0.4)
diff --git a/maximus/python/lib/proto/pyserial/examples/miniterm.py b/maximus/python/lib/proto/pyserial/examples/miniterm.py
new file mode 100644
index 0000000000..345c0c42e3
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/miniterm.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+
+# Very simple serial terminal
+# (C)2002-2004 Chris Liechti <cliecht@gmx.net>
+
+# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
+# done), received characters are displayed as is (or as trough pythons
+# repr, useful for debug purposes)
+# Baudrate and echo configuartion is done through globals
+
+
+import sys, os, serial, threading, getopt
+
+EXITCHARCTER = '\x04' #ctrl+D
+
+#first choose a platform dependant way to read single characters from the console
+if os.name == 'nt':
+ import msvcrt
+ def getkey():
+ while 1:
+ if echo:
+ z = msvcrt.getche()
+ else:
+ z = msvcrt.getch()
+ if z == '\0' or z == '\xe0': #functions keys
+ msvcrt.getch()
+ else:
+ if z == '\r':
+ return '\n'
+ return z
+
+elif os.name == 'posix':
+ import termios, sys, os
+ fd = sys.stdin.fileno()
+ old = termios.tcgetattr(fd)
+ new = termios.tcgetattr(fd)
+ new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
+ new[6][termios.VMIN] = 1
+ new[6][termios.VTIME] = 0
+ termios.tcsetattr(fd, termios.TCSANOW, new)
+ s = '' # We'll save the characters typed and add them to the pool.
+ def getkey():
+ c = os.read(fd, 1)
+ #~ c = sys.stdin.read(1)
+ if echo: sys.stdout.write(c); sys.stdout.flush()
+ return c
+ def clenaup_console():
+ termios.tcsetattr(fd, termios.TCSAFLUSH, old)
+ sys.exitfunc = clenaup_console #terminal modes have to be restored on exit...
+
+else:
+ raise "Sorry no implementation for your platform (%s) available." % sys.platform
+
+CONVERT_CRLF = 2
+CONVERT_CR = 1
+CONVERT_LF = 0
+
+def reader():
+ """loop forever and copy serial->console"""
+ while 1:
+ data = s.read()
+ if repr_mode:
+ sys.stdout.write(repr(data)[1:-1])
+ else:
+ sys.stdout.write(data)
+ sys.stdout.flush()
+
+def writer():
+ """loop and copy console->serial until EOF character is found"""
+ while 1:
+ c = getkey()
+ if c == EXITCHARCTER:
+ break #exit app
+ elif c == '\n':
+ if convert_outgoing == CONVERT_CRLF:
+ s.write('\r\n') #make it a CR+LF
+ elif convert_outgoing == CONVERT_CR:
+ s.write('\r') #make it a CR
+ elif convert_outgoing == CONVERT_LF:
+ s.write('\n') #make it a LF
+ else:
+ s.write(c) #send character
+
+
+#print a short help message
+def usage():
+ sys.stderr.write("""USAGE: %s [options]
+ Miniterm - A simple terminal program for the serial port.
+
+ options:
+ -p, --port=PORT: port, a number, default = 0 or a device name
+ -b, --baud=BAUD: baudrate, default 9600
+ -r, --rtscts: enable RTS/CTS flow control (default off)
+ -x, --xonxoff: enable software flow control (default off)
+ -e, --echo: enable local echo (default off)
+ -c, --cr: do not send CR+LF, send CR only
+ -n, --newline: do not send CR+LF, send LF only
+ -D, --debug: debug received data (escape nonprintable chars)
+
+""" % (sys.argv[0], ))
+
+if __name__ == '__main__':
+ #initialize with defaults
+ port = 0
+ baudrate = 9600
+ echo = 0
+ convert_outgoing = CONVERT_CRLF
+ rtscts = 0
+ xonxoff = 0
+ repr_mode = 0
+
+ #parse command line options
+ try:
+ opts, args = getopt.getopt(sys.argv[1:],
+ "hp:b:rxecnD",
+ ["help", "port=", "baud=", "rtscts", "xonxoff", "echo",
+ "cr", "newline", "debug"]
+ )
+ except getopt.GetoptError:
+ # print help information and exit:
+ usage()
+ sys.exit(2)
+
+ for o, a in opts:
+ if o in ("-h", "--help"): #help text
+ usage()
+ sys.exit()
+ elif o in ("-p", "--port"): #specified port
+ try:
+ port = int(a)
+ except ValueError:
+ port = a
+ elif o in ("-b", "--baud"): #specified baudrate
+ try:
+ baudrate = int(a)
+ except ValueError:
+ raise ValueError, "Baudrate must be a integer number, not %r" % a
+ elif o in ("-r", "--rtscts"):
+ rtscts = 1
+ elif o in ("-x", "--xonxoff"):
+ xonxoff = 1
+ elif o in ("-e", "--echo"):
+ echo = 1
+ elif o in ("-c", "--cr"):
+ convert_outgoing = CONVERT_CR
+ elif o in ("-n", "--newline"):
+ convert_outgoing = CONVERT_LF
+ elif o in ("-D", "--debug"):
+ repr_mode = 1
+
+ #open the port
+ try:
+ s = serial.Serial(port, baudrate, rtscts=rtscts, xonxoff=xonxoff)
+ except:
+ sys.stderr.write("Could not open port\n")
+ sys.exit(1)
+ sys.stderr.write("--- Miniterm --- type Ctrl-D to quit\n")
+ #start serial->console thread
+ r = threading.Thread(target=reader)
+ r.setDaemon(1)
+ r.start()
+ #and enter console->serial loop
+ writer()
+
+ sys.stderr.write("\n--- exit ---\n")
diff --git a/maximus/python/lib/proto/pyserial/examples/scan.py b/maximus/python/lib/proto/pyserial/examples/scan.py
new file mode 100644
index 0000000000..ee0b92a337
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/scan.py
@@ -0,0 +1,27 @@
+#!/usr/bin/env python
+"""Scan for serial ports.
+Part of pySerial (http://pyserial.sf.net) (C)2002-2003 <cliechti@gmx.net>
+
+The scan function of this module tries to open each port number
+from 0 to 255 and it builds a list of those ports where this was
+successful.
+"""
+
+import serial
+
+def scan():
+ """scan for available ports. return a list of tuples (num, name)"""
+ available = []
+ for i in range(256):
+ try:
+ s = serial.Serial(i)
+ available.append( (i, s.portstr))
+ s.close() #explicit close 'cause of delayed GC in java
+ except serial.SerialException:
+ pass
+ return available
+
+if __name__=='__main__':
+ print "Found ports:"
+ for n,s in scan():
+ print "(%d) %s" % (n,s)
diff --git a/maximus/python/lib/proto/pyserial/examples/setup_demo.py b/maximus/python/lib/proto/pyserial/examples/setup_demo.py
new file mode 100644
index 0000000000..34c8c122e0
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/setup_demo.py
@@ -0,0 +1,35 @@
+# This is a setup.py example script for the use with py2exe
+from distutils.core import setup
+import py2exe
+import sys, os
+
+#this script is only useful for py2exe so just run that distutils command.
+#that allows to run it with a simple double click.
+sys.argv.append('py2exe')
+
+#get an icon from somewhere.. the python installation should have one:
+icon = os.path.join(os.path.dirname(sys.executable), 'py.ico')
+
+setup(
+ options = {'py2exe': {
+ 'excludes': ['javax.comm'],
+ 'optimize': 2,
+ 'dist_dir': 'dist',
+ }
+ },
+
+ name = "wxTerminal",
+ windows = [
+ {
+ 'script': "wxTerminal.py",
+ 'icon_resources': [(0x0004, icon)]
+ },
+ ],
+ zipfile = "stuff.lib",
+
+ description = "Simple serial terminal application",
+ version = "0.1",
+ author = "Chris Liechti",
+ author_email = "cliechti@gmx.net",
+ url = "http://pyserial.sf.net",
+)
diff --git a/maximus/python/lib/proto/pyserial/examples/tcp_serial_redirect.py b/maximus/python/lib/proto/pyserial/examples/tcp_serial_redirect.py
new file mode 100644
index 0000000000..771f3c268e
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/tcp_serial_redirect.py
@@ -0,0 +1,150 @@
+#!/usr/bin/env python
+
+#(C)2002-2003 Chris Liechti <cliechti@gmx.net>
+#redirect data from a TCP/IP connection to a serial port and vice versa
+#requires Python 2.2 'cause socket.sendall is used
+
+"""USAGE: tcp_serial_redirect.py [options]
+Simple Serial to Network (TCP/IP) redirector.
+
+Options:
+ -p, --port=PORT serial port, a number, defualt = 0 or a device name
+ -b, --baud=BAUD baudrate, default 9600
+ -r, --rtscts enable RTS/CTS flow control (default off)
+ -x, --xonxoff enable software flow control (default off)
+ -P, --localport TCP/IP port on which to run the server (default 7777)
+
+Note: no security measures are implemeted. Anyone can remotely connect
+to this service over the network.
+Only one connection at once is supported. If the connection is terminaed
+it waits for the next connect.
+"""
+
+import sys, os, serial, threading, getopt, socket
+
+try:
+ True
+except NameError:
+ True = 1
+ False = 0
+
+class Redirector:
+ def __init__(self, serial, socket):
+ self.serial = serial
+ self.socket = socket
+
+ def shortcut(self):
+ """connect the serial port to the tcp port by copying everything
+ from one side to the other"""
+ self.alive = True
+ self.thread_read = threading.Thread(target=self.reader)
+ self.thread_read.setDaemon(1)
+ self.thread_read.start()
+ self.writer()
+
+ def reader(self):
+ """loop forever and copy serial->socket"""
+ while self.alive:
+ try:
+ data = self.serial.read(1) #read one, blocking
+ n = self.serial.inWaiting() #look if there is more
+ if n:
+ data = data + self.serial.read(n) #and get as much as possible
+ if data:
+ self.socket.sendall(data) #send it over TCP
+ except socket.error, msg:
+ print msg
+ #probably got disconnected
+ break
+ self.alive = False
+
+ def writer(self):
+ """loop forever and copy socket->serial"""
+ while self.alive:
+ try:
+ data = self.socket.recv(1024)
+ if not data:
+ break
+ self.serial.write(data) #get a bunch of bytes and send them
+ except socket.error, msg:
+ print msg
+ #probably got disconnected
+ break
+ self.alive = False
+ self.thread_read.join()
+
+ def stop(self):
+ """Stop copying"""
+ if self.alive:
+ self.alive = False
+ self.thread_read.join()
+
+if __name__ == '__main__':
+ ser = serial.Serial()
+
+ #parse command line options
+ try:
+ opts, args = getopt.getopt(sys.argv[1:],
+ "hp:b:rxP",
+ ["help", "port=", "baud=", "rtscts", "xonxoff", "localport="])
+ except getopt.GetoptError:
+ # print help information and exit:
+ print >>sys.stderr, __doc__
+ sys.exit(2)
+
+ ser.port = 0
+ ser.baudrate = 9600
+ ser.rtscts = False
+ ser.xonxoff = False
+ ser.timeout = 1 #required so that the reader thread can exit
+
+ localport = 7777
+ for o, a in opts:
+ if o in ("-h", "--help"): #help text
+ usage()
+ sys.exit()
+ elif o in ("-p", "--port"): #specified port
+ try:
+ ser.port = int(a)
+ except ValueError:
+ ser.port = a
+ elif o in ("-b", "--baud"): #specified baudrate
+ try:
+ ser.baudrate = int(a)
+ except ValueError:
+ raise ValueError, "Baudrate must be a integer number"
+ elif o in ("-r", "--rtscts"):
+ ser.rtscts = True
+ elif o in ("-x", "--xonxoff"):
+ ser.xonxoff = True
+ elif o in ("-P", "--localport"):
+ try:
+ localport = int(a)
+ except ValueError:
+ raise ValueError, "Local port must be an integer number"
+
+ print "--- TCP/IP to Serial redirector --- type Ctrl-C / BREAK to quit"
+
+ try:
+ ser.open()
+ except serial.SerialException, e:
+ print "Could not open serial port %s: %s" % (ser.portstr, e)
+ sys.exit(1)
+
+ srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ srv.bind( ('', localport) )
+ srv.listen(1)
+ while 1:
+ try:
+ print "Waiting for connection..."
+ connection, addr = srv.accept()
+ print 'Connected by', addr
+ #enter console->serial loop
+ r = Redirector(ser, connection)
+ r.shortcut()
+ print 'Disconnected'
+ connection.close()
+ except socket.error, msg:
+ print msg
+
+ print "\n--- exit ---"
diff --git a/maximus/python/lib/proto/pyserial/examples/test.py b/maximus/python/lib/proto/pyserial/examples/test.py
new file mode 100644
index 0000000000..ab3f830b52
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/test.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python
+#Python Serial Port Extension for Win32, Linux, BSD, Jython
+#see __init__.py
+#
+#(C) 2001-2003 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+"""Some tests for the serial module.
+Part of pyserial (http://pyserial.sf.net) (C)2002-2003 cliechti@gmx.net
+
+Intended to be run on different platforms, to ensure portability of
+the code.
+
+For all these tests a simple hardware is required.
+Loopback HW adapter:
+Shortcut these pin pairs:
+ TX <-> RX
+ RTS <-> CTS
+ DTR <-> DSR
+
+On a 9 pole DSUB these are the pins (2-3) (4-6) (7-8)
+"""
+
+import unittest, threading, time
+import serial
+
+#on which port should the tests be performed:
+PORT=0
+
+
+class Test4_Nonblocking(unittest.TestCase):
+ """Test with timeouts"""
+ timeout=0
+ def setUp(self):
+ self.s = serial.Serial(PORT,timeout=self.timeout)
+ def tearDown(self):
+ self.s.close()
+
+ def test0_Messy(self):
+ """NonBlocking (timeout=0)"""
+ #this is only here to write out the message in verbose mode
+ #because Test3 and Test4 print the same messages
+
+ def test1_ReadEmpty(self):
+ """timeout: After port open, the input buffer must be empty"""
+ self.failUnless(self.s.read(1)=='', "expected empty buffer")
+ def test2_Loopback(self):
+ """timeout: each sent character should return (binary test).
+ this is also a test for the binary capability of a port."""
+ for c in map(chr,range(256)):
+ self.s.write(c)
+ time.sleep(0.02) #there might be a small delay until the character is ready (especialy on win32)
+ self.failUnless(self.s.inWaiting()==1, "expected exactly one character for inWainting()")
+ self.failUnless(self.s.read(1)==c, "expected a '%s' which was written before" % c)
+ self.failUnless(self.s.read(1)=='', "expected empty buffer after all sent chars are read")
+ def test2_LoopbackTimeout(self):
+ """timeout: test the timeout/immediate return.
+ partial results should be returned."""
+ self.s.write("HELLO")
+ time.sleep(0.02) #there might be a small delay until the character is ready (especialy on win32)
+ #read more characters as are available to run in the timeout
+ self.failUnless(self.s.read(10)=='HELLO', "expected an 'HELLO' which was written before")
+ self.failUnless(self.s.read(1)=='', "expected empty buffer after all sent chars are read")
+
+
+class Test3_Timeout(Test4_Nonblocking):
+ """Same tests as the NonBlocking ones but this time with timeout"""
+ timeout=1
+ def test0_Messy(self):
+ """Blocking (timeout=1)"""
+ #this is only here to write out the message in verbose mode
+ #because Test3 and Test4 print the same messages
+
+class SendEvent(threading.Thread):
+ def __init__(self, serial, delay=1):
+ threading.Thread.__init__(self)
+ self.serial = serial
+ self.delay = delay
+ self.x = threading.Event()
+ self.stopped = 0
+ self.start()
+ def run(self):
+ time.sleep(self.delay)
+ if not self.stopped:
+ self.serial.write("E")
+ self.x.set()
+ def isSet(self):
+ return self.x.isSet()
+ def stop(self):
+ self.stopped = 1
+ self.x.wait()
+
+class Test1_Forever(unittest.TestCase):
+ """Tests a port with no timeout. These tests require that a
+ character is sent after some time to stop the test, this is done
+ through the SendEvent class and the Loopback HW."""
+ def setUp(self):
+ self.s = serial.Serial(PORT, timeout=None)
+ self.event = SendEvent(self.s)
+ def tearDown(self):
+ self.event.stop()
+ self.s.close()
+
+ def test2_ReadEmpty(self):
+ """no timeout: after port open, the input buffer must be empty (read).
+ a character is sent after some time to terminate the test (SendEvent)."""
+ c = self.s.read(1)
+ if not (self.event.isSet() and c == 'E'):
+ self.fail("expected marker")
+
+class Test2_Forever(unittest.TestCase):
+ """Tests a port with no timeout"""
+ def setUp(self):
+ self.s = serial.Serial(PORT,timeout=None)
+ def tearDown(self):
+ self.s.close()
+
+ def test1_inWaitingEmpty(self):
+ """no timeout: after port open, the input buffer must be empty (inWaiting)"""
+ self.failUnless(self.s.inWaiting()==0, "expected empty buffer")
+
+ def test2_Loopback(self):
+ """no timeout: each sent character should return (binary test).
+ this is also a test for the binary capability of a port."""
+ for c in map(chr,range(256)):
+ self.s.write(c)
+ time.sleep(0.02) #there might be a small delay until the character is ready (especialy on win32)
+ self.failUnless(self.s.inWaiting()==1, "expected exactly one character for inWainting()")
+ self.failUnless(self.s.read(1)==c, "expected an '%s' which was written before" % c)
+ self.failUnless(self.s.inWaiting()==0, "expected empty buffer after all sent chars are read")
+
+
+class Test0_DataWires(unittest.TestCase):
+ """Test modem control lines"""
+ def setUp(self):
+ self.s = serial.Serial(PORT)
+ def tearDown(self):
+ self.s.close()
+
+ def test1_RTS(self):
+ """Test RTS/CTS"""
+ self.s.setRTS(0)
+ self.failUnless(self.s.getCTS()==0, "CTS -> 0")
+ self.s.setRTS(1)
+ self.failUnless(self.s.getCTS()==1, "CTS -> 1")
+
+ def test2_DTR(self):
+ """Test DTR/DSR"""
+ self.s.setDTR(0)
+ self.failUnless(self.s.getDSR()==0, "DSR -> 0")
+ self.s.setDTR(1)
+ self.failUnless(self.s.getDSR()==1, "DSR -> 1")
+
+ def test3_RI(self):
+ """Test RI"""
+ self.failUnless(self.s.getRI()==0, "RI -> 0")
+
+class Test_MoreTimeouts(unittest.TestCase):
+ """Test with timeouts"""
+ def setUp(self):
+ self.s = serial.Serial() #create an closed serial port
+
+ def tearDown(self):
+ self.s.close()
+
+ def test_WriteTimeout(self):
+ """Test write() timeout."""
+ #use xonxoff setting and the loopback adapter to switch traffic on hold
+ self.s.port = PORT
+ self.s.writeTimeout = 1
+ self.s.xonxoff = 1
+ self.s.open()
+ self.s.write(serial.XOFF)
+ time.sleep(0.1) #some systems need a little delay so that they can react on XOFF
+ t1 = time.time()
+ self.failUnlessRaises(serial.SerialTimeoutException, self.s.write, "timeout please"*100)
+ t2 = time.time()
+ self.failUnless( 1 <= (t2-t1) < 2, "Timeout not in the given intervall (%s)" % (t2-t1))
+
+if __name__ == '__main__':
+ import sys
+ print __doc__
+ print "Testing port", PORT
+ sys.argv.append('-v')
+ # When this module is executed from the command-line, it runs all its tests
+ unittest.main()
diff --git a/maximus/python/lib/proto/pyserial/examples/test_advanced.py b/maximus/python/lib/proto/pyserial/examples/test_advanced.py
new file mode 100644
index 0000000000..980d29005f
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/test_advanced.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python
+#needs at least python 2.2.3
+
+#Python Serial Port Extension for Win32, Linux, BSD, Jython
+#see __init__.py
+#
+#(C) 2001-2003 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+"""Some tests for the serial module.
+Part of pyserial (http://pyserial.sf.net) (C)2002 cliechti@gmx.net
+
+Intended to be run on different platforms, to ensure portability of
+the code.
+
+These tests open a serial port and change all the settings on the fly.
+If the port is realy correctly configured cannot be determined - that
+would require external hardware or a nullmodem cable and an other
+serial port library... Thus it mainly tests that all features are
+correctly implemented and that the interface does what it should.
+"""
+
+import unittest
+import serial
+
+#on which port should the tests be performed:
+PORT=0
+
+class Test_ChangeAttributes(unittest.TestCase):
+ """Test with timeouts"""
+
+ def setUp(self):
+ self.s = serial.Serial() #create an closed serial port
+
+ def tearDown(self):
+ self.s.close()
+
+ def test_PortSetting(self):
+ self.s.port = PORT
+ #portstr has to be set
+ self.failUnlessEqual(self.s.portstr, serial.device(PORT))
+ #test internals
+ self.failUnlessEqual(self.s._port, PORT)
+ #test on the fly change
+ self.s.open()
+ self.failUnless(self.s.isOpen())
+ self.s.port = 0
+ self.failUnless(self.s.isOpen())
+ self.failUnlessEqual(self.s.port, 0)
+ self.failUnlessEqual(self.s.portstr, serial.device(0))
+ try:
+ self.s.port = 1
+ except serial.SerialException: #port not available on system
+ pass #cant test on this machine...
+ else:
+ self.failUnless(self.s.isOpen())
+ self.failUnlessEqual(self.s.port, 1)
+ self.failUnlessEqual(self.s.portstr, serial.device(1))
+
+ def test_BaudrateSetting(self):
+ self.s.port = PORT
+ self.s.open()
+ for baudrate in (300, 9600, 19200, 115200):
+ self.s.baudrate = baudrate
+ #test get method
+ self.failUnlessEqual(self.s.baudrate, baudrate)
+ #test internals
+ self.failUnlessEqual(self.s._baudrate, baudrate)
+ #test illegal values
+ for illegal_value in (-300, -1, 'a', None):
+ self.failUnlessRaises(ValueError, self.s.setBaudrate, illegal_value)
+
+ def test_BaudrateSetting2(self):
+ #test illegal values, depending on machine/port some of these may be valid...
+ self.s.port = PORT
+ self.s.open()
+ for illegal_value in (500000,576000,921600,92160):
+ self.failUnlessRaises(ValueError, self.s.setBaudrate, illegal_value)
+
+ def test_BytesizeSetting(self):
+ for bytesize in (5,6,7,8):
+ self.s.bytesize = bytesize
+ #test get method
+ self.failUnlessEqual(self.s.bytesize, bytesize)
+ #test internals
+ self.failUnlessEqual(self.s._bytesize, bytesize)
+ #test illegal values
+ for illegal_value in (0, 1, 3, 4, 9, 10, 'a', None):
+ self.failUnlessRaises(ValueError, self.s.setByteSize, illegal_value)
+
+ def test_ParitySetting(self):
+ for parity in (serial.PARITY_NONE, serial.PARITY_EVEN, serial.PARITY_ODD):
+ self.s.parity = parity
+ #test get method
+ self.failUnlessEqual(self.s.parity, parity)
+ #test internals
+ self.failUnlessEqual(self.s._parity, parity)
+ #test illegal values
+ for illegal_value in (0, 57, 'a', None):
+ self.failUnlessRaises(ValueError, self.s.setParity, illegal_value)
+
+ def test_StopbitsSetting(self):
+ for stopbits in (1, 2):
+ self.s.stopbits = stopbits
+ #test get method
+ self.failUnlessEqual(self.s.stopbits, stopbits)
+ #test internals
+ self.failUnlessEqual(self.s._stopbits, stopbits)
+ #test illegal values
+ for illegal_value in (0, 3, 1.5, 57, 'a', None):
+ self.failUnlessRaises(ValueError, self.s.setStopbits, illegal_value)
+
+ def test_TimeoutSetting(self):
+ for timeout in (None, 0, 1, 3.14159, 10, 1000, 3600):
+ self.s.timeout = timeout
+ #test get method
+ self.failUnlessEqual(self.s.timeout, timeout)
+ #test internals
+ self.failUnlessEqual(self.s._timeout, timeout)
+ #test illegal values
+ for illegal_value in (-1, 'a'):
+ self.failUnlessRaises(ValueError, self.s.setTimeout, illegal_value)
+
+ def test_XonXoffSetting(self):
+ for xonxoff in (True, False):
+ self.s.xonxoff = xonxoff
+ #test get method
+ self.failUnlessEqual(self.s.xonxoff, xonxoff)
+ #test internals
+ self.failUnlessEqual(self.s._xonxoff, xonxoff)
+ #no illegal values here, normal rules for the boolean value of an
+ #object are used thus all objects have a truth value.
+
+ def test_RtsCtsSetting(self):
+ for rtscts in (True, False):
+ self.s.rtscts = rtscts
+ #test get method
+ self.failUnlessEqual(self.s.rtscts, rtscts)
+ #test internals
+ self.failUnlessEqual(self.s._rtscts, rtscts)
+ #no illegal values here, normal rules for the boolean value of an
+ #object are used thus all objects have a truth value.
+
+ def test_UnconfiguredPort(self):
+ #an unconfigured port cannot be opened
+ self.failUnlessRaises(serial.SerialException, self.s.open)
+
+ def test_PortOpenClose(self):
+ self.s.port = PORT
+ for i in range(3):
+ #open the port and check flag
+ self.failUnless(not self.s.isOpen())
+ self.s.open()
+ self.failUnless(self.s.isOpen())
+ self.s.close()
+ self.failUnless(not self.s.isOpen())
+
+if __name__ == '__main__':
+ import sys
+ print __doc__
+ print "Testing port", PORT
+ sys.argv.append('-v')
+ # When this module is executed from the command-line, it runs all its tests
+ unittest.main()
diff --git a/maximus/python/lib/proto/pyserial/examples/test_high_load.py b/maximus/python/lib/proto/pyserial/examples/test_high_load.py
new file mode 100644
index 0000000000..ce884b32b3
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/test_high_load.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+#Python Serial Port Extension for Win32, Linux, BSD, Jython
+#see __init__.py
+#
+#(C) 2001-2003 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+"""Some tests for the serial module.
+Part of pyserial (http://pyserial.sf.net) (C)2002-2003 cliechti@gmx.net
+
+Intended to be run on different platforms, to ensure portability of
+the code.
+
+For all these tests a simple hardware is required.
+Loopback HW adapter:
+Shortcut these pin pairs:
+ TX <-> RX
+ RTS <-> CTS
+ DTR <-> DSR
+
+On a 9 pole DSUB these are the pins (2-3) (4-6) (7-8)
+"""
+
+import unittest, threading, time
+import serial
+
+#on which port should the tests be performed:
+PORT=0
+BAUDRATE=115200
+#~ BAUDRATE=9600
+
+
+class TestHighLoad(unittest.TestCase):
+ """Test sending and receiving large amount of data"""
+
+ N = 16
+ #~ N = 1
+
+ def setUp(self):
+ self.s = serial.Serial(PORT,BAUDRATE, timeout=10)
+ def tearDown(self):
+ self.s.close()
+
+ def test0_WriteReadLoopback(self):
+ """Send big strings, write/read order."""
+ for i in range(self.N):
+ q = ''.join(map(chr,range(256)))
+ self.s.write(q)
+ self.failUnless(self.s.read(len(q))==q, "expected a '%s' which was written before" % q)
+ self.failUnless(self.s.inWaiting()==0, "expected empty buffer after all sent chars are read")
+
+ def test1_WriteWriteReadLoopback(self):
+ """Send big strings, multiple write one read."""
+ q = ''.join(map(chr,range(256)))
+ for i in range(self.N):
+ self.s.write(q)
+ read = self.s.read(len(q)*self.N)
+ self.failUnless(read==q*self.N, "expected what was written before. got %d bytes, expected %d" % (len(read), self.N*len(q)))
+ self.failUnless(self.s.inWaiting()==0, "expected empty buffer after all sent chars are read")
+
+if __name__ == '__main__':
+ import sys
+ print __doc__
+ print "Testing port", PORT
+ sys.argv.append('-v')
+ # When this module is executed from the command-line, it runs all its tests
+ unittest.main()
diff --git a/maximus/python/lib/proto/pyserial/examples/wxSerialConfigDialog.py b/maximus/python/lib/proto/pyserial/examples/wxSerialConfigDialog.py
new file mode 100644
index 0000000000..57436ceae2
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/wxSerialConfigDialog.py
@@ -0,0 +1,259 @@
+#!/usr/bin/env python
+# generated by wxGlade 0.3.1 on Thu Oct 02 23:25:44 2003
+
+from wxPython.wx import *
+import serial
+
+SHOW_BAUDRATE = 1<<0
+SHOW_FORMAT = 1<<1
+SHOW_FLOW = 1<<2
+SHOW_TIMEOUT = 1<<3
+SHOW_ALL = SHOW_BAUDRATE|SHOW_FORMAT|SHOW_FLOW|SHOW_TIMEOUT
+
+try:
+ enumerate
+except NameError:
+ def enumerate(sequence):
+ return zip(range(len(sequence)), sequence)
+
+class SerialConfigDialog(wxDialog):
+ """Serial Port confiuration dialog, to be used with pyserial 2.0+
+ When instantiating a class of this dialog, then the "serial" keyword
+ argument is mandatory. It is a reference to a serial.Serial instance.
+ the optional "show" keyword argument can be used to show/hide different
+ settings. The default is SHOW_ALL which coresponds to
+ SHOW_BAUDRATE|SHOW_FORMAT|SHOW_FLOW|SHOW_TIMEOUT. All constants can be
+ found in ths module (not the class)."""
+
+ def __init__(self, *args, **kwds):
+ #grab the serial keyword and remove it from the dict
+ self.serial = kwds['serial']
+ del kwds['serial']
+ self.show = SHOW_ALL
+ if kwds.has_key('show'):
+ self.show = kwds['show']
+ del kwds['show']
+ # begin wxGlade: SerialConfigDialog.__init__
+ # end wxGlade
+ kwds["style"] = wxDEFAULT_DIALOG_STYLE
+ wxDialog.__init__(self, *args, **kwds)
+ self.label_2 = wxStaticText(self, -1, "Port")
+ self.combo_box_port = wxComboBox(self, -1, choices=["dummy1", "dummy2", "dummy3", "dummy4", "dummy5"], style=wxCB_DROPDOWN)
+ if self.show & SHOW_BAUDRATE:
+ self.label_1 = wxStaticText(self, -1, "Baudrate")
+ self.choice_baudrate = wxChoice(self, -1, choices=["choice 1"])
+ if self.show & SHOW_FORMAT:
+ self.label_3 = wxStaticText(self, -1, "Data Bits")
+ self.choice_databits = wxChoice(self, -1, choices=["choice 1"])
+ self.label_4 = wxStaticText(self, -1, "Stop Bits")
+ self.choice_stopbits = wxChoice(self, -1, choices=["choice 1"])
+ self.label_5 = wxStaticText(self, -1, "Parity")
+ self.choice_parity = wxChoice(self, -1, choices=["choice 1"])
+ if self.show & SHOW_TIMEOUT:
+ self.checkbox_timeout = wxCheckBox(self, -1, "Use Timeout")
+ self.text_ctrl_timeout = wxTextCtrl(self, -1, "")
+ self.label_6 = wxStaticText(self, -1, "seconds")
+ if self.show & SHOW_FLOW:
+ self.checkbox_rtscts = wxCheckBox(self, -1, "RTS/CTS")
+ self.checkbox_xonxoff = wxCheckBox(self, -1, "Xon/Xoff")
+ self.button_ok = wxButton(self, -1, "OK")
+ self.button_cancel = wxButton(self, -1, "Cancel")
+
+ self.__set_properties()
+ self.__do_layout()
+ #fill in ports and select current setting
+ index = 0
+ self.combo_box_port.Clear()
+ for n in range(4):
+ portname = serial.device(n)
+ self.combo_box_port.Append(portname)
+ if self.serial.portstr == portname:
+ index = n
+ if self.serial.portstr is not None:
+ self.combo_box_port.SetValue(str(self.serial.portstr))
+ else:
+ self.combo_box_port.SetSelection(index)
+ if self.show & SHOW_BAUDRATE:
+ #fill in badrates and select current setting
+ self.choice_baudrate.Clear()
+ for n, baudrate in enumerate(self.serial.BAUDRATES):
+ self.choice_baudrate.Append(str(baudrate))
+ if self.serial.baudrate == baudrate:
+ index = n
+ self.choice_baudrate.SetSelection(index)
+ if self.show & SHOW_FORMAT:
+ #fill in databits and select current setting
+ self.choice_databits.Clear()
+ for n, bytesize in enumerate(self.serial.BYTESIZES):
+ self.choice_databits.Append(str(bytesize))
+ if self.serial.bytesize == bytesize:
+ index = n
+ self.choice_databits.SetSelection(index)
+ #fill in stopbits and select current setting
+ self.choice_stopbits.Clear()
+ for n, stopbits in enumerate(self.serial.STOPBITS):
+ self.choice_stopbits.Append(str(stopbits))
+ if self.serial.stopbits == stopbits:
+ index = n
+ self.choice_stopbits.SetSelection(index)
+ #fill in parities and select current setting
+ self.choice_parity.Clear()
+ for n, parity in enumerate(self.serial.PARITIES):
+ self.choice_parity.Append(str(serial.PARITY_NAMES[parity]))
+ if self.serial.parity == parity:
+ index = n
+ self.choice_parity.SetSelection(index)
+ if self.show & SHOW_TIMEOUT:
+ #set the timeout mode and value
+ if self.serial.timeout is None:
+ self.checkbox_timeout.SetValue(False)
+ self.text_ctrl_timeout.Enable(False)
+ else:
+ self.checkbox_timeout.SetValue(True)
+ self.text_ctrl_timeout.Enable(True)
+ self.text_ctrl_timeout.SetValue(str(self.serial.timeout))
+ if self.show & SHOW_FLOW:
+ #set the rtscts mode
+ self.checkbox_rtscts.SetValue(self.serial.rtscts)
+ #set the rtscts mode
+ self.checkbox_xonxoff.SetValue(self.serial.xonxoff)
+ #attach the event handlers
+ self.__attach_events()
+
+ def __set_properties(self):
+ # begin wxGlade: SerialConfigDialog.__set_properties
+ # end wxGlade
+ self.SetTitle("Serial Port Configuration")
+ if self.show & SHOW_TIMEOUT:
+ self.text_ctrl_timeout.Enable(0)
+ self.button_ok.SetDefault()
+
+ def __do_layout(self):
+ # begin wxGlade: SerialConfigDialog.__do_layout
+ # end wxGlade
+ sizer_2 = wxBoxSizer(wxVERTICAL)
+ sizer_3 = wxBoxSizer(wxHORIZONTAL)
+ sizer_basics = wxStaticBoxSizer(wxStaticBox(self, -1, "Basics"), wxVERTICAL)
+ sizer_5 = wxBoxSizer(wxHORIZONTAL)
+ sizer_5.Add(self.label_2, 1, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_5.Add(self.combo_box_port, 1, 0, 0)
+ sizer_basics.Add(sizer_5, 0, wxRIGHT|wxEXPAND, 0)
+ if self.show & SHOW_BAUDRATE:
+ sizer_baudrate = wxBoxSizer(wxHORIZONTAL)
+ sizer_baudrate.Add(self.label_1, 1, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_baudrate.Add(self.choice_baudrate, 1, wxALIGN_RIGHT, 0)
+ sizer_basics.Add(sizer_baudrate, 0, wxEXPAND, 0)
+ sizer_2.Add(sizer_basics, 0, wxEXPAND, 0)
+ if self.show & SHOW_FORMAT:
+ sizer_8 = wxBoxSizer(wxHORIZONTAL)
+ sizer_7 = wxBoxSizer(wxHORIZONTAL)
+ sizer_6 = wxBoxSizer(wxHORIZONTAL)
+ sizer_format = wxStaticBoxSizer(wxStaticBox(self, -1, "Data Format"), wxVERTICAL)
+ sizer_6.Add(self.label_3, 1, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_6.Add(self.choice_databits, 1, wxALIGN_RIGHT, 0)
+ sizer_format.Add(sizer_6, 0, wxEXPAND, 0)
+ sizer_7.Add(self.label_4, 1, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_7.Add(self.choice_stopbits, 1, wxALIGN_RIGHT, 0)
+ sizer_format.Add(sizer_7, 0, wxEXPAND, 0)
+ sizer_8.Add(self.label_5, 1, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_8.Add(self.choice_parity, 1, wxALIGN_RIGHT, 0)
+ sizer_format.Add(sizer_8, 0, wxEXPAND, 0)
+ sizer_2.Add(sizer_format, 0, wxEXPAND, 0)
+ if self.show & SHOW_TIMEOUT:
+ sizer_timeout = wxStaticBoxSizer(wxStaticBox(self, -1, "Timeout"), wxHORIZONTAL)
+ sizer_timeout.Add(self.checkbox_timeout, 0, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_timeout.Add(self.text_ctrl_timeout, 0, 0, 0)
+ sizer_timeout.Add(self.label_6, 0, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_2.Add(sizer_timeout, 0, 0, 0)
+ if self.show & SHOW_FLOW:
+ sizer_flow = wxStaticBoxSizer(wxStaticBox(self, -1, "Flow Control"), wxHORIZONTAL)
+ sizer_flow.Add(self.checkbox_rtscts, 0, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_flow.Add(self.checkbox_xonxoff, 0, wxALL|wxALIGN_CENTER_VERTICAL, 4)
+ sizer_flow.Add((10,10), 1, wxEXPAND, 0)
+ sizer_2.Add(sizer_flow, 0, wxEXPAND, 0)
+ sizer_3.Add(self.button_ok, 0, 0, 0)
+ sizer_3.Add(self.button_cancel, 0, 0, 0)
+ sizer_2.Add(sizer_3, 0, wxALL|wxALIGN_RIGHT, 4)
+ self.SetAutoLayout(1)
+ self.SetSizer(sizer_2)
+ sizer_2.Fit(self)
+ sizer_2.SetSizeHints(self)
+ self.Layout()
+
+ def __attach_events(self):
+ EVT_BUTTON(self, self.button_ok.GetId(), self.OnOK)
+ EVT_BUTTON(self, self.button_cancel.GetId(), self.OnCancel)
+ if self.show & SHOW_TIMEOUT:
+ EVT_CHECKBOX(self, self.checkbox_timeout.GetId(), self.OnTimeout)
+
+ def OnOK(self, events):
+ success = True
+ self.serial.port = str(self.combo_box_port.GetValue())
+ if self.show & SHOW_BAUDRATE:
+ self.serial.baudrate = self.serial.BAUDRATES[self.choice_baudrate.GetSelection()]
+ if self.show & SHOW_FORMAT:
+ self.serial.bytesize = self.serial.BYTESIZES[self.choice_databits.GetSelection()]
+ self.serial.stopbits = self.serial.STOPBITS[self.choice_stopbits.GetSelection()]
+ self.serial.parity = self.serial.PARITIES[self.choice_parity.GetSelection()]
+ if self.show & SHOW_FLOW:
+ self.serial.rtscts = self.checkbox_rtscts.GetValue()
+ self.serial.xonxoff = self.checkbox_xonxoff.GetValue()
+ if self.show & SHOW_TIMEOUT:
+ if self.checkbox_timeout.GetValue():
+ try:
+ self.serial.timeout = float(self.text_ctrl_timeout.GetValue())
+ except ValueError:
+ dlg = wxMessageDialog(self, 'Timeout must be a numeric value',
+ 'Value Error', wxOK | wxICON_ERROR)
+ dlg.ShowModal()
+ dlg.Destroy()
+ success = False
+ else:
+ self.serial.timeout = None
+ if success:
+ self.EndModal(wxID_OK)
+
+ def OnCancel(self, events):
+ self.EndModal(wxID_CANCEL)
+
+ def OnTimeout(self, events):
+ if self.checkbox_timeout.GetValue():
+ self.text_ctrl_timeout.Enable(True)
+ else:
+ self.text_ctrl_timeout.Enable(False)
+
+# end of class SerialConfigDialog
+
+
+class MyApp(wxApp):
+ """Test code"""
+ def OnInit(self):
+ wxInitAllImageHandlers()
+
+ ser = serial.Serial()
+ print ser
+ #loop until cancel is pressed, old values are used as start for the next run
+ #show the different views, one after the other
+ #value are kept.
+ for flags in (SHOW_BAUDRATE, SHOW_FLOW, SHOW_FORMAT, SHOW_TIMEOUT, SHOW_ALL):
+ dialog_serial_cfg = SerialConfigDialog(None, -1, "", serial=ser, show=flags)
+ self.SetTopWindow(dialog_serial_cfg)
+ result = dialog_serial_cfg.ShowModal()
+ print ser
+ if result != wxID_OK:
+ break
+ #the user can play around with the values, CANCEL aborts the loop
+ while 1:
+ dialog_serial_cfg = SerialConfigDialog(None, -1, "", serial=ser)
+ self.SetTopWindow(dialog_serial_cfg)
+ result = dialog_serial_cfg.ShowModal()
+ print ser
+ if result != wxID_OK:
+ break
+ return 0
+
+# end of class MyApp
+
+if __name__ == "__main__":
+ app = MyApp(0)
+ app.MainLoop()
diff --git a/maximus/python/lib/proto/pyserial/examples/wxSerialConfigDialog.wxg b/maximus/python/lib/proto/pyserial/examples/wxSerialConfigDialog.wxg
new file mode 100644
index 0000000000..8888611195
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/wxSerialConfigDialog.wxg
@@ -0,0 +1,262 @@
+<?xml version="1.0"?>
+<!-- generated by wxGlade 0.3.1 on Fri Oct 03 01:53:04 2003 -->
+
+<application path="D:\prog\python\pyserial_sf\pyserial\examples\wxSerialConfigDialog.py" name="app" class="MyApp" option="0" language="python" top_window="dialog_serial_cfg" encoding="ISO-8859-1" use_gettext="0" overwrite="0">
+ <object class="SerialConfigDialog" name="dialog_serial_cfg" base="EditDialog">
+ <style>wxDEFAULT_DIALOG_STYLE</style>
+ <title>Serial Port Configuration</title>
+ <object class="wxBoxSizer" name="sizer_2" base="EditBoxSizer">
+ <orient>wxVERTICAL</orient>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxStaticBoxSizer" name="sizer_basics" base="EditStaticBoxSizer">
+ <orient>wxVERTICAL</orient>
+ <label>Basics</label>
+ <object class="sizeritem">
+ <flag>wxRIGHT|wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxBoxSizer" name="sizer_5" base="EditBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>1</option>
+ <object class="wxStaticText" name="label_2" base="EditStaticText">
+ <attribute>1</attribute>
+ <label>Port</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <border>0</border>
+ <option>1</option>
+ <object class="wxComboBox" name="combo_box_port" base="EditComboBox">
+ <selection>0</selection>
+ <choices>
+ <choice>dummy1</choice>
+ <choice>dummy2</choice>
+ <choice>dummy3</choice>
+ <choice>dummy4</choice>
+ <choice>dummy5</choice>
+ </choices>
+ </object>
+ </object>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxBoxSizer" name="sizer_baudrate" base="EditBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>1</option>
+ <object class="wxStaticText" name="label_1" base="EditStaticText">
+ <attribute>1</attribute>
+ <label>Baudrate</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALIGN_RIGHT</flag>
+ <border>0</border>
+ <option>1</option>
+ <object class="wxChoice" name="choice_baudrate" base="EditChoice">
+ <selection>0</selection>
+ <choices>
+ <choice>choice 1</choice>
+ </choices>
+ </object>
+ </object>
+ </object>
+ </object>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxStaticBoxSizer" name="sizer_format" base="EditStaticBoxSizer">
+ <orient>wxVERTICAL</orient>
+ <label>Data Format</label>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxBoxSizer" name="sizer_6" base="EditBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>1</option>
+ <object class="wxStaticText" name="label_3" base="EditStaticText">
+ <attribute>1</attribute>
+ <label>Data Bits</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALIGN_RIGHT</flag>
+ <border>0</border>
+ <option>1</option>
+ <object class="wxChoice" name="choice_databits" base="EditChoice">
+ <selection>0</selection>
+ <choices>
+ <choice>choice 1</choice>
+ </choices>
+ </object>
+ </object>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxBoxSizer" name="sizer_7" base="EditBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>1</option>
+ <object class="wxStaticText" name="label_4" base="EditStaticText">
+ <attribute>1</attribute>
+ <label>Stop Bits</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALIGN_RIGHT</flag>
+ <border>0</border>
+ <option>1</option>
+ <object class="wxChoice" name="choice_stopbits" base="EditChoice">
+ <selection>0</selection>
+ <choices>
+ <choice>choice 1</choice>
+ </choices>
+ </object>
+ </object>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxBoxSizer" name="sizer_8" base="EditBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>1</option>
+ <object class="wxStaticText" name="label_5" base="EditStaticText">
+ <attribute>1</attribute>
+ <label>Parity</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALIGN_RIGHT</flag>
+ <border>0</border>
+ <option>1</option>
+ <object class="wxChoice" name="choice_parity" base="EditChoice">
+ <selection>0</selection>
+ <choices>
+ <choice>choice 1</choice>
+ </choices>
+ </object>
+ </object>
+ </object>
+ </object>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <border>0</border>
+ <option>0</option>
+ <object class="wxStaticBoxSizer" name="sizer_timeout" base="EditStaticBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <label>Timeout</label>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>0</option>
+ <object class="wxCheckBox" name="checkbox_timeout" base="EditCheckBox">
+ <label>Use Timeout</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <border>0</border>
+ <option>0</option>
+ <object class="wxTextCtrl" name="text_ctrl_timeout" base="EditTextCtrl">
+ <disabled>1</disabled>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>0</option>
+ <object class="wxStaticText" name="label_6" base="EditStaticText">
+ <attribute>1</attribute>
+ <label>seconds</label>
+ </object>
+ </object>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxStaticBoxSizer" name="sizer_flow" base="EditStaticBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <label>Flow Control</label>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>0</option>
+ <object class="wxCheckBox" name="checkbox_rtscts" base="EditCheckBox">
+ <label>RTS/CTS</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_CENTER_VERTICAL</flag>
+ <border>4</border>
+ <option>0</option>
+ <object class="wxCheckBox" name="checkbox_xonxoff" base="EditCheckBox">
+ <label>Xon/Xoff</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>1</option>
+ <object class="spacer" name="spacer" base="EditSpacer">
+ <height>10</height>
+ <width>10</width>
+ </object>
+ </object>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_RIGHT</flag>
+ <border>4</border>
+ <option>0</option>
+ <object class="wxBoxSizer" name="sizer_3" base="EditBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <object class="sizeritem">
+ <border>0</border>
+ <option>0</option>
+ <object class="wxButton" name="button_ok" base="EditButton">
+ <default>1</default>
+ <label>OK</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <border>0</border>
+ <option>0</option>
+ <object class="wxButton" name="button_cancel" base="EditButton">
+ <label>Cancel</label>
+ </object>
+ </object>
+ </object>
+ </object>
+ </object>
+ </object>
+</application>
diff --git a/maximus/python/lib/proto/pyserial/examples/wxTerminal.py b/maximus/python/lib/proto/pyserial/examples/wxTerminal.py
new file mode 100644
index 0000000000..fcac57195a
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/wxTerminal.py
@@ -0,0 +1,332 @@
+#!/usr/bin/env python
+# generated by wxGlade 0.3.1 on Fri Oct 03 23:23:45 2003
+
+from wxPython.wx import *
+import wxSerialConfigDialog
+import serial
+import threading
+
+#----------------------------------------------------------------------
+# Create an own event type, so that GUI updates can be delegated
+# this is required as on some platforms only the main thread can
+# access the GUI without crashing. wxMutexGuiEnter/wxMutexGuiLeave
+# could be used too, but an event is more elegant.
+
+SERIALRX = wxNewEventType()
+# bind to serial data receive events
+EVT_SERIALRX = wxPyEventBinder(SERIALRX, 0)
+
+class SerialRxEvent(wxPyCommandEvent):
+ eventType = SERIALRX
+ def __init__(self, windowID, data):
+ wxPyCommandEvent.__init__(self, self.eventType, windowID)
+ self.data = data
+
+ def Clone(self):
+ self.__class__(self.GetId(), self.data)
+
+#----------------------------------------------------------------------
+
+ID_CLEAR = wxNewId()
+ID_SAVEAS = wxNewId()
+ID_SETTINGS = wxNewId()
+ID_TERM = wxNewId()
+ID_EXIT = wxNewId()
+
+NEWLINE_CR = 0
+NEWLINE_LF = 1
+NEWLINE_CRLF = 2
+
+class TerminalSetup:
+ """Placeholder for various terminal settings. Used to pass the
+ options to the TerminalSettingsDialog."""
+ def __init__(self):
+ self.echo = False
+ self.unprintable = False
+ self.newline = NEWLINE_CRLF
+
+class TerminalSettingsDialog(wxDialog):
+ """Simple dialog with common terminal settings like echo, newline mode."""
+
+ def __init__(self, *args, **kwds):
+ self.settings = kwds['settings']
+ del kwds['settings']
+ # begin wxGlade: TerminalSettingsDialog.__init__
+ kwds["style"] = wxDEFAULT_DIALOG_STYLE
+ wxDialog.__init__(self, *args, **kwds)
+ self.checkbox_echo = wxCheckBox(self, -1, "Local Echo")
+ self.checkbox_unprintable = wxCheckBox(self, -1, "Show unprintable characters")
+ self.radio_box_newline = wxRadioBox(self, -1, "Newline Handling", choices=["CR only", "LF only", "CR+LF"], majorDimension=0, style=wxRA_SPECIFY_ROWS)
+ self.button_ok = wxButton(self, -1, "OK")
+ self.button_cancel = wxButton(self, -1, "Cancel")
+
+ self.__set_properties()
+ self.__do_layout()
+ # end wxGlade
+ self.__attach_events()
+ self.checkbox_echo.SetValue(self.settings.echo)
+ self.checkbox_unprintable.SetValue(self.settings.unprintable)
+ self.radio_box_newline.SetSelection(self.settings.newline)
+
+ def __set_properties(self):
+ # begin wxGlade: TerminalSettingsDialog.__set_properties
+ self.SetTitle("Terminal Settings")
+ self.radio_box_newline.SetSelection(0)
+ self.button_ok.SetDefault()
+ # end wxGlade
+
+ def __do_layout(self):
+ # begin wxGlade: TerminalSettingsDialog.__do_layout
+ sizer_2 = wxBoxSizer(wxVERTICAL)
+ sizer_3 = wxBoxSizer(wxHORIZONTAL)
+ sizer_4 = wxStaticBoxSizer(wxStaticBox(self, -1, "Input/Output"), wxVERTICAL)
+ sizer_4.Add(self.checkbox_echo, 0, wxALL, 4)
+ sizer_4.Add(self.checkbox_unprintable, 0, wxALL, 4)
+ sizer_4.Add(self.radio_box_newline, 0, 0, 0)
+ sizer_2.Add(sizer_4, 0, wxEXPAND, 0)
+ sizer_3.Add(self.button_ok, 0, 0, 0)
+ sizer_3.Add(self.button_cancel, 0, 0, 0)
+ sizer_2.Add(sizer_3, 0, wxALL|wxALIGN_RIGHT, 4)
+ self.SetAutoLayout(1)
+ self.SetSizer(sizer_2)
+ sizer_2.Fit(self)
+ sizer_2.SetSizeHints(self)
+ self.Layout()
+ # end wxGlade
+
+ def __attach_events(self):
+ self.Bind(EVT_BUTTON, self.OnOK, id = self.button_ok.GetId())
+ self.Bind(EVT_BUTTON, self.OnCancel, id = self.button_cancel.GetId())
+
+ def OnOK(self, events):
+ """Update data wil new values and close dialog."""
+ self.settings.echo = self.checkbox_echo.GetValue()
+ self.settings.unprintable = self.checkbox_unprintable.GetValue()
+ self.settings.newline = self.radio_box_newline.GetSelection()
+ self.EndModal(wxID_OK)
+
+ def OnCancel(self, events):
+ """Do not update data but close dialog."""
+ self.EndModal(wxID_CANCEL)
+
+# end of class TerminalSettingsDialog
+
+
+class TerminalFrame(wxFrame):
+ """Simple terminal program for wxPython"""
+
+ def __init__(self, *args, **kwds):
+ self.serial = serial.Serial()
+ self.serial.timeout = 0.5 #make sure that the alive event can be checked from time to time
+ self.settings = TerminalSetup() #placeholder for the settings
+ self.thread = None
+ self.alive = threading.Event()
+ # begin wxGlade: TerminalFrame.__init__
+ kwds["style"] = wxDEFAULT_FRAME_STYLE
+ wxFrame.__init__(self, *args, **kwds)
+ self.text_ctrl_output = wxTextCtrl(self, -1, "", style=wxTE_MULTILINE|wxTE_READONLY)
+
+ # Menu Bar
+ self.frame_terminal_menubar = wxMenuBar()
+ self.SetMenuBar(self.frame_terminal_menubar)
+ wxglade_tmp_menu = wxMenu()
+ wxglade_tmp_menu.Append(ID_CLEAR, "&Clear", "", wxITEM_NORMAL)
+ wxglade_tmp_menu.Append(ID_SAVEAS, "&Save Text As...", "", wxITEM_NORMAL)
+ wxglade_tmp_menu.AppendSeparator()
+ wxglade_tmp_menu.Append(ID_SETTINGS, "&Port Settings...", "", wxITEM_NORMAL)
+ wxglade_tmp_menu.Append(ID_TERM, "&Terminal Settings...", "", wxITEM_NORMAL)
+ wxglade_tmp_menu.AppendSeparator()
+ wxglade_tmp_menu.Append(ID_EXIT, "&Exit", "", wxITEM_NORMAL)
+ self.frame_terminal_menubar.Append(wxglade_tmp_menu, "&File")
+ # Menu Bar end
+
+ self.__set_properties()
+ self.__do_layout()
+ # end wxGlade
+ self.__attach_events() #register events
+ self.OnPortSettings(None) #call setup dialog on startup, opens port
+ if not self.alive.isSet():
+ self.Close()
+
+ def StartThread(self):
+ """Start the receiver thread"""
+ self.thread = threading.Thread(target=self.ComPortThread)
+ self.thread.setDaemon(1)
+ self.thread.start()
+ self.alive.set()
+
+ def StopThread(self):
+ """Stop the receiver thread, wait util it's finished."""
+ if self.thread is not None:
+ self.alive.clear() #clear alive event for thread
+ self.thread.join() #wait until thread has finished
+ self.thread = None
+
+ def __set_properties(self):
+ # begin wxGlade: TerminalFrame.__set_properties
+ self.SetTitle("Serial Terminal")
+ self.SetSize((546, 383))
+ # end wxGlade
+
+ def __do_layout(self):
+ # begin wxGlade: TerminalFrame.__do_layout
+ sizer_1 = wxBoxSizer(wxVERTICAL)
+ sizer_1.Add(self.text_ctrl_output, 1, wxEXPAND, 0)
+ self.SetAutoLayout(1)
+ self.SetSizer(sizer_1)
+ self.Layout()
+ # end wxGlade
+
+ def __attach_events(self):
+ #register events at the controls
+ self.Bind(EVT_MENU, self.OnClear, id = ID_CLEAR)
+ self.Bind(EVT_MENU, self.OnSaveAs, id = ID_SAVEAS)
+ self.Bind(EVT_MENU, self.OnExit, id = ID_EXIT)
+ self.Bind(EVT_MENU, self.OnPortSettings, id = ID_SETTINGS)
+ self.Bind(EVT_MENU, self.OnTermSettings, id = ID_TERM)
+ self.text_ctrl_output.Bind(EVT_CHAR, self.OnKey)
+ self.Bind(EVT_SERIALRX, self.OnSerialRead)
+ self.Bind(EVT_CLOSE, self.OnClose)
+
+ def OnExit(self, event):
+ """Menu point Exit"""
+ self.Close()
+
+ def OnClose(self, event):
+ """Called on application shutdown."""
+ self.StopThread() #stop reader thread
+ self.serial.close() #cleanup
+ self.Destroy() #close windows, exit app
+
+ def OnSaveAs(self, event):
+ """Save contents of output window."""
+ filename = None
+ dlg = wxFileDialog(None, "Save Text As...", ".", "", "Text File|*.txt|All Files|*", wxSAVE)
+ if dlg.ShowModal() == wxID_OK:
+ filename = dlg.GetPath()
+ dlg.Destroy()
+
+ if filename is not None:
+ f = file(filename, 'w')
+ text = self.text_ctrl_output.GetValue()
+ if type(text) == unicode:
+ text = text.encode("latin1") #hm, is that a good asumption?
+ f.write(text)
+ f.close()
+
+ def OnClear(self, event):
+ """Clear contents of output window."""
+ self.text_ctrl_output.Clear()
+
+ def OnPortSettings(self, event=None):
+ """Show the portsettings dialog. The reader thread is stopped for the
+ settings change."""
+ if event is not None: #will be none when called on startup
+ self.StopThread()
+ self.serial.close()
+ ok = False
+ while not ok:
+ dialog_serial_cfg = wxSerialConfigDialog.SerialConfigDialog(None, -1, "",
+ show=wxSerialConfigDialog.SHOW_BAUDRATE|wxSerialConfigDialog.SHOW_FORMAT|wxSerialConfigDialog.SHOW_FLOW,
+ serial=self.serial
+ )
+ result = dialog_serial_cfg.ShowModal()
+ dialog_serial_cfg.Destroy()
+ #open port if not called on startup, open it on startup and OK too
+ if result == wxID_OK or event is not None:
+ try:
+ self.serial.open()
+ except serial.SerialException, e:
+ dlg = wxMessageDialog(None, str(e), "Serial Port Error", wxOK | wxICON_ERROR)
+ dlg.ShowModal()
+ dlg.Destroy()
+ else:
+ self.StartThread()
+ self.SetTitle("Serial Terminal on %s [%s, %s%s%s%s%s]" % (
+ self.serial.portstr,
+ self.serial.baudrate,
+ self.serial.bytesize,
+ self.serial.parity,
+ self.serial.stopbits,
+ self.serial.rtscts and ' RTS/CTS' or '',
+ self.serial.xonxoff and ' Xon/Xoff' or '',
+ )
+ )
+ ok = True
+ else:
+ #on startup, dialog aborted
+ self.alive.clear()
+ ok = True
+
+ def OnTermSettings(self, event):
+ """Menu point Terminal Settings. Show the settings dialog
+ with the current terminal settings"""
+ dialog = TerminalSettingsDialog(None, -1, "", settings=self.settings)
+ result = dialog.ShowModal()
+ dialog.Destroy()
+
+ def OnKey(self, event):
+ """Key event handler. if the key is in the ASCII range, write it to the serial port.
+ Newline handling and local echo is also done here."""
+ code = event.GetKeyCode()
+ if code < 256: #is it printable?
+ if code == 13: #is it a newline? (check for CR which is the RETURN key)
+ if self.settings.echo: #do echo if needed
+ self.text_ctrl_output.AppendText('\n')
+ if self.settings.newline == NEWLINE_CR:
+ self.serial.write('\r') #send CR
+ elif self.settings.newline == NEWLINE_LF:
+ self.serial.write('\n') #send LF
+ elif self.settings.newline == NEWLINE_CRLF:
+ self.serial.write('\r\n') #send CR+LF
+ else:
+ char = chr(code)
+ if self.settings.echo: #do echo if needed
+ self.text_ctrl_output.WriteText(char)
+ self.serial.write(char) #send the charcater
+ else:
+ print "Extra Key:", code
+
+ def OnSerialRead(self, event):
+ """Handle input from the serial port."""
+ text = event.data
+ if self.settings.unprintable:
+ text = ''.join([(c >= ' ') and c or '<%d>' % ord(c) for c in text])
+ self.text_ctrl_output.AppendText(text)
+
+ def ComPortThread(self):
+ """Thread that handles the incomming traffic. Does the basic input
+ transformation (newlines) and generates an SerialRxEvent"""
+ while self.alive.isSet(): #loop while alive event is true
+ text = self.serial.read(1) #read one, with timout
+ if text: #check if not timeout
+ n = self.serial.inWaiting() #look if there is more to read
+ if n:
+ text = text + self.serial.read(n) #get it
+ #newline transformation
+ if self.settings.newline == NEWLINE_CR:
+ text = text.replace('\r', '\n')
+ elif self.settings.newline == NEWLINE_LF:
+ pass
+ elif self.settings.newline == NEWLINE_CRLF:
+ text = text.replace('\r\n', '\n')
+ event = SerialRxEvent(self.GetId(), text)
+ self.GetEventHandler().AddPendingEvent(event)
+ #~ self.OnSerialRead(text) #output text in window
+
+# end of class TerminalFrame
+
+
+class MyApp(wxApp):
+ def OnInit(self):
+ wxInitAllImageHandlers()
+ frame_terminal = TerminalFrame(None, -1, "")
+ self.SetTopWindow(frame_terminal)
+ frame_terminal.Show(1)
+ return 1
+
+# end of class MyApp
+
+if __name__ == "__main__":
+ app = MyApp(0)
+ app.MainLoop()
diff --git a/maximus/python/lib/proto/pyserial/examples/wxTerminal.wxg b/maximus/python/lib/proto/pyserial/examples/wxTerminal.wxg
new file mode 100644
index 0000000000..1f20511f6b
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/examples/wxTerminal.wxg
@@ -0,0 +1,127 @@
+<?xml version="1.0"?>
+<!-- generated by wxGlade 0.3.1 on Sat Oct 04 02:41:48 2003 -->
+
+<application path="D:\prog\python\pyserial_sf\pyserial\examples\wxTerminal.py" name="app" class="MyApp" option="0" language="python" top_window="frame_terminal" encoding="ISO-8859-1" use_gettext="0" overwrite="0">
+ <object class="TerminalFrame" name="frame_terminal" base="EditFrame">
+ <style>wxDEFAULT_FRAME_STYLE</style>
+ <title>Serial Terminal</title>
+ <menubar>1</menubar>
+ <size>546, 383</size>
+ <object class="wxBoxSizer" name="sizer_1" base="EditBoxSizer">
+ <orient>wxVERTICAL</orient>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>1</option>
+ <object class="wxTextCtrl" name="text_ctrl_output" base="EditTextCtrl">
+ <style>wxTE_MULTILINE|wxTE_READONLY</style>
+ </object>
+ </object>
+ </object>
+ <object class="wxMenuBar" name="frame_terminal_menubar" base="EditMenuBar">
+ <menus>
+ <menu name="" label="&amp;File">
+ <item>
+ <label>&amp;Clear</label>
+ <id>ID_CLEAR</id>
+ </item>
+ <item>
+ <label>&amp;Save Text As...</label>
+ <id>ID_SAVEAS</id>
+ </item>
+ <item>
+ <label>---</label>
+ <id>---</id>
+ <name>---</name>
+ </item>
+ <item>
+ <label>&amp;Port Settings...</label>
+ <id>ID_SETTINGS</id>
+ </item>
+ <item>
+ <label>&amp;Terminal Settings...</label>
+ <id>ID_TERM</id>
+ </item>
+ <item>
+ <label>---</label>
+ <name>---</name>
+ </item>
+ <item>
+ <label>&amp;Exit</label>
+ <id>ID_EXIT</id>
+ </item>
+ </menu>
+ </menus>
+ </object>
+ </object>
+ <object class="TerminalSettingsDialog" name="dialog_terminal_Settings" base="EditDialog">
+ <style>wxDEFAULT_DIALOG_STYLE</style>
+ <title>Terminal Settings</title>
+ <object class="wxBoxSizer" name="sizer_2" base="EditBoxSizer">
+ <orient>wxVERTICAL</orient>
+ <object class="sizeritem">
+ <flag>wxEXPAND</flag>
+ <border>0</border>
+ <option>0</option>
+ <object class="wxStaticBoxSizer" name="sizer_4" base="EditStaticBoxSizer">
+ <orient>wxVERTICAL</orient>
+ <label>Input/Output</label>
+ <object class="sizeritem">
+ <flag>wxALL</flag>
+ <border>4</border>
+ <option>0</option>
+ <object class="wxCheckBox" name="checkbox_echo" base="EditCheckBox">
+ <label>Local Echo</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALL</flag>
+ <border>4</border>
+ <option>0</option>
+ <object class="wxCheckBox" name="checkbox_unprintable" base="EditCheckBox">
+ <label>Show unprintable characters</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <border>0</border>
+ <option>0</option>
+ <object class="wxRadioBox" name="radio_box_newline" base="EditRadioBox">
+ <style>wxRA_SPECIFY_ROWS</style>
+ <selection>0</selection>
+ <dimension>0</dimension>
+ <label>Newline Handling</label>
+ <choices>
+ <choice>CR only</choice>
+ <choice>LF only</choice>
+ <choice>CR+LF</choice>
+ </choices>
+ </object>
+ </object>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <flag>wxALL|wxALIGN_RIGHT</flag>
+ <border>4</border>
+ <option>0</option>
+ <object class="wxBoxSizer" name="sizer_3" base="EditBoxSizer">
+ <orient>wxHORIZONTAL</orient>
+ <object class="sizeritem">
+ <border>0</border>
+ <option>0</option>
+ <object class="wxButton" name="button_ok" base="EditButton">
+ <default>1</default>
+ <label>OK</label>
+ </object>
+ </object>
+ <object class="sizeritem">
+ <border>0</border>
+ <option>0</option>
+ <object class="wxButton" name="button_cancel" base="EditButton">
+ <label>Cancel</label>
+ </object>
+ </object>
+ </object>
+ </object>
+ </object>
+ </object>
+</application>
diff --git a/maximus/python/lib/proto/pyserial/serial/__init__.py b/maximus/python/lib/proto/pyserial/serial/__init__.py
new file mode 100644
index 0000000000..2894b30055
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/serial/__init__.py
@@ -0,0 +1,20 @@
+#!/usr/bin/env python
+#portable serial port access with python
+#this is a wrapper module for different platform implementations
+#
+# (C)2001-2002 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+import sys, os, string
+VERSION = string.split("$Revision: 1.3 $")[1] #extract CVS version
+
+#chose an implementation, depending on os
+if os.name == 'nt': #sys.platform == 'win32':
+ from serialwin32 import *
+elif os.name == 'posix':
+ from serialposix import *
+elif os.name == 'java':
+ from serialjava import *
+else:
+ raise Exception("Sorry: no implementation for your platform ('%s') available" % os.name)
+
diff --git a/maximus/python/lib/proto/pyserial/serial/serialjava.py b/maximus/python/lib/proto/pyserial/serial/serialjava.py
new file mode 100644
index 0000000000..f5c84fb99b
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/serial/serialjava.py
@@ -0,0 +1,212 @@
+#!jython
+#Python Serial Port Extension for Win32, Linux, BSD, Jython
+#module for serial IO for Jython and JavaComm
+#see __init__.py
+#
+#(C) 2002-2003 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+import javax.comm
+from serialutil import *
+
+VERSION = "$Revision: 1.8 $".split()[1] #extract CVS version
+
+
+def device(portnumber):
+ """Turn a port number into a device name"""
+ enum = javax.comm.CommPortIdentifier.getPortIdentifiers()
+ ports = []
+ while enum.hasMoreElements():
+ el = enum.nextElement()
+ if el.getPortType() == javax.comm.CommPortIdentifier.PORT_SERIAL:
+ ports.append(el)
+ return ports[portnumber].getName()
+
+class Serial(SerialBase):
+ """Serial port class, implemented with javax.comm and thus usable with
+ jython and the appropriate java extension."""
+
+ def open(self):
+ """Open port with current settings. This may throw a SerialException
+ if the port cannot be opened."""
+ if self._port is None:
+ raise SerialException("Port must be configured before it can be used.")
+ if type(self._port) == type(''): #strings are taken directly
+ portId = javax.comm.CommPortIdentifier.getPortIdentifier(self._port)
+ else:
+ portId = javax.comm.CommPortIdentifier.getPortIdentifier(device(self._port)) #numbers are transformed to a comportid obj
+ try:
+ self.sPort = portId.open("python serial module", 10)
+ except Exception, msg:
+ self.sPort = None
+ raise SerialException("Could not open port: %s" % msg)
+ self._reconfigurePort()
+ self._instream = self.sPort.getInputStream()
+ self._outstream = self.sPort.getOutputStream()
+ self._isOpen = True
+
+ def _reconfigurePort(self):
+ """Set commuication parameters on opened port."""
+ if not self.sPort:
+ raise SerialException("Can only operate on a valid port handle")
+
+ self.sPort.enableReceiveTimeout(30)
+ if self._bytesize == FIVEBITS:
+ jdatabits = javax.comm.SerialPort.DATABITS_5
+ elif self._bytesize == SIXBITS:
+ jdatabits = javax.comm.SerialPort.DATABITS_6
+ elif self._bytesize == SEVENBITS:
+ jdatabits = javax.comm.SerialPort.DATABITS_7
+ elif self._bytesize == EIGHTBITS:
+ jdatabits = javax.comm.SerialPort.DATABITS_8
+ else:
+ raise ValueError("unsupported bytesize: %r" % self._bytesize)
+
+ if self._stopbits == STOPBITS_ONE:
+ jstopbits = javax.comm.SerialPort.STOPBITS_1
+ elif stopbits == STOPBITS_ONE_HALVE:
+ self._jstopbits = javax.comm.SerialPort.STOPBITS_1_5
+ elif self._stopbits == STOPBITS_TWO:
+ jstopbits = javax.comm.SerialPort.STOPBITS_2
+ else:
+ raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
+
+ if self._parity == PARITY_NONE:
+ jparity = javax.comm.SerialPort.PARITY_NONE
+ elif self._parity == PARITY_EVEN:
+ jparity = javax.comm.SerialPort.PARITY_EVEN
+ elif self._parity == PARITY_ODD:
+ jparity = javax.comm.SerialPort.PARITY_ODD
+ #~ elif self._parity == PARITY_MARK:
+ #~ jparity = javax.comm.SerialPort.PARITY_MARK
+ #~ elif self._parity == PARITY_SPACE:
+ #~ jparity = javax.comm.SerialPort.PARITY_SPACE
+ else:
+ raise ValueError("unsupported parity type: %r" % self._parity)
+
+ jflowin = jflowout = 0
+ if self._rtscts:
+ jflowin |= javax.comm.SerialPort.FLOWCONTROL_RTSCTS_IN
+ jflowout |= javax.comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
+ if self._xonxoff:
+ jflowin |= javax.comm.SerialPort.FLOWCONTROL_XONXOFF_IN
+ jflowout |= javax.comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
+
+ self.sPort.setSerialPortParams(baudrate, jdatabits, jstopbits, jparity)
+ self.sPort.setFlowControlMode(jflowin | jflowout)
+
+ if self._timeout >= 0:
+ self.sPort.enableReceiveTimeout(self._timeout*1000)
+ else:
+ self.sPort.disableReceiveTimeout()
+
+ def close(self):
+ """Close port"""
+ if self._isOpen:
+ if self.sPort:
+ self._instream.close()
+ self._outstream.close()
+ self.sPort.close()
+ self.sPort = None
+ self._isOpen = False
+
+ def makeDeviceName(self, port):
+ return device(port)
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def inWaiting(self):
+ """Return the number of characters currently in the input buffer."""
+ if not self.sPort: raise portNotOpenError
+ return self._instream.available()
+
+ def read(self, size=1):
+ """Read size bytes from the serial port. If a timeout is set it may
+ return less characters as requested. With no timeout it will block
+ until the requested number of bytes is read."""
+ if not self.sPort: raise portNotOpenError
+ read = ''
+ if size > 0:
+ while len(read) < size:
+ x = self._instream.read()
+ if x == -1:
+ if self.timeout >= 0:
+ break
+ else:
+ read = read + chr(x)
+ return read
+
+ def write(self, data):
+ """Output the given string over the serial port."""
+ if not self.sPort: raise portNotOpenError
+ self._outstream.write(data)
+
+ def flushInput(self):
+ """Clear input buffer, discarding all that is in the buffer."""
+ if not self.sPort: raise portNotOpenError
+ self._instream.skip(self._instream.available())
+
+ def flushOutput(self):
+ """Clear output buffer, aborting the current output and
+ discarding all that is in the buffer."""
+ if not self.sPort: raise portNotOpenError
+ self._outstream.flush()
+
+ def sendBreak(self):
+ """Send break condition."""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.sendBreak()
+
+ def setRTS(self,on=1):
+ """Set terminal status line: Request To Send"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.setRTS(on)
+
+ def setDTR(self,on=1):
+ """Set terminal status line: Data Terminal Ready"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.setDTR(on)
+
+ def getCTS(self):
+ """Read terminal status line: Clear To Send"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.isCTS()
+
+ def getDSR(self):
+ """Read terminal status line: Data Set Ready"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.isDSR()
+
+ def getRI(self):
+ """Read terminal status line: Ring Indicator"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.isRI()
+
+ def getCD(self):
+ """Read terminal status line: Carrier Detect"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.isCD()
+
+
+
+if __name__ == '__main__':
+ s = Serial(0,
+ baudrate=19200, #baudrate
+ bytesize=EIGHTBITS, #number of databits
+ parity=PARITY_EVEN, #enable parity checking
+ stopbits=STOPBITS_ONE, #number of stopbits
+ timeout=3, #set a timeout value, None for waiting forever
+ xonxoff=0, #enable software flow control
+ rtscts=0, #enable RTS/CTS flow control
+ )
+ s.setRTS(1)
+ s.setDTR(1)
+ s.flushInput()
+ s.flushOutput()
+ s.write('hello')
+ print repr(s.read(5))
+ print s.inWaiting()
+ del s
+
+
+
diff --git a/maximus/python/lib/proto/pyserial/serial/serialposix.py b/maximus/python/lib/proto/pyserial/serial/serialposix.py
new file mode 100644
index 0000000000..09aef6ca9c
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/serial/serialposix.py
@@ -0,0 +1,406 @@
+#!/usr/bin/env python
+#Python Serial Port Extension for Win32, Linux, BSD, Jython
+#module for serial IO for POSIX compatible systems, like Linux
+#see __init__.py
+#
+#(C) 2001-2003 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+#
+#parts based on code from Grant B. Edwards <grante@visi.com>:
+# ftp://ftp.visi.com/users/grante/python/PosixSerial.py
+# references: http://www.easysw.com/~mike/serial/serial.html
+
+import sys, os, fcntl, termios, struct, select, errno
+from serialutil import *
+
+VERSION = "$Revision: 1.27 $".split()[1] #extract CVS version
+
+#Do check the Python version as some constants have moved.
+if (sys.hexversion < 0x020100f0):
+ import TERMIOS
+else:
+ TERMIOS = termios
+
+if (sys.hexversion < 0x020200f0):
+ import FCNTL
+else:
+ FCNTL = fcntl
+
+#try to detect the os so that a device can be selected...
+plat = sys.platform.lower()
+
+if plat[:5] == 'linux': #Linux (confirmed)
+ def device(port):
+ return '/dev/ttyS%d' % port
+
+elif plat == 'cygwin': #cywin/win32 (confirmed)
+ def device(port):
+ return '/dev/com%d' % (port + 1)
+
+elif plat == 'openbsd3': #BSD (confirmed)
+ def device(port):
+ return '/dev/ttyp%d' % port
+
+elif plat[:3] == 'bsd' or \
+ plat[:7] == 'freebsd' or \
+ plat[:7] == 'openbsd' or \
+ plat[:6] == 'darwin': #BSD (confirmed for freebsd4: cuaa%d)
+ def device(port):
+ return '/dev/cuaa%d' % port
+
+elif plat[:6] == 'netbsd': #NetBSD 1.6 testing by Erk
+ def device(port):
+ return '/dev/dty%02d' % port
+
+elif plat[:4] == 'irix': #IRIX (not tested)
+ def device(port):
+ return '/dev/ttyf%d' % port
+
+elif plat[:2] == 'hp': #HP-UX (not tested)
+ def device(port):
+ return '/dev/tty%dp0' % (port+1)
+
+elif plat[:5] == 'sunos': #Solaris/SunOS (confirmed)
+ def device(port):
+ return '/dev/tty%c' % (ord('a')+port)
+
+elif plat[:3] == 'aix': #aix
+ def device(port):
+ return '/dev/tty%d' % (port)
+
+else:
+ #platform detection has failed...
+ print """don't know how to number ttys on this system.
+! Use an explicit path (eg /dev/ttyS1) or send this information to
+! the author of this module:
+
+sys.platform = %r
+os.name = %r
+serialposix.py version = %s
+
+also add the device name of the serial port and where the
+counting starts for the first serial port.
+e.g. 'first serial port: /dev/ttyS0'
+and with a bit luck you can get this module running...
+""" % (sys.platform, os.name, VERSION)
+ #no exception, just continue with a brave attempt to build a device name
+ #even if the device name is not correct for the platform it has chances
+ #to work using a string with the real device name as port paramter.
+ def device(portum):
+ return '/dev/ttyS%d' % portnum
+ #~ raise Exception, "this module does not run on this platform, sorry."
+
+#whats up with "aix", "beos", ....
+#they should work, just need to know the device names.
+
+
+#load some constants for later use.
+#try to use values from TERMIOS, use defaults from linux otherwise
+TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415
+TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416
+TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417
+TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418
+
+#TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001
+TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002
+TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004
+#TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008
+#TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010
+
+TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020
+TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040
+TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080
+TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100
+TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR
+TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG
+#TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000
+#TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000
+TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or 0x541B
+
+TIOCM_zero_str = struct.pack('I', 0)
+TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
+TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
+
+
+class Serial(SerialBase):
+ """Serial port class POSIX implementation. Serial port configuration is
+ done with termios and fcntl. Runs on Linux and many other Un*x like
+ systems."""
+
+ def open(self):
+ """Open port with current settings. This may throw a SerialException
+ if the port cannot be opened."""
+ if self._port is None:
+ raise SerialException("Port must be configured before it can be used.")
+ self.fd = None
+ #open
+ try:
+ self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)
+ except Exception, msg:
+ self.fd = None
+ raise SerialException("Could not open port: %s" % msg)
+ #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) #set blocking
+
+ self._reconfigurePort()
+ self._isOpen = True
+ #~ self.flushInput()
+
+
+ def _reconfigurePort(self):
+ """Set commuication parameters on opened port."""
+ if self.fd is None:
+ raise SerialException("Can only operate on a valid port handle")
+
+ vmin = vtime = 0 #timeout is done via select
+ try:
+ iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self.fd)
+ except termios.error, msg: #if a port is nonexistent but has a /dev file, it'll fail here
+ raise SerialException("Could not configure port: %s" % msg)
+ #set up raw mode / no echo / binary
+ cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD)
+ lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL|
+ TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT
+ for flag in ('ECHOCTL', 'ECHOKE'): #netbsd workaround for Erk
+ if hasattr(TERMIOS, flag):
+ lflag &= ~getattr(TERMIOS, flag)
+
+ oflag &= ~(TERMIOS.OPOST)
+ iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK)
+ if hasattr(TERMIOS, 'IUCLC'):
+ iflag &= ~TERMIOS.IUCLC
+ if hasattr(TERMIOS, 'PARMRK'):
+ iflag &= ~TERMIOS.PARMRK
+
+ #setup baudrate
+ try:
+ ispeed = ospeed = getattr(TERMIOS,'B%s' % (self._baudrate))
+ except AttributeError:
+ raise ValueError('Invalid baud rate: %r' % self._baudrate)
+ #setup char len
+ cflag &= ~TERMIOS.CSIZE
+ if self._bytesize == 8:
+ cflag |= TERMIOS.CS8
+ elif self._bytesize == 7:
+ cflag |= TERMIOS.CS7
+ elif self._bytesize == 6:
+ cflag |= TERMIOS.CS6
+ elif self._bytesize == 5:
+ cflag |= TERMIOS.CS5
+ else:
+ raise ValueError('Invalid char len: %r' % self._bytesize)
+ #setup stopbits
+ if self._stopbits == STOPBITS_ONE:
+ cflag &= ~(TERMIOS.CSTOPB)
+ elif self._stopbits == STOPBITS_TWO:
+ cflag |= (TERMIOS.CSTOPB)
+ else:
+ raise ValueError('Invalid stopit specification: %r' % self._stopbits)
+ #setup parity
+ iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP)
+ if self._parity == PARITY_NONE:
+ cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD)
+ elif self._parity == PARITY_EVEN:
+ cflag &= ~(TERMIOS.PARODD)
+ cflag |= (TERMIOS.PARENB)
+ elif self._parity == PARITY_ODD:
+ cflag |= (TERMIOS.PARENB|TERMIOS.PARODD)
+ else:
+ raise ValueError('Invalid parity: %r' % self._parity)
+ #setup flow control
+ #xonxoff
+ if hasattr(TERMIOS, 'IXANY'):
+ if self._xonxoff:
+ iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY)
+ else:
+ iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY)
+ else:
+ if self._xonxoff:
+ iflag |= (TERMIOS.IXON|TERMIOS.IXOFF)
+ else:
+ iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF)
+ #rtscts
+ if hasattr(TERMIOS, 'CRTSCTS'):
+ if self._rtscts:
+ cflag |= (TERMIOS.CRTSCTS)
+ else:
+ cflag &= ~(TERMIOS.CRTSCTS)
+ elif hasattr(TERMIOS, 'CNEW_RTSCTS'): #try it with alternate constant name
+ if self._rtscts:
+ cflag |= (TERMIOS.CNEW_RTSCTS)
+ else:
+ cflag &= ~(TERMIOS.CNEW_RTSCTS)
+ #XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
+
+ #buffer
+ #vmin "minimal number of characters to be read. = for non blocking"
+ if vmin < 0 or vmin > 255:
+ raise ValueError('Invalid vmin: %r ' % vmin)
+ cc[TERMIOS.VMIN] = vmin
+ #vtime
+ if vtime < 0 or vtime > 255:
+ raise ValueError('Invalid vtime: %r' % vtime)
+ cc[TERMIOS.VTIME] = vtime
+ #activate settings
+ termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
+
+ def close(self):
+ """Close port"""
+ if self._isOpen:
+ if self.fd is not None:
+ os.close(self.fd)
+ self.fd = None
+ self._isOpen = False
+
+ def makeDeviceName(self, port):
+ return device(port)
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def inWaiting(self):
+ """Return the number of characters currently in the input buffer."""
+ #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str)
+ s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
+ return struct.unpack('I',s)[0]
+
+ def read(self, size=1):
+ """Read size bytes from the serial port. If a timeout is set it may
+ return less characters as requested. With no timeout it will block
+ until the requested number of bytes is read."""
+ if self.fd is None: raise portNotOpenError
+ read = ''
+ inp = None
+ if size > 0:
+ while len(read) < size:
+ #print "\tread(): size",size, "have", len(read) #debug
+ ready,_,_ = select.select([self.fd],[],[], self._timeout)
+ if not ready:
+ break #timeout
+ buf = os.read(self.fd, size-len(read))
+ read = read + buf
+ if self._timeout >= 0 and not buf:
+ break #early abort on timeout
+ return read
+
+ def write(self, data):
+ """Output the given string over the serial port."""
+ if self.fd is None: raise portNotOpenError
+ t = len(data)
+ d = data
+ while t > 0:
+ try:
+ if self._writeTimeout is not None and self._writeTimeout > 0:
+ _,ready,_ = select.select([],[self.fd],[], self._writeTimeout)
+ if not ready:
+ raise writeTimeoutError
+ n = os.write(self.fd, d)
+ if self._writeTimeout is not None and self._writeTimeout > 0:
+ _,ready,_ = select.select([],[self.fd],[], self._writeTimeout)
+ if not ready:
+ raise writeTimeoutError
+ d = d[n:]
+ t = t - n
+ except OSError,v:
+ if v.errno != errno.EAGAIN:
+ raise
+
+ def flush(self):
+ """Flush of file like objects. In this case, wait until all data
+ is written."""
+ self.drainOutput()
+
+ def flushInput(self):
+ """Clear input buffer, discarding all that is in the buffer."""
+ if self.fd is None:
+ raise portNotOpenError
+ termios.tcflush(self.fd, TERMIOS.TCIFLUSH)
+
+ def flushOutput(self):
+ """Clear output buffer, aborting the current output and
+ discarding all that is in the buffer."""
+ if self.fd is None:
+ raise portNotOpenError
+ termios.tcflush(self.fd, TERMIOS.TCOFLUSH)
+
+ def sendBreak(self):
+ """Send break condition."""
+ if self.fd is None:
+ raise portNotOpenError
+ termios.tcsendbreak(self.fd, 0)
+
+ def setRTS(self,on=1):
+ """Set terminal status line: Request To Send"""
+ if self.fd is None: raise portNotOpenError
+ if on:
+ fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
+ else:
+ fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
+
+ def setDTR(self,on=1):
+ """Set terminal status line: Data Terminal Ready"""
+ if self.fd is None: raise portNotOpenError
+ if on:
+ fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
+ else:
+ fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
+
+ def getCTS(self):
+ """Read terminal status line: Clear To Send"""
+ if self.fd is None: raise portNotOpenError
+ s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
+ return struct.unpack('I',s)[0] & TIOCM_CTS != 0
+
+ def getDSR(self):
+ """Read terminal status line: Data Set Ready"""
+ if self.fd is None: raise portNotOpenError
+ s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
+ return struct.unpack('I',s)[0] & TIOCM_DSR != 0
+
+ def getRI(self):
+ """Read terminal status line: Ring Indicator"""
+ if self.fd is None: raise portNotOpenError
+ s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
+ return struct.unpack('I',s)[0] & TIOCM_RI != 0
+
+ def getCD(self):
+ """Read terminal status line: Carrier Detect"""
+ if self.fd is None: raise portNotOpenError
+ s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
+ return struct.unpack('I',s)[0] & TIOCM_CD != 0
+
+ # - - platform specific - - - -
+
+ def drainOutput(self):
+ """internal - not portable!"""
+ if self.fd is None: raise portNotOpenError
+ termios.tcdrain(self.fd)
+
+ def nonblocking(self):
+ """internal - not portable!"""
+ if self.fd is None:
+ raise portNotOpenError
+ fcntl.fcntl(self.fd, FCNTL.F_SETFL, FCNTL.O_NONBLOCK)
+
+ def fileno(self):
+ """For easier of the serial port instance with select.
+ WARNING: this function is not portable to different platforms!"""
+ if self.fd is None: raise portNotOpenError
+ return self.fd
+
+if __name__ == '__main__':
+ s = Serial(0,
+ baudrate=19200, #baudrate
+ bytesize=EIGHTBITS, #number of databits
+ parity=PARITY_EVEN, #enable parity checking
+ stopbits=STOPBITS_ONE, #number of stopbits
+ timeout=3, #set a timeout value, None for waiting forever
+ xonxoff=0, #enable software flow control
+ rtscts=0, #enable RTS/CTS flow control
+ )
+ s.setRTS(1)
+ s.setDTR(1)
+ s.flushInput()
+ s.flushOutput()
+ s.write('hello')
+ print repr(s.read(5))
+ print s.inWaiting()
+ del s
diff --git a/maximus/python/lib/proto/pyserial/serial/serialutil.py b/maximus/python/lib/proto/pyserial/serial/serialutil.py
new file mode 100644
index 0000000000..d58cc53caf
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/serial/serialutil.py
@@ -0,0 +1,366 @@
+#! python
+#Python Serial Port Extension for Win32, Linux, BSD, Jython
+#see __init__.py
+#
+#(C) 2001-2003 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+PARITY_NONE, PARITY_EVEN, PARITY_ODD = 'N', 'E', 'O'
+STOPBITS_ONE, STOPBITS_TWO = (1, 2)
+FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5,6,7,8)
+
+PARITY_NAMES = {
+ PARITY_NONE: 'None',
+ PARITY_EVEN: 'Even',
+ PARITY_ODD: 'Odd',
+}
+
+XON = chr(17)
+XOFF = chr(19)
+
+#Python < 2.2.3 compatibility
+try:
+ True
+except:
+ True = 1
+ False = not True
+
+class SerialException(Exception):
+ """Base class for serial port related exceptions."""
+
+portNotOpenError = SerialException('Port not open')
+
+class SerialTimeoutException(SerialException):
+ """Write timeouts give an exception"""
+
+writeTimeoutError = SerialTimeoutException("Write timeout")
+
+class FileLike(object):
+ """An abstract file like class.
+
+ This class implements readline and readlines based on read and
+ writelines based on write.
+ This class is used to provide the above functions for to Serial
+ port objects.
+
+ Note that when the serial port was opened with _NO_ timeout that
+ readline blocks until it sees a newline (or the specified size is
+ reached) and that readlines would never return and therefore
+ refuses to work (it raises an exception in this case)!
+ """
+
+ def read(self, size): raise NotImplementedError
+ def write(self, s): raise NotImplementedError
+
+ def readline(self, size=None, eol='\n'):
+ """read a line which is terminated with end-of-line (eol) character
+ ('\n' by default) or until timeout"""
+ line = ''
+ while 1:
+ c = self.read(1)
+ if c:
+ line += c #not very efficient but lines are usually not that long
+ if c == eol:
+ break
+ if size is not None and len(line) >= size:
+ break
+ else:
+ break
+ return line
+
+ def readlines(self, sizehint=None, eol='\n'):
+ """read a list of lines, until timeout
+ sizehint is ignored"""
+ if self.timeout is None:
+ raise ValueError, "Serial port MUST have enabled timeout for this function!"
+ lines = []
+ while 1:
+ line = self.readline(eol=eol)
+ if line:
+ lines.append(line)
+ if line[-1] != eol: #was the line received with a timeout?
+ break
+ else:
+ break
+ return lines
+
+ def xreadlines(self, sizehint=None):
+ """just call readlines - here for compatibility"""
+ return self.readlines()
+
+ def writelines(self, sequence):
+ for line in sequence:
+ self.write(line)
+
+ def flush(self):
+ """flush of file like objects"""
+ pass
+
+class SerialBase(FileLike):
+ """Serial port base class. Provides __init__ function and properties to
+ get/set port settings."""
+
+ #default values, may be overriden in subclasses that do not support all values
+ BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
+ 19200,38400,57600,115200,230400,460800,500000,576000,921600,
+ 1000000,1152000,1500000,2000000,2500000,3000000,3500000,4000000)
+ BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
+ PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD)
+ STOPBITS = (STOPBITS_ONE, STOPBITS_TWO)
+
+ def __init__(self,
+ port = None, #number of device, numbering starts at
+ #zero. if everything fails, the user
+ #can specify a device string, note
+ #that this isn't portable anymore
+ #port will be opened if one is specified
+ baudrate=9600, #baudrate
+ bytesize=EIGHTBITS, #number of databits
+ parity=PARITY_NONE, #enable parity checking
+ stopbits=STOPBITS_ONE, #number of stopbits
+ timeout=None, #set a timeout value, None to wait forever
+ xonxoff=0, #enable software flow control
+ rtscts=0, #enable RTS/CTS flow control
+ writeTimeout=None, #set a timeout for writes
+ dsrdtr=None, #None: use rtscts setting, dsrdtr override if true or false
+ ):
+ """Initialize comm port object. If a port is given, then the port will be
+ opened immediately. Otherwise a Serial port object in closed state
+ is returned."""
+
+ self._isOpen = False
+ self._port = None #correct value is assigned below trough properties
+ self._baudrate = None #correct value is assigned below trough properties
+ self._bytesize = None #correct value is assigned below trough properties
+ self._parity = None #correct value is assigned below trough properties
+ self._stopbits = None #correct value is assigned below trough properties
+ self._timeout = None #correct value is assigned below trough properties
+ self._writeTimeout = None #correct value is assigned below trough properties
+ self._xonxoff = None #correct value is assigned below trough properties
+ self._rtscts = None #correct value is assigned below trough properties
+ self._dsrdtr = None #correct value is assigned below trough properties
+
+ #assign values using get/set methods using the properties feature
+ self.port = port
+ self.baudrate = baudrate
+ self.bytesize = bytesize
+ self.parity = parity
+ self.stopbits = stopbits
+ self.timeout = timeout
+ self.writeTimeout = writeTimeout
+ self.xonxoff = xonxoff
+ self.rtscts = rtscts
+ self.dsrdtr = dsrdtr
+
+ if port is not None:
+ self.open()
+
+ def isOpen(self):
+ """Check if the port is opened."""
+ return self._isOpen
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ #TODO: these are not realy needed as the is the BAUDRATES etc attribute...
+ #maybe i remove them before the final release...
+
+ def getSupportedBaudrates(self):
+ return [(str(b), b) for b in self.BAUDRATES]
+
+ def getSupportedByteSizes(self):
+ return [(str(b), b) for b in self.BYTESIZES]
+
+ def getSupportedStopbits(self):
+ return [(str(b), b) for b in self.STOPBITS]
+
+ def getSupportedParities(self):
+ return [(PARITY_NAMES[b], b) for b in self.PARITIES]
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def setPort(self, port):
+ """Change the port. The attribute portstr is set to a string that
+ contains the name of the port."""
+
+ was_open = self._isOpen
+ if was_open: self.close()
+ if port is not None:
+ if type(port) in [type(''), type(u'')]: #strings are taken directly
+ self.portstr = port
+ else:
+ self.portstr = self.makeDeviceName(port)
+ else:
+ self.portstr = None
+ self._port = port
+ if was_open: self.open()
+
+ def getPort(self):
+ """Get the current port setting. The value that was passed on init or using
+ setPort() is passed back. See also the attribute portstr which contains
+ the name of the port as a string."""
+ return self._port
+
+ port = property(getPort, setPort, doc="Port setting")
+
+
+ def setBaudrate(self, baudrate):
+ """Change baudrate. It raises a ValueError if the port is open and the
+ baudrate is not possible. If the port is closed, then tha value is
+ accepted and the exception is raised when the port is opened."""
+ #~ if baudrate not in self.BAUDRATES: raise ValueError("Not a valid baudrate: %r" % baudrate)
+ try:
+ self._baudrate = int(baudrate)
+ except TypeError:
+ raise ValueError("Not a valid baudrate: %r" % baudrate)
+ else:
+ if self._isOpen: self._reconfigurePort()
+
+ def getBaudrate(self):
+ """Get the current baudrate setting."""
+ return self._baudrate
+
+ baudrate = property(getBaudrate, setBaudrate, doc="Baudrate setting")
+
+
+ def setByteSize(self, bytesize):
+ """Change byte size."""
+ if bytesize not in self.BYTESIZES: raise ValueError("Not a valid byte size: %r" % bytesize)
+ self._bytesize = bytesize
+ if self._isOpen: self._reconfigurePort()
+
+ def getByteSize(self):
+ """Get the current byte size setting."""
+ return self._bytesize
+
+ bytesize = property(getByteSize, setByteSize, doc="Byte size setting")
+
+
+ def setParity(self, parity):
+ """Change parity setting."""
+ if parity not in self.PARITIES: raise ValueError("Not a valid parity: %r" % parity)
+ self._parity = parity
+ if self._isOpen: self._reconfigurePort()
+
+ def getParity(self):
+ """Get the current parity setting."""
+ return self._parity
+
+ parity = property(getParity, setParity, doc="Parity setting")
+
+
+ def setStopbits(self, stopbits):
+ """Change stopbits size."""
+ if stopbits not in self.STOPBITS: raise ValueError("Not a valid stopbit size: %r" % stopbits)
+ self._stopbits = stopbits
+ if self._isOpen: self._reconfigurePort()
+
+ def getStopbits(self):
+ """Get the current stopbits setting."""
+ return self._stopbits
+
+ stopbits = property(getStopbits, setStopbits, doc="Stopbits setting")
+
+
+ def setTimeout(self, timeout):
+ """Change timeout setting."""
+ if timeout is not None:
+ if timeout < 0: raise ValueError("Not a valid timeout: %r" % timeout)
+ try:
+ timeout + 1 #test if it's a number, will throw a TypeError if not...
+ except TypeError:
+ raise ValueError("Not a valid timeout: %r" % timeout)
+
+ self._timeout = timeout
+ if self._isOpen: self._reconfigurePort()
+
+ def getTimeout(self):
+ """Get the current timeout setting."""
+ return self._timeout
+
+ timeout = property(getTimeout, setTimeout, doc="Timeout setting for read()")
+
+
+ def setWriteTimeout(self, timeout):
+ """Change timeout setting."""
+ if timeout is not None:
+ if timeout < 0: raise ValueError("Not a valid timeout: %r" % timeout)
+ try:
+ timeout + 1 #test if it's a number, will throw a TypeError if not...
+ except TypeError:
+ raise ValueError("Not a valid timeout: %r" % timeout)
+
+ self._writeTimeout = timeout
+ if self._isOpen: self._reconfigurePort()
+
+ def getWriteTimeout(self):
+ """Get the current timeout setting."""
+ return self._writeTimeout
+
+ writeTimeout = property(getWriteTimeout, setWriteTimeout, doc="Timeout setting for write()")
+
+
+ def setXonXoff(self, xonxoff):
+ """Change XonXoff setting."""
+ self._xonxoff = xonxoff
+ if self._isOpen: self._reconfigurePort()
+
+ def getXonXoff(self):
+ """Get the current XonXoff setting."""
+ return self._xonxoff
+
+ xonxoff = property(getXonXoff, setXonXoff, doc="Xon/Xoff setting")
+
+ def setRtsCts(self, rtscts):
+ """Change RtsCts flow control setting."""
+ self._rtscts = rtscts
+ if self._isOpen: self._reconfigurePort()
+
+ def getRtsCts(self):
+ """Get the current RtsCts flow control setting."""
+ return self._rtscts
+
+ rtscts = property(getRtsCts, setRtsCts, doc="RTS/CTS flow control setting")
+
+ def setDsrDtr(self, dsrdtr=None):
+ """Change DsrDtr flow control setting."""
+ if dsrdtr is None:
+ #if not set, keep backwards compatibility and follow rtscts setting
+ self._dsrdtr = self._rtscts
+ else:
+ #if defined independently, follow its value
+ self._dsrdtr = dsrdtr
+ if self._isOpen: self._reconfigurePort()
+
+ def getDsrDtr(self):
+ """Get the current DsrDtr flow control setting."""
+ return self._dsrdtr
+
+ dsrdtr = property(getDsrDtr, setDsrDtr, "DSR/DTR flow control setting")
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def __repr__(self):
+ """String representation of the current port settings and its state."""
+ return "%s<id=0x%x, open=%s>(port=%r, baudrate=%r, bytesize=%r, parity=%r, stopbits=%r, timeout=%r, xonxoff=%r, rtscts=%r, dsrdtr=%r)" % (
+ self.__class__.__name__,
+ id(self),
+ self._isOpen,
+ self.portstr,
+ self.baudrate,
+ self.bytesize,
+ self.parity,
+ self.stopbits,
+ self.timeout,
+ self.xonxoff,
+ self.rtscts,
+ self.dsrdtr,
+ )
+
+if __name__ == '__main__':
+ s = SerialBase()
+ print s.portstr
+ print s.getSupportedBaudrates()
+ print s.getSupportedByteSizes()
+ print s.getSupportedParities()
+ print s.getSupportedStopbits()
+ print s
diff --git a/maximus/python/lib/proto/pyserial/serial/serialwin32.py b/maximus/python/lib/proto/pyserial/serial/serialwin32.py
new file mode 100644
index 0000000000..1c08c42782
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/serial/serialwin32.py
@@ -0,0 +1,314 @@
+#! python
+#Python Serial Port Extension for Win32, Linux, BSD, Jython
+#serial driver for win32
+#see __init__.py
+#
+#(C) 2001-2003 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+import win32file # The base COM port and file IO functions.
+import win32event # We use events and the WaitFor[Single|Multiple]Objects functions.
+import win32con # constants.
+from serialutil import *
+
+VERSION = "$Revision: 1.31 $".split()[1] #extract CVS version
+
+#from winbase.h. these should realy be in win32con
+MS_CTS_ON = 16
+MS_DSR_ON = 32
+MS_RING_ON = 64
+MS_RLSD_ON = 128
+
+def device(portnum):
+ """Turn a port number into a device name"""
+ #the "//./COMx" format is required for devices >= 9
+ #not all versions of windows seem to support this propperly
+ #so that the first few ports are used with the DOS device name
+ if portnum < 9:
+ return 'COM%d' % (portnum+1) #numbers are transformed to a string
+ else:
+ return r'\\.\COM%d' % (portnum+1)
+
+class Serial(SerialBase):
+ """Serial port implemenation for Win32. This implemenatation requires a
+ win32all installation."""
+
+ BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
+ 19200,38400,57600,115200)
+
+ def open(self):
+ """Open port with current settings. This may throw a SerialException
+ if the port cannot be opened."""
+ if self._port is None:
+ raise SerialException("Port must be configured before it can be used.")
+ self.hComPort = None
+ try:
+ self.hComPort = win32file.CreateFile(self.portstr,
+ win32con.GENERIC_READ | win32con.GENERIC_WRITE,
+ 0, # exclusive access
+ None, # no security
+ win32con.OPEN_EXISTING,
+ win32con.FILE_ATTRIBUTE_NORMAL | win32con.FILE_FLAG_OVERLAPPED,
+ None)
+ except Exception, msg:
+ self.hComPort = None #'cause __del__ is called anyway
+ raise SerialException("could not open port: %s" % msg)
+ # Setup a 4k buffer
+ win32file.SetupComm(self.hComPort, 4096, 4096)
+
+ #Save original timeout values:
+ self._orgTimeouts = win32file.GetCommTimeouts(self.hComPort)
+
+ self._rtsState = win32file.RTS_CONTROL_ENABLE
+ self._dtrState = win32file.RTS_CONTROL_ENABLE
+
+ self._reconfigurePort()
+
+ # Clear buffers:
+ # Remove anything that was there
+ win32file.PurgeComm(self.hComPort,
+ win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT |
+ win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)
+
+ self._overlappedRead = win32file.OVERLAPPED()
+ self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
+ self._overlappedWrite = win32file.OVERLAPPED()
+ #~ self._overlappedWrite.hEvent = win32event.CreateEvent(None, 1, 0, None)
+ self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
+ self._isOpen = True
+
+ def _reconfigurePort(self):
+ """Set commuication parameters on opened port."""
+ if not self.hComPort:
+ raise SerialException("Can only operate on a valid port handle")
+
+ #Set Windows timeout values
+ #timeouts is a tuple with the following items:
+ #(ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
+ # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
+ # WriteTotalTimeoutConstant)
+ if self._timeout is None:
+ timeouts = (0, 0, 0, 0, 0)
+ elif self._timeout == 0:
+ timeouts = (win32con.MAXDWORD, 0, 0, 0, 0)
+ else:
+ timeouts = (0, 0, int(self._timeout*1000), 0, 0)
+ if self._writeTimeout is None:
+ pass
+ elif self._writeTimeout == 0:
+ timeouts = timeouts[:-2] + (0, win32con.MAXDWORD)
+ else:
+ timeouts = timeouts[:-2] + (0, int(self._writeTimeout*1000))
+ win32file.SetCommTimeouts(self.hComPort, timeouts)
+
+ win32file.SetCommMask(self.hComPort, win32file.EV_ERR)
+
+ # Setup the connection info.
+ # Get state and modify it:
+ comDCB = win32file.GetCommState(self.hComPort)
+ comDCB.BaudRate = self._baudrate
+
+ if self._bytesize == FIVEBITS:
+ comDCB.ByteSize = 5
+ elif self._bytesize == SIXBITS:
+ comDCB.ByteSize = 6
+ elif self._bytesize == SEVENBITS:
+ comDCB.ByteSize = 7
+ elif self._bytesize == EIGHTBITS:
+ comDCB.ByteSize = 8
+ else:
+ raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
+
+ if self._parity == PARITY_NONE:
+ comDCB.Parity = win32file.NOPARITY
+ comDCB.fParity = 0 # Dis/Enable Parity Check
+ elif self._parity == PARITY_EVEN:
+ comDCB.Parity = win32file.EVENPARITY
+ comDCB.fParity = 1 # Dis/Enable Parity Check
+ elif self._parity == PARITY_ODD:
+ comDCB.Parity = win32file.ODDPARITY
+ comDCB.fParity = 1 # Dis/Enable Parity Check
+ else:
+ raise ValueError("Unsupported parity mode: %r" % self._parity)
+
+ if self._stopbits == STOPBITS_ONE:
+ comDCB.StopBits = win32file.ONESTOPBIT
+ elif self._stopbits == STOPBITS_TWO:
+ comDCB.StopBits = win32file.TWOSTOPBITS
+ else:
+ raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
+
+ comDCB.fBinary = 1 # Enable Binary Transmission
+ # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
+ if self._rtscts:
+ comDCB.fRtsControl = win32file.RTS_CONTROL_HANDSHAKE
+ else:
+ comDCB.fRtsControl = self._rtsState
+ if self._dsrdtr:
+ comDCB.fDtrControl = win32file.DTR_CONTROL_HANDSHAKE
+ else:
+ comDCB.fDtrControl = self._dtrState
+ comDCB.fOutxCtsFlow = self._rtscts
+ comDCB.fOutxDsrFlow = self._dsrdtr
+ comDCB.fOutX = self._xonxoff
+ comDCB.fInX = self._xonxoff
+ comDCB.fNull = 0
+ comDCB.fErrorChar = 0
+ comDCB.fAbortOnError = 0
+ comDCB.XonChar = XON
+ comDCB.XoffChar = XOFF
+
+ try:
+ win32file.SetCommState(self.hComPort, comDCB)
+ except win32file.error, e:
+ raise ValueError("Cannot configure port, some setting was wrong. Original message: %s" % e)
+
+ #~ def __del__(self):
+ #~ self.close()
+
+ def close(self):
+ """Close port"""
+ if self._isOpen:
+ if self.hComPort:
+ #Restore original timeout values:
+ win32file.SetCommTimeouts(self.hComPort, self._orgTimeouts)
+ #Close COM-Port:
+ win32file.CloseHandle(self.hComPort)
+ self.hComPort = None
+ self._isOpen = False
+
+ def makeDeviceName(self, port):
+ return device(port)
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def inWaiting(self):
+ """Return the number of characters currently in the input buffer."""
+ flags, comstat = win32file.ClearCommError(self.hComPort)
+ return comstat.cbInQue
+
+ def read(self, size=1):
+ """Read size bytes from the serial port. If a timeout is set it may
+ return less characters as requested. With no timeout it will block
+ until the requested number of bytes is read."""
+ if not self.hComPort: raise portNotOpenError
+ if size > 0:
+ win32event.ResetEvent(self._overlappedRead.hEvent)
+ flags, comstat = win32file.ClearCommError(self.hComPort)
+ if self.timeout == 0:
+ n = min(comstat.cbInQue, size)
+ if n > 0:
+ rc, buf = win32file.ReadFile(self.hComPort, win32file.AllocateReadBuffer(n), self._overlappedRead)
+ win32event.WaitForSingleObject(self._overlappedRead.hEvent, win32event.INFINITE)
+ read = str(buf)
+ else:
+ read = ''
+ else:
+ rc, buf = win32file.ReadFile(self.hComPort, win32file.AllocateReadBuffer(size), self._overlappedRead)
+ n = win32file.GetOverlappedResult(self.hComPort, self._overlappedRead, 1)
+ read = str(buf[:n])
+ else:
+ read = ''
+ return read
+
+ def write(self, s):
+ """Output the given string over the serial port."""
+ if not self.hComPort: raise portNotOpenError
+ #print repr(s),
+ if s:
+ #~ win32event.ResetEvent(self._overlappedWrite.hEvent)
+ err, n = win32file.WriteFile(self.hComPort, s, self._overlappedWrite)
+ if err: #will be ERROR_IO_PENDING:
+ # Wait for the write to complete.
+ #~ win32event.WaitForSingleObject(self._overlappedWrite.hEvent, win32event.INFINITE)
+ n = win32file.GetOverlappedResult(self.hComPort, self._overlappedWrite, 1)
+ if n != len(s):
+ raise writeTimeoutError
+
+
+ def flushInput(self):
+ """Clear input buffer, discarding all that is in the buffer."""
+ if not self.hComPort: raise portNotOpenError
+ win32file.PurgeComm(self.hComPort, win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)
+
+ def flushOutput(self):
+ """Clear output buffer, aborting the current output and
+ discarding all that is in the buffer."""
+ if not self.hComPort: raise portNotOpenError
+ win32file.PurgeComm(self.hComPort, win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT)
+
+ def sendBreak(self):
+ """Send break condition."""
+ if not self.hComPort: raise portNotOpenError
+ import time
+ win32file.SetCommBreak(self.hComPort)
+ #TODO: how to set the correct duration??
+ time.sleep(0.020)
+ win32file.ClearCommBreak(self.hComPort)
+
+ def setRTS(self,level=1):
+ """Set terminal status line: Request To Send"""
+ if not self.hComPort: raise portNotOpenError
+ if level:
+ self._rtsState = win32file.RTS_CONTROL_ENABLE
+ win32file.EscapeCommFunction(self.hComPort, win32file.SETRTS)
+ else:
+ self._rtsState = win32file.RTS_CONTROL_DISABLE
+ win32file.EscapeCommFunction(self.hComPort, win32file.CLRRTS)
+
+ def setDTR(self,level=1):
+ """Set terminal status line: Data Terminal Ready"""
+ if not self.hComPort: raise portNotOpenError
+ if level:
+ self._dtrState = win32file.DTR_CONTROL_ENABLE
+ win32file.EscapeCommFunction(self.hComPort, win32file.SETDTR)
+ else:
+ self._dtrState = win32file.DTR_CONTROL_DISABLE
+ win32file.EscapeCommFunction(self.hComPort, win32file.CLRDTR)
+
+ def getCTS(self):
+ """Read terminal status line: Clear To Send"""
+ if not self.hComPort: raise portNotOpenError
+ return MS_CTS_ON & win32file.GetCommModemStatus(self.hComPort) != 0
+
+ def getDSR(self):
+ """Read terminal status line: Data Set Ready"""
+ if not self.hComPort: raise portNotOpenError
+ return MS_DSR_ON & win32file.GetCommModemStatus(self.hComPort) != 0
+
+ def getRI(self):
+ """Read terminal status line: Ring Indicator"""
+ if not self.hComPort: raise portNotOpenError
+ return MS_RING_ON & win32file.GetCommModemStatus(self.hComPort) != 0
+
+ def getCD(self):
+ """Read terminal status line: Carrier Detect"""
+ if not self.hComPort: raise portNotOpenError
+ return MS_RLSD_ON & win32file.GetCommModemStatus(self.hComPort) != 0
+
+ # - - platform specific - - - -
+
+ def setXON(self, level=True):
+ """Platform specific - set flow state."""
+ if not self.hComPort: raise portNotOpenError
+ if level:
+ win32file.EscapeCommFunction(self.hComPort, win32file.SETXON)
+ else:
+ win32file.EscapeCommFunction(self.hComPort, win32file.SETXOFF)
+
+#Nur Testfunktion!!
+if __name__ == '__main__':
+ print __name__
+ s = Serial()
+ print s
+
+ s = Serial(0)
+ print s
+
+ s.baudrate = 19200
+ s.databits = 7
+ s.close()
+ s.port = 3
+ s.open()
+ print s
+
diff --git a/maximus/python/lib/proto/pyserial/setup.py b/maximus/python/lib/proto/pyserial/setup.py
new file mode 100644
index 0000000000..b3412f6ff5
--- /dev/null
+++ b/maximus/python/lib/proto/pyserial/setup.py
@@ -0,0 +1,38 @@
+# setup.py
+from distutils.core import setup
+import sys
+
+#windows installer:
+# python setup.py bdist_wininst
+
+# patch distutils if it can't cope with the "classifiers" or
+# "download_url" keywords
+if sys.version < '2.2.3':
+ from distutils.dist import DistributionMetadata
+ DistributionMetadata.classifiers = None
+ DistributionMetadata.download_url = None
+
+setup(
+ name="pyserial",
+ description="Python Serial Port Extension",
+ version="2.2",
+ author="Chris Liechti",
+ author_email="cliechti@gmx.net",
+ url="http://pyserial.sourceforge.net/",
+ packages=['serial'],
+ license="Python",
+ long_description="Python Serial Port Extension for Win32, Linux, BSD, Jython",
+ classifiers = [
+ 'Development Status :: 5 - Production/Stable',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: End Users/Desktop',
+ 'License :: OSI Approved :: Python Software Foundation License',
+ 'Natural Language :: English',
+ 'Operating System :: POSIX',
+ 'Operating System :: Microsoft :: Windows',
+ 'Programming Language :: Python',
+ 'Topic :: Communications',
+ 'Topic :: Software Development :: Libraries',
+ 'Topic :: Terminals :: Serial',
+ ],
+)
diff --git a/maximus/python/lib/proto/uspp/AUTHORS b/maximus/python/lib/proto/uspp/AUTHORS
new file mode 100644
index 0000000000..f21051cb3a
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/AUTHORS
@@ -0,0 +1,4 @@
+Isaac Barona Martínez <ibarona@tid.es> Madrid (SPAIN)
+Damien Géranton <dgeranton@voila.fr>
+Douglas Jones <dfj23@drexel.edu>
+J.Grauheding <juergen.grauheding@a-city.de>
diff --git a/maximus/python/lib/proto/uspp/Copyright b/maximus/python/lib/proto/uspp/Copyright
new file mode 100644
index 0000000000..a9ed744a19
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/Copyright
@@ -0,0 +1,21 @@
+USPP Library (Universal Serial Port Python Library)
+
+Copyright (C) 2006 Isaac Barona Martínez <ibarona@tid.es>
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+
+The complete text of the GNU Lesser General Public License can be found in
+the file 'lesser.txt'.
diff --git a/maximus/python/lib/proto/uspp/Readme b/maximus/python/lib/proto/uspp/Readme
new file mode 100644
index 0000000000..623cc2b9b6
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/Readme
@@ -0,0 +1,190 @@
+ USPP Library
+
+ Universal Serial Port Python Library
+
+ Copyright 2006 Isaac Barona <ibarona@gmail.com>
+
+
+Contents
+--------
+ 1. Introduction
+ 2. Motivation
+ 3. Where can I find it
+ 4. Features
+ 5. Pre-requisites
+ 6. Usage and documentation
+ 7. Where does it work
+ 8. Known problems
+ 9. To-do list
+10. Porting to other platforms
+11. Licence
+12. Author
+13. Version
+
+
+1. Introduction
+---------------
+
+USPP Library is a multi-platform Python module to access serial ports. At the
+moment, it only works in Windows, Linux and MacOS but as it is written entirely
+in Python (doesn't wrap any C/C++ library) I hope you can extend it to support
+any other platforms.
+
+
+2. Motivation
+-------------
+
+I like very much to make electronic widgets with microcontrollers, specially
+those that can be connected to the computer to send and receive data.
+Some months ago, I discovered Python and inmediatelly liked it a lot.
+I started playing with it and saw that I could use it to make prototypes of
+comunication protocols between computer and microcontrollers really
+fast and easily than using C. At the same time, I was interested in
+working over different platforms.
+I started looking for Python modules to access serial port and I found
+the following projects:
+
+ * win32comport_demo from the win32 extension module
+ * win32comm module of wheineman@uconect.net
+ * Sio Module of Roger Rurnham (rburnham@cri-inc.com)
+ * pyxal (Python X10 Abstraction Layer) of Les Smithson
+ (lsmithson@open-networks.co.uk)
+
+but they were not multi-platform, were just a wrap of propietary libraries or
+were just simple examples of serial port access.
+For these reasons and also for learning more Python, I decided to start
+this project. Of course, I have used all this projects as reference to
+my module and so, I want to thanks the authors for their excellent work and
+for allowing us to study the code.
+I hope you enjoy using the uspp module as much as I am enjoying doing it.
+
+
+3. Where can I find it
+----------------------
+
+You may find it at:
+ * http://ibarona.googlepages.com/uspp
+ * http://www.telefonica.net/web/babur
+
+as a tar.gz package or as a winzip file.
+
+
+4. Features
+-----------
+
+This module has the following features:
+
+ - hight level access to serial port under several platforms.
+ - autodetects the platform in which it is working and exports
+ the correct classes for that platform.
+ - object oriented approach.
+ - file object semantic operations over the ports.
+ - allows using the serial port with different speeds and
+ characteristics.
+ - RS-232 and RS-485 modes (now only RS-232). In RS-485 mode
+ the communication is half-duplex and uses the RTS line
+ to control the direction of the transference.
+ - blocking, non-blocking or configurable timeout reads.
+
+
+5. Prerequisites
+----------------
+
+You need the following to use the library:
+
+ - Python 2.1 or better
+ - In windows you need the win32 extension modules
+
+
+6. Usage and documentation
+--------------------------
+
+You only have to import in your program the uspp module and automatically
+it loads the correct classes for the platform in which you are running
+the program.
+
+First of all you have to create a SerialPort object with the settings you
+want. If a SerialPortException is not generated then you just can
+use the read and write methods of the object to read and write to
+the serial port.
+
+Example:
+
+>>> from uspp import *
+>>> tty=SerialPort("COM2", 1000, 9600)
+>>> # Opens COM2 at 9600 bps and with a read timeout of 1 second.
+>>> tty.write("a") # Writes a character to the COM2 port
+>>> # Now suppose we receive the string "abc"
+>>> tty.inWaiting()
+3
+>>> tty.read()
+'a'
+>>> tty.inWaiting()
+2
+>>> tty.read(2)
+'bc'
+
+
+Documentation of the different classes and methods can be found on
+uspp module docstring.
+
+
+7. Where does it work
+---------------------
+
+The library has been tested in Windows 95, Windows XP and Windows 2000
+machines with Python 2.1+ and in a Linux (2.0.34 kernel) machine with
+Python 2.1+.
+
+
+8. Known problems
+-----------------
+
+
+
+
+9. To-do list
+-------------
+
+This is the to-do list:
+
+ - implement RS-485 mode.
+ - port the library to other platforms so that it can be really
+ multi-platform.
+
+
+10. Porting to other platforms
+-----------------------------
+
+If you want to port the library to other platforms you only have to follow
+these steps:
+
+* Create a new python file called SerialPort_XXXX.py in which you
+implement the same public classes and methods found in the SerialPort_win
+and SerialPort_linux modules.
+* Append the new platform to the uspp.py file.
+
+
+11. Licence
+----------
+
+This code is released under the "LGPL" that can be found in
+http://www.gnu.org/copyleft/lesser.html or in the lesser.txt file that
+is with the library.
+If you use this software, I'd like to know about it.
+
+
+12. Author
+---------
+
+This library has been created by Isaac Barona Martinez <ibarona@gmail.com>.
+
+
+13. Version
+----------
+
+0.1 - 09/01/2001 (September 2001)
+0.2 - 05/13/2003
+1.0 - 02/24/2006
+
+
diff --git a/maximus/python/lib/proto/uspp/Readme_es b/maximus/python/lib/proto/uspp/Readme_es
new file mode 100644
index 0000000000..08e1a9a7aa
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/Readme_es
@@ -0,0 +1,199 @@
+ USPP Library
+
+ Universal Serial Port Python Library
+ (Librería en Python para el acceso universal al puerto serie)
+
+ Copyright 2006 Isaac Barona <ibarona@gmail.com>
+
+
+Contenidos
+----------
+ 1. Introducción
+ 2. Motivación
+ 3. Dónde encontrar la librería
+ 4. Características
+ 5. Pre-requisitos
+ 6. Utilización y documentación
+ 7. Dónde funciona
+ 8. Problemas pendientes
+ 9. Tareas pendientes
+10. Portado a otras plataformas
+11. Licencia
+12. Autor
+13. Versión
+
+
+1. Introducción
+---------------
+
+La librería USPP es un módulo desarrollado en Python para el acceso
+multiplataforma al puerto serie. En el momento, sólo funciona en Linux
+Windows y MacOS, pero como está escrita completamente en Python
+(no es únicamente un recubrimiento en Python de una librería desarrollada
+en C/C++) espero que pueda ser ampliada para que soporte otras plataformas.
+
+
+2. Motivación
+-------------
+
+A mí me gusta mucho hacer pequeños cacharros electrónicos con
+microcontroladores, especialmente aquellos que pueden ser conectados a
+un ordenador para enviar y recibir datos.
+Hace un par de meses descubrí Python y realmente me encantó.
+Empezé a jugar con él y ví que podía utilizarlo para hacer prototipos
+de protocolos de comunicación entre el ordenador y los microcontroladores
+de manera mucho más fácil y rápida que utilizando C (que era el lenguaje
+que solía utilizar). Al mismo tiempo, estaba interesado en poder utilizar
+los desarrollos bajo diferentes arquitecturas.
+Empezé a buscar en la red módulos de Python que accedieran al puerto serie
+y encontré los siguientes:
+
+ * win32comport_demo que viene junto a la extensión win32.
+ * Módulo win32comm de wheineman@uconect.net.
+ * Sio Module de Roger Rurnham (rburnham@cri-inc.com)
+ * pyxal (Python X10 Abstraction Layer) de Les Smithson
+ (lsmithson@open-networks.co.uk)
+
+pero no eran multiplataforma, eran únicamente un recubrimiento de una librería
+propietaria o eran simples ejemplos de acceso al puerto serie bajo una
+determinada plataforma.
+Por estas razones, y también por supuesto, por aprender más Python, decidí
+empezar este proyecto. Por supuesto, he utilizado los módulos indicados
+anteriormente como referencia para realizar mi librería y por tanto, me
+creo en la obligación de felicitar a sus autores por su excelente trabajo y
+por haberlo compartido con los demás.
+
+Espero que disfrutes utilizándo el módulo uspp tanto como yo lo
+he hecho haciéndolo.
+
+
+3. Dónde encontrar la librería
+------------------------------
+
+Puedes encontrarla en:
+ * http://ibarona.googlepages.com/uspp
+ * http://www.telefonica.net/web/babur
+
+como un fichero tar.gz o como un fichero .zip.
+
+
+4. Características
+------------------
+
+Este módulo tiene las siguientes características destacadas:
+
+ - acceso de alto nivel al puerto serie bajo diversas plataformas.
+ - autodetecta la plataforma en la que se está ejecutando y
+ carga las clases adecuadas para esa plataforma.
+ - Orientado a objetos.
+ - Las operaciones sobre el puerto serie tienen la misma semántica
+ que las operaciones sobre objetos de tipo fichero.
+ - permite utilizar el puerto serie con diferentes velocidades y
+ características.
+ - permite la utilización del puerto bajo dos modos de funcionamiento:
+ RS-232 y RS-485 (de momento, sólo RS-232). En modo 485 la
+ comunicación es half-duplex y se utiliza la línea RTS para controlar
+ la dirección de la transferencia.
+ - lecturas en modo bloqueante, no bloqueante o con timeout.
+
+
+5. Pre-requisitos
+----------------
+
+Se necesita los siguiente para utilizar la librería:
+
+ - Python 2.1 o superior
+ - En windows los módulos win32
+
+
+6. Utilización y documentación
+------------------------------
+
+Únicamente tienes que importar en tu programa el módulo uspp y automáticamente
+él se encarga de cargar las clases adecuadas para la plataforma en la que
+se está ejecutando el programa.
+
+Lo primero de todo, tendrás que crear un objeto de tipo SerialPort con las
+características que desees. Si no se genera ninguna excepción del tipo
+SerialPortException, puedes utilizar los métodos de lectura y escritura
+del objeto para leer y escribir en el puerto serie.
+
+Ejemplo:
+
+>>> from uspp import *
+>>> tty=SerialPort("COM2", 1000, 9600)
+>>> # Abre el puerto serie COM2 a 9600 bps y con un timeout de 1 segundo.
+>>> tty.write("a") # Envía el carácter 'a' al puerto serie.
+>>> # Ahora suponemos que recibimos el string 'abc'
+>>> tty.inWaiting()
+3
+>>> tty.read()
+'a'
+>>> tty.inWaiting()
+2
+>>> tty.read(2)
+'bc'
+
+
+La documentación de las diferentes clases y métodos que componen el módulo
+puede encontrarse en el string de documentación del módulo uspp.
+
+
+7. Dónde funciona
+-----------------
+
+La librería ha sido probada en una máquina con Windows 95, Windows XP y
+Windows 2000 con Python 2.1+ y en un Linux (con el kernel 2.0.34) con Python
+2.1+.
+
+
+8. Problemas pendientes
+-----------------------
+
+
+
+
+9. Tareas pendientes
+--------------------
+
+Esta es la lista de tareas pendientes:
+
+ - implementar el modo RS-485.
+ - portar la librería a otras plataformas de forma que sea
+ realmente multiplataforma.
+
+
+10. Portado a otras plataformas
+-------------------------------
+
+Si quieres portar la librería a otras plataformas sólo tienes que seguir
+los siguientes pasos:
+
+* Crear un nuevo fichero en python llamado SerialPort_XXX.py en el que
+implementes las mismas clases y métodos públicos que aparecen en los
+módulos SerialPort_win y SerialPort_linux.
+* Añadir la nueva plataforma en el fichero uspp.py.
+
+
+11. Licencia
+------------
+
+Este código se libera bajo la licencia "LGPL" que puedes encontrar en
+http://www.gnu.org/copyleft/lesser.html o en el fichero lesser.txt que
+acompaña a la librería.
+Si utilizas este software estaría muy agradecido de saberlo.
+
+
+12. Autor
+---------
+
+Esta librería ha sido creada por Isaac Barona Martínez <ibarona@gmail.com>.
+
+
+13. Versión
+----------
+
+0.1 - 01/09/2001
+0.2 - 13/05/2003
+1.0 - 24/02/2006
+
diff --git a/maximus/python/lib/proto/uspp/SerialPort_darwin.py b/maximus/python/lib/proto/uspp/SerialPort_darwin.py
new file mode 100644
index 0000000000..ff478b511f
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/SerialPort_darwin.py
@@ -0,0 +1,326 @@
+##########################################################################
+# USPP Library (Universal Serial Port Python Library)
+#
+# Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+##########################################################################
+
+#-------------------------------------------------------------------------
+# Project: USPP Library (Universal Serial Port Python Library)
+# Name: SerialPort_darwin.py
+# Purpose: Handle low level access to serial port in MacOS.
+#
+# Author: Isaac Barona Martinez <ibarona@gmail.com>
+# Copyright: (c) 2001 by Isaac Barona Martínez
+# Licence: LGPL
+#
+# Created: 26 June 2001
+# History: 06.02.2003 Modified and extended by J.Grauheding
+# <juergen.grauheding@a-city.de>
+# adapt it for Python 2.2 on Mac OS X
+# Douglas Jones (dfj23@drexel.edu)
+# - readline method.
+#
+#-------------------------------------------------------------------------
+
+"""
+SerialPort_darwin.py - Handle low level access to serial port in Mac OS X.
+
+See also uspp module docstring.
+
+
+"""
+
+import os
+import tty
+import termios
+import array
+import fcntl
+import exceptions
+import string
+
+class SerialPortException(exceptions.Exception):
+ """Exception raise in the SerialPort methods"""
+ def __init__(self, args=None):
+ self.args=args
+
+
+class SerialPort:
+ """Encapsulate methods for accesing to a serial port."""
+
+ BaudRatesDic={
+ 50: termios.B50,
+ 75: termios.B75,
+ 110: termios.B110,
+ 134: termios.B134,
+ 150: termios.B150,
+ 200: termios.B200,
+ 300: termios.B300,
+ 600: termios.B600,
+ 1200: termios.B1200,
+ 1800: termios.B1800,
+ 2400: termios.B2400,
+ 4800: termios.B4800,
+ 9600: termios.B9600,
+ 19200: termios.B19200,
+ 38400: termios.B38400,
+ 57600: termios.B57600,
+ 115200: termios.B115200,
+ 230400: termios.B230400
+ }
+ buf = array.array('h', '\000'*4)
+
+ def __init__(self, dev, timeout=None, speed=None, mode='232', params=None):
+ """Open the serial port named by the string 'dev'
+
+ 'dev' can be any of the following strings: '/dev/ttyS0', '/dev/ttyS1',
+ ..., '/dev/ttySX' or '/dev/cua0', '/dev/cua1', ..., '/dev/cuaX'.
+
+ 'timeout' specifies the inter-byte timeout or first byte timeout
+ (in miliseconds) for all subsequent reads on SerialPort.
+ If we specify None time-outs are not used for reading operations
+ (blocking reading).
+ If 'timeout' is 0 then reading operations are non-blocking. It
+ specifies that the reading operation is to return inmediately
+ with the bytes that have already been received, even if
+ no bytes have been received.
+
+ 'speed' is an integer that specifies the input and output baud rate to
+ use. Possible values are: 110, 300, 600, 1200, 2400, 4800, 9600,
+ 19200, 38400, 57600 and 115200.
+ If None a default speed of 9600 bps is selected.
+
+ 'mode' specifies if we are using RS-232 or RS-485. The RS-485 mode
+ is half duplex and use the RTS signal to indicate the
+ direction of the communication (transmit or recive).
+ Default to RS232 mode (at moment, only the RS-232 mode is
+ implemented).
+
+ 'params' is a list that specifies properties of the serial
+ communication.
+ If params=None it uses default values for the number of bits
+ per byte (8), the parity (NOPARITY) and the number of stop bits (1)
+ else params is the termios package mode array to use for
+ initialization.
+
+ """
+ self.__devName, self.__timeout, self.__speed=dev, timeout, speed
+ self.__mode=mode
+ self.__params=params
+ try:
+ self.__handle=os.open(dev, os.O_RDWR)
+ except:
+ raise SerialPortException('Unable to open port')
+
+ self.__configure()
+
+ def __del__(self):
+ """Close the serial port and restore its initial configuration
+
+ To close the serial port we have to do explicity: del s
+ (where s is an instance of SerialPort)
+ """
+
+ termios.tcsetattr(self.__handle, termios.TCSANOW, self.__oldmode)
+
+ try:
+ os.close(self.__handle)
+ except IOError:
+ raise SerialPortException('Unable to close port')
+
+
+ def __configure(self):
+ """Configure the serial port.
+
+ Private method called in the class constructor that configure the
+ serial port with the characteristics given in the constructor.
+ """
+ if not self.__speed:
+ self.__speed=9600
+
+ # Save the initial port configuration
+ self.__oldmode=termios.tcgetattr(self.__handle)
+ if not self.__params:
+ # self.__params is a list of attributes of the file descriptor
+ # self.__handle as follows:
+ # [c_iflag, c_oflag, c_cflag, c_lflag, c_ispeed, c_ospeed, cc]
+ # where cc is a list of the tty special characters.
+ self.__params=[]
+ # c_iflag
+ self.__params.append(termios.IGNPAR)
+ # c_oflag
+ self.__params.append(0)
+ # c_cflag
+ self.__params.append(termios.CS8|termios.CLOCAL|termios.CREAD)
+ # c_lflag
+ self.__params.append(0)
+ # c_ispeed
+ self.__params.append(SerialPort.BaudRatesDic[self.__speed])
+ # c_ospeed
+ self.__params.append(SerialPort.BaudRatesDic[self.__speed])
+ # XXX FIX: Theorically, it should be better to put:
+ # cc=[0]*termios.NCCS
+ # but it doesn't work because NCCS is 19 and self.__oldmode[6]
+ # is 32 ¿¿¿¿¿¿¿¿¿¿¿ Any help ??????????????
+ cc=[0]*len(self.__oldmode[6])
+ if self.__timeout==None:
+ # A reading is only complete when VMIN characters have
+ # been received (blocking reading)
+ cc[termios.VMIN]=1
+ cc[termios.VTIME]=0
+ elif self.__timeout==0:
+ # Non-blocking reading. The reading operation returns
+ # inmeditately, returning the characters waiting to
+ # be read.
+ cc[termios.VMIN]=0
+ cc[termios.VTIME]=0
+ else:
+ # Time-out reading. For a reading to be correct
+ # a character must be recieved in VTIME*100 seconds.
+ cc[termios.VMIN]=0
+ cc[termios.VTIME]=self.__timeout/100
+ self.__params.append(cc) # c_cc
+
+ termios.tcsetattr(self.__handle, termios.TCSANOW, self.__params)
+
+
+ def fileno(self):
+ """Return the file descriptor for opened device.
+
+ This information can be used for example with the
+ select funcion.
+ """
+ return self.__handle
+
+
+ def setraw(self):
+ tty.setraw(self.__handle)
+
+ def setcbreak(self):
+ tty.setcbreak(self.__handle)
+
+ def __read1(self):
+ """Read 1 byte from the serial port.
+
+ Generate an exception if no byte is read and self.timeout!=0
+ because a timeout has expired.
+ """
+ byte = os.read(self.__handle, 1)
+ if len(byte)==0 and self.__timeout!=0: # Time-out
+ raise SerialPortException('Timeout')
+ else:
+ return byte
+
+
+ def read(self, num=1):
+ """Read num bytes from the serial port.
+
+ Uses the private method __read1 to read num bytes. If an exception
+ is generated in any of the calls to __read1 the exception is reraised.
+ """
+ s=''
+ for i in range(num):
+ s=s+SerialPort.__read1(self)
+
+ return s
+
+
+ def readline(self):
+ """Read a line from the serial port. Returns input once a '\n'
+ character is found.
+ Douglas Jones (dfj23@drexel.edu) 09/09/2005.
+ """
+
+ s = ''
+ while not '\n' in s:
+ s = s+SerialPort.__read1(self)
+
+ return s
+
+
+ def write(self, s):
+ """Write the string s to the serial port"""
+
+ os.write(self.__handle, s)
+
+ def inWaiting(self):
+ """Returns the number of bytes waiting to be read
+ mod. by J.Grauheding
+ """
+ rbuf=fcntl.ioctl(self.__handle, termios.TIOCINQ, self.buf)
+ return rbuf
+
+ def outWaiting(self):
+ """Returns the number of bytes waiting to be write
+ mod. by J.Grauheding
+ """
+ rbuf=fcntl.ioctl(self.__handle, termios.TIOCOUTQ, self.buf)
+ return rbuf
+
+
+ def flush(self):
+ """Discards all bytes from the output or input buffer"""
+ termios.tcflush(self.__handle, termios.TCIOFLUSH)
+
+ def rts_on(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMGET, SerialPort.buf)
+ SerialPort.buf[1] = ord(rbuf[3]) | termios.TIOCM_RTS
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMSET, SerialPort.buf)
+ return rbuf
+
+ def rts_off(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMGET, self.buf)
+ self.buf[1]=ord(rbuf[3]) & ~termios.TIOCM_RTS
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMSET, self.buf)
+ return rbuf
+
+ def dtr_on(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMGET, SerialPort.buf)
+ SerialPort.buf[1] = ord(rbuf[3]) | termios.TIOCM_DTR
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMSET, SerialPort.buf)
+ return rbuf
+
+ def dtr_off(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMGET, self.buf)
+ self.buf[1]=ord(rbuf[3]) & ~termios.TIOCM_DTR
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMSET, self.buf)
+ return rbuf
+
+ def cts(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMGET, self.buf)
+ return ord(rbuf[3]) & termios.TIOCM_CTS
+
+ def cd(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMGET, self.buf)
+ return ord(rbuf[3]) & termios.TIOCM_CAR
+
+ def dsr(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMGET, self.buf)
+ return ord(rbuf[2]) & (termios.TIOCM_DSR>>8)
+
+ def ri(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, termios.TIOCMGET, self.buf)
+ return ord(rbuf[3]) & termios.TIOCM_RNG
+
+
diff --git a/maximus/python/lib/proto/uspp/SerialPort_linux.py b/maximus/python/lib/proto/uspp/SerialPort_linux.py
new file mode 100644
index 0000000000..de8d69714e
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/SerialPort_linux.py
@@ -0,0 +1,329 @@
+# -*- coding: iso-8859-1 -*-
+
+##########################################################################
+# USPP Library (Universal Serial Port Python Library)
+#
+# Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+##########################################################################
+
+#------------------------------------------------------------------------
+# Project: USPP Library (Universal Serial Port Python Library)
+# Name: SerialPort_linux.py
+# Purpose: Handle low level access to serial port in linux.
+#
+# Author: Isaac Barona Martinez <ibarona@gmail.com>
+# Copyright: (c) 2006 by Isaac Barona Martínez
+# Licence: LGPL
+#
+# Created: 26 June 2001
+# History:
+# 20 January 2002 : Damien Geranton <dgeranton@voila.fr>
+# - NCCS worry fixed. We must not use TERMIOS
+# - inWaiting call fixed.
+# 09 Sept 2005: Douglas Jones <dfj23@drexel.edu>
+# - readline method.
+#
+#-------------------------------------------------------------------------
+
+"""
+SerialPort_linux.py - Handle low level access to serial port in linux.
+
+See also uspp module docstring.
+
+
+"""
+
+import os
+from termios import *
+import fcntl
+import exceptions
+import struct
+import array
+
+
+class SerialPortException(exceptions.Exception):
+ """Exception raise in the SerialPort methods"""
+ def __init__(self, args=None):
+ self.args=args
+
+
+class SerialPort:
+ """Encapsulate methods for accesing to a serial port."""
+
+ BaudRatesDic={
+ 110: B110,
+ 300: B300,
+ 600: B600,
+ 1200: B1200,
+ 2400: B2400,
+ 4800: B4800,
+ 9600: B9600,
+ 19200: B19200,
+ 38400: B38400,
+ 57600: B57600,
+ 115200: B115200
+ }
+ buf = array.array('h', '\000'*4)
+
+ def __init__(self, dev, timeout=None, speed=None, mode='232', params=None):
+ """Open the serial port named by the string 'dev'
+
+ 'dev' can be any of the following strings: '/dev/ttyS0', '/dev/ttyS1',
+ ..., '/dev/ttySX' or '/dev/cua0', '/dev/cua1', ..., '/dev/cuaX'.
+
+ 'timeout' specifies the inter-byte timeout or first byte timeout
+ (in miliseconds) for all subsequent reads on SerialPort.
+ If we specify None time-outs are not used for reading operations
+ (blocking reading).
+ If 'timeout' is 0 then reading operations are non-blocking. It
+ specifies that the reading operation is to return inmediately
+ with the bytes that have already been received, even if
+ no bytes have been received.
+
+ 'speed' is an integer that specifies the input and output baud rate to
+ use. Possible values are: 110, 300, 600, 1200, 2400, 4800, 9600,
+ 19200, 38400, 57600 and 115200.
+ If None a default speed of 9600 bps is selected.
+
+ 'mode' specifies if we are using RS-232 or RS-485. The RS-485 mode
+ is half duplex and use the RTS signal to indicate the
+ direction of the communication (transmit or recive).
+ Default to RS232 mode (at moment, only the RS-232 mode is
+ implemented).
+
+ 'params' is a list that specifies properties of the serial
+ communication.
+ If params=None it uses default values for the number of bits
+ per byte (8), the parity (NOPARITY) and the number of stop bits (1)
+ else params is the termios package mode array to use for
+ initialization.
+
+ """
+ self.__devName, self.__timeout, self.__speed=dev, timeout, speed
+ self.__mode=mode
+ self.__params=params
+ try:
+ self.__handle=os.open(dev, os.O_RDWR)
+ except:
+ raise SerialPortException('Unable to open port')
+
+ self.__configure()
+
+ def __del__(self):
+ """Close the serial port and restore its initial configuration
+
+ To close the serial port we have to do explicity: del s
+ (where s is an instance of SerialPort)
+ """
+
+ tcsetattr(self.__handle, TCSANOW, self.__oldmode)
+
+ try:
+ os.close(self.__handle)
+ except IOError:
+ raise SerialPortException('Unable to close port')
+
+
+ def __configure(self):
+ """Configure the serial port.
+
+ Private method called in the class constructor that configure the
+ serial port with the characteristics given in the constructor.
+ """
+ if not self.__speed:
+ self.__speed=9600
+
+ # Save the initial port configuration
+ self.__oldmode=tcgetattr(self.__handle)
+ if not self.__params:
+ # self.__params is a list of attributes of the file descriptor
+ # self.__handle as follows:
+ # [c_iflag, c_oflag, c_cflag, c_lflag, c_ispeed, c_ospeed, cc]
+ # where cc is a list of the tty special characters.
+ self.__params=[]
+ # c_iflag
+ self.__params.append(IGNPAR)
+ # c_oflag
+ self.__params.append(0)
+ # c_cflag
+ self.__params.append(CS8|CLOCAL|CREAD)
+ # c_lflag
+ self.__params.append(0)
+ # c_ispeed
+ self.__params.append(SerialPort.BaudRatesDic[self.__speed])
+ # c_ospeed
+ self.__params.append(SerialPort.BaudRatesDic[self.__speed])
+ cc=[0]*NCCS
+ if self.__timeout==None:
+ # A reading is only complete when VMIN characters have
+ # been received (blocking reading)
+ cc[VMIN]=1
+ cc[VTIME]=0
+ elif self.__timeout==0:
+ # Non-blocking reading. The reading operation returns
+ # inmeditately, returning the characters waiting to
+ # be read.
+ cc[VMIN]=0
+ cc[VTIME]=0
+ else:
+ # Time-out reading. For a reading to be correct
+ # a character must be recieved in VTIME*100 seconds.
+ cc[VMIN]=0
+ cc[VTIME]=self.__timeout/100
+ self.__params.append(cc) # c_cc
+
+ tcsetattr(self.__handle, TCSANOW, self.__params)
+
+
+ def fileno(self):
+ """Return the file descriptor for opened device.
+
+ This information can be used for example with the
+ select funcion.
+ """
+ return self.__handle
+
+
+ def __read1(self):
+ """Read 1 byte from the serial port.
+
+ Generate an exception if no byte is read and self.timeout!=0
+ because a timeout has expired.
+ """
+ byte = os.read(self.__handle, 1)
+ if len(byte)==0 and self.__timeout!=0: # Time-out
+ raise SerialPortException('Timeout')
+ else:
+ return byte
+
+
+ def read(self, num=1):
+ """Read num bytes from the serial port.
+
+ Uses the private method __read1 to read num bytes. If an exception
+ is generated in any of the calls to __read1 the exception is reraised.
+ """
+ s=''
+ for i in range(num):
+ s=s+SerialPort.__read1(self)
+
+ return s
+
+
+ def readline(self):
+ """Read a line from the serial port. Returns input once a '\n'
+ character is found.
+ Douglas Jones (dfj23@drexel.edu) 09/09/2005.
+ """
+
+ s = ''
+ while not '\n' in s:
+ s = s+SerialPort.__read1(self)
+
+ return s
+
+
+ def write(self, s):
+ """Write the string s to the serial port"""
+
+ os.write(self.__handle, s)
+
+
+ def inWaiting(self):
+ """Returns the number of bytes waiting to be read"""
+ data = struct.pack("L", 0)
+ data=fcntl.ioctl(self.__handle, TIOCINQ, data)
+ return struct.unpack("L", data)[0]
+
+ def outWaiting(self):
+ """Returns the number of bytes waiting to be write
+ mod. by J.Grauheding
+ result needs some finetunning
+ """
+ rbuf=fcntl.ioctl(self.__handle, TIOCOUTQ, self.buf)
+ return rbuf
+
+ def getlsr(self):
+ """Returns the status of the UART LSR Register
+ J.Grauheding
+ """
+ rbuf=fcntl.ioctl(self.__handle, TIOCSERGETLSR, self.buf)
+ return ord(rbuf[0])
+
+ def get_temt(self):
+ """Returns the Tranmitterbuffer Empty Bit of LSR Register
+ J.Grauheding
+ test result against TIOCSER_TEMT
+ """
+ rbuf=fcntl.ioctl(self.__handle, TIOCSERGETLSR, self.buf)
+ return ord(rbuf[0]) & TIOSER_TEMT
+
+
+ def flush(self):
+ """Discards all bytes from the output or input buffer"""
+ tcflush(self.__handle, TCIOFLUSH)
+
+ def rts_on(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, TIOCMGET, SerialPort.buf)
+ SerialPort.buf[1] = ord(rbuf[3]) | TIOCM_RTS
+ rbuf = fcntl.ioctl(self.__handle, TIOCMSET, SerialPort.buf)
+ return rbuf
+
+ def rts_off(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
+ self.buf[1]=ord(rbuf[3]) & ~TIOCM_RTS
+ rbuf = fcntl.ioctl(self.__handle, TIOCMSET, self.buf)
+ return rbuf
+
+ def dtr_on(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, TIOCMGET, SerialPort.buf)
+ SerialPort.buf[1] = ord(rbuf[3]) | TIOCM_DTR
+ rbuf = fcntl.ioctl(self.__handle, TIOCMSET, SerialPort.buf)
+ return rbuf
+
+ def dtr_off(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
+ self.buf[1]=ord(rbuf[3]) & ~TIOCM_DTR
+ rbuf = fcntl.ioctl(self.__handle, TIOCMSET, self.buf)
+ return rbuf
+
+ def cts(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
+ return ord(rbuf[3]) & TIOCM_CTS
+
+ def cd(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
+ return ord(rbuf[3]) & TIOCM_CAR
+
+ def dsr(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
+ return ord(rbuf[2]) & (TIOCM_DSR>>8)
+
+ def ri(self):
+ """ J.Grauheding """
+ rbuf = fcntl.ioctl(self.__handle, TIOCMGET, self.buf)
+ return ord(rbuf[3]) & TIOCM_RNG
+
+
+
diff --git a/maximus/python/lib/proto/uspp/SerialPort_win.py b/maximus/python/lib/proto/uspp/SerialPort_win.py
new file mode 100644
index 0000000000..80410b9f40
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/SerialPort_win.py
@@ -0,0 +1,239 @@
+# -*- coding: iso-8859-1 -*-
+
+##########################################################################
+# USPP Library (Universal Serial Port Python Library)
+#
+# Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+##########################################################################
+
+#-------------------------------------------------------------------------
+# Project: USPP Library (Universal Serial Port Python Library)
+# Name: SerialPort_win.py
+# Purpose: Handle low level access to serial port in windows.
+#
+# Author: Isaac Barona Martinez <ibarona@gmail.com>
+# Copyright: (c) 2001 by Isaac Barona Martínez
+# Licence: LGPL
+#
+# Created: 26 June 2001
+# History:
+# 20 January 2002 : Damien Géranton <dgeranton@voila.fr>
+# Bug fix for Win2000, the file must not be open with
+# FILE_FLAG_OVERLAPPED
+#
+#-------------------------------------------------------------------------
+
+"""
+SerialPort_win.py - Handle low level access to serial port in windows.
+
+See also uspp module docstring.
+
+"""
+
+
+from win32file import *
+from win32event import *
+import win32con
+import exceptions
+
+class SerialPortException(exceptions.Exception):
+ """Exception raise in the SerialPort methods"""
+ def __init__(self, args=None):
+ self.args=args
+
+
+class SerialPort:
+ """Encapsulate methods for accesing to a serial port."""
+
+ BaudRatesDic={110: CBR_110,
+ 300: CBR_300,
+ 600: CBR_600,
+ 1200: CBR_1200,
+ 2400: CBR_2400,
+ 4800: CBR_4800,
+ 9600: CBR_9600,
+ 19200: CBR_19200,
+ 38400: CBR_38400,
+ 57600: CBR_57600,
+ 115200: CBR_115200,
+ }
+
+ def __init__(self, dev, timeout=None, speed=None, mode='232', params=None):
+ """Open the serial port named by the string 'dev'
+
+ 'dev' can be any of the following strings: 'COM1', 'COM2', ... 'COMX'
+
+ 'timeout' specifies the inter-byte timeout or first byte timeout
+ (in miliseconds) for all subsequent reads on SerialPort.
+ If we specify None time-outs are not used for reading operations
+ (blocking reading).
+ If 'timeout' is 0 then reading operations are non-blocking. It
+ specifies that the reading operation is to return inmediately
+ with the bytes that have already been received, even if
+ no bytes have been received.
+
+ 'speed' is an integer that specifies the input and output baud rate to
+ use. Possible values are: 110, 300, 600, 1200, 2400, 4800, 9600,
+ 19200, 38400, 57600 and 115200.
+ If None a default speed of 9600 bps is selected.
+
+ 'mode' specifies if we are using RS-232 or RS-485. The RS-485 mode
+ is half duplex and use the RTS signal to indicate the
+ direction of the communication (transmit or recive).
+ Default to RS232 mode (at moment, only the RS-232 mode is
+ implemented).
+
+ 'params' is a list that specifies properties of the serial
+ communication.
+ If params=None it uses default values for the number of bits
+ per byte (8), the parity (NOPARITY) and the number of stop bits (1)
+ else params must be a list with three items setting up the
+ these values in this order.
+
+ """
+ self.__devName, self.__timeout, self.__speed=dev, timeout, speed
+ self.__mode=mode
+ self.__params=params
+ try:
+ self.__handle=CreateFile (dev,
+ win32con.GENERIC_READ|win32con.GENERIC_WRITE,
+ 0, # exclusive access
+ None, # no security
+ win32con.OPEN_EXISTING,
+ win32con.FILE_ATTRIBUTE_NORMAL,
+ None)
+ except:
+ raise SerialPortException('Unable to open port')
+
+ self.__configure()
+
+ def __del__(self):
+ """Close the serial port
+
+ To close the serial port we have to do explicity: del s
+ (where s is an instance of SerialPort)
+ """
+ try:
+ CloseHandle(self.__handle)
+ except IOError:
+ raise SerialPortException('Unable to close port')
+
+
+ def __configure(self):
+ """Configure the serial port.
+
+ Private method called in the class constructor that configure the
+ serial port with the characteristics given in the constructor.
+ """
+ if not self.__speed:
+ self.__speed=9600
+ # Tell the port we want a notification on each char
+ SetCommMask(self.__handle, EV_RXCHAR)
+ # Setup a 4k buffer
+ SetupComm(self.__handle, 4096, 4096)
+ # Remove anything that was there
+ PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
+ PURGE_RXCLEAR)
+
+ # Setup the timeouts parameters for the port
+ # timeouts is a tuple with the following items:
+ # [0] int : ReadIntervalTimeout
+ # [1] int : ReadTotalTimeoutMultiplier
+ # [2] int : ReadTotalTimeoutConstant
+ # [3] int : WriteTotalTimeoutMultiplier
+ # [4] int : WriteTotalTimeoutConstant
+
+ if self.__timeout==None:
+ timeouts= 0, 0, 0, 0, 0
+ elif self.__timeout==0:
+ timeouts = win32con.MAXDWORD, 0, 0, 0, 1000
+ else:
+ timeouts= self.__timeout, 0, self.__timeout, 0 , 1000
+ SetCommTimeouts(self.__handle, timeouts)
+
+ # Setup the connection info
+ dcb=GetCommState(self.__handle)
+ dcb.BaudRate=SerialPort.BaudRatesDic[self.__speed]
+ if not self.__params:
+ dcb.ByteSize=8
+ dcb.Parity=NOPARITY
+ dcb.StopBits=ONESTOPBIT
+ else:
+ dcb.ByteSize, dcb.Parity, dcb.StopBits=self.__params
+ SetCommState(self.__handle, dcb)
+
+
+ def fileno(self):
+ """Return the file descriptor for opened device.
+
+ This information can be used for example with the
+ select function.
+ """
+ return self.__handle
+
+
+ def read(self, num=1):
+ """Read num bytes from the serial port.
+
+ If self.__timeout!=0 and != None and the number of read bytes is less
+ than num an exception is generated because a timeout has expired.
+ If self.__timeout==0 read is non-blocking and inmediately returns
+ up to num bytes that have previously been received.
+ """
+
+ (hr, buff) = ReadFile(self.__handle, num)
+ if len(buff)<>num and self.__timeout!=0: # Time-out
+ raise SerialPortException('Timeout')
+ else:
+ return buff
+
+
+ def readline(self):
+ """Read a line from the serial port. Returns input once a '\n'
+ character is found.
+
+ """
+
+ s = ''
+ while not '\n' in s:
+ s = s+SerialPort.read1(self,1)
+
+ return s
+
+
+ def write(self, s):
+ """Write the string s to the serial port"""
+ overlapped=OVERLAPPED()
+ overlapped.hEvent=CreateEvent(None, 0,0, None)
+ WriteFile(self.__handle, s, overlapped)
+ # Wait for the write to complete
+ WaitForSingleObject(overlapped.hEvent, INFINITE)
+
+ def inWaiting(self):
+ """Returns the number of bytes waiting to be read"""
+ flags, comstat = ClearCommError(self.__handle)
+ return comstat.cbInQue
+
+ def flush(self):
+ """Discards all bytes from the output or input buffer"""
+ PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
+ PURGE_RXCLEAR)
+
+
+
+
+
diff --git a/maximus/python/lib/proto/uspp/lesser.txt b/maximus/python/lib/proto/uspp/lesser.txt
new file mode 100644
index 0000000000..54905a6050
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/lesser.txt
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/maximus/python/lib/proto/uspp/uspp.htm b/maximus/python/lib/proto/uspp/uspp.htm
new file mode 100644
index 0000000000..d3bffac7c7
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/uspp.htm
@@ -0,0 +1,635 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><title>ibarona - USPP(Universal Serial Port Python Library)</title>
+
+
+
+
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+
+ <style type="text/css">
+ #g_title p, #g_footer p, #g_description p {
+ margin: 0;
+ }
+ /*
+
+ -- -- -- -- -- -- --
+ Browser Fixes
+ -- -- -- -- -- -- --
+
+ This file uses CSS filtering methods to fix various
+ layout bugs.
+
+ Each of the following three imported files is a
+ separate, browser-specific CSS file that keeps all
+ hacks out of the main style sheet.
+
+ Over time, as supporting these browsers no longer
+ remains a priority, cleaning up the hacks is as
+ easy as deleting the @import statement below, or
+ simply no longer linking this file from the HTML.
+
+ */
+
+ /*
+ fix ie6 "peekaboo bug" using the "holly hack".
+ Note, this style only gets applied to ie6
+ */
+ * html .wrapper {
+ height: 0.1%;
+ }
+
+ /*
+ * IE5 mac - overrides the IE/Win hack
+ */
+
+ /*\*//*/
+
+ * html #threecolumn div {
+ height: auto;
+ }
+
+ /**/
+
+
+ /*
+ * IE5/Win-specific CSS -ensures #container wraps all content on window resize
+ */
+
+ @media tty {
+ i{content:"\";/*" "*/}} * html #container { height: 1%; } /*";}
+ }/* */
+ /* Styling for editable elements. Eventually, this will be part of the style. */
+ .editable {
+ border: 1px dashed blue;
+ }
+
+ #footer {
+ clear: both;
+ }
+
+ /* Extra divs hidden by default. The custom CSS can override this though */
+ #extraDiv1, #extraDiv2, #extraDiv3, #extraDiv4, #extraDiv5, #extraDiv6 {
+ display: none;
+ }
+
+ /*
+ -- -- -- -- -- -- --
+ 1 Column Layout
+ -- -- -- -- -- -- --
+ */
+
+ /* Center #container, constrain to 718px width
+ ----------------------------------------------- */
+ body {
+ text-align: center;
+ }
+ #container {
+ width: 718px;
+ text-align: left;
+ margin: 0 auto;
+ }
+
+ #main-content {
+ overflow: hidden;
+ }
+
+ /** BEGIN CUSTOM SKIN **/
+ /*
+
+ -- -- -- -- -- -- --
+ Base CSS
+ -- -- -- -- -- -- --
+
+ This file simply removes default styling on most HTML elements in
+ order to reduce the need to later override them.
+
+ */
+
+ h1,h2,h3,h4,h5,h6,pre,code,p {font-size: 1em;}
+ dl,li,dt,dd,h1,h2,h3,h4,h5,h6,pre,form,body,html,p,blockquote,fieldset,input {margin: 0; padding: 0;}
+ a img,:link img,:visited img {border: none;}
+ address {font-style: normal;}/*
+
+ -- -- -- -- -- -- --
+ Type Scheme: Deco
+ -- -- -- -- -- -- --
+
+ */
+
+ body {
+ font: 76% Verdana, sans-serif;
+ }
+
+ h1, h2, h3, h4, h5, h6, p.description {
+ font-family: "Trebuchet MS", Trebuchet, sans-serif;
+ }
+ h1 {
+ font-size: 3em;
+ font-weight: bold;
+ letter-spacing: 2px;
+ }
+ h2 {
+ font-size: 2em;
+ font-weight: normal;
+ }
+ h3 {
+ font-size: 1.5em;
+ }
+ h4 {
+ font-size: 1.2em;
+ letter-spacing: 0.2em;
+ }
+ h5 {
+ font-size: 1.2em;
+ }
+ h6 {
+ font-size: 1em;
+ font-weight: bold;
+ }
+
+ p, td {
+ line-height: 1.8em;
+ }
+ code, kbd {
+ font-size: 1.25em;
+ }/*
+
+ -- -- -- -- -- -- --
+ STYLE: Micro
+ -- -- -- -- -- -- --
+
+ */
+
+
+
+
+ /* ie6win */
+
+ /* IE/Win fixes for various layouts
+ ----------------------------------------------- */
+ * html #onecolumn #header {
+ margin-right: -3px;
+ }
+ * html #onecolumn #header,
+ * html #twocolumn-left #header, * html #twocolumn-right #header,
+ * html #twocolumn-liquid-left #header, * html #twocolumn-liquid-right #header {
+ padding-bottom: 1px;
+ }
+ * html #twocolumn-left #main-content, * html #twocolumn-right #main-content {
+ width: 459px;
+ }
+ * html #threecolumn #main-content {
+ width: 409px;
+ }
+
+ /* ie5mac */
+
+ /*\*//*/
+ /* Undoing IE/Win fixes
+ ----------------------------------------------- */
+ * html #onecolumn #header {
+ margin-right: 0;
+ }
+ * html #twocolumn-left #header, * html #twocolumn-right #header,
+ * html #twocolumn-liquid-left #header, * html #twocolumn-liquid-right #header {
+ padding-bottom: 0;
+ }
+ * html #twocolumn-left #main-content, * html #twocolumn-right #main-content {
+ width: 479px;
+ }
+ * html #threecolumn #main-content {
+ width: 429px;
+ }
+ /**/
+
+ @media tty {
+ i{content:"\";/*" "*/}} td { font-size: 0.8em; } /*";}
+ }/* */
+
+
+
+ /* Basic HTML style
+ ----------------------------------------------- */
+ body {
+ font: 76% "Lucida Grande", "Lucida Sans Unicode", Arial, sans-serif;
+ color: #000;
+ background: #fff;
+ margin: 0;
+ padding: 0;
+ }
+ blockquote {
+ margin: 1em 2em;
+ font-style: italic;
+ }
+ caption {
+ font-weight: bold;
+ color: #444;
+ background: #ccc;
+ border-bottom: 0;
+ padding: 0.3em 1em;
+ }
+ dd {
+ margin: 1em 2em;
+ }
+ dl {
+ margin: 2em 0;
+ }
+ dt {
+ font-weight: bold;
+ }
+ hr {
+ margin: 2em 0;
+ color: #C7C7C7;
+ background: #C7C7C7;
+ border-color: #C7C7C7;
+ border-style: none;
+ height: 1px;
+ }
+ li {
+ margin: 1em 0;
+ }
+ table {
+ border: solid 1px #ccc;
+ }
+ td {
+ vertical-align: top;
+ padding: 0.5em;
+ }
+ th {
+ text-align: left;
+ color: #fff;
+ background: #777;
+ padding: 0.5em;
+ }
+ ol, ul {
+ margin: 2em 0;
+ padding-left: 1em;
+ }
+
+
+
+ /* Nested HTML elements, and basic classes
+ ----------------------------------------------- */
+ ol li {
+ list-style-type: decimal;
+ margin-left: 2em;
+ }
+ ul li {
+ margin-left: 2em;
+ list-style-type: square;
+ }
+ td p {
+ margin-top: 0;
+ }
+
+
+
+ /* Set the stage with main layout tweaks
+ ----------------------------------------------- */
+ #container {
+ border: solid 7px #999;
+ border-left: 0;
+ border-right: 0;
+ padding-top: 1px;
+ }
+ #header {
+ color: #04172D;
+ border-top: solid 3px #777;
+ padding: 0;
+ margin: 0 0 1.5em 0;
+ }
+ #main-content .wrapper {
+ margin: 0;
+ }
+ .description {
+ font: normal 1em "Lucida Grande", "Lucida Sans Unicode", Arial, sans-serif;
+ color: #444;
+ background: #C7C7C7;
+ padding: 3px 25px 2.2em 25px;
+ margin: 0;
+ line-height: 1;
+ }
+ #footer {
+ clear: both;
+ color: #999;
+ padding: 0 1em 1em 1em;
+ border-bottom: solid 3px #777;
+ margin-bottom: 1px;
+ }
+
+
+ /* Content area offset
+ ----------------------------------------------- */
+ #main-content .wrapper {
+ padding: 0 25px;
+ }
+
+ #main-content td p {
+ margin: 0 0 1em 0;
+ }
+
+
+
+ /* Custom font definitions
+ ----------------------------------------------- */
+ p {
+ margin: 1em 0;
+ line-height: 1.5;
+ }
+ h1,h2,h3,h4,h5,h6 {
+ font-family: "Trebuchet MS", arial, sans-serif;
+ }
+ h1 {
+ color: #B2B2B2;
+ font-size: 2.4em;
+ letter-spacing: 0.2em;
+ font-weight: normal;
+ padding: 1em 25px 0 25px;
+ }
+ h2 {
+ margin: 0 0 0.5em 0;
+ color: #777;
+ font-size: 1.4em;
+ font-weight: normal;
+ border-bottom: double 3px #C7C7C7;
+ padding: 0 0 0.4em 0;
+ }
+ h3 {
+ font-size: 1.2em;
+ background: #eee;
+ border: dotted 1px #C7C7C7;
+ padding: 0.2em;
+ }
+ h4 {
+ font-size: 1.2em;
+ padding: 0 0 0.2em 0;
+ margin: 0.6em 0 0 0.4em;
+ color: #777;
+ }
+ h5 {
+ border-bottom: dotted 1px #C7C7C7;
+ }
+ h6 {
+ color: #777;
+ border-left: solid 1.2em #777;
+ padding-left: 0.6em;
+ }
+
+ a:link {
+ color: #9db2df;
+ }
+ a:hover {
+ text-decoration: none;
+ border-bottom: 1px dotted #bb242d;
+ background-color: #e0e0e0;
+ }
+
+
+ /* Sidebar
+ ----------------------------------------------- */
+ #sidebar h3, #sidebar-alternate h3 {
+ margin: 0;
+ color: #777;
+ background: none;
+ font-size: 1.4em;
+ font-weight: normal;
+ border: none;
+ padding: 0;
+ }
+
+ #sidebar blockquote, #sidebar blockquote p,
+ #sidebar-alternate blockquote, #sidebar-alternate blockquote p {
+ margin-left: 0;
+ margin-right: 0;
+ }
+ #sidebar blockquote {
+ margin: 1em 0;
+ padding: 0;
+ }
+ #adsense {
+ text-align: center;
+ }
+
+
+
+ .editable {
+ border: dashed 1px #c33;
+ }
+
+
+
+
+ /* Tweaks for Two-column Right layout
+ ----------------------------------------------- */
+ #twocolumn-right #sidebar .wrapper {
+ margin: 0 10px;
+ }
+
+
+
+ /* Tweaks for Two-column Left layout
+ ----------------------------------------------- */
+ #twocolumn-left #sidebar .wrapper {
+ margin: 0 10px;
+ }
+
+
+ /* Tweaks for Three-column layout
+ ----------------------------------------------- */
+ #threecolumn #sidebar .wrapper {
+ margin: 0 10px;
+ }
+ #threecolumn #sidebar-alternate .wrapper {
+ margin: 0 10px;
+ }
+ /*
+
+ -- -- -- -- -- -- --
+ COLOR SCHEME: Blueprint
+ -- -- -- -- -- -- --
+
+ */
+
+
+ /* Basic HTML style
+ ----------------------------------------------- */
+ a:link {
+ color: #445AA9;
+ }
+ a:visited {
+ color: #283D88;
+ }
+ body {
+ color: #283769;
+ background: #ECEEF6;
+ }
+ caption {
+ color: inherit;
+ background: #ECEEF6;
+ }
+ hr {
+ color: #C7C7C7;
+ background: #C7C7C7;
+ border-color: #C7C7C7;
+ }
+ table {
+ background: #fff;
+ border-color: #B3BCDC;
+ }
+ th {
+ color: #fff;
+ background: #445AA9;
+ }
+
+
+
+ /* Set the stage with main layout tweaks
+ ----------------------------------------------- */
+ #container {
+ background-color: #F6F7FB;
+ border-color: #6678B8;
+ }
+ #header {
+ color: #445AA9;
+ border-top-color: #6678B8;
+ }
+ .description {
+ color: #445AA9;
+ background: #C9D0E6;
+ }
+ #footer {
+ color: #5064AE;
+ border-bottom-color: #6678B8;
+ }
+
+
+
+ /* Custom font definitions
+ ----------------------------------------------- */
+ h1 {
+ color: #445AA9;
+ }
+ h2 {
+ color: #5064AE;
+ border-bottom-color: #B3BCDC;
+ }
+ h3 {
+ background: #ECEEF6;
+ border-color: #C9D0E6;
+ }
+ h4 {
+ border-bottom-color: #B3BCDC;
+ color: #1A4292;
+ }
+ h5 {
+ border-bottom-color: #C7C7C7;
+ }
+ h6 {
+ color: #5064AE;
+ border-left-color: #B3BCDC;
+ }
+
+
+
+
+
+ /* Sidebar
+ ----------------------------------------------- */
+ #sidebar h3, #sidebar-alternate h3 {
+ color: #5064AE;
+ background: none;
+ }
+ /** END CUSTOM SKIN **/
+ </style><!-- Hack to avoid flash of unstyled content in IE -->
+
+
+ <script> </script></head><body id="onecolumn">
+ <div id="container">
+ <div class="wrapper">
+ <div id="header">
+ <div class="wrapper">
+ <h1 id="page-title"><div id="g_title">USPP(Universal Serial Port Python Library)<br></div></h1>
+ <div style="clear: both;"></div>
+ <p class="description"></p><div id="g_description"><p>Isaac Barona (ibarona@gmail.com)&nbsp;</p></div>
+ <div style="clear: both;"></div>
+ </div>
+ </div>
+
+ <div id="main-content">
+ <div class="wrapper">
+ <div class="content-item"><div id="g_body"><h2>Introduction</h2><p><i>USPP Library </i>is a multi-platform Python module to access serial ports.
+At the moment, it only works in Windows, Linux and MacOS but as it is written entirely in Python (doesn't wrap any C/C++
+library) I hope you can extend it to support any other platforms.&nbsp;</p><h2>Motivation</h2><p>
+I like very much to make electronic widgets with microcontrollers, specially
+those that can be connected to the computer to send and receive data.
+</p><p>Some months ago, I discovered Python and inmediatelly liked it a lot.
+I started playing with it and saw that I could use it to make prototypes of
+comunication protocols between computer and microcontrollers really
+fast and easily than using C. At the same time, I was interested in
+working over different platforms.
+</p><p>I started looking for Python modules to access serial port and I found
+the following projects:
+</p><ul><li><i>win32comport_demo</i> from the win32 extension module</li><li><i>win32comm</i> module of wheineman@uconect.net</li><li><i>Sio Module </i>of Roger Rurnham (rburnham@cri-inc.com)</li><li><i>pyxal (Python X10 Abstraction Layer) </i>of Les Smithson (lsmithson@open-networks.co.uk)</li></ul><p>but they were not multi-platform, were just a wrap of propietary libraries or
+were just simple examples of serial port access.
+</p><p>For these reasons and also for learning more Python, I decided to start
+this project. Of course, I have used all this projects as reference to
+my module and so, I want to thanks the authors for their excellent work and
+for allowing us to study the code.
+I hope you enjoy using the uspp module as much as I am enjoying doing it.</p><h2>Features</h2><p>
+This module has the following features:
+</p><ul><li>hight level access to serial port under several platforms.</li><li>autodetects the platform in which it is working and exports the correct
+classes for that platform.</li><li>object oriented approach.</li><li>file object semantic operations over the ports.</li><li>allows using the serial port with different speeds and
+characteristics.</li><li>RS-232 and RS-485 modes (now only RS-232). In RS-485 mode the communication
+is half-duplex and uses the RTS line to control the direction of the
+transference.</li><li>blocking, non-blocking or configurable timeout reads.</li></ul><h2>&nbsp;Prerequisites</h2><p>You need the following to use the library:
+</p><ul><li>Python 2.1 or better</li><li>In windows you need the win32 extension modules. You can get it from <a href="http://sourceforge.net/projects/pywin32/">here</a>.<br></li></ul><h2>Usage and documentation</h2><p>You only have to import in your program the <i>uspp</i> module and automatically
+it loads the correct classes for the platform in which you are running
+the program.
+
+</p><p>First of all you have to create a <i>SerialPort</i> object with the settings you
+want. If a <i>SerialPortException</i> is not generated then you just can
+use the read and write methods of the object to read and write to
+the serial port.
+
+</p><p>Example:
+
+</p><pre><tt><br>&gt;&gt;&gt; from uspp import *<br>&gt;&gt;&gt; tty=SerialPort("COM2", 1000, 9600) <br>&gt;&gt;&gt; # Opens COM2 at 9600 bps and with a read timeout of 1 second.<br>&gt;&gt;&gt; tty.write("a") # Writes a character to the COM2 port<br>&gt;&gt;&gt; # Now suppose we receive the string "abc"<br>&gt;&gt;&gt; tty.inWaiting()<br>3<br>&gt;&gt;&gt; tty.read()<br>'a'<br>&gt;&gt;&gt; tty.inWaiting()<br>2<br>&gt;&gt;&gt; tty.read(2)<br>'bc'<br></tt></pre>
+
+<p>Documentation of the different classes and methods can be found on
+uspp module docstring.</p><h2>Where does it works?&nbsp;</h2><p>&nbsp;
+The library has been tested in&nbsp; Windows 95, Windows XP and Windows 2000&nbsp; machines with Python 2.0+
+and in a Linux (2.0.34 and 2.4.20 kernels) machine with Python 2.1+.</p><h2>Porting to other frameworks</h2><p>
+If you want to port the library to other platforms you only have to follow
+these steps:
+</p><ul><li>Create a new python file called <i>SerialPort_XXXX.py </i>in which you
+implement the same public classes and methods found in the
+<i>SerialPort_win</i>
+and <i>SerialPort_linux</i> modules.</li><li>Append the new platform to the <i>uspp.py</i> file.</li></ul><h2>License&nbsp;</h2><p>&nbsp;
+This code is released under the "GPL" that can be found in
+<a href="http://www.gnu.org/copyleft/gpl.html%20">http://www.gnu.org/copyleft/gpl.html </a>or in the GPL.txt file that
+is with the library.
+</p><p>If you use this software, I'd like to know about it.</p><h2>&nbsp;Author</h2><p>
+This library has been created by Isaac Barona Martínez
+<a href="mailto:ibarona%20at%20gmail.com">(ibarona at gmail.com)</a>&nbsp;</p><h2>Versions <br></h2><h3>Version 1.0 - 02/24/2006 (February 2006) &nbsp;&nbsp;&nbsp;</h3><p>Lot
+to time after 0.1 version I have enouth time to publish the final
+version of the library. This version correct some bugs of 0.1 version,
+works in MacOS and have been extended.</p><p>The library contains more functions in Linux and MacOS platforms than in Windows platform.&nbsp;</p><p>I have to thanks a lot of people his contribution to the library, especially:</p><ul><li>Damien Geranton &lt;dgeranton at voila.fr&gt;&nbsp;</li><li>Douglas Jones &lt;dfj23 at drexel.edu&gt;</li><li>&nbsp;J.Grauheding &lt;juergen.grauheding at a-city.de&gt; </li></ul><p>&nbsp;Files:</p><ul><ul><li>Zip file: uspp-0_1.zip</li><li>tar.gz file: uspp-0_1.tar.gz</li></ul></ul><h4>&nbsp;</h4><h3>Version 0.1 - 09/01/2001 (September 2001)</h3><p></p></div></div>
+ <div style="clear: both;"></div>
+ </div>
+ </div>
+
+ <div id="footer"><div class="wrapper">
+ <hr>
+ <p></p><div id="g_footer">&nbsp;</div>
+ <div style="clear: both;"></div>
+ </div></div>
+
+ </div>
+ </div>
+
+
+<div id="extraDiv1"><span></span></div><div id="extraDiv2"><span></span></div>
+<div id="extraDiv3"><span></span></div><div id="extraDiv4"><span></span></div>
+<div id="extraDiv5"><span></span></div><div id="extraDiv6"><span></span></div>
+
+</body></html> \ No newline at end of file
diff --git a/maximus/python/lib/proto/uspp/uspp.py b/maximus/python/lib/proto/uspp/uspp.py
new file mode 100644
index 0000000000..1255613d62
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/uspp.py
@@ -0,0 +1,193 @@
+#! /usr/bin/env python
+
+# -*- coding: iso-8859-1 -*-
+
+##########################################################################
+# USPP Library (Universal Serial Port Python Library)
+#
+# Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+##########################################################################
+
+#-------------------------------------------------------------------------
+# Project: USPP Library (Universal Serial Port Python Library)
+# Name: uspp.py
+# Purpose: Main module. Imports the correct module for the platform
+# in which it is running.
+#
+# Author: Isaac Barona Martinez <ibarona@gmail.com>
+# Copyright: (c) 2006 by Isaac Barona Martinez
+# Licence: LGPL
+#
+# Created: 26 June 2001
+# History:
+# 05/08/2001: Release version 0.1.
+# 24/02/2006: Final version 1.0.
+#
+#-------------------------------------------------------------------------
+
+
+"""
+USPP - Universal Serial Port Python Library
+
+This module exports a SerialPort class to access serial ports in
+different platforms (currently W9X and Linux) with the same code.
+
+When the library user import the uspp module, it automatically
+loads the correct class implementation for the platform in which
+is running.
+
+The public classes, exceptions and methods are the following:
+
+SerialPortException
+===================
+Exception raised in the SerialPort methods.
+
+
+SerialPort
+==========
+Class that encapsulate methods to access serial ports. It has the
+following public methods:
+
+* __init__(self, dev, timeout=None, speed=None, mode='232', params=None)
+
+ Create an object to access serial port 'dev'
+
+ Arguments:
+
+ dev: String that indicate the name of the port. Possible values are:
+ In Linux: '/dev/ttyS0', '/dev/ttyS1', ..., '/dev/ttySX' or
+ '/dev/cua0', '/dev/cua1', ..., '/dev/cuaX'
+ In W9X: 'COM1', 'COM2', ..., 'COMX'
+
+ timeout: specifies in milliseconds the inter-byte timeout. Possible
+ values are:
+ * None: For blocking readings. Time-outs are not used for reading
+ operations.
+ * 0: For non-blocking readings. The reading operation is to return
+ inmediately with the characters that have already been received,
+ even if no characters have been received.
+ * >0: For time-out readings. A character must be read in less than
+ this value.
+
+ speed: integer that specifies the input and output baud rate to
+ use. Possible values are: 110, 300, 600, 1200, 2400, 4800, 9600,
+ 19200, 38400, 57600 and 115200.
+ If None a default speed of 9600 bps is selected.
+
+ mode: string that specifies RS-232 or RS-485 mode. The RS-485 mode
+ is half duplex and use the RTS signal to indicate the
+ direction of the communication (transmit or recive).
+ Posible values are: '232' or '485'. Default to RS232 mode (the
+ only implemented just now).
+
+ params: list that specifies properties of the serial communication.
+ If params=None it uses default values for the number of bits
+ per byte (8), the parity (NOPARITY) and the number of stop bits (1)
+ else:
+ * In W9X: params must be a list with three items setting up the
+ these values in this order.
+ * In Linux: params must is the termios package mode array to use
+ for initialization.
+
+
+
+* __del__(self):
+
+ Destroy the SerialPort object and close the serial port. It is a good
+ idea that when you finish working with the serial port you explicity
+ do: del tty (where tty is a SerialPort object).
+
+* fileno(self):
+
+ Returns the file descriptor of the serial port. This information is
+ sometimes necessary for example if you want to use the select function.
+
+* read(self, num=1):
+
+ Read num bytes from the serial port. Depending the timeout value used in
+ the inicialitation this operation can be:
+
+ - Blocking (if timeout=None): The operation blocks until num bytes
+ arrive the serial port.
+ - Non-blocking (if timeout=0): The operation returns inmediatelly
+ with as many as num bytes that were waiting in the serial port to be read.
+ - Time-out (if timeout>0): A byte must arrive in less milliseconds than
+ the specified. If the number of read bytes is less than num a
+ SerialPortException is raised because a time-out has happened.
+
+* write(self, s):
+
+ Write the string s to the serial port.
+
+* inWaiting(self):
+
+ Returns the number of bytes waiting to be read.
+
+
+* flush(self):
+
+ Discards all characters from the output or input buffer.
+
+
+
+NOTE ON CHARACTERS AND BYTES
+============================
+
+The write and read methods of the SerialPort class expect data
+in string buffers. Do not think this library only works for
+ASCII communications. To interpret string elements as bytes (integer number)
+you only have to use the built-in ord() function. To convert a byte
+into a string element, use chr().
+
+Example: Suppose you want to transmit the following three bytes:
+0x02, 0x10, 0x30. You only have to do:
+
+packet = ''
+packet = packet + chr(0x02) + chr(0x10) + chr(0x30)
+tty.write(packet)
+
+So, you can see the bytes you send or receive as integers or as characters
+depending the situation.
+
+
+
+"""
+
+
+
+__author__="Isaac Barona Martinez <ibarona@tid.es>"
+
+__copyright__="""
+Copyright (C) 2001 Isaac Barona Martinez <ibarona@tid.es>
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; version 2 dated
+June, 1991.
+"""
+
+__version__="0.1"
+
+
+import sys
+
+if sys.platform=='win32':
+ from SerialPort_win import *
+elif sys.platform=='linux2':
+ from SerialPort_linux import *
+else:
+ sys.exit('Sorry, no implemented for this platform yet')
diff --git a/maximus/python/lib/proto/uspp/uspp_es.htm b/maximus/python/lib/proto/uspp/uspp_es.htm
new file mode 100644
index 0000000000..337ee34dc5
--- /dev/null
+++ b/maximus/python/lib/proto/uspp/uspp_es.htm
@@ -0,0 +1,629 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><title>ibarona - USPP(Universal Serial Port Python Library)</title>
+
+
+
+
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+
+ <style type="text/css">
+ #g_title p, #g_footer p, #g_description p {
+ margin: 0;
+ }
+ /*
+
+ -- -- -- -- -- -- --
+ Browser Fixes
+ -- -- -- -- -- -- --
+
+ This file uses CSS filtering methods to fix various
+ layout bugs.
+
+ Each of the following three imported files is a
+ separate, browser-specific CSS file that keeps all
+ hacks out of the main style sheet.
+
+ Over time, as supporting these browsers no longer
+ remains a priority, cleaning up the hacks is as
+ easy as deleting the @import statement below, or
+ simply no longer linking this file from the HTML.
+
+ */
+
+ /*
+ fix ie6 "peekaboo bug" using the "holly hack".
+ Note, this style only gets applied to ie6
+ */
+ * html .wrapper {
+ height: 0.1%;
+ }
+
+ /*
+ * IE5 mac - overrides the IE/Win hack
+ */
+
+ /*\*//*/
+
+ * html #threecolumn div {
+ height: auto;
+ }
+
+ /**/
+
+
+ /*
+ * IE5/Win-specific CSS -ensures #container wraps all content on window resize
+ */
+
+ @media tty {
+ i{content:"\";/*" "*/}} * html #container { height: 1%; } /*";}
+ }/* */
+ /* Styling for editable elements. Eventually, this will be part of the style. */
+ .editable {
+ border: 1px dashed blue;
+ }
+
+ #footer {
+ clear: both;
+ }
+
+ /* Extra divs hidden by default. The custom CSS can override this though */
+ #extraDiv1, #extraDiv2, #extraDiv3, #extraDiv4, #extraDiv5, #extraDiv6 {
+ display: none;
+ }
+
+ /*
+ -- -- -- -- -- -- --
+ 1 Column Layout
+ -- -- -- -- -- -- --
+ */
+
+ /* Center #container, constrain to 718px width
+ ----------------------------------------------- */
+ body {
+ text-align: center;
+ }
+ #container {
+ width: 718px;
+ text-align: left;
+ margin: 0 auto;
+ }
+
+ #main-content {
+ overflow: hidden;
+ }
+
+ /** BEGIN CUSTOM SKIN **/
+ /*
+
+ -- -- -- -- -- -- --
+ Base CSS
+ -- -- -- -- -- -- --
+
+ This file simply removes default styling on most HTML elements in
+ order to reduce the need to later override them.
+
+ */
+
+ h1,h2,h3,h4,h5,h6,pre,code,p {font-size: 1em;}
+ dl,li,dt,dd,h1,h2,h3,h4,h5,h6,pre,form,body,html,p,blockquote,fieldset,input {margin: 0; padding: 0;}
+ a img,:link img,:visited img {border: none;}
+ address {font-style: normal;}/*
+
+ -- -- -- -- -- -- --
+ Type Scheme: Deco
+ -- -- -- -- -- -- --
+
+ */
+
+ body {
+ font: 76% Verdana, sans-serif;
+ }
+
+ h1, h2, h3, h4, h5, h6, p.description {
+ font-family: "Trebuchet MS", Trebuchet, sans-serif;
+ }
+ h1 {
+ font-size: 3em;
+ font-weight: bold;
+ letter-spacing: 2px;
+ }
+ h2 {
+ font-size: 2em;
+ font-weight: normal;
+ }
+ h3 {
+ font-size: 1.5em;
+ }
+ h4 {
+ font-size: 1.2em;
+ letter-spacing: 0.2em;
+ }
+ h5 {
+ font-size: 1.2em;
+ }
+ h6 {
+ font-size: 1em;
+ font-weight: bold;
+ }
+
+ p, td {
+ line-height: 1.8em;
+ }
+ code, kbd {
+ font-size: 1.25em;
+ }/*
+
+ -- -- -- -- -- -- --
+ STYLE: Micro
+ -- -- -- -- -- -- --
+
+ */
+
+
+
+
+ /* ie6win */
+
+ /* IE/Win fixes for various layouts
+ ----------------------------------------------- */
+ * html #onecolumn #header {
+ margin-right: -3px;
+ }
+ * html #onecolumn #header,
+ * html #twocolumn-left #header, * html #twocolumn-right #header,
+ * html #twocolumn-liquid-left #header, * html #twocolumn-liquid-right #header {
+ padding-bottom: 1px;
+ }
+ * html #twocolumn-left #main-content, * html #twocolumn-right #main-content {
+ width: 459px;
+ }
+ * html #threecolumn #main-content {
+ width: 409px;
+ }
+
+ /* ie5mac */
+
+ /*\*//*/
+ /* Undoing IE/Win fixes
+ ----------------------------------------------- */
+ * html #onecolumn #header {
+ margin-right: 0;
+ }
+ * html #twocolumn-left #header, * html #twocolumn-right #header,
+ * html #twocolumn-liquid-left #header, * html #twocolumn-liquid-right #header {
+ padding-bottom: 0;
+ }
+ * html #twocolumn-left #main-content, * html #twocolumn-right #main-content {
+ width: 479px;
+ }
+ * html #threecolumn #main-content {
+ width: 429px;
+ }
+ /**/
+
+ @media tty {
+ i{content:"\";/*" "*/}} td { font-size: 0.8em; } /*";}
+ }/* */
+
+
+
+ /* Basic HTML style
+ ----------------------------------------------- */
+ body {
+ font: 76% "Lucida Grande", "Lucida Sans Unicode", Arial, sans-serif;
+ color: #000;
+ background: #fff;
+ margin: 0;
+ padding: 0;
+ }
+ blockquote {
+ margin: 1em 2em;
+ font-style: italic;
+ }
+ caption {
+ font-weight: bold;
+ color: #444;
+ background: #ccc;
+ border-bottom: 0;
+ padding: 0.3em 1em;
+ }
+ dd {
+ margin: 1em 2em;
+ }
+ dl {
+ margin: 2em 0;
+ }
+ dt {
+ font-weight: bold;
+ }
+ hr {
+ margin: 2em 0;
+ color: #C7C7C7;
+ background: #C7C7C7;
+ border-color: #C7C7C7;
+ border-style: none;
+ height: 1px;
+ }
+ li {
+ margin: 1em 0;
+ }
+ table {
+ border: solid 1px #ccc;
+ }
+ td {
+ vertical-align: top;
+ padding: 0.5em;
+ }
+ th {
+ text-align: left;
+ color: #fff;
+ background: #777;
+ padding: 0.5em;
+ }
+ ol, ul {
+ margin: 2em 0;
+ padding-left: 1em;
+ }
+
+
+
+ /* Nested HTML elements, and basic classes
+ ----------------------------------------------- */
+ ol li {
+ list-style-type: decimal;
+ margin-left: 2em;
+ }
+ ul li {
+ margin-left: 2em;
+ list-style-type: square;
+ }
+ td p {
+ margin-top: 0;
+ }
+
+
+
+ /* Set the stage with main layout tweaks
+ ----------------------------------------------- */
+ #container {
+ border: solid 7px #999;
+ border-left: 0;
+ border-right: 0;
+ padding-top: 1px;
+ }
+ #header {
+ color: #04172D;
+ border-top: solid 3px #777;
+ padding: 0;
+ margin: 0 0 1.5em 0;
+ }
+ #main-content .wrapper {
+ margin: 0;
+ }
+ .description {
+ font: normal 1em "Lucida Grande", "Lucida Sans Unicode", Arial, sans-serif;
+ color: #444;
+ background: #C7C7C7;
+ padding: 3px 25px 2.2em 25px;
+ margin: 0;
+ line-height: 1;
+ }
+ #footer {
+ clear: both;
+ color: #999;
+ padding: 0 1em 1em 1em;
+ border-bottom: solid 3px #777;
+ margin-bottom: 1px;
+ }
+
+
+ /* Content area offset
+ ----------------------------------------------- */
+ #main-content .wrapper {
+ padding: 0 25px;
+ }
+
+ #main-content td p {
+ margin: 0 0 1em 0;
+ }
+
+
+
+ /* Custom font definitions
+ ----------------------------------------------- */
+ p {
+ margin: 1em 0;
+ line-height: 1.5;
+ }
+ h1,h2,h3,h4,h5,h6 {
+ font-family: "Trebuchet MS", arial, sans-serif;
+ }
+ h1 {
+ color: #B2B2B2;
+ font-size: 2.4em;
+ letter-spacing: 0.2em;
+ font-weight: normal;
+ padding: 1em 25px 0 25px;
+ }
+ h2 {
+ margin: 0 0 0.5em 0;
+ color: #777;
+ font-size: 1.4em;
+ font-weight: normal;
+ border-bottom: double 3px #C7C7C7;
+ padding: 0 0 0.4em 0;
+ }
+ h3 {
+ font-size: 1.2em;
+ background: #eee;
+ border: dotted 1px #C7C7C7;
+ padding: 0.2em;
+ }
+ h4 {
+ font-size: 1.2em;
+ padding: 0 0 0.2em 0;
+ margin: 0.6em 0 0 0.4em;
+ color: #777;
+ }
+ h5 {
+ border-bottom: dotted 1px #C7C7C7;
+ }
+ h6 {
+ color: #777;
+ border-left: solid 1.2em #777;
+ padding-left: 0.6em;
+ }
+
+ a:link {
+ color: #9db2df;
+ }
+ a:hover {
+ text-decoration: none;
+ border-bottom: 1px dotted #bb242d;
+ background-color: #e0e0e0;
+ }
+
+
+ /* Sidebar
+ ----------------------------------------------- */
+ #sidebar h3, #sidebar-alternate h3 {
+ margin: 0;
+ color: #777;
+ background: none;
+ font-size: 1.4em;
+ font-weight: normal;
+ border: none;
+ padding: 0;
+ }
+
+ #sidebar blockquote, #sidebar blockquote p,
+ #sidebar-alternate blockquote, #sidebar-alternate blockquote p {
+ margin-left: 0;
+ margin-right: 0;
+ }
+ #sidebar blockquote {
+ margin: 1em 0;
+ padding: 0;
+ }
+ #adsense {
+ text-align: center;
+ }
+
+
+
+ .editable {
+ border: dashed 1px #c33;
+ }
+
+
+
+
+ /* Tweaks for Two-column Right layout
+ ----------------------------------------------- */
+ #twocolumn-right #sidebar .wrapper {
+ margin: 0 10px;
+ }
+
+
+
+ /* Tweaks for Two-column Left layout
+ ----------------------------------------------- */
+ #twocolumn-left #sidebar .wrapper {
+ margin: 0 10px;
+ }
+
+
+ /* Tweaks for Three-column layout
+ ----------------------------------------------- */
+ #threecolumn #sidebar .wrapper {
+ margin: 0 10px;
+ }
+ #threecolumn #sidebar-alternate .wrapper {
+ margin: 0 10px;
+ }
+ /*
+
+ -- -- -- -- -- -- --
+ COLOR SCHEME: Blueprint
+ -- -- -- -- -- -- --
+
+ */
+
+
+ /* Basic HTML style
+ ----------------------------------------------- */
+ a:link {
+ color: #445AA9;
+ }
+ a:visited {
+ color: #283D88;
+ }
+ body {
+ color: #283769;
+ background: #ECEEF6;
+ }
+ caption {
+ color: inherit;
+ background: #ECEEF6;
+ }
+ hr {
+ color: #C7C7C7;
+ background: #C7C7C7;
+ border-color: #C7C7C7;
+ }
+ table {
+ background: #fff;
+ border-color: #B3BCDC;
+ }
+ th {
+ color: #fff;
+ background: #445AA9;
+ }
+
+
+
+ /* Set the stage with main layout tweaks
+ ----------------------------------------------- */
+ #container {
+ background-color: #F6F7FB;
+ border-color: #6678B8;
+ }
+ #header {
+ color: #445AA9;
+ border-top-color: #6678B8;
+ }
+ .description {
+ color: #445AA9;
+ background: #C9D0E6;
+ }
+ #footer {
+ color: #5064AE;
+ border-bottom-color: #6678B8;
+ }
+
+
+
+ /* Custom font definitions
+ ----------------------------------------------- */
+ h1 {
+ color: #445AA9;
+ }
+ h2 {
+ color: #5064AE;
+ border-bottom-color: #B3BCDC;
+ }
+ h3 {
+ background: #ECEEF6;
+ border-color: #C9D0E6;
+ }
+ h4 {
+ border-bottom-color: #B3BCDC;
+ color: #1A4292;
+ }
+ h5 {
+ border-bottom-color: #C7C7C7;
+ }
+ h6 {
+ color: #5064AE;
+ border-left-color: #B3BCDC;
+ }
+
+
+
+
+
+ /* Sidebar
+ ----------------------------------------------- */
+ #sidebar h3, #sidebar-alternate h3 {
+ color: #5064AE;
+ background: none;
+ }
+ /** END CUSTOM SKIN **/
+ </style><!-- Hack to avoid flash of unstyled content in IE -->
+
+
+ <script> </script></head><body id="onecolumn">
+ <div id="container">
+ <div class="wrapper">
+ <div id="header">
+ <div class="wrapper">
+ <h1 id="page-title"><div id="g_title">USPP(Universal Serial Port Python Library)</div></h1>
+ <div style="clear: both;"></div>
+ <p class="description"></p><div id="g_description"><p>Isaac Barona (ibarona@gmail.com) <br></p></div>
+ <div style="clear: both;"></div>
+ </div>
+ </div>
+
+ <div id="main-content">
+ <div class="wrapper">
+ <div class="content-item"><div id="g_body"><h2>Introduccion</h2><p>La
+librería USPP es un módulo desarrollado en Python para el acceso
+multiplataforma al puerto serie. En el momento, sólo funciona en Linux,
+Windows y MacOS, pero como está escrita completamente en Python&nbsp;
+(no es únicamente un recubrimiento en Python de una librería
+desarrollada&nbsp; en C/C++) espero que pueda ser ampliada para que
+soporte otras plataformas.<i><br><br></i></p><h2>Motivacion</h2><p>&nbsp;A
+mí me gusta mucho hacer pequeños cacharros electrónicos con
+microcontroladores, especialmente aquellos que pueden ser conectados a
+un ordenador para enviar y recibir datos. Hace un par de meses descubrí
+Python y realmente me encantó. Empezé a jugar con él y ví que podía
+utilizarlo para hacer prototipos de protocolos de comunicación entre el
+ordenador y los microcontroladores&nbsp; de manera mucho más fácil y
+rápida que utilizando C (que era el lenguaje que solía utilizar). Al
+mismo tiempo, estaba interesado en poder utilizar los desarrollos bajo
+diferentes arquitecturas. Empezé a buscar en la red módulos de Python
+que accedieran al puerto serie<br>y encontré los siguientes:<br><br>&nbsp;&nbsp; &nbsp;* win32comport_demo que viene junto a la extensión win32.<br>&nbsp;&nbsp; &nbsp;* Módulo win32comm de wheineman@uconect.net.<br>&nbsp;&nbsp; &nbsp;* Sio Module de Roger Rurnham (rburnham@cri-inc.com)<br>&nbsp;&nbsp; &nbsp;* pyxal (Python X10 Abstraction Layer) de Les Smithson <br>&nbsp;&nbsp; &nbsp;&nbsp; (lsmithson@open-networks.co.uk)<br><br>pero
+no eran multiplataforma, eran únicamente un recubrimiento de una
+librería propietaria o eran simples ejemplos de acceso al puerto serie
+bajo una&nbsp; determinada plataforma.<br>Por estas razones, y también
+por supuesto, por aprender más Python, decidí empezar este proyecto.
+Por supuesto, he utilizado los módulos indicados anteriormente como
+referencia para realizar mi librería y por tanto, me creo en la
+obligación de felicitar a sus autores por su excelente trabajo y por
+haberlo compartido con los demás.<br><br>Espero que disfrutes utilizándo el módulo uspp tanto como yo lo&nbsp; he hecho haciéndolo.</p><h2>Características&nbsp;</h2><p>Este módulo tiene las siguientes características destacadas:<br>&nbsp;</p><ul><li>&nbsp;acceso de alto nivel al puerto serie bajo diversas plataformas.</li><li>autodetecta la plataforma en la que se está ejecutando y carga las clases adecuadas para esa plataforma.</li><li>Orientado a objetos.</li><li>Las operaciones sobre el puerto serie tienen la misma semántica que las operaciones sobre objetos de tipo fichero.</li><li>&nbsp;permite utilizar el puerto serie con diferentes velocidades y características.</li><li>permite
+la utilización del puerto bajo dos modos de funcionamiento: RS-232 y
+RS-485 (de momento, sólo RS-232). En modo 485 la comunicación es
+half-duplex y se utiliza la línea RTS para controlar la dirección de la
+transferencia.</li><li>lecturas en modo bloqueante, no bloqueante o con timeout.</li></ul><h2>Prerequisitos</h2><p>Se necesita los siguiente para utilizar la librería:</p><ul><li>Python 2.1 o superior</li><li>En windows los módulos win32</li></ul><h2>Utilización y documentación<br></h2><p>Únicamente
+tienes que importar en tu programa el módulo uspp y automáticamente él
+se encarga de cargar las clases adecuadas para la plataforma en la que
+se está ejecutando el programa.<br><br>Lo primero de todo, tendrás que
+crear un objeto de tipo SerialPort con las características que desees.
+Si no se genera ninguna excepción del tipo SerialPortException, puedes
+utilizar los métodos de lectura y escritura<br>del objeto para leer y escribir en el puerto serie.<br><br>Ejemplo:</p><pre><tt><tt>&gt;&gt;&gt; from uspp import *<br>&gt;&gt;&gt; tty=SerialPort("COM2", 1000, 9600) <br>&gt;&gt;&gt; # Opens COM2 at 9600 bps and with a read timeout of 1 second.<br>&gt;&gt;&gt; tty.write("a") # Writes a character to the COM2 port<br>&gt;&gt;&gt; # Now suppose we receive the string "abc"<br>&gt;&gt;&gt; tty.inWaiting()<br>3<br>&gt;&gt;&gt; tty.read()<br>'a'<br>&gt;&gt;&gt; tty.inWaiting()<br>2<br>&gt;&gt;&gt; tty.read(2)<br>'bc'</tt></tt></pre><pre><tt><tt>&nbsp;</tt></tt></pre><pre><br></pre><p><font face="arial,sans-serif" size="2">La
+documentación de las diferentes clases y métodos que componen el módulo
+puede encontrarse en el string de documentación del módulo uspp.</font></p><h2>Donde funciona<br></h2><p>La
+librería ha sido probada en una máquina con Windows 95, Windows XP y
+Windows 2000 con Python 2.1+ y en un Linux (con el kernel 2.0.34) con
+Python 2.1+.</p><h2>Portado a otras plataformas<br></h2><p></p><p>&nbsp;Si quieres portar la librería a otras plataformas sólo tienes que seguir los siguientes pasos:</p><ul><li>Crear
+un nuevo fichero en python llamado SerialPort_XXX.py en el que
+implementes las mismas clases y métodos públicos que aparecen en los
+módulos SerialPort_win y SerialPort_linux.</li><li>Añadir la nueva plataforma en el fichero uspp.py.<br></li></ul><h2>&nbsp;Licencia&nbsp;</h2><p>Este
+código se libera bajo la licencia "LGPL" que puedes encontrar en&nbsp;
+http://www.gnu.org/copyleft/lesser.html o en el fichero lesser.txt que
+acompaña a la librería. Si utilizas este software estaría muy
+agradecido de saberlo.&nbsp;</p><h2>Autor</h2><p>Esta librería ha sido creada por Isaac Barona Martínez &lt;ibarona@gmail.com&gt;.</p><h2>Versiones</h2><h3>Versión 1.0 - 24/02/2006&nbsp;</h3><p>Mucho
+tiempo después de la versión 0.1 he tenido el tiempo suficiente de
+liberar la versión definitiva de la librería. Esta versión corrige los
+errores encontrados en la versión anterior, funciona en MacOS y ha sido
+ampliada.</p><p>La libería contiene más funciones en las versiones para Linux y MacOS que para Windows.&nbsp;</p><p>Tengo que agradecer a muchas personas su contribución a esta librería, especialmente a:</p><ul><li>Damien Geranton &lt;dgeranton at voila.fr&gt;&nbsp;</li><li>Douglas Jones &lt;dfj23 at drexel.edu&gt;</li><li>J.Grauheding &lt;juergen.grauheding at a-city.de&gt;</li></ul><p>Puedes descargar los ficheros desde aqui:</p><ul><li>Zip file: uspp-0_1.zip</li><li>tar.gz file: uspp-0_1.tar.gz</li></ul><h3>&nbsp;Version 0.1 - 01/09/2001 (Septiembre 2001)</h3><p>&nbsp;</p><p>&nbsp;</p></div></div>
+ <div style="clear: both;"></div>
+ </div>
+ </div>
+
+ <div id="footer"><div class="wrapper">
+ <hr>
+ <p></p><div id="g_footer">&nbsp;</div>
+ <div style="clear: both;"></div>
+ </div></div>
+
+ </div>
+ </div>
+
+
+<div id="extraDiv1"><span></span></div><div id="extraDiv2"><span></span></div>
+<div id="extraDiv3"><span></span></div><div id="extraDiv4"><span></span></div>
+<div id="extraDiv5"><span></span></div><div id="extraDiv6"><span></span></div>
+
+</body></html> \ No newline at end of file