summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--pyparallel/CHANGES.txt6
-rw-r--r--pyparallel/examples/lcd.py70
-rw-r--r--pyparallel/parallel/parallelppdev.py22
-rw-r--r--pyparallel/parallel/parallelutil.py60
-rw-r--r--pyparallel/parallel/parallelwin32.py13
-rw-r--r--pyparallel/setup.py38
-rw-r--r--pyserial/CHANGES.txt331
-rw-r--r--pyserial/LICENSE.txt61
-rw-r--r--pyserial/MANIFEST.in29
-rw-r--r--pyserial/README.txt277
-rw-r--r--pyserial/documentation/Makefile88
-rw-r--r--pyserial/documentation/appendix.rst68
-rw-r--r--pyserial/documentation/conf.py194
-rw-r--r--pyserial/documentation/examples.rst282
-rw-r--r--pyserial/documentation/index.rst29
-rw-r--r--pyserial/documentation/pyparallel.rst165
-rw-r--r--pyserial/documentation/pyserial.pngbin7050 -> 0 bytes
-rw-r--r--pyserial/documentation/pyserial.rst110
-rw-r--r--pyserial/documentation/pyserial_api.rst531
-rw-r--r--pyserial/documentation/shortintro.rst57
-rw-r--r--pyserial/examples/enhancedserial.py62
-rw-r--r--pyserial/examples/miniterm.py562
-rw-r--r--pyserial/examples/port_publisher.py451
-rw-r--r--pyserial/examples/port_publisher.sh44
-rw-r--r--pyserial/examples/scan.py30
-rw-r--r--pyserial/examples/scanlinux.py20
-rw-r--r--pyserial/examples/scanwin32.py200
-rw-r--r--pyserial/examples/setup-miniterm-py2exe.py26
-rw-r--r--pyserial/examples/setup_demo.py35
-rw-r--r--pyserial/examples/tcp_serial_redirect.py305
-rw-r--r--pyserial/examples/test.py216
-rw-r--r--pyserial/examples/test_advanced.py173
-rw-r--r--pyserial/examples/test_high_load.py76
-rw-r--r--pyserial/examples/test_iolib.py78
-rw-r--r--pyserial/examples/wxSerialConfigDialog.py260
-rw-r--r--pyserial/examples/wxSerialConfigDialog.wxg262
-rw-r--r--pyserial/examples/wxTerminal.py333
-rw-r--r--pyserial/examples/wxTerminal.wxg127
-rw-r--r--pyserial/serial/.cvsignore1
-rw-r--r--pyserial/serial/__init__.py26
-rw-r--r--pyserial/serial/serialcli.py271
-rw-r--r--pyserial/serial/serialjava.py260
-rw-r--r--pyserial/serial/serialposix.py612
-rw-r--r--pyserial/serial/serialutil.py478
-rw-r--r--pyserial/serial/serialwin32.py383
-rw-r--r--pyserial/serial/sermsdos.py200
-rw-r--r--pyserial/serial/win32.py288
-rw-r--r--pyserial/setup.py65
48 files changed, 46 insertions, 8229 deletions
diff --git a/pyparallel/CHANGES.txt b/pyparallel/CHANGES.txt
index 5ed7b95..94b0269 100644
--- a/pyparallel/CHANGES.txt
+++ b/pyparallel/CHANGES.txt
@@ -2,8 +2,4 @@ Version 0.1 29 Jul 2002
added to CVS
Version 0.2 27 Jan 2005
- Windows version now using ctypes
-
-Version ... ...
- add setDataDir to Windows backend
- [SF 2785532] add getData for ppdev backend
+ Windows version now using ctypes \ No newline at end of file
diff --git a/pyparallel/examples/lcd.py b/pyparallel/examples/lcd.py
index 8e1c66b..b56c2a5 100644
--- a/pyparallel/examples/lcd.py
+++ b/pyparallel/examples/lcd.py
@@ -5,7 +5,7 @@
# this is distributed under a free software license, see license.txt
import sys, time
-sys.path.insert(0, '..')
+sys.path.append('..')
import parallel
LCDON = 0x01 #0x00000001 Switch on display
@@ -31,8 +31,9 @@ LCD_D6 = 1<<6
LCD_D7 = 1<<7
-class FourBitIO(object):
+class LCD:
def __init__(self):
+ self.p = parallel.Parallel()
self.data = 0
self.out(0) #reset pins
@@ -96,69 +97,6 @@ class FourBitIO(object):
self.toggleE() #toggle LCD_E, the enable pin
time.sleep(0.001) #wait until instr is finished
-
-class EightBitIO(object):
- def __init__(self):
- self.data = 0
-
- self.setRS(0)
- self.setRW(0)
- self.out(0) #reset pins
- time.sleep(0.050) #wait more than 30ms
- #send the reset sequece (3 times the same pattern)
- self.out(LCD8BITS) #set 8 bit interface
- self.toggleE() #toggle LCD_E, the enable pin
- time.sleep(0.005) #wait a bit
- self.toggleE() #toggle LCD_E, the enable pin
- time.sleep(0.005) #wait a bit
- self.toggleE() #toggle LCD_E, the enable pin
- time.sleep(0.005) #wait a bit
-
- #~ self.instr(LCD2LINES) #set 2 lines display
- self.instr(LCDCURSOROFF) #hide cursor
- self.instr(LCDCLEAR) #clear display
-
- def setRW(self, state):
- self.p.setAutoFeed(state)
-
- def setRS(self, state):
- self.p.setInitOut(state)
-
- def toggleE(self):
- """toggle enable pin"""
- self.p.setDataStrobe(1) #toggle LCD_E, the enable pin
- #~ time.sleep(0.001)
- self.p.setDataStrobe(0) #back to inactive position
- #~ time.sleep(0.001)
-
- def out(self, data):
- """set data to LCD port"""
- self.data = data
- self.p.setData(self.data)
-
- def instr(self, cmd):
- """send instruction byte to LCD"""
- self.setRS(0)
- self.setRW(0)
- self.out(cmd)
- self.toggleE() #toggle LCD_E, the enable pin
- time.sleep(0.005) #wait until instr is finished
-
- def putc(self, c):
- """send a data byte to the LCD"""
- self.setRS(1)
- self.setRW(0)
- self.out(ord(c))
- self.toggleE() #toggle LCD_E, the enable pin
- time.sleep(0.001) #wait until instr is finished
-
-
-#~ class HD44780(FourBitIO):
-class HD44780(EightBitIO):
- def __init__(self):
- self.p = parallel.Parallel()
- super(HD44780, self).__init__()
-
def write(self, str):
"""write a string to the LCD"""
for c in str:
@@ -171,7 +109,7 @@ class HD44780(EightBitIO):
self.instr(LCDLINE1) #just in case, set cursor to a visible pos
if __name__ == '__main__':
- lcd = HD44780()
+ lcd = LCD()
lcd.write("Hello World")
lcd.instr(LCDLINE2)
lcd.write("from Python")
diff --git a/pyparallel/parallel/parallelppdev.py b/pyparallel/parallel/parallelppdev.py
index d600c4a..18cc54c 100644
--- a/pyparallel/parallel/parallelppdev.py
+++ b/pyparallel/parallel/parallelppdev.py
@@ -183,21 +183,15 @@ class Parallel:
self.device = port
else:
self.device = "/dev/parport%d" % port
- self._fd = None
self._fd = os.open(self.device, os.O_RDWR)
- try:
- self.PPEXCL()
- self.PPCLAIM()
- self.setDataDir(1)
- self.setData(0)
- except IOError:
- os.close(self._fd)
- self._fd = None
- raise
+ self.PPEXCL()
+ self.PPCLAIM()
+ self.setDataDir(1)
+ self.setData(0)
def __del__(self):
+ self.PPRELEASE()
if self._fd is not None:
- self.PPRELEASE()
os.close(self._fd)
def timevalToFloat(self, timeval):
@@ -567,12 +561,8 @@ class Parallel:
"""Sets the states of the data bus line drivers (pins 2-9)"""
self._data=d
return self.PPWDATA(d)
-
- def getData(self):
- """Gets the states of the data bus line (pin 2-9)"""
- return self.PPRDATA()
- # status lines
+ #status lines
def getInError(self):
"""Returns the level on the nFault pin (15)"""
return (self.PPRSTATUS() & PARPORT_STATUS_ERROR) != 0
diff --git a/pyparallel/parallel/parallelutil.py b/pyparallel/parallel/parallelutil.py
index 036028e..a1a262a 100644
--- a/pyparallel/parallel/parallelutil.py
+++ b/pyparallel/parallel/parallelutil.py
@@ -1,15 +1,15 @@
class BitaccessMeta(type):
"""meta class that adds bit access properties to a
parallel port implementation"""
-
+
def __new__(self, classname, bases, classdict):
klass = type.__new__(self, classname, bases, classdict)
- # status lines
+ #status lines
klass.paperOut = property(klass.getInPaperOut, None, "Read the PaperOut signal")
- # control lines
+ #control lines
klass.dataStrobe = property(None, klass.setDataStrobe, "Set the DataStrobe signal")
- # XXX ... other bits
- # data bits
+ #XXX ... other bits
+ #data bits
for bit in range(8):
mask = (1<<bit)
def getter(self, mask=mask):
@@ -20,7 +20,7 @@ class BitaccessMeta(type):
else:
self.setData(self.getData() & ~mask)
setattr(klass, "D%d" % bit, property(getter, setter, "Access databit %d" % bit))
- # nibbles
+ #nibbles
for name, shift, width in [('D0_D3', 0, 4), ('D4_D7', 4, 4)]:
mask = (1<<width) - 1
def getter(self, shift=shift, mask=mask):
@@ -33,34 +33,34 @@ class BitaccessMeta(type):
class VirtualParallelPort:
"""provides a virtual parallel port implementation, useful
for tests and simulations without real hardware"""
-
+
__metaclass__ = BitaccessMeta
-
+
def __init__(self, port=None):
self._data = 0
-
+
def setData(self, value):
self._data = value
def getData(self):
return self._data
- # inputs return dummy value
+ #inputs return dummy value
def getInPaperOut(self): return self._dummy
- # ...
- # outputs just store a tuple with (action, value) pair
+ #...
+ #outputs just store a tuple with (action, value) pair
def setDataStrobe(self, value): self._last = ('setDataStrobe', value)
- # ...
+ #...
-# testing
+#testing
if __name__ == '__main__':
import unittest, sys
-
+
class TestBitaccess(unittest.TestCase):
"""Tests a port with no timeout"""
def setUp(self):
self.p = VirtualParallelPort()
-
+
def testDatabits(self):
"""bit by bit D0..D7"""
p = self.p
@@ -75,7 +75,7 @@ if __name__ == '__main__':
[p.D7, p.D6, p.D5, p.D4, p.D3, p.D2, p.D1, p.D0],
[1, 0, 1, 0, 1, 0, 1, 0]
)
-
+
def testDatabitsGroups(self):
"""nibbles D0..D7"""
p = self.p
@@ -86,39 +86,39 @@ if __name__ == '__main__':
self.failUnlessEqual(p._data, 0xd0)
p.D0_D3 = p.D4_D7 = 0xa
self.failUnlessEqual(p._data, 0xaa)
- # test bit patterns
+ #test bit patterns
for x in range(256):
- # test getting
+ #test getting
p._data = x
self.failUnlessEqual((p.D4_D7, p.D0_D3), (((x>>4) & 0xf), (x & 0xf)))
- # test setting
+ #test setting
p._data = 0
(p.D4_D7, p.D0_D3) = (((x>>4) & 0xf), (x & 0xf))
self.failUnlessEqual(p._data, x)
-
+
def testStatusbits(self):
"""bit by bit status lines"""
- # read the property:
+ #read the property:
self.p._dummy = 0
self.failUnlessEqual(self.p.paperOut, 0)
-
+
self.p._dummy = 1
self.failUnlessEqual(self.p.paperOut, 1)
-
- # read only, must not be writable:
+
+ #read only, must not be writable:
self.failUnlessRaises(AttributeError, setattr, self.p, 'paperOut', 1)
-
+
def testControlbits(self):
"""bit by bit control lines"""
self.p.dataStrobe = 0
self.failUnlessEqual(self.p._last, ('setDataStrobe', 0))
self.p.dataStrobe = 1
self.failUnlessEqual(self.p._last, ('setDataStrobe', 1))
-
- # write only, must not be writable:
+
+ #write only, must not be writable:
self.failUnlessRaises(AttributeError, getattr, self.p, 'dataStrobe')
-
+
sys.argv.append('-v')
# When this module is executed from the command-line, it runs all its tests
unittest.main()
-
+ \ No newline at end of file
diff --git a/pyparallel/parallel/parallelwin32.py b/pyparallel/parallel/parallelwin32.py
index c8f0d23..5c287cb 100644
--- a/pyparallel/parallel/parallelwin32.py
+++ b/pyparallel/parallel/parallelwin32.py
@@ -58,8 +58,7 @@ os.environ['PATH'] = os.environ['PATH'] + ';' + os.path.abspath(os.path.dirname(
#python extension in earlier versions of this modules
_pyparallel = ctypes.windll.simpleio
#need to initialize giveio on WinNT based systems
-if _pyparallel.init():
- raise IOError('Could not access the giveio driver which is required on NT based systems.')
+_pyparallel.init()
class Parallel:
@@ -77,14 +76,6 @@ class Parallel:
def setData(self, value):
_pyparallel.outp(self.dataRegAdr, value)
- def setDataDir( self, level):
- """set for port as input, clear for output"""
- if level:
- self.ctrlReg |= 0x20
- else:
- self.ctrlReg &= ~0x20
- _pyparallel.outp(self.ctrlRegAdr, self.ctrlReg)
-
# control register output functions
def setDataStrobe(self, level):
"""data strobe bit"""
@@ -109,7 +100,7 @@ class Parallel:
else:
self.ctrlReg = self.ctrlReg & ~0x04
_pyparallel.outp(self.ctrlRegAdr, self.ctrlReg)
-
+
def setSelect(self, level):
"""select bit"""
if level:
diff --git a/pyparallel/setup.py b/pyparallel/setup.py
index 937923f..749470c 100644
--- a/pyparallel/setup.py
+++ b/pyparallel/setup.py
@@ -1,34 +1,13 @@
#!/usr/bin/env python
-# setup.py
-try:
- from setuptools import setup
-except ImportError:
- print "standart distutils"
- from distutils.core import setup
-else:
- print "setuptools"
-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
+from distutils.core import setup
import os
if os.name == 'nt':
- print "# set dependedcies for windows version"
data_files = {'parallel': ['simpleio.dll']}
else:
- print "# no dependedcies"
- data_files = {}
+ data_files = None
-setup(
- name = "pyparallel",
+setup (name = "pyparallel",
description="Python Parallel Port Extension",
version="0.2",
author="Chris Liechti",
@@ -37,16 +16,5 @@ setup(
packages=['parallel'],
license="Python",
long_description="Python Parallel Port Extension for Win32, Linux, BSD",
- classifiers = [
- 'Development Status :: 4 - Beta',
- 'Intended Audience :: Developers',
- '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',
- ],
package_data = data_files
)
diff --git a/pyserial/CHANGES.txt b/pyserial/CHANGES.txt
deleted file mode 100644
index aee250b..0000000
--- a/pyserial/CHANGES.txt
+++ /dev/null
@@ -1,331 +0,0 @@
-========================
- pySerial Release Notes
-========================
-
-Version 1.0 13 Feb 2002
----------------------------
-- First public release.
-- Split from the pybsl application (see http://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 nonexistent ports with /dev file. bug report
- by Louis Cordier
-
-Bugfixes (win32):
-
-- RTS/CTS handling as suggested in Bug #635072
-- bugfix of timeouts brought up by Markus Hoffrogge
-
-
-Version 1.19 19 Mar 2003
----------------------------
-Bugfixes (posix):
-
-- removed ``dgux`` entry which actually 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 method of win32
- version. [Bug 669625]
-
-
-Version 1.20 28 Aug 2003
----------------------------
-- Added ``serial.device()`` for all platforms
-
-Bugfixes (win32):
-
-- don't recreate overlapped structures and events on each
- read/write.
-- don't set unneeded 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 Python 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 currently 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
-- Multithreading 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 disabled 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)
-
-
-Version 2.3 19 Jun 2008
----------------------------
-New Features:
-
-- iterator interface. ``for line in Serial(...): ...`` is now possible
- Suggested by Bernhard Bender
-- ``sendBreak()`` accepts a ``duration`` argument. Default duration increased.
-- win32 handles \\.\COMx format automatically for com ports of higher number
- (COM10 is internally translated to \\.\COM10 etc.)
-- miniterm.py has a new feature to send a file (upload) and configurable
- special characters for exit and upload. Refactored internals to class based
- structure (upload and class refactoring by Colin D Bennett)
-
-Bugfixes:
-
-- [Bug 1451535] TCP/serial redirect example "--help"
-- update VERSION variable
-- update wxSerialConfigDialog.py and wxTerminal.py compatibility with
- wxPython 2.8 (Peleg)
-- Check for string in write function. Using unicode causes errors, this
- helps catching errors early (Tom Lynn)
-
-Bugfixes (posix):
-
-- [Bug 1554183] setRTS/setDTR reference to non existing local "on"
-- [Bug 1513653] file descriptor not closed when exception is thrown
-- FreeBSD now uses cuadX instead of cuaaX (Patrick Phalen)
-
-Bugfixes (win32):
-
-- [Bug 1520357] Handle leak
-- [Bug 1679013] Ignore exception raised by SetCommTimeout() in close().
-- [Bug 1938118] process hang forever under XP
-
-
-Version 2.4 6 Jul 2008
----------------------------
-New Features:
-
-- [Patch 1616790] pyserial: Add inter-character timeout feature
-- [Patch 1924805] add a setBreak function
-- Add mark/space parity
-- Add .NET/Mono backend (IronPython)
-
-Bugfixes (posix):
-
-- [Bug 1783159] Arbitrary baud rates (Linux/Posix)
-
-Bugfixes (win32):
-
-- [Patch 1561423] Add mark/space parity, Win32
-- [Bug 2000771] serial port CANNOT be specified by number on windows
-- examples/scanwin32.py does no longer return \\.\ names
-- fix \\.\ handling for some cases
-
-Bugfixes (jython):
-
- - The Jython backend tries javax.comm and gnu.io (Seo Sanghyeon)
-
-
-Version 2.5 <date>
----------------------------
-New Features:
-
-- Python 3.x support (through 2to3)
-- compatible with Python io library (Python 2.6+)
-- Support for Win32 is now written on the top of ctypes (bundled with
- Python 2.5+) instead of pywin32 (patch by Giovanni Bajo).
-- 1.5 stop bits (STOPBITS_ONE_POINT_FIVE, implemented on all platforms)
-- Documentation update, now written with Sphinx/ReST
-- miniterm application extended (CTRL+T -> menu)
-- miniterm.py is now installed as "script"
-- add scanlinux.py example
-- add port_publisher example
-
-Bugfixes:
-
-- Improve and fix tcp_serial_redirector example.
-- [Bug 2603052] 5-bit mode (needs 1.5 stop bits in some cases)
-
-Bugfixes (posix):
-
-- [Bug 2810169] Propagate exceptions raised in serialposix _reconfigure
-- [Bug 2562610] setting non standard baud rates on Darwin (Emmanuel Blot)
-
-Bugfixes (win32):
-
-- [Bug 2469098] parity PARITY_MARK, PARITY_SPACE isn't supported on win32
-- [SF 2446218] outWaiting implemented
-- [Bug 2392892] scanwin32.py better exception handling
-- [Bug 2505422] scanwin32.py Vista 64bit compatibility
diff --git a/pyserial/LICENSE.txt b/pyserial/LICENSE.txt
deleted file mode 100644
index e8664f4..0000000
--- a/pyserial/LICENSE.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-Copyright (c) 2001-2008 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/pyserial/MANIFEST.in b/pyserial/MANIFEST.in
deleted file mode 100644
index 24429f0..0000000
--- a/pyserial/MANIFEST.in
+++ /dev/null
@@ -1,29 +0,0 @@
-include README.txt
-include LICENSE.txt
-include CHANGES.txt
-include MANIFEST.in
-include setup.py
-
-include examples/enhancedserial.py
-include examples/miniterm.py
-include examples/port_publisher.py
-include examples/port_publisher.sh
-include examples/scan.py
-include examples/scanlinux.py
-include examples/scanwin32.py
-include examples/setup_demo.py
-include examples/setup-miniterm-py2exe.py
-include examples/tcp_serial_redirect.py
-include examples/test.py
-include examples/test_advanced.py
-include examples/test_high_load.py
-include examples/wxSerialConfigDialog.py
-include examples/wxSerialConfigDialog.wxg
-include examples/wxTerminal.py
-include examples/wxTerminal.wxg
-
-include documentation/*.rst
-include documentation/pyserial.png
-include documentation/conf.py
-include documentation/Makefile
-
diff --git a/pyserial/README.txt b/pyserial/README.txt
deleted file mode 100644
index 60793a4..0000000
--- a/pyserial/README.txt
+++ /dev/null
@@ -1,277 +0,0 @@
-========
-pySerial
-========
-This module encapsulates the access for the serial port. It provides backends
-for standard Python running on Windows, Linux, BSD (possibly any POSIX
-compliant system), Jython and IronPython. The module named "serial"
-automatically selects the appropriate backend.
-
-It is released under a free software license, see LICENSE.txt for more
-details.
-
-Project Homepage: http://pyserial.sourceforge.net
-(C) 2001-2008 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 byte sizes, 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 hundred 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 baud rate 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
-
-
-Read only Attributes of Serial instances::
-
- portstr # device name
- BAUDRATES # list of valid baud rates
- 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 attributes, 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 baud rate setting
- bytesize # byte size 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 attributes also have corresponding getX and setXX methods.
-
-
-Exceptions that can be raised::
-
- 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
-
-Iterator interface
-~~~~~~~~~~~~~~~~~~
-It is possible to iterate over lines coming from a serial port::
-
- >>> ser = serial.Serial(0, timeout=10)
- >>> for line in ser:
- ... print line
-
-The use is somewhat restricted tough, as many protocols on the wire require
-that commands are sent and answers are read and this one only reads lines.
-
-
-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/
-- IronPython: http://www.codeplex.com/IronPython
-- setuptools: http://peak.telecommunity.com/DevCenter/setuptools
-
diff --git a/pyserial/documentation/Makefile b/pyserial/documentation/Makefile
deleted file mode 100644
index 8384360..0000000
--- a/pyserial/documentation/Makefile
+++ /dev/null
@@ -1,88 +0,0 @@
-# Makefile for Sphinx documentation
-#
-
-# You can set these variables from the command line.
-SPHINXOPTS =
-SPHINXBUILD = sphinx-build
-PAPER =
-
-# Internal variables.
-PAPEROPT_a4 = -D latex_paper_size=a4
-PAPEROPT_letter = -D latex_paper_size=letter
-ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
-
-.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
-
-help:
- @echo "Please use \`make <target>' where <target> is one of"
- @echo " html to make standalone HTML files"
- @echo " dirhtml to make HTML files named index.html in directories"
- @echo " pickle to make pickle files"
- @echo " json to make JSON files"
- @echo " htmlhelp to make HTML files and a HTML help project"
- @echo " qthelp to make HTML files and a qthelp project"
- @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
- @echo " changes to make an overview of all changed/added/deprecated items"
- @echo " linkcheck to check all external links for integrity"
- @echo " doctest to run all doctests embedded in the documentation (if enabled)"
-
-clean:
- -rm -rf _build/*
-
-html:
- $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html
- @echo
- @echo "Build finished. The HTML pages are in _build/html."
-
-dirhtml:
- $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) _build/dirhtml
- @echo
- @echo "Build finished. The HTML pages are in _build/dirhtml."
-
-pickle:
- $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle
- @echo
- @echo "Build finished; now you can process the pickle files."
-
-json:
- $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json
- @echo
- @echo "Build finished; now you can process the JSON files."
-
-htmlhelp:
- $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp
- @echo
- @echo "Build finished; now you can run HTML Help Workshop with the" \
- ".hhp project file in _build/htmlhelp."
-
-qthelp:
- $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) _build/qthelp
- @echo
- @echo "Build finished; now you can run "qcollectiongenerator" with the" \
- ".qhcp project file in _build/qthelp, like this:"
- @echo "# qcollectiongenerator _build/qthelp/pySerial.qhcp"
- @echo "To view the help file:"
- @echo "# assistant -collectionFile _build/qthelp/pySerial.qhc"
-
-latex:
- $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex
- @echo
- @echo "Build finished; the LaTeX files are in _build/latex."
- @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
- "run these through (pdf)latex."
-
-changes:
- $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes
- @echo
- @echo "The overview file is in _build/changes."
-
-linkcheck:
- $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck
- @echo
- @echo "Link check complete; look for any errors in the above output " \
- "or in _build/linkcheck/output.txt."
-
-doctest:
- $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) _build/doctest
- @echo "Testing of doctests in the sources finished, look at the " \
- "results in _build/doctest/output.txt."
diff --git a/pyserial/documentation/appendix.rst b/pyserial/documentation/appendix.rst
deleted file mode 100644
index 001c6e5..0000000
--- a/pyserial/documentation/appendix.rst
+++ /dev/null
@@ -1,68 +0,0 @@
-==========
- Appendix
-==========
-
-Related software
-================
-
-com0com - http://com0com.sourceforge.net/
- Provides virtual serial ports for Windows.
-
-
-License
-=======
-
-Copyright (C) 2001-2009 Chris Liechti <cliechti(at)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/pyserial/documentation/conf.py b/pyserial/documentation/conf.py
deleted file mode 100644
index 7420982..0000000
--- a/pyserial/documentation/conf.py
+++ /dev/null
@@ -1,194 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# pySerial documentation build configuration file, created by
-# sphinx-quickstart on Tue Jul 21 00:27:45 2009.
-#
-# This file is execfile()d with the current directory set to its containing dir.
-#
-# Note that not all possible configuration values are present in this
-# autogenerated file.
-#
-# All configuration values have a default; values that are commented out
-# serve to show the default.
-
-import sys, os
-
-# If extensions (or modules to document with autodoc) are in another directory,
-# add these directories to sys.path here. If the directory is relative to the
-# documentation root, use os.path.abspath to make it absolute, like shown here.
-#sys.path.append(os.path.abspath('.'))
-
-# -- General configuration -----------------------------------------------------
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = []
-
-# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
-
-# The suffix of source filenames.
-source_suffix = '.rst'
-
-# The encoding of source files.
-#source_encoding = 'utf-8'
-
-# The master toctree document.
-master_doc = 'index'
-
-# General information about the project.
-project = u'pySerial'
-copyright = u'2009, Chris Liechti'
-
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
-version = '2.5'
-# The full version, including alpha/beta/rc tags.
-release = '2.5 preview'
-
-# The language for content autogenerated by Sphinx. Refer to documentation
-# for a list of supported languages.
-#language = None
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
-
-# List of documents that shouldn't be included in the build.
-#unused_docs = []
-
-# List of directories, relative to source directory, that shouldn't be searched
-# for source files.
-exclude_trees = ['_build']
-
-# The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
-
-# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
-
-
-# -- Options for HTML output ---------------------------------------------------
-
-# The theme to use for HTML and HTML Help pages. Major themes that come with
-# Sphinx are currently 'default' and 'sphinxdoc'.
-html_theme = 'default'
-
-# Theme options are theme-specific and customize the look and feel of a theme
-# further. For a list of options available for each theme, see the
-# documentation.
-#html_theme_options = {}
-
-# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
-
-# The name for this set of Sphinx documents. If None, it defaults to
-# "<project> v<release> documentation".
-#html_title = None
-
-# A shorter title for the navigation bar. Default is the same as html_title.
-#html_short_title = None
-
-# The name of an image file (relative to this directory) to place at the top
-# of the sidebar.
-html_logo = 'pyserial.png'
-
-# The name of an image file (within the static path) to use as favicon of the
-# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
-# pixels large.
-#html_favicon = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = ['_static']
-
-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
-# using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
-
-# If true, SmartyPants will be used to convert quotes and dashes to
-# typographically correct entities.
-#html_use_smartypants = True
-
-# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
-
-# Additional templates that should be rendered to pages, maps page names to
-# template names.
-#html_additional_pages = {}
-
-# If false, no module index is generated.
-#html_use_modindex = True
-
-# If false, no index is generated.
-#html_use_index = True
-
-# If true, the index is split into individual pages for each letter.
-#html_split_index = False
-
-# If true, links to the reST sources are added to the pages.
-#html_show_sourcelink = True
-
-# If true, an OpenSearch description file will be output, and all pages will
-# contain a <link> tag referring to it. The value of this option must be the
-# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
-
-# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = ''
-
-# Output file base name for HTML help builder.
-htmlhelp_basename = 'pySerialdoc'
-
-
-# -- Options for LaTeX output --------------------------------------------------
-
-# The paper size ('letter' or 'a4').
-#latex_paper_size = 'letter'
-
-# The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
-
-# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author, documentclass [howto/manual]).
-latex_documents = [
- ('index', 'pySerial.tex', u'pySerial Documentation',
- u'Chris Liechti', 'manual'),
-]
-
-# The name of an image file (relative to this directory) to place at the top of
-# the title page.
-latex_logo = 'pyserial.png'
-
-# For "manual" documents, if this is true, then toplevel headings are parts,
-# not chapters.
-#latex_use_parts = False
-
-# Additional stuff for the LaTeX preamble.
-#latex_preamble = ''
-
-# Documents to append as an appendix to all manuals.
-#latex_appendices = []
-
-# If false, no module index is generated.
-#latex_use_modindex = True
diff --git a/pyserial/documentation/examples.rst b/pyserial/documentation/examples.rst
deleted file mode 100644
index 283f2d6..0000000
--- a/pyserial/documentation/examples.rst
+++ /dev/null
@@ -1,282 +0,0 @@
-==========
- Examples
-==========
-
-Miniterm
-========
-This is a console application that provides a small terminal application.
-miniterm itself does not implement any terminal features such as VT102
-compatibility. However it inherits these features from the terminal it is run.
-For example on GNU/Linux running from an xterm it will support the escape
-sequences of the xterm. On Windows the typical console window is dumb and does
-not support any escapes. When ANSI.sys is loaded it supports some escapes.
-
-miniterm::
-
- --- Miniterm on /dev/ttyS0: 9600,8,N,1 ---
- --- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
-
-Command line options can be given so that binary data including escapes for
-terminals are escaped or output as hex.
-
-Command line options ``miniterm.py -h``::
-
- Usage: miniterm.py [options] [port [baudrate]]
-
- Miniterm - A simple terminal program for the serial port.
-
- Options:
- -h, --help show this help message and exit
- -p PORT, --port=PORT port, a number (default 0) or a device name
- (deprecated option)
- -b BAUDRATE, --baud=BAUDRATE
- set baud rate, default 9600
- --parity=PARITY set parity, one of [N, E, O, S, M], default=N
- -e, --echo enable local echo (default off)
- --rtscts enable RTS/CTS flow control (default off)
- --xonxoff enable software flow control (default off)
- --cr do not send CR+LF, send CR only
- --lf do not send CR+LF, send LF only
- -D, --debug debug received data (escape non-printable chars)
- --debug can be given multiple times: 0: just print
- what is received 1: escape non-printable characters,
- do newlines as unusual 2: escape non-printable
- characters, newlines too 3: hex dump everything
- --rts=RTS_STATE set initial RTS line state (possible values: 0, 1)
- --dtr=DTR_STATE set initial DTR line state (possible values: 0, 1)
- -q, --quiet suppress non error messages
- --exit-char=EXIT_CHAR
- ASCII code of special character that is used to exit
- the application
- --menu-char=MENU_CHAR
- ASCII code of special character that is used to
- control miniterm (menu)
-
-
-miniterm supports some control functions. Typing :kbd:`Control+t Control+h` when it is
-running shows the help text::
-
- --- pySerial - miniterm - help
- ---
- --- Ctrl+] Exit program
- --- Ctrl+T Menu escape key, followed by:
- --- Menu keys:
- --- Ctrl+T Send the menu character itself to remote
- --- Ctrl+] Send the exit character to remote
- --- Ctrl+I Show info
- --- Ctrl+U Upload file (prompt will be shown)
- --- Toggles:
- --- Ctrl+R RTS Ctrl+E local echo
- --- Ctrl+D DTR Ctrl+B BREAK
- --- Ctrl+L line feed Ctrl+A Cycle repr mode
- ---
- --- Port settings (Ctrl+T followed by the following):
- --- 7 8 set data bits
- --- n e o s m change parity (None, Even, Odd, Space, Mark)
- --- 1 2 3 set stop bits (1, 2, 1.5)
- --- b change baud rate
- --- x X disable/enable software flow control
- --- r R disable/enable hardware flow control
-
-
-miniterm.py_
- The miniterm program.
-
-setup-miniterm-py2exe.py_
- This is a py2exe setup script for Windows. It can be used to create a
- standalone ``miniterm.exe``.
-
-.. _miniterm.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/miniterm.py
-.. _setup-miniterm-py2exe.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/setup-miniterm-py2exe.py
-
-
-TCP/IP - serial bridge
-======================
-This program opens a TCP/IP port. When a connection is made to that port (e.g.
-with telnet) it forwards all data to the serial port and vice versa.
-
-The serial port settings are set on the command line when starting the program.
-There is no possibility to change settings from remote.
-::
-
- Usage: tcp_serial_redirect.py [options] [port [baudrate]]
-
- Simple Serial to Network (TCP/IP) redirector.
-
- Options:
- -h, --help show this help message and exit
- -q, --quiet suppress non error messages
- --spy peek at the communication and print all data to the
- console
-
- Serial Port:
- Serial port settings
-
- -p PORT, --port=PORT
- port, a number (default 0) or a device name
- -b BAUDRATE, --baud=BAUDRATE
- set baud rate, default: 9600
- --parity=PARITY set parity, one of [N, E, O], default=N
- --rtscts enable RTS/CTS flow control (default off)
- --xonxoff enable software flow control (default off)
- --rts=RTS_STATE set initial RTS line state (possible values: 0, 1)
- --dtr=DTR_STATE set initial DTR line state (possible values: 0, 1)
-
- Network settings:
- Network configuration.
-
- -P LOCAL_PORT, --localport=LOCAL_PORT
- local TCP port
-
- Newline Settings:
- Convert newlines between network and serial port. Conversion is
- normally disabled and can be enabled by --convert.
-
- -c, --convert enable newline conversion (default off)
- --net-nl=NET_NEWLINE
- type of newlines that are expected on the network
- (default: LF)
- --ser-nl=SER_NEWLINE
- type of newlines that are expected on the serial port
- (default: CR+LF)
-
- NOTE: no security measures are implemented. Anyone can remotely connect to
- this service over the network. Only one connection at once is supported. When
- the connection is terminated it waits for the next connect.
-
-
-tcp_serial_redirect.py_
- Main program.
-
-.. _tcp_serial_redirect.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/tcp_serial_redirect.py
-
-
-Multi-port TCP/IP - serial bridge
-=================================
-This example implements a TCP/IP to serial port service that works with
-multiple ports at once. It uses select, no threads, and runs on POSIX systems
-only.
-
-- Check existence of ``/tty/USB0...9``.
-- Ports are periodically checked using ``os.path.exists``.
-- Send Zeroconfig announcements when port appears or disappears (uses
- python-avahi and dbus).
-- Single process for all ports (not per port).
-- All published services are kept in a dictionary that maps device->publisher
- object.
-- A delay of 5 seconds slows down the poll loop to a reasonable period.
-- The script implements a daemon that logs to the syslog, unless specified
- otherwise on the command line.
-
-
-Requirements
-------------
-- python (>2.4)
-- python-avahi
-- python-dbus
-- python-serial
-
-
-Installation
-------------
-- Copy the script ``port_publisher.py`` to ``/usr/local/bin``.
-- Copy the script ``port_publisher.sh`` to ``/etc/init.d``.
-- Add links to the runlevels using ``update-rc.d port_publisher.sh defaults 99``
-- Thats it :-) the service will be started on next reboot. Alternatively run
- ``invoke-rc.d port_publisher.sh start`` as root.
-
-
-port_publisher.py_
- Multi-port TCP/IP-serial converter for POSIX environments.
-
-port_publisher.sh_
- Example init.d script.
-
-.. _port_publisher.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/port_publisher.py
-.. _port_publisher.sh: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/port_publisher.sh
-
-
-wxPython examples
-=================
-A simple terminal application for wxPython and a flexible serial port
-configuration dialog are shown here.
-
-wxTerminal.py_
- A simple terminal application. Note that the length of the buffer is
- limited by wx and it may suddenly stop displaying new input.
-
-wxTerminal.wxg_
-test_high_load.py_
- Tests involving sending a lot of data.
- A wxGlade design file for the terminal application.
-
-wxSerialConfigDialog.py_
- A flexible serial port configuration dialog.
-
-wxSerialConfigDialog.wxg_
- The wxGlade design file for the configuration dialog.
-
-setup_demo.py_
- A py2exe setup script to package the terminal application.
-
-.. _wxTerminal.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/wxTerminal.py
-.. _wxTerminal.wxg: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/wxTerminal.wxg
-.. _wxSerialConfigDialog.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/wxSerialConfigDialog.py
-.. _wxSerialConfigDialog.wxg: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/wxSerialConfigDialog.wxg
-.. _setup_demo.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/setup_demo.py
-
-
-Wrapper class
-=============
-This example provides a subclass based on ``Serial`` that has an alternative
-implementation of ``readline()``
-
-enhancedserial.py_
- A class with alternative ``readline()`` implementation.
-
-.. _enhancedserial.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/enhancedserial.py
-
-
-Finding serial ports
-====================
-scan.py_
- A simple loop that probes serial ports by number.
-
-scanlinux.py_
- A Linux only version looking at the entries in ``/dev``. It works best with
- on systems with devfs or udev that only create those entries that represent
- devices. On older installations a lot of pre-created device files are found
- and an additional open check should be added to ensure that the device is
- real.
-
-scanwin32.py_
- A Windows only version that returns a list of serial ports with information
- from the registry.
-
-.. _scan.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/scan.py
-.. _scanlinux.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/scanlinux.py
-.. _scanwin32.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/scanwin32.py
-
-
-Unit tests
-==========
-The project uses a number of unit test to verify the functionality. They all
-need a loop back connector. The scripts itself contain more information.
-
-test.py_
- Basic tests.
-
-test_advanced.py_
- Test more advanced features.
-
-test_high_load.py_
- Tests involving sending a lot of data.
-
-test_iolib.py_
- Tests involving the :mod:`io` library. Only available for Python 2.6 and
- newer.
-
-.. _test.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/test.py
-.. _test_advanced.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/test_advanced.py
-.. _test_high_load.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/test_high_load.py
-.. _test_iolib.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/test_iolib.py
diff --git a/pyserial/documentation/index.rst b/pyserial/documentation/index.rst
deleted file mode 100644
index 96a78b5..0000000
--- a/pyserial/documentation/index.rst
+++ /dev/null
@@ -1,29 +0,0 @@
-.. pySerial documentation master file
-
-Welcome to pySerial's documentation
-===================================
-
-This module encapsulates the access for the serial port. It provides backends
-for Python running on Windows, Linux, BSD (possibly any POSIX compliant
-system), Jython and IronPython (.NET and Mono). The module named "serial"
-automatically selects the appropriate backend.
-
-Contents:
-
-.. toctree::
- :maxdepth: 2
-
- pyserial
- shortintro
- examples
- pyserial_api
- pyparallel
- appendix
-
-Indices and tables
-==================
-
-* :ref:`genindex`
-* :ref:`modindex`
-* :ref:`search`
-
diff --git a/pyserial/documentation/pyparallel.rst b/pyserial/documentation/pyparallel.rst
deleted file mode 100644
index 00c0b95..0000000
--- a/pyserial/documentation/pyparallel.rst
+++ /dev/null
@@ -1,165 +0,0 @@
-============
- pyParallel
-============
-
-.. note:: This module is in development (since years ;-)
-
-Overview
-========
-This module encapsulates the access for the parallel port. It provides backends
-for Python running on Windows and Linux. Other platforms are possible too but
-not yet integrated.
-
-This module is still under development. But it may be useful for developers.
-
-Copyright (C) 2001-2003 Chris Liechti <cliechti(at)gmx.net>
-
-Here is the `project page on SourceForge`_ and here is the `SVN repository`_.
-
-.. _`project page on SourceForge`: http://sourceforge.net/projects/pyserial/
-.. _`SVN repository`: http://sourceforge.net/svn/?group_id=46487
-
-
-Features
---------
-* same class based interface on all supported platforms
-* port numbering starts at zero, no need to know the port name in the user program
-* port string (device name) can be specified if access through numbering is inappropriate
-
-
-Requirements
-------------
-* Python 2.2 or newer
-* "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 in newer Python versions.
-
-The windows version needs a compiled extension and the giveio.sys driver for
-Windows NT/2k/XP. The extension module can be compiled with Distutils with
-either MSVC or GCC/mingw32.
-
-It is released under a free software license, see LICENSE.txt for more details.
-
-
-Short introduction
-==================
-::
-
- >>> import parallel
- >>> p = parallel.Parallel() # open LPT1
- >>> p.setData(0x55)
-
-
-Examples
---------
-Please look in the SVN Repository. There is an example directory where you can
-find a simple terminal and more.
-http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyparallel/examples/
-
-
-API
-===
-
-.. module:: parallel
-
-.. class:: Parallel
-
- .. method:: __init__(port)
-
- Open given parallel port.
-
- .. method:: setData(value)
-
- Apply the given byte to the data pins of the parallel port.
-
- .. method:: setDataStrobe(level)
-
- Set the "data strobe" line to the given state.
-
- .. method:: setAutoFeed(level)
-
- Set "auto feed" line to given state.
-
- .. method:: setInitOut(level)
-
- Set "initialize" line to given state.
-
- .. method: setSelect(level)
-
- Set "select" line to given state.
-
- .. method:getInError()
-
- Set "Error" line to given state.
-
- .. method:: getInSelected()
-
- Read level of "select" line.
-
- .. method:: getInPaperOut()
-
- Read level of "paper out" line.
-
- .. method:: getInAcknowledge()
-
- Read level of "Acknowledge" line.
-
- .. method: getInBusy()
-
- Read level of "busy" line.
-
-
-.. module:: parallel.parallelutil
-
-.. class:: BitaccessMeta
-
- This mix-in class adds a few properties that allow easier bit access to the
- data lines. (D0 .. D7) e.g. p.D0 refers to the first bit of the data
- lines.
-
-.. class:: VirtualParallelPort
-
- This class provides a virtual parallel port implementation, useful
- for tests and simulations without real hardware.
-
-
-Notes
-=====
-
-Linux
------
-1. The :manpage:`lp(4)` module must be unloaded, ``rmmod lp``. ``lp`` claims
- exclusive access to the port and other programs won't be able to use it.
-
-2. The :manpage:`ppdev(4)` module needs to be loaded, ``modprobe ppdev``. When
- ``udev`` is in use, (default with 2.6 kernels) this will create a
- ``/dev/parport0``.
-
-3. The user needs to have write permissions to ``/dev/parport0``. Many
- distributions have an ``lp`` group that owns the device; the simplest is to
- add the user account to this group. Simply changing permissions on the
- device is not the best strategy as they will be reverted to their defaults
- next time the driver is loaded.
-
-
-Windows
--------
-The giveio driver must be installed as the module needs direct access to the
-hardware. This also means that USB parallel port adapters won't be supported.
-
-
-Misc
-====
-References
-----------
-* Python: http://www.python.org/
-* Jython: http://www.jython.org/
-* 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/pyserial/documentation/pyserial.png b/pyserial/documentation/pyserial.png
deleted file mode 100644
index 7fd45f4..0000000
--- a/pyserial/documentation/pyserial.png
+++ /dev/null
Binary files differ
diff --git a/pyserial/documentation/pyserial.rst b/pyserial/documentation/pyserial.rst
deleted file mode 100644
index 2db8c21..0000000
--- a/pyserial/documentation/pyserial.rst
+++ /dev/null
@@ -1,110 +0,0 @@
-==========
- pySerial
-==========
-
-Overview
-========
-This module encapsulates the access for the serial port. It provides backends
-for Python running on Windows, Linux, BSD (possibly any POSIX compliant
-system), Jython and IronPython (.NET and Mono). The module named "serial"
-automatically selects the appropriate backend.
-
-It is released under a free software license, see LICENSE_ for more
-details.
-
-Copyright (C) 2001-2009 Chris Liechti <cliechti(at)gmx.net>
-
-The `project page on SourceForge`_ and here is the `SVN repository`_ and the
-`Download Page`_.
-
-The homepage is at http://pyserial.sf.net.
-
-.. _LICENSE: appendix.html#license
-.. _`project page on SourceForge`: http://sourceforge.net/projects/pyserial/
-.. _`SVN repository`: http://sourceforge.net/svn/?group_id=46487
-.. _`Download Page`: http://sourceforge.net/project/showfiles.php?group_id=46487
-
-
-Features
-========
-* Same class based interface on all supported platforms.
-* Access to the port settings through Python properties.
-* Support for different byte sizes, stop bits, parity and flow control with
- RTS/CTS and/or Xon/Xoff.
-* Working with or without receive timeout.
-* File like API with "read" and "write" ("readline" etc. also supported).
-* The files in this package are 100% pure Python.
-* 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.
-* Compatible with :mod:`io` library (Python 2.6+)
-
-
-Requirements
-============
-* Python 2.3 or newer, including Python 3.x
-* ctypes extensions on Windows (is in standard library since Python 2.5+)
-* "Java Communications" (JavaComm) or compatible extension for Java/Jython
-
-
-Installation
-============
-
-pyserial
---------
-This installs a package that can be used from Python (``import serial``).
-
-To install the module for all users on the system, administrator rights (root)
-is required..
-
-From source (tar.gz or checkout)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-http://pypi.python.org/pypi/pyserial
-Unpack the archive, enter the ``pyserial-x.y`` directory and run::
-
- python setup.py install
-
-Setuptools/PyPI
-~~~~~~~~~~~~~~~
-Alternatively it can be installed from PyPI, either manually downloading the
-files and installing as described above or using::
-
- easy_install -U pyserial
-
-Packages
-~~~~~~~~
-There are also packaged versions for some Linux distributions and Windows:
-
-Debian/Ubuntu
- A package is available under the name "python-serial".
-
-Windows
- There is also a Windows installer for end users. It is located in the
- PyPi_. Developers may be interested to get the source archive, because it
- contains examples and the readme.
-
-.. _PyPi: http://pypi.python.org/pypi/pyserial
-
-
-References
-==========
-* Python: http://www.python.org/
-* Jython: http://www.jython.org/
-* 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/
-* IronPython: http://www.codeplex.com/IronPython
-* setuptools: http://peak.telecommunity.com/DevCenter/setuptools
-
-
-Older Versions
-==============
-Older versions are still available on the `Download Page`_. pySerial 1.21 is
-compatible with Python 2.0 on Windows, Linux and several un*x like systems,
-MacOSX and Jython.
-
-On windows releases older than 2.5 will depend on pywin32_ (previously known as
-win32all)
-
-.. _`Download Page`: http://sourceforge.net/project/showfiles.php?group_id=46487
-.. _pywin32: http://pypi.python.org/pypi/pywin32
diff --git a/pyserial/documentation/pyserial_api.rst b/pyserial/documentation/pyserial_api.rst
deleted file mode 100644
index 9833254..0000000
--- a/pyserial/documentation/pyserial_api.rst
+++ /dev/null
@@ -1,531 +0,0 @@
-==============
- pySerial API
-==============
-
-.. module:: serial
-
-Classes
-=======
-
-.. class:: Serial
-
- .. method:: __init__(port=None, baudrate=9600, bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, timeout=None, xonxoff=0, rtscts=0, interCharTimeout=None)
-
- :param port:
- Device name or port number number or :const:`None`.
-
- :param baudrate:
- Baud rate such as 9600 or 115200 etc.
-
- :param bytesize:
- Number of data bits. Possible values:
- :const:`FIVEBITS`, :const:`SIXBITS`, :const:`SEVENBITS`,
- :const:`EIGHTBITS`
-
- :param parity:
- Enable parity checking. Possible values:
- :const:`PARITY_NONE` :const:`PARITY_EVEN` :const:`PARITY_ODD`
- :const:`PARITY_MARK` :const:`PARITY_SPACE`
-
- :param stopbits:
- Number of stop bits. Possible values:
- :const:`STOPBITS_ONE` :const:`STOPBITS_ONE_POINT_FIVE`
- :const:`STOPBITS_TWO`
-
- :param timeout:
- Set a read timeout value.
-
- :param xonxoff:
- Enable software flow control.
-
- :param rtscts:
- Enable hardware (RTS/CTS) flow control.
-
- :param interCharTimeout:
- Inter-character timeout, :const:`None` to disable (default).
-
- :exception ValueError:
- Will be raised when parameter are out of range, e.g. baud rate, data bits.
-
- :exception SerialException:
- In case the device can not be found or can not be configured.
-
-
- The port is immediately opened on object creation, when a *port* is
- given. It is not opened when *port* is :const:`None` and a successive call
- to :meth:`open` will be needed.
-
- Possible values for the parameter *port*:
-
- - Number: number of device, numbering starts at zero.
- - Device name: depending on operating system. e.g. ``/dev/ttyUSB0``
- on GNU/Linux or ``COM3`` on Windows.
-
- Possible values for the parameter *timeout*:
-
- - ``timeout = None``: wait forever
- - ``timeout = 0``: non-blocking mode (return immediately on read)
- - ``timeout = x``: set timeout to ``x`` seconds (float allowed)
-
-
- .. method:: open()
-
- Open port.
-
- .. method:: close()
-
- Close port immediately.
-
-
- The following methods may raise :exc:`ValueError` when applied to a closed
- port.
-
- .. method:: read(size=1)
-
- :param size: Number of bytes to read.
- :return: Bytes read from the port.
-
- 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.
-
- .. versionchanged:: 2.5
- Returns an instance of :class:`bytes` when available (Python 2.6
- and newer) and :class:`str` otherwiese.
-
- .. method:: write(data)
-
- :param data: Data to send.
- :return: Number of bytes written.
- :exception SerialTimeoutException:
- In case a write timeout is configured for the port and the time is
- exceeded.
-
- Write the string *data* to the port.
-
- .. versionchanged:: 2.5
- Accepts instances of :class:`bytes` and :class:`bytearray` when
- available (Python 2.6 and newer) and :class:`str` otherwiese.
-
- .. method:: inWaiting()
-
- Return the number of chars in the receive buffer.
-
- .. method:: flush()
-
- Flush of file like objects. In this case, wait until all data is
- written.
-
- .. method:: flushInput()
-
- Flush input buffer, discarding all it's contents.
-
- .. method:: flushOutput()
-
- Clear output buffer, aborting the current output and
- discarding all that is in the buffer.
-
- .. method:: sendBreak(duration=0.25)
-
- :param duration: Time (float) to activate the BREAK condition.
-
- Send break condition. Timed, returns to idle state after given
- duration.
-
- .. method:: setBreak(level=True)
-
- :param level: when true activate BREAK condition, else disable.
-
- Set break: Controls TXD. When active, no transmitting is possible.
-
- .. method:: setRTS(level=True)
-
- :param level: Set control line to logic level.
-
- Set RTS line to specified logic level.
-
- .. method:: setDTR(level=True)
-
- :param level: Set control line to logic level.
-
- Set DTR line to specified logic level.
-
- .. method:: getCTS()
-
- :return: Current state (boolean)
-
- Return the state of the CTS line.
-
- .. method:: getDSR()
-
- :return: Current state (boolean)
-
- Return the state of the DSR line.
-
- .. method:: getRI()
-
- :return: Current state (boolean)
-
- Return the state of the RI line.
-
- .. method:: getCD()
-
- :return: Current state (boolean)
-
- Return the state of the CD line
-
- Read-only attributes:
-
- .. attribute:: name
-
- Device name. This is always the device name even if the
- port was opened by a number. (Read Only).
-
- .. versionadded:: 2.5
-
- .. attribute:: portstr
-
- :deprecated: use :attr:`name` instead
-
- .. attribute:: BAUDRATES
-
- A list of valid baud rates. The list may be incomplete such that higher
- baud rates may be supported by the device and that values in between the
- standard baud rates are supported. (Read Only).
-
- .. attribute:: BYTESIZES
-
- A list of valid byte sizes for the device (Read Only).
-
- .. attribute:: PARITIES
-
- A list of valid parities for the device (Read Only).
-
- .. attribute:: STOPBITS
-
- A list of valid stop bit widths for the device (Read Only).
-
-
- New values can be assigned to the following attributes, the port will be
- reconfigured, even if it's opened at that time:
-
- .. attribute:: port
-
- Port name/number as set by the user.
-
- .. attribute:: baudrate
-
- Current baud rate setting.
-
- .. attribute:: bytesize
-
- Byte size in bits.
-
- .. attribute:: parity
-
- Parity setting.
-
- .. attribute:: stopbits
-
- Stop bit with.
-
- .. attribute:: timeout
-
- Timeout setting (seconds, float).
-
- .. attribute:: xonxoff
-
- If Xon/Xoff flow control is enabled.
-
- .. attribute:: rtscts
-
- If hardware flow control is enabled.
-
- Platform specific methods.
-
- .. warning:: Programs using the following methods are not portable to other platforms!
-
- .. method:: nonblocking()
-
- :platform: Unix
-
- Configure the device for nonblocking operations. This can be useful if
- the port is used with ``select``.
-
- .. method:: fileno()
-
- :platform: Unix
- :return: File descriptor.
-
- Return file descriptor number for the port that is opened by this object.
-
- .. method:: setXON(level=True)
-
- :platform: Windows
- :param level: Set flow control state.
-
- Set software flow control state.
-
-
-.. class:: SerialBase
-
- The following attributes are implemented as properties. They work with open
- and closed ports.
-
- .. attribute:: port
-
- Read or write port. When the port is already open, it will be closed
- and reopened with the new setting.
-
- .. attribute:: baudrate
-
- Read or write current baud rate setting.
-
- .. attribute:: bytesize
-
- Read or write current data byte size setting.
-
- .. attribute:: parity
-
- Read or write current parity setting.
-
- .. attribute:: stopbits
-
- Read or write current stop bit width setting.
-
- .. attribute:: timeout
-
- Read or write current read timeout setting.
-
- .. attribute:: writeTimeout
-
- Read or write current write timeout setting.
-
- .. attribute:: xonxoff
-
- Read or write current software flow control rate setting.
-
- .. attribute:: rtscts
-
- Read or write current hardware flow control setting.
-
- .. attribute:: dsrdtr
-
- Read or write current hardware flow control setting.
-
- .. attribute:: interCharTimeout
-
- Read or write current inter character timeout setting.
-
- The following constants are also provided:
-
- .. attribute:: BAUDRATES
-
- A tuple of standard baud rate values. The actual device may support more
- or less...
-
- .. attribute:: BYTESIZES
-
- A tuple of supported byte size values.
-
- .. attribute:: PARITIES
-
- A tuple of supported parity settings.
-
- .. attribute:: STOPBITS
-
- A tuple of supported stop bit settings.
-
- .. method:: readline(size=None, eol='\\n')
-
- :param size: Max number of bytes to read, ``None`` -> no limit.
- :param eol: The end of line character.
-
- Read a line which is terminated with end-of-line (*eol*) character
- (``\\n`` by default) or until timeout.
-
- .. method:: readlines(sizehint=None, eol='\\n')
-
- :param size: Ignored parameter.
- :param eol: The end of line character.
-
- Read a list of lines, until timeout. *sizehint* is ignored and only
- present for API compatibility with built-in File objects.
-
- .. method:: xreadlines(sizehint=None)
-
- Just calls :meth:`readlines` - here for compatibility.
-
- For compatibility with the :mod:`io` library are the following methods.
-
- .. method:: readable()
-
- :return: True
- .. versionadded:: 2.5
-
- .. method:: writable()
-
- :return: True
- .. versionadded:: 2.5
-
- .. method:: seekable()
-
- :return: False
- .. versionadded:: 2.5
-
- .. method:: readinto(b)
-
- :param b: bytearray or array instace
- :return: Number of byte read
-
- Read up to len(b) bytes into bytearray b and return the number of bytes read.
-
- .. versionadded:: 2.5
-
-
-.. note::
-
- For systems that provide the :mod:`io` library (Python 2.6 and newer), the
- class :class:`Serial` will derrive from :class:`io.RawIOBase`. For all
- others from :class:`FileLike`.
-
-.. class:: FileLike
-
- An abstract file like class. It is used as base class for :class:`Serial`.
-
- This class implements :meth:`readline` and :meth:`readlines` based on read
- and :meth:`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
- :meth:`readline` blocks until it sees a newline (or the specified size is
- reached) and that :meth:`readlines` would never return and therefore
- refuses to work (it raises an exception in this case)!
-
- .. method:: writelines(sequence)
-
- Write a list of strings to the port.
-
-
- The following three methods are overridden in :class:`Serial`.
-
- .. method:: flush()
-
- Flush of file like objects. It's a no-op in this class, may be overridden.
-
- .. method:: read()
-
- Raises NotImplementedError, needs to be overridden by subclass.
-
- .. method:: write(data)
-
- Raises NotImplementedError, needs to be overridden by subclass.
-
- The following functions are implemented for compatibility with other
- file-like objects, however serial ports are not seekable.
-
-
- .. method:: seek(pos, whence=0)
-
- :exception IOError: always, as method is not supported on serial port
-
- .. versionadded:: 2.5
-
- .. method:: tell()
-
- :exception IOError: always, as method is not supported on serial port
-
- .. versionadded:: 2.5
-
- .. method:: truncate(self, n=None)
-
- :exception IOError: always, as method is not supported on serial port
-
- .. versionadded:: 2.5
-
- .. method:: isatty()
-
- :exception IOError: always, as method is not supported on serial port
-
- .. versionadded:: 2.5
-
- To be able to use the file like object as iterator for e.g.
- ``for line in Serial(0): ...`` usage:
-
- .. method:: next()
-
- Return the next line by calling :meth:`readline`.
-
- .. method:: __iter__()
-
- Returns self.
-
-
-
-Exceptions
-==========
-
-.. exception:: SerialException
-
- Base class for serial port exceptions.
-
- .. versionchanged:: 2.5
- Now derrives from :exc:`IOError` instead of :exc:`Exception`
-
-.. exception:: SerialTimeoutException
-
- Exception that is raised on write timeouts.
-
-
-Constants
-=========
-
-Parity
-------
-.. data:: PARITY_NONE
-.. data:: PARITY_EVEN
-.. data:: PARITY_ODD
-.. data:: PARITY_MARK
-.. data:: PARITY_SPACE
-
-Stop bits
----------
-.. data:: STOPBITS_ONE
-.. data:: STOPBITS_ONE_POINT_FIVE
-.. data:: STOPBITS_TWO
-
-Byte size
----------
-.. data:: FIVEBITS
-.. data:: SIXBITS
-.. data:: SEVENBITS
-.. data:: EIGHTBITS
-
-Others
--------
-Default control characters (instnces of :class:`bytes` for Python 3.0+) for
-software flow control:
-
-.. data:: XON
-.. data:: XOFF
-
-Module version:
-
-.. data:: VERSION
-
- A string indicating the pySerial version, such as ``2.5``.
-
-Functions:
-
-.. function:: device(number)
-
- :param number: Port number.
- :return: String containing device name.
- :deprecated: Use device names directly.
-
- Convert a port number to a platform dependent device name. Unfortunately
- this does not work well for all platforms; e.g. some may miss USB-Serial
- converters and enumerate only internal serial ports.
-
- The conversion may be made off-line, that is, there is no guarantee that
- the returned device name really exists on the system.
diff --git a/pyserial/documentation/shortintro.rst b/pyserial/documentation/shortintro.rst
deleted file mode 100644
index 048f94d..0000000
--- a/pyserial/documentation/shortintro.rst
+++ /dev/null
@@ -1,57 +0,0 @@
-====================
- Short introduction
-====================
-
-Opening serial ports
-====================
-
-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 really 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 hundred bytes
- ... # or as much is in the buffer
-
-Configuring ports later
-=======================
-
-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
-
-Readline
-========
-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.
-
-Do also have a look at the example files in the examples directory in the
-source distribution or online.
diff --git a/pyserial/examples/enhancedserial.py b/pyserial/examples/enhancedserial.py
deleted file mode 100644
index 2c81ae1..0000000
--- a/pyserial/examples/enhancedserial.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/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/pyserial/examples/miniterm.py b/pyserial/examples/miniterm.py
deleted file mode 100644
index 48d07a7..0000000
--- a/pyserial/examples/miniterm.py
+++ /dev/null
@@ -1,562 +0,0 @@
-#!/usr/bin/env python
-
-# Very simple serial terminal
-# (C)2002-2009 Chris Liechti <cliechti@gmx.net>
-
-# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
-# done), received characters are displayed as is (or escaped trough pythons
-# repr, useful for debug purposes)
-
-
-import sys, os, serial, threading
-
-EXITCHARCTER = '\x1d' # GS/CTRL+]
-MENUCHARACTER = '\x14' # Menu: CTRL+T
-
-
-def key_description(character):
- """generate a readable description for a key"""
- ascii_code = ord(character)
- if ascii_code < 32:
- return 'Ctrl+%c' % (ord('@') + ascii_code)
- else:
- return repr(character)
-
-# help text, starts with blank line! it's a function so that the current values
-# for the shortcut keys is used and not the value at program start
-def get_help_text():
- return """
---- pySerial - miniterm - help
----
---- %(exit)-8s Exit program
---- %(menu)-8s Menu escape key, followed by:
---- Menu keys:
---- %(itself)-8s Send the menu character itself to remote
---- %(exchar)-8s Send the exit character to remote
---- %(info)-8s Show info
---- %(upload)-8s Upload file (prompt will be shown)
---- Toggles:
---- %(rts)s RTS %(echo)s local echo
---- %(dtr)s DTR %(break)s BREAK
---- %(lfm)s line feed %(repr)s Cycle repr mode
----
---- Port settings (%(menu)s followed by the following):
---- 7 8 set data bits
---- n e o s m change parity (None, Even, Odd, Space, Mark)
---- 1 2 3 set stop bits (1, 2, 1.5)
---- b change baud rate
---- x X disable/enable software flow control
---- r R disable/enable hardware flow control
-""" % {
- 'exit': key_description(EXITCHARCTER),
- 'menu': key_description(MENUCHARACTER),
- 'rts': key_description('\x12'),
- 'repr': key_description('\x01'),
- 'dtr': key_description('\x04'),
- 'lfm': key_description('\x0c'),
- 'break': key_description('\x02'),
- 'echo': key_description('\x05'),
- 'info': key_description('\x09'),
- 'upload': key_description('\x15'),
- 'itself': key_description(MENUCHARACTER),
- 'exchar': key_description(EXITCHARCTER),
-}
-
-# first choose a platform dependant way to read single characters from the console
-global console
-
-if os.name == 'nt':
- import msvcrt
- class Console:
- def __init__(self):
- pass
-
- def setup(self):
- pass # Do nothing for 'nt'
-
- def cleanup(self):
- pass # Do nothing for 'nt'
-
- def getkey(self):
- while 1:
- z = msvcrt.getch()
- if z == '\0' or z == '\xe0': #functions keys
- msvcrt.getch()
- else:
- if z == '\r':
- return '\n'
- return z
-
- console = Console()
-
-elif os.name == 'posix':
- import termios, sys, os
- class Console:
- def __init__(self):
- self.fd = sys.stdin.fileno()
-
- def setup(self):
- self.old = termios.tcgetattr(self.fd)
- new = termios.tcgetattr(self.fd)
- new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
- new[6][termios.VMIN] = 1
- new[6][termios.VTIME] = 0
- termios.tcsetattr(self.fd, termios.TCSANOW, new)
- #s = '' # We'll save the characters typed and add them to the pool.
-
- def getkey(self):
- c = os.read(self.fd, 1)
- return c
-
- def cleanup(self):
- termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
-
- console = Console()
-
- def cleanup_console():
- console.cleanup()
-
- console.setup()
- sys.exitfunc = cleanup_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
-NEWLINE_CONVERISON_MAP = ('\n', '\r', '\r\n')
-LF_MODES = ('LF', 'CR', 'CR/LF')
-
-REPR_MODES = ('raw', 'some control', 'all control', 'hex')
-
-class Miniterm:
- def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
- self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=0.7)
- self.echo = echo
- self.repr_mode = repr_mode
- self.convert_outgoing = convert_outgoing
- self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
- self.dtr_state = True
- self.rts_state = True
- self.break_state = False
-
- def start(self):
- self.alive = True
- # start serial->console thread
- self.receiver_thread = threading.Thread(target=self.reader)
- self.receiver_thread.setDaemon(1)
- self.receiver_thread.start()
- # enter console->serial loop
- self.transmitter_thread = threading.Thread(target=self.writer)
- self.transmitter_thread.setDaemon(1)
- self.transmitter_thread.start()
-
- def stop(self):
- self.alive = False
-
- def join(self, transmit_only=False):
- self.transmitter_thread.join()
- if not transmit_only:
- self.receiver_thread.join()
-
- def dump_port_settings(self):
- sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
- self.serial.portstr,
- self.serial.baudrate,
- self.serial.bytesize,
- self.serial.parity,
- self.serial.stopbits,
- ))
- sys.stderr.write('--- RTS %s\n' % (self.rts_state and 'active' or 'inactive'))
- sys.stderr.write('--- DTR %s\n' % (self.dtr_state and 'active' or 'inactive'))
- sys.stderr.write('--- BREAK %s\n' % (self.break_state and 'active' or 'inactive'))
- sys.stderr.write('--- software flow control %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
- sys.stderr.write('--- hardware flow control %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
- sys.stderr.write('--- data escaping: %s\n' % (REPR_MODES[self.repr_mode],))
- sys.stderr.write('--- linefeed: %s\n' % (LF_MODES[self.convert_outgoing],))
-
- def reader(self):
- """loop and copy serial->console"""
- while self.alive:
- data = self.serial.read(1)
-
- if self.repr_mode == 0:
- # direct output, just have to care about newline setting
- if data == '\r' and self.convert_outgoing == CONVERT_CR:
- sys.stdout.write('\n')
- else:
- sys.stdout.write(data)
- elif self.repr_mode == 1:
- # escape non-printable, let pass newlines
- if self.convert_outgoing == CONVERT_CRLF and data in '\r\n':
- if data == '\n':
- sys.stdout.write('\n')
- elif data == '\r':
- pass
- elif data == '\n' and self.convert_outgoing == CONVERT_LF:
- sys.stdout.write('\n')
- elif data == '\r' and self.convert_outgoing == CONVERT_CR:
- sys.stdout.write('\n')
- else:
- sys.stdout.write(repr(data)[1:-1])
- elif self.repr_mode == 2:
- # escape all non-printable, including newline
- sys.stdout.write(repr(data)[1:-1])
- elif self.repr_mode == 3:
- # escape everything (hexdump)
- for character in data:
- sys.stdout.write("%s " % character.encode('hex'))
- sys.stdout.flush()
-
-
- def writer(self):
- """loop and copy console->serial until EXITCHARCTER character is
- found. when MENUCHARACTER is found, interpret the next key
- locally.
- """
- menu_active = False
- try:
- while self.alive:
- try:
- c = console.getkey()
- except KeyboardInterrupt:
- c = '\x03'
- if menu_active:
- if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
- self.serial.write(c) # send character
- if self.echo:
- sys.stdout.write(c)
- elif c == '\x15': # CTRL+U -> upload file
- sys.stderr.write('\n--- File to upload: ')
- sys.stderr.flush()
- console.cleanup()
- filename = sys.stdin.readline().rstrip('\r\n')
- if filename:
- try:
- file = open(filename, 'r')
- sys.stderr.write('--- Sending file %s ---\n' % filename)
- while True:
- line = file.readline().rstrip('\r\n')
- if not line:
- break
- self.serial.write(line)
- self.serial.write('\r\n')
- # Wait for output buffer to drain.
- self.serial.flush()
- sys.stderr.write('.') # Progress indicator.
- sys.stderr.write('\n--- File %s sent ---\n' % filename)
- except IOError, e:
- sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
- console.setup()
- elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
- sys.stderr.write(get_help_text())
- elif c == '\x12': # CTRL+R -> Toggle RTS
- self.rts_state = not self.rts_state
- self.serial.setRTS(self.rts_state)
- sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
- elif c == '\x04': # CTRL+D -> Toggle DTR
- self.dtr_state = not self.dtr_state
- self.serial.setDTR(self.dtr_state)
- sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
- elif c == '\x02': # CTRL+B -> toggle BREAK condition
- self.break_state = not self.break_state
- self.serial.setBreak(self.break_state)
- sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
- elif c == '\x05': # CTRL+E -> toggle local echo
- self.echo = not self.echo
- sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
- elif c == '\x09': # CTRL+I -> info
- self.dump_port_settings()
- elif c == '\x01': # CTRL+A -> cycle escape mode
- self.repr_mode += 1
- if self.repr_mode > 3:
- self.repr_mode = 0
- sys.stderr.write('--- escape data: %s ---\n' % (
- REPR_MODES[self.repr_mode],
- ))
- elif c == '\x0c': # CTRL+L -> cycle linefeed mode
- self.convert_outgoing += 1
- if self.convert_outgoing > 2:
- self.convert_outgoing = 0
- self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
- sys.stderr.write('--- line feed %s ---\n' % (
- LF_MODES[self.convert_outgoing],
- ))
- #~ elif c in 'pP': # P -> change port XXX reader thread would exit
- elif c in 'bB': # B -> change baudrate
- sys.stderr.write('\n--- Baudrate: ')
- sys.stderr.flush()
- console.cleanup()
- backup = self.serial.baudrate
- try:
- self.serial.baudrate = int(sys.stdin.readline().strip())
- except ValueError, e:
- sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
- self.serial.baudrate = backup
- else:
- self.dump_port_settings()
- console.setup()
- elif c == '8': # 8 -> change to 8 bits
- self.serial.bytesize = serial.EIGHTBITS
- self.dump_port_settings()
- elif c == '7': # 7 -> change to 8 bits
- self.serial.bytesize = serial.SEVENBITS
- self.dump_port_settings()
- elif c in 'eE': # E -> change to even parity
- self.serial.parity = serial.PARITY_EVEN
- self.dump_port_settings()
- elif c in 'oO': # O -> change to odd parity
- self.serial.parity = serial.PARITY_ODD
- self.dump_port_settings()
- elif c in 'mM': # M -> change to mark parity
- self.serial.parity = serial.PARITY_MARK
- self.dump_port_settings()
- elif c in 'sS': # S -> change to space parity
- self.serial.parity = serial.PARITY_SPACE
- self.dump_port_settings()
- elif c in 'nN': # N -> change to no parity
- self.serial.parity = serial.PARITY_NONE
- self.dump_port_settings()
- elif c == '1': # 1 -> change to 1 stop bits
- self.serial.stopbits = serial.STOPBITS_ONE
- self.dump_port_settings()
- elif c == '2': # 2 -> change to 2 stop bits
- self.serial.stopbits = serial.STOPBITS_TWO
- self.dump_port_settings()
- elif c == '3': # 3 -> change to 1.5 stop bits
- self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
- self.dump_port_settings()
- elif c in 'xX': # X -> change software flow control
- self.serial.xonxoff = (c == 'X')
- self.dump_port_settings()
- elif c in 'rR': # R -> change hardware flow control
- self.serial.rtscts = (c == 'R')
- self.dump_port_settings()
- else:
- sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
- menu_active = False
- elif c == MENUCHARACTER: # next char will be for menu
- menu_active = True
- elif c == EXITCHARCTER:
- self.stop()
- break # exit app
- elif c == '\n':
- self.serial.write(self.newline) # send newline character(s)
- if self.echo:
- sys.stdout.write(c) # local echo is a real newline in any case
- sys.stdout.flush()
- else:
- self.serial.write(c) # send character
- if self.echo:
- sys.stdout.write(c)
- sys.stdout.flush()
- except:
- self.alive = False
- raise
-
-def main():
- import optparse
-
- parser = optparse.OptionParser(
- usage = "%prog [options] [port [baudrate]]",
- description = "Miniterm - A simple terminal program for the serial port."
- )
-
- parser.add_option("-p", "--port",
- dest = "port",
- help = "port, a number (default 0) or a device name (deprecated option)",
- default = None
- )
-
- parser.add_option("-b", "--baud",
- dest = "baudrate",
- action = "store",
- type = 'int',
- help = "set baud rate, default %default",
- default = 9600
- )
-
- parser.add_option("--parity",
- dest = "parity",
- action = "store",
- help = "set parity, one of [N, E, O, S, M], default=N",
- default = 'N'
- )
-
- parser.add_option("-e", "--echo",
- dest = "echo",
- action = "store_true",
- help = "enable local echo (default off)",
- default = False
- )
-
- parser.add_option("--rtscts",
- dest = "rtscts",
- action = "store_true",
- help = "enable RTS/CTS flow control (default off)",
- default = False
- )
-
- parser.add_option("--xonxoff",
- dest = "xonxoff",
- action = "store_true",
- help = "enable software flow control (default off)",
- default = False
- )
-
- parser.add_option("--cr",
- dest = "cr",
- action = "store_true",
- help = "do not send CR+LF, send CR only",
- default = False
- )
-
- parser.add_option("--lf",
- dest = "lf",
- action = "store_true",
- help = "do not send CR+LF, send LF only",
- default = False
- )
-
- parser.add_option("-D", "--debug",
- dest = "repr_mode",
- action = "count",
- help = """debug received data (escape non-printable chars)
---debug can be given multiple times:
-0: just print what is received
-1: escape non-printable characters, do newlines as unusual
-2: escape non-printable characters, newlines too
-3: hex dump everything""",
- default = 0
- )
-
- parser.add_option("--rts",
- dest = "rts_state",
- action = "store",
- type = 'int',
- help = "set initial RTS line state (possible values: 0, 1)",
- default = None
- )
-
- parser.add_option("--dtr",
- dest = "dtr_state",
- action = "store",
- type = 'int',
- help = "set initial DTR line state (possible values: 0, 1)",
- default = None
- )
-
- parser.add_option("-q", "--quiet",
- dest = "quiet",
- action = "store_true",
- help = "suppress non error messages",
- default = False
- )
-
- parser.add_option("--exit-char",
- dest = "exit_char",
- action = "store",
- type = 'int',
- help = "ASCII code of special character that is used to exit the application",
- default = 0x1d
- )
-
- parser.add_option("--menu-char",
- dest = "menu_char",
- action = "store",
- type = 'int',
- help = "ASCII code of special character that is used to control miniterm (menu)",
- default = 0x14
- )
-
- (options, args) = parser.parse_args()
-
- options.parity = options.parity.upper()
- if options.parity not in 'NEOSM':
- parser.error("invalid parity")
-
- if options.cr and options.lf:
- parser.error("only one of --cr or --lf can be specified")
-
- if options.dtr_state is not None and options.rts_state is not None and options.dtr_state == options.rts_state:
- parser.error('--exit-char can not be the same as --menu-char')
-
- global EXITCHARCTER, MENUCHARACTER
- EXITCHARCTER = chr(options.exit_char)
- MENUCHARACTER = chr(options.menu_char)
-
- port = options.port
- baudrate = options.baudrate
- if args:
- if options.port is not None:
- parser.error("no arguments are allowed, options only when --port is given")
- port = args.pop(0)
- if args:
- try:
- baudrate = int(args[0])
- except ValueError:
- parser.error("baud rate must be a number, not %r" % args[0])
- args.pop(0)
- if args:
- parser.error("too many arguments")
- else:
- if port is None: port = 0
-
- convert_outgoing = CONVERT_CRLF
- if options.cr:
- convert_outgoing = CONVERT_CR
- elif options.lf:
- convert_outgoing = CONVERT_LF
-
- try:
- miniterm = Miniterm(
- port,
- baudrate,
- options.parity,
- rtscts=options.rtscts,
- xonxoff=options.xonxoff,
- echo=options.echo,
- convert_outgoing=convert_outgoing,
- repr_mode=options.repr_mode,
- )
- except serial.SerialException:
- sys.stderr.write("could not open port %r\n" % port)
- sys.exit(1)
-
- if not options.quiet:
- sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
- miniterm.serial.portstr,
- miniterm.serial.baudrate,
- miniterm.serial.bytesize,
- miniterm.serial.parity,
- miniterm.serial.stopbits,
- ))
- sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
- key_description(EXITCHARCTER),
- key_description(MENUCHARACTER),
- key_description(MENUCHARACTER),
- key_description('\x08'),
- ))
-
- if options.dtr_state is not None:
- if not options.quiet:
- sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
- miniterm.serial.setDTR(options.dtr_state)
- miniterm.dtr_state = options.dtr_state
- if options.rts_state is not None:
- if not options.quiet:
- sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
- miniterm.serial.setRTS(options.rts_state)
- miniterm.rts_state = options.rts_state
-
- miniterm.start()
- miniterm.join(True)
- if not options.quiet:
- sys.stderr.write("\n--- exit ---\n")
- miniterm.join()
-
-
-if __name__ == '__main__':
- main()
diff --git a/pyserial/examples/port_publisher.py b/pyserial/examples/port_publisher.py
deleted file mode 100644
index e695a98..0000000
--- a/pyserial/examples/port_publisher.py
+++ /dev/null
@@ -1,451 +0,0 @@
-#! /usr/bin/env python
-"""\
-Multi-port serial<->TCP/IP forwarder.
-- check existence of serial port periodically
-- start/stop forwarders
-- each forwarder creates a server socket and opens the serial port
-- serial ports are opened only once. network connect/disconnect
- does not influence serial port
-- only one client per connection
-"""
-import sys, os, time
-import socket
-import select
-import serial
-import traceback
-import avahi
-import dbus
-
-class ZeroconfService:
- """\
- A simple class to publish a network service with zeroconf using avahi.
- """
-
- def __init__(self, name, port, stype="_http._tcp",
- domain="", host="", text=""):
- self.name = name
- self.stype = stype
- self.domain = domain
- self.host = host
- self.port = port
- self.text = text
- self.group = None
-
- def publish(self):
- bus = dbus.SystemBus()
- server = dbus.Interface(
- bus.get_object(
- avahi.DBUS_NAME,
- avahi.DBUS_PATH_SERVER
- ),
- avahi.DBUS_INTERFACE_SERVER
- )
-
- g = dbus.Interface(
- bus.get_object(
- avahi.DBUS_NAME,
- server.EntryGroupNew()
- ),
- avahi.DBUS_INTERFACE_ENTRY_GROUP
- )
-
- g.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0),
- self.name, self.stype, self.domain, self.host,
- dbus.UInt16(self.port), self.text)
-
- g.Commit()
- self.group = g
-
- def unpublish(self):
- if self.group is not None:
- self.group.Reset()
- self.group = None
-
- def __str__(self):
- return "%r @ %s:%s (%s)" % (self.name, self.host, self.port, self.stype)
-
-
-
-class Forwarder(ZeroconfService):
- """\
- Single port serial<->TCP/IP forarder that depends on an external select
- loop. Zeroconf publish/unpublish on open/close.
- """
-
- def __init__(self, device, name, network_port, on_close=None):
- ZeroconfService.__init__(self, name, network_port, stype='_serial_port._tcp')
- self.alive = False
- self.network_port = network_port
- self.on_close = on_close
- self.device = device
- self.serial = serial.Serial()
- self.serial.port = device
- self.serial.baudrate = 115200
- self.serial.timeout = 0
- self.socket = None
- self.server_socket = None
-
- def __del__(self):
- try:
- if self.alive: self.close()
- except:
- pass # XXX errors on shutdown
-
- def open(self):
- """open serial port, start network server and publish service"""
- self.buffer_net2ser = ''
- self.buffer_ser2net = ''
-
- # open serial port
- try:
- self.serial.open()
- self.serial.setRTS(False)
- except Exception, msg:
- self.handle_serial_error(msg)
-
- # start the socket server
- self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.server_socket.setsockopt(
- socket.SOL_SOCKET,
- socket.SO_REUSEADDR,
- self.server_socket.getsockopt(
- socket.SOL_SOCKET,
- socket.SO_REUSEADDR
- ) | 1
- )
- self.server_socket.setblocking(0)
- try:
- self.server_socket.bind( ('', self.network_port) )
- self.server_socket.listen(1)
- except socket.error, msg:
- self.handle_server_error()
- #~ raise
- if not options.quiet:
- print "%s: Waiting for connection on %s..." % (self.device, self.network_port)
-
- # zeroconfig
- self.publish()
-
- # now we are ready
- self.alive = True
-
- def close(self):
- """Close all resources and unpublish service"""
- if not options.quiet:
- print "%s: closing..." % (self.device, )
- self.alive = False
- self.unpublish()
- if self.server_socket: self.server_socket.close()
- if self.socket:
- self.handle_disconnect()
- self.serial.close()
- if self.on_close is not None:
- # ensure it is only called once
- callback = self.on_close
- self.on_close = None
- callback(self)
-
- def update_select_maps(self, read_map, write_map, error_map):
- """Update dictionaries for select call. insert fd->callback mapping"""
- if self.alive:
- # always handle serial port reads
- read_map[self.serial] = self.handle_serial_read
- error_map[self.serial] = self.handle_serial_error
- # handle serial port writes if buffer is not empty
- if self.buffer_net2ser:
- write_map[self.serial] = self.handle_serial_write
- # handle network
- if self.socket is not None:
- # handle socket if connected
- # only read from network if the internal buffer is not
- # already filled. the TCP flow control will hold back data
- if len(self.buffer_net2ser) < 2048:
- read_map[self.socket] = self.handle_socket_read
- # only check for write readiness when there is data
- if self.buffer_ser2net:
- write_map[self.socket] = self.handle_socket_write
- error_map[self.socket] = self.handle_socket_error
- else:
- # no connection, ensure clear buffer
- self.buffer_ser2net = ''
- # check the server socket
- read_map[self.server_socket] = self.handle_connect
- error_map[self.server_socket] = self.handle_server_error
-
-
- def handle_serial_read(self):
- """Reading from serial port"""
- try:
- data = os.read(self.serial.fileno(), 1024)
- if data:
- # store data in buffer if there is a client connected
- if self.socket is not None:
- self.buffer_ser2net += data
- else:
- self.handle_serial_error()
- except Exception, msg:
- self.handle_serial_error(msg)
-
- def handle_serial_write(self):
- """Writing to serial port"""
- try:
- # write a chunk
- n = os.write(self.serial.fileno(), self.buffer_net2ser)
- # and see how large that chunk was, remove that from buffer
- self.buffer_net2ser = self.buffer_net2ser[n:]
- except Exception, msg:
- self.handle_serial_error(msg)
-
- def handle_serial_error(self, error=None):
- """Serial port error"""
- # terminate connection
- self.close()
-
- def handle_socket_read(self):
- """Read from socket"""
- try:
- # read a chunk from the serial port
- data = self.socket.recv(1024)
- if data:
- # add data to buffer
- self.buffer_net2ser += data
- else:
- # empty read indicates disconnection
- self.handle_disconnect()
- except socket.error:
- self.handle_socket_error()
-
- def handle_socket_write(self):
- """Write to socket"""
- try:
- # write a chunk
- count = self.socket.send(self.buffer_ser2net)
- # and remove the sent data from the buffer
- self.buffer_ser2net = self.buffer_ser2net[count:]
- except socket.error:
- self.handle_socket_error()
-
- def handle_socket_error(self):
- """Socket connection fails"""
- self.handle_disconnect()
-
- def handle_connect(self):
- """Server socket gets a connection"""
- # accept a connection in any case, close connection
- # below if already busy
- connection, addr = self.server_socket.accept()
- if self.socket is None:
- self.socket = connection
- self.socket.setblocking(0)
- if not options.quiet:
- print '%s: Connected by %s:%s' % (self.device, addr[0], addr[1])
- else:
- # reject connection if there is already one
- connection.close()
- if not options.quiet:
- print '%s: Rejecting connect from %s:%s' % (self.device, addr[0], addr[1])
-
- def handle_server_error(self):
- """Socker server fails"""
- self.close()
-
- def handle_disconnect(self):
- """Socket gets disconnected"""
- # clear send buffer
- self.buffer_ser2net = ''
- # close network connection
- if self.socket is not None:
- self.socket.close()
- self.socket = None
- if not options.quiet:
- print '%s: Disconnected' % self.device
-
-
-def test():
- service = ZeroconfService(name="TestService", port=3000)
- service.publish()
- raw_input("Press any key to unpublish the service ")
- service.unpublish()
-
-
-if __name__ == '__main__':
- import optparse
-
- parser = optparse.OptionParser(usage="""\
-%prog [options]
-
-Announce the existence of devices using zeroconf and provide
-a TCP/IP <-> serial port gateway.
-
-Note that the TCP/IP server is not protected. Everyone can connect
-to it!
-
-If running as daemon, write to syslog. Otherwise write to stdout.
-""")
-
- parser.add_option("-q", "--quiet", dest="quiet", action="store_true",
- help="suppress non error messages", default=False)
-
- parser.add_option("-o", "--logfile", dest="log_file",
- help="write messages file instead of stdout", default=None, metavar="FILE")
-
- parser.add_option("-d", "--daemon", dest="daemonize", action="store_true",
- help="start as daemon", default=False)
-
- parser.add_option("", "--pidfile", dest="pid_file",
- help="specify a name for the PID file", default=None, metavar="FILE")
-
- (options, args) = parser.parse_args()
-
- # redirect output if specified
- if options.log_file is not None:
- class WriteFlushed:
- def __init__(self, fileobj):
- self.fileobj = fileobj
- def write(self, s):
- self.fileobj.write(s)
- self.fileobj.flush()
- def close(self):
- self.fileobj.close()
- sys.stdout = sys.stderr = WriteFlushed(open(options.log_file, 'a'))
- # atexit.register(lambda: sys.stdout.close())
-
- if options.daemonize:
- # if running as daemon is requested, do the fork magic
- # options.quiet = True
- import pwd
- # do the UNIX double-fork magic, see Stevens' "Advanced
- # Programming in the UNIX Environment" for details (ISBN 0201563177)
- try:
- pid = os.fork()
- if pid > 0:
- # exit first parent
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
- sys.exit(1)
-
- # decouple from parent environment
- os.chdir("/") # don't prevent unmounting....
- os.setsid()
- os.umask(0)
-
- # do second fork
- try:
- pid = os.fork()
- if pid > 0:
- # exit from second parent, print eventual PID before
- # print "Daemon PID %d" % pid
- if options.pid_file is not None:
- open(options.pid_file,'w').write("%d"%pid)
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
- sys.exit(1)
-
- if options.log_file is None:
- import syslog
- syslog.openlog("serial port publisher")
- # redirect output to syslog
- class WriteToSysLog:
- def __init__(self):
- self.buffer = ''
- def write(self, s):
- self.buffer += s
- if '\n' in self.buffer:
- output, self.buffer = self.buffer.split('\n', 1)
- syslog.syslog(output)
- def flush(self):
- syslog.syslog(self.buffer)
- self.buffer = ''
- def close(self):
- self.flush()
- sys.stdout = sys.stderr = WriteToSysLog()
-
- # ensure the that the daemon runs a normal user, if run as root
- #if os.getuid() == 0:
- # name, passwd, uid, gid, desc, home, shell = pwd.getpwnam('someuser')
- # os.setgid(gid) # set group first
- # os.setuid(uid) # set user
-
- # keep the published stuff in a dictionary
- published = {}
- # prepare list of device names (hard coded)
- device_list = ['/dev/ttyUSB%d' % p for p in range(8)]
- # get a nice hostname
- hostname = socket.gethostname()
-
- def unpublish(forwarder):
- """when forwarders die, we need to unregister them"""
- try:
- del published[forwarder.device]
- except KeyError:
- pass
- else:
- if not options.quiet: print "unpublish: %s" % (forwarder)
-
- alive = True
- next_check = 0
- # main loop
- while alive:
- try:
- # if it is time, check for serial port devices
- now = time.time()
- if now > next_check:
- next_check = now + 5
- # check each device
- for device in device_list:
- # if it appeared
- if os.path.exists(device):
- if device not in published:
- num = int(device[-1])
- published[device] = Forwarder(
- device,
- "%s on %s" % (device, hostname),
- 7000+num,
- on_close=unpublish
- )
- if not options.quiet: print "publish: %s" % (published[device])
- published[device].open()
- else:
- # or when it disappeared
- if device in published:
- if not options.quiet: print "unpublish: %s" % (published[device])
- published[device].close()
- try:
- del published[device]
- except KeyError:
- pass
-
- # select_start = time.time()
- read_map = {}
- write_map = {}
- error_map = {}
- for publisher in published.values():
- publisher.update_select_maps(read_map, write_map, error_map)
- try:
- readers, writers, errors = select.select(
- read_map.keys(),
- write_map.keys(),
- error_map.keys(),
- 5
- )
- except select.error, err:
- if err[0] != EINTR:
- raise
- # select_end = time.time()
- # print "select used %.3f s" % (select_end - select_start)
- for reader in readers:
- read_map[reader]()
- for writer in writers:
- write_map[writer]()
- for error in errors:
- error_map[error]()
- # print "operation used %.3f s" % (time.time() - select_end)
- except KeyboardInterrupt:
- alive = False
- except SystemExit:
- raise
- except:
- raise
- traceback.print_exc()
diff --git a/pyserial/examples/port_publisher.sh b/pyserial/examples/port_publisher.sh
deleted file mode 100644
index 50d4f17..0000000
--- a/pyserial/examples/port_publisher.sh
+++ /dev/null
@@ -1,44 +0,0 @@
-#! /bin/sh
-# daemon starter script
-# based on skeleton from Debian GNU/Linux
-# cliechti at gmx.net
-
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-DAEMON=/usr/local/bin/port_publisher.py
-NAME=port_publisher
-DESC="serial port avahi device publisher"
-
-test -f $DAEMON || exit 0
-
-set -e
-
-case "$1" in
- start)
- echo -n "Starting $DESC: "
- $DAEMON --daemon --pidfile /var/run/$NAME.pid
- echo "$NAME."
- ;;
- stop)
- echo -n "Stopping $DESC: "
- start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid
- # \ --exec $DAEMON
- echo "$NAME."
- ;;
- restart|force-reload)
- echo -n "Restarting $DESC: "
- start-stop-daemon --stop --quiet --pidfile \
- /var/run/$NAME.pid
- # --exec $DAEMON
- sleep 1
- $DAEMON --daemon --pidfile /var/run/$NAME.pid
- echo "$NAME."
- ;;
- *)
- N=/etc/init.d/$NAME
- echo "Usage: $N {start|stop|restart|force-reload}" >&2
- exit 1
- ;;
-esac
-
-exit 0
-
diff --git a/pyserial/examples/scan.py b/pyserial/examples/scan.py
deleted file mode 100644
index 82c5458..0000000
--- a/pyserial/examples/scan.py
+++ /dev/null
@@ -1,30 +0,0 @@
-#! /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/pyserial/examples/scanlinux.py b/pyserial/examples/scanlinux.py
deleted file mode 100644
index 7cf6383..0000000
--- a/pyserial/examples/scanlinux.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#! /usr/bin/env python
-"""\
-Scan for serial ports. Linux specific variant that also includes USB/Serial
-adapters.
-
-Part of pySerial (http://pyserial.sf.net)
-(C) 2009 <cliechti@gmx.net>
-"""
-
-import serial
-import glob
-
-def scan():
- """scan for available ports. return a list of device names."""
- return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*')
-
-if __name__=='__main__':
- print "Found ports:"
- for name in scan():
- print name
diff --git a/pyserial/examples/scanwin32.py b/pyserial/examples/scanwin32.py
deleted file mode 100644
index 6d58d89..0000000
--- a/pyserial/examples/scanwin32.py
+++ /dev/null
@@ -1,200 +0,0 @@
-import ctypes
-import re
-
-def ValidHandle(value):
- if value == 0:
- raise ctypes.WinError()
- return value
-
-NULL = 0
-HDEVINFO = ctypes.c_int
-BOOL = ctypes.c_int
-CHAR = ctypes.c_char
-PCTSTR = ctypes.c_char_p
-HWND = ctypes.c_uint
-DWORD = ctypes.c_ulong
-PDWORD = ctypes.POINTER(DWORD)
-ULONG = ctypes.c_ulong
-ULONG_PTR = ctypes.POINTER(ULONG)
-#~ PBYTE = ctypes.c_char_p
-PBYTE = ctypes.c_void_p
-
-class GUID(ctypes.Structure):
- _fields_ = [
- ('Data1', ctypes.c_ulong),
- ('Data2', ctypes.c_ushort),
- ('Data3', ctypes.c_ushort),
- ('Data4', ctypes.c_ubyte*8),
- ]
- def __str__(self):
- return "{%08x-%04x-%04x-%s-%s}" % (
- self.Data1,
- self.Data2,
- self.Data3,
- ''.join(["%02x" % d for d in self.Data4[:2]]),
- ''.join(["%02x" % d for d in self.Data4[2:]]),
- )
-
-class SP_DEVINFO_DATA(ctypes.Structure):
- _fields_ = [
- ('cbSize', DWORD),
- ('ClassGuid', GUID),
- ('DevInst', DWORD),
- ('Reserved', ULONG_PTR),
- ]
- def __str__(self):
- return "ClassGuid:%s DevInst:%s" % (self.ClassGuid, self.DevInst)
-PSP_DEVINFO_DATA = ctypes.POINTER(SP_DEVINFO_DATA)
-
-class SP_DEVICE_INTERFACE_DATA(ctypes.Structure):
- _fields_ = [
- ('cbSize', DWORD),
- ('InterfaceClassGuid', GUID),
- ('Flags', DWORD),
- ('Reserved', ULONG_PTR),
- ]
- def __str__(self):
- return "InterfaceClassGuid:%s Flags:%s" % (self.InterfaceClassGuid, self.Flags)
-
-PSP_DEVICE_INTERFACE_DATA = ctypes.POINTER(SP_DEVICE_INTERFACE_DATA)
-
-PSP_DEVICE_INTERFACE_DETAIL_DATA = ctypes.c_void_p
-
-class dummy(ctypes.Structure):
- _fields_=[("d1",ctypes.DWORD), ("d2",ctypes.CHAR)]
-SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_A = ctypes.sizeof(dummy)
-
-SetupDiDestroyDeviceInfoList = ctypes.windll.setupapi.SetupDiDestroyDeviceInfoList
-SetupDiDestroyDeviceInfoList.argtypes = [HDEVINFO]
-SetupDiDestroyDeviceInfoList.restype = BOOL
-
-SetupDiGetClassDevs = ctypes.windll.setupapi.SetupDiGetClassDevsA
-SetupDiGetClassDevs.argtypes = [ctypes.POINTER(GUID), PCTSTR, HWND, DWORD]
-SetupDiGetClassDevs.restype = ValidHandle # HDEVINFO
-
-SetupDiEnumDeviceInterfaces = ctypes.windll.setupapi.SetupDiEnumDeviceInterfaces
-SetupDiEnumDeviceInterfaces.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, ctypes.POINTER(GUID), DWORD, PSP_DEVICE_INTERFACE_DATA]
-SetupDiEnumDeviceInterfaces.restype = BOOL
-
-SetupDiGetDeviceInterfaceDetail = ctypes.windll.setupapi.SetupDiGetDeviceInterfaceDetailA
-SetupDiGetDeviceInterfaceDetail.argtypes = [HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA]
-SetupDiGetDeviceInterfaceDetail.restype = BOOL
-
-SetupDiGetDeviceRegistryProperty = ctypes.windll.setupapi.SetupDiGetDeviceRegistryPropertyA
-SetupDiGetDeviceRegistryProperty.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, DWORD, PDWORD, PBYTE, DWORD, PDWORD]
-SetupDiGetDeviceRegistryProperty.restype = BOOL
-
-
-GUID_CLASS_COMPORT = GUID(0x86e0d1e0L, 0x8089, 0x11d0,
- (ctypes.c_ubyte*8)(0x9c, 0xe4, 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73))
-
-DIGCF_PRESENT = 2
-DIGCF_DEVICEINTERFACE = 16
-INVALID_HANDLE_VALUE = 0
-ERROR_INSUFFICIENT_BUFFER = 122
-SPDRP_HARDWAREID = 1
-SPDRP_FRIENDLYNAME = 12
-ERROR_NO_MORE_ITEMS = 259
-
-def comports(available_only=True):
- """This generator scans the device registry for com ports and yields port, desc, hwid.
- If available_only is true only return currently existing ports."""
- flags = DIGCF_DEVICEINTERFACE
- if available_only:
- flags |= DIGCF_PRESENT
- g_hdi = SetupDiGetClassDevs(ctypes.byref(GUID_CLASS_COMPORT), None, NULL, flags);
- #~ for i in range(256):
- for dwIndex in range(256):
- did = SP_DEVICE_INTERFACE_DATA()
- did.cbSize = ctypes.sizeof(did)
-
- if not SetupDiEnumDeviceInterfaces(
- g_hdi,
- None,
- ctypes.byref(GUID_CLASS_COMPORT),
- dwIndex,
- ctypes.byref(did)
- ):
- if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS:
- raise ctypes.WinError()
- break
-
- dwNeeded = DWORD()
- # get the size
- if not SetupDiGetDeviceInterfaceDetail(
- g_hdi,
- ctypes.byref(did),
- None, 0, ctypes.byref(dwNeeded),
- None
- ):
- # Ignore ERROR_INSUFFICIENT_BUFFER
- if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
- raise ctypes.WinError()
- # allocate buffer
- class SP_DEVICE_INTERFACE_DETAIL_DATA_A(ctypes.Structure):
- _fields_ = [
- ('cbSize', DWORD),
- ('DevicePath', CHAR*(dwNeeded.value - ctypes.sizeof(DWORD))),
- ]
- def __str__(self):
- return "DevicePath:%s" % (self.DevicePath,)
- idd = SP_DEVICE_INTERFACE_DETAIL_DATA_A()
- idd.cbSize = SIZEOF_SP_DEVICE_INTERFACE_DETAIL_DATA_A
- devinfo = SP_DEVINFO_DATA()
- devinfo.cbSize = ctypes.sizeof(devinfo)
- if not SetupDiGetDeviceInterfaceDetail(
- g_hdi,
- ctypes.byref(did),
- ctypes.byref(idd), dwNeeded, None,
- ctypes.byref(devinfo)
- ):
- raise ctypes.WinError()
-
- # hardware ID
- szHardwareID = ctypes.create_string_buffer('\0' * 250)
- if not SetupDiGetDeviceRegistryProperty(
- g_hdi,
- ctypes.byref(devinfo),
- SPDRP_HARDWAREID,
- None,
- ctypes.byref(szHardwareID), ctypes.sizeof(szHardwareID) - 1,
- None
- ):
- # Ignore ERROR_INSUFFICIENT_BUFFER
- if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
- raise ctypes.WinError()
-
- # friendly name
- szFriendlyName = ctypes.create_string_buffer('\0' * 250)
- if not SetupDiGetDeviceRegistryProperty(
- g_hdi,
- ctypes.byref(devinfo),
- SPDRP_FRIENDLYNAME,
- None,
- ctypes.byref(szFriendlyName), ctypes.sizeof(szFriendlyName) - 1,
- None
- ):
- # Ignore ERROR_INSUFFICIENT_BUFFER
- if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
- raise ctypes.WinError()
- try:
- port_name = re.search(r"\((.*)\)", szFriendlyName.value).group(1)
- except AttributeError,msg:
- port_name = "???"
- yield port_name, szFriendlyName.value, szHardwareID.value
-
- SetupDiDestroyDeviceInfoList(g_hdi)
-
-
-if __name__ == '__main__':
- import serial
- for port, desc, hwid in comports():
- try:
- print "%s: %s (%s)" % (port, desc, hwid)
- print " "*10, serial.Serial(port) #test open
- except serial.serialutil.SerialException:
- print "can't be openend."
- # list of all ports the system knows
- print "-"*60
- for port, desc, hwid in comports(False):
- print "%-10s: %s (%s)" % (port, desc, hwid)
diff --git a/pyserial/examples/setup-miniterm-py2exe.py b/pyserial/examples/setup-miniterm-py2exe.py
deleted file mode 100644
index e935cf0..0000000
--- a/pyserial/examples/setup-miniterm-py2exe.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# setup script for py2exe to create the miniterm.exe
-# $Id: setup-miniterm-py2exe.py,v 1.1 2005-09-21 19:51:19 cliechti Exp $
-
-from distutils.core import setup
-import glob, sys, py2exe, os
-
-sys.path.append('..')
-
-sys.argv.extend("py2exe --bundle 1".split())
-
-setup(
- name='miniterm',
- #~ version='0.5',
- zipfile=None,
- options = {"py2exe":
- {
- 'dist_dir': 'bin',
- 'excludes': ['javax.comm'],
- 'compressed': 1,
- }
- },
- console = [
- #~ "miniterm_exe_wrapper.py",
- "miniterm.py",
- ],
-)
diff --git a/pyserial/examples/setup_demo.py b/pyserial/examples/setup_demo.py
deleted file mode 100644
index 854c0b9..0000000
--- a/pyserial/examples/setup_demo.py
+++ /dev/null
@@ -1,35 +0,0 @@
-# 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/pyserial/examples/tcp_serial_redirect.py b/pyserial/examples/tcp_serial_redirect.py
deleted file mode 100644
index e62d8a5..0000000
--- a/pyserial/examples/tcp_serial_redirect.py
+++ /dev/null
@@ -1,305 +0,0 @@
-#!/usr/bin/env python
-
-# (C) 2002-2009 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
-
-
-import sys, os, serial, threading, socket, codecs
-
-try:
- True
-except NameError:
- True = 1
- False = 0
-
-class Redirector:
- def __init__(self, serial, socket, ser_newline=None, net_newline=None, spy=False):
- self.serial = serial
- self.socket = socket
- self.ser_newline = ser_newline
- self.net_newline = net_newline
- self.spy = spy
-
- 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:
- # the spy shows what's on the serial port, so log it before converting newlines
- if self.spy:
- sys.stdout.write(codecs.escape_encode(data)[0])
- sys.stdout.flush()
- if self.ser_newline and self.net_newline:
- # do the newline conversion
- # XXX fails for CR+LF in input when it is cut in half at the begin or end of the string
- data = net_newline.join(data.split(ser_newline))
- self.socket.sendall(data) # send it over TCP
- except socket.error, msg:
- sys.stderr.write('ERROR: %s\n' % 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
- if self.ser_newline and self.net_newline:
- # do the newline conversion
- # XXX fails for CR+LF in input when it is cut in half at the begin or end of the string
- data = ser_newline.join(data.split(net_newline))
- self.serial.write(data) # get a bunch of bytes and send them
- # the spy shows what's on the serial port, so log it after converting newlines
- if self.spy:
- sys.stdout.write(codecs.escape_encode(data)[0])
- sys.stdout.flush()
- except socket.error, msg:
- sys.stderr.write('ERROR: %s\n' % 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__':
- import optparse
-
- parser = optparse.OptionParser(
- usage = "%prog [options] [port [baudrate]]",
- description = "Simple Serial to Network (TCP/IP) redirector.",
- epilog = """\
-NOTE: no security measures are implemented. Anyone can remotely connect
-to this service over the network.
-
-Only one connection at once is supported. When the connection is terminated
-it waits for the next connect.
-""")
-
- parser.add_option("-q", "--quiet",
- dest = "quiet",
- action = "store_true",
- help = "suppress non error messages",
- default = False
- )
-
- parser.add_option("--spy",
- dest = "spy",
- action = "store_true",
- help = "peek at the communication and print all data to the console",
- default = False
- )
-
- group = optparse.OptionGroup(parser,
- "Serial Port",
- "Serial port settings"
- )
- parser.add_option_group(group)
-
- group.add_option("-p", "--port",
- dest = "port",
- help = "port, a number (default 0) or a device name",
- default = None
- )
-
- group.add_option("-b", "--baud",
- dest = "baudrate",
- action = "store",
- type = 'int',
- help = "set baud rate, default: %default",
- default = 9600
- )
-
- group.add_option("", "--parity",
- dest = "parity",
- action = "store",
- help = "set parity, one of [N, E, O], default=%default",
- default = 'N'
- )
-
- group.add_option("--rtscts",
- dest = "rtscts",
- action = "store_true",
- help = "enable RTS/CTS flow control (default off)",
- default = False
- )
-
- group.add_option("--xonxoff",
- dest = "xonxoff",
- action = "store_true",
- help = "enable software flow control (default off)",
- default = False
- )
-
- group.add_option("--rts",
- dest = "rts_state",
- action = "store",
- type = 'int',
- help = "set initial RTS line state (possible values: 0, 1)",
- default = None
- )
-
- group.add_option("--dtr",
- dest = "dtr_state",
- action = "store",
- type = 'int',
- help = "set initial DTR line state (possible values: 0, 1)",
- default = None
- )
-
- group = optparse.OptionGroup(parser,
- "Network settings",
- "Network configuration."
- )
- parser.add_option_group(group)
-
- group.add_option("-P", "--localport",
- dest = "local_port",
- action = "store",
- type = 'int',
- help = "local TCP port",
- default = 7777
- )
-
- group = optparse.OptionGroup(parser,
- "Newline Settings",
- "Convert newlines between network and serial port. Conversion is normally disabled and can be enabled by --convert."
- )
- parser.add_option_group(group)
-
- group.add_option("-c", "--convert",
- dest = "convert",
- action = "store_true",
- help = "enable newline conversion (default off)",
- default = False
- )
-
- group.add_option("--net-nl",
- dest = "net_newline",
- action = "store",
- help = "type of newlines that are expected on the network (default: %default)",
- default = "LF"
- )
-
- group.add_option("--ser-nl",
- dest = "ser_newline",
- action = "store",
- help = "type of newlines that are expected on the serial port (default: %default)",
- default = "CR+LF"
- )
-
- (options, args) = parser.parse_args()
-
- # get port and baud rate from command line arguments or the option switches
- port = options.port
- baudrate = options.baudrate
- if args:
- if options.port is not None:
- parser.error("no arguments are allowed, options only when --port is given")
- port = args.pop(0)
- if args:
- try:
- baudrate = int(args[0])
- except ValueError:
- parser.error("baud rate must be a number, not %r" % args[0])
- args.pop(0)
- if args:
- parser.error("too many arguments")
- else:
- if port is None: port = 0
-
- # check newline modes for network connection
- mode = options.net_newline.upper()
- if mode == 'CR':
- net_newline = '\r'
- elif mode == 'LF':
- net_newline = '\n'
- elif mode == 'CR+LF' or mode == 'CRLF':
- net_newline = '\r\n'
- else:
- parser.error("Invalid value for --net-nl. Valid are 'CR', 'LF' and 'CR+LF'/'CRLF'.")
-
- # check newline modes for serial connection
- mode = options.ser_newline.upper()
- if mode == 'CR':
- ser_newline = '\r'
- elif mode == 'LF':
- ser_newline = '\n'
- elif mode == 'CR+LF' or mode == 'CRLF':
- ser_newline = '\r\n'
- else:
- parser.error("Invalid value for --ser-nl. Valid are 'CR', 'LF' and 'CR+LF'/'CRLF'.")
-
- # connect to serial port
- ser = serial.Serial()
- ser.port = port
- ser.baudrate = baudrate
- ser.parity = options.parity
- ser.rtscts = options.rtscts
- ser.xonxoff = options.xonxoff
- ser.timeout = 1 # required so that the reader thread can exit
-
- if not options.quiet:
- sys.stderr.write("--- TCP/IP to Serial redirector --- type Ctrl-C / BREAK to quit\n")
- sys.stderr.write("--- %s %s,%s,%s,%s ---\n" % (ser.portstr, ser.baudrate, 8, ser.parity, 1))
-
- try:
- ser.open()
- except serial.SerialException, e:
- sys.stderr.write("Could not open serial port %s: %s\n" % (ser.portstr, e))
- sys.exit(1)
-
- if options.rts_state is not None:
- ser.setRTS(options.rts_state)
-
- if options.dtr_state is not None:
- ser.setDTR(options.dtr_state)
-
- srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- srv.bind( ('', options.local_port) )
- srv.listen(1)
- while 1:
- try:
- sys.stderr.write("Waiting for connection on %s...\n" % options.local_port)
- connection, addr = srv.accept()
- sys.stderr.write('Connected by %s\n' % (addr,))
- # enter console->serial loop
- r = Redirector(
- ser,
- connection,
- options.convert and ser_newline or None,
- options.convert and net_newline or None,
- options.spy,
- )
- r.shortcut()
- if options.spy: sys.stdout.write('\n')
- sys.stderr.write('Disconnected\n')
- connection.close()
- except socket.error, msg:
- sys.stderr.write('ERROR: %s\n' % msg)
-
- sys.stderr.write('\n--- exit ---\n')
-
diff --git a/pyserial/examples/test.py b/pyserial/examples/test.py
deleted file mode 100644
index 666275f..0000000
--- a/pyserial/examples/test.py
+++ /dev/null
@@ -1,216 +0,0 @@
-#! /usr/bin/env python
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see __init__.py
-#
-# (C) 2001-2008 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)2001-2008 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 sys
-import serial
-
-# on which port should the tests be performed:
-PORT=0
-
-if sys.version_info >= (3, 0):
- def data(string):
- return bytes(string, 'latin1')
- bytes_0to255 = [bytes([x]) for x in range(256)]
-else:
- def data(string): return string
- bytes_0to255 = [chr(x) for x in range(256)]
-
-
-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.failUnlessEqual(self.s.read(1), data(''), "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 bytes_0to255:
- self.s.write(c)
- # there might be a small delay until the character is ready (especially on win32)
- time.sleep(0.02)
- self.failUnlessEqual(self.s.inWaiting(), 1, "expected exactly one character for inWainting()")
- self.failUnlessEqual(self.s.read(1), c, "expected a '%s' which was written before" % c)
- self.failUnlessEqual(self.s.read(1), data(''), "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(data("HELLO"))
- time.sleep(0.1) # there might be a small delay until the character is ready (especially on win32)
- # read more characters as are available to run in the timeout
- self.failUnlessEqual(self.s.read(10), data('HELLO'), "expected the 'HELLO' which was written before")
- self.failUnlessEqual(self.s.read(1), data(''), "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(data("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 == data('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.failUnlessEqual(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 bytes_0to255:
- self.s.write(c)
- # there might be a small delay until the character is ready (especially on win32)
- time.sleep(0.02)
- self.failUnlessEqual(self.s.inWaiting(), 1, "expected exactly one character for inWainting()")
- self.failUnlessEqual(self.s.read(1), c, "expected an '%s' which was written before" % c)
- self.failUnlessEqual(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)
- time.sleep(0.1)
- self.failUnless(not self.s.getCTS(), "CTS -> 0")
- self.s.setRTS(1)
- time.sleep(0.1)
- self.failUnless(self.s.getCTS(), "CTS -> 1")
-
- def test2_DTR(self):
- """Test DTR/DSR"""
- self.s.setDTR(0)
- time.sleep(0.1)
- self.failUnless(not self.s.getDSR(), "DSR -> 0")
- self.s.setDTR(1)
- time.sleep(0.1)
- self.failUnless(self.s.getDSR(), "DSR -> 1")
-
- def test3_RI(self):
- """Test RI"""
- self.failUnless(not self.s.getRI(), "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 loop-back 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.5) # some systems need a little delay so that they can react on XOFF
- t1 = time.time()
- self.failUnlessRaises(serial.SerialTimeoutException, self.s.write, data("timeout please"*100))
- t2 = time.time()
- self.failUnless( 0.9 <= (t2-t1) < 2.1, "Timeout not in the given interval (%s)" % (t2-t1))
-
-
-if __name__ == '__main__':
- import sys
- sys.stdout.write(__doc__)
- if len(sys.argv) > 1:
- PORT = sys.argv[1]
- sys.stdout.write("Testing port: %r\n" % PORT)
- sys.argv[1:] = ['-v']
- # When this module is executed from the command-line, it runs all its tests
- unittest.main()
diff --git a/pyserial/examples/test_advanced.py b/pyserial/examples/test_advanced.py
deleted file mode 100644
index a19361c..0000000
--- a/pyserial/examples/test_advanced.py
+++ /dev/null
@@ -1,173 +0,0 @@
-#!/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 really 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 a closed serial port
-
- def tearDown(self):
- self.s.close()
-
- def test_PortSetting(self):
- self.s.port = PORT
- # portstr has to be set
- if isinstance(PORT, str):
- self.failUnlessEqual(self.s.portstr.lower(), PORT.lower())
- else:
- 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 # can't 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)
-
- # skip this test as pyserial now tries to set even non standard baud rates.
- # therefore the test can not choose a value that fails on any system.
- def disabled_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, 2.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
- sys.stdout.write(__doc__)
- if len(sys.argv) > 1:
- PORT = sys.argv[1]
- sys.stdout.write("Testing port: %r\n" % PORT)
- sys.argv[1:] = ['-v']
- # When this module is executed from the command-line, it runs all its tests
- unittest.main()
diff --git a/pyserial/examples/test_high_load.py b/pyserial/examples/test_high_load.py
deleted file mode 100644
index a4d8e04..0000000
--- a/pyserial/examples/test_high_load.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/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 sys
-import serial
-
-#on which port should the tests be performed:
-PORT = 0
-BAUDRATE = 115200
-#~ BAUDRATE=9600
-
-if sys.version_info >= (2, 6):
- bytes_0to255 = bytes(range(256))
-else:
- def data(string): return string
- bytes_0to255 = ''.join([chr(x) for x in range(256)])
-
-
-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 = bytes_0to255
- 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 = bytes_0to255
- 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
- sys.stdout.write(__doc__)
- if len(sys.argv) > 1:
- PORT = sys.argv[1]
- sys.stdout.write("Testing port: %r\n" % PORT)
- sys.argv[1:] = ['-v']
- # When this module is executed from the command-line, it runs all its tests
- unittest.main()
diff --git a/pyserial/examples/test_iolib.py b/pyserial/examples/test_iolib.py
deleted file mode 100644
index e740a4c..0000000
--- a/pyserial/examples/test_iolib.py
+++ /dev/null
@@ -1,78 +0,0 @@
-##! /usr/bin/env python
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see __init__.py
-#
-# (C) 2001-2008 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)2001-2009 cliechti@gmx.net
-
-Intended to be run on different platforms, to ensure portability of
-the code.
-
-This modules contains test for the interaction between Serial and the io
-library. This only works on Python 2.6+ that introduced the io library.
-
-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
-import sys
-
-if sys.version_info < (2, 6):
- sys.stderr.write("""\
-==============================================================================
-WARNING: this test is intended for Python 2.6 and newer where the io library
-is available. This seems to be an older version of Python running.
-Continuing anyway...
-==============================================================================
-""")
-
-import io
-import serial
-
-# trick to make that this test run under 2.6 and 3.x without modification.
-# problem is, io library on 2.6 does NOT accept type 'str' and 3.x doesn't
-# like u'nicode' strings with the prefix and it is not providing an unicode
-# function ('str' is now what 'unicode' used to be)
-if sys.version_info >= (3, 0):
- def unicode(x): return x
-
-
-# on which port should the tests be performed:
-PORT = 0
-
-class Test_SerialAndIO(unittest.TestCase):
-
- def setUp(self):
- self.s = serial.Serial(PORT, timeout=1)
- self.io = io.TextIOWrapper(io.BufferedRWPair(self.s, self.s))
-
- def tearDown(self):
- self.s.close()
-
- def test_hello_raw(self):
- self.io.write(unicode("hello\n"))
- self.io.flush() # it is buffering. required to get the data out
- hello = self.io.readline()
- self.failUnlessEqual(hello, unicode("hello\n"))
-
-
-if __name__ == '__main__':
- import sys
- sys.stdout.write(__doc__)
- if len(sys.argv) > 1:
- PORT = sys.argv[1]
- sys.stdout.write("Testing port: %r\n" % PORT)
- sys.argv[1:] = ['-v']
- # When this module is executed from the command-line, it runs all its tests
- unittest.main()
diff --git a/pyserial/examples/wxSerialConfigDialog.py b/pyserial/examples/wxSerialConfigDialog.py
deleted file mode 100644
index 7085035..0000000
--- a/pyserial/examples/wxSerialConfigDialog.py
+++ /dev/null
@@ -1,260 +0,0 @@
-#!/usr/bin/env python
-# generated by wxGlade 0.3.1 on Thu Oct 02 23:25:44 2003
-
-#from wxPython.wx import *
-import wx
-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(wx.Dialog):
- """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"] = wx.DEFAULT_DIALOG_STYLE
- wx.Dialog.__init__(self, *args, **kwds)
- self.label_2 = wx.StaticText(self, -1, "Port")
- self.combo_box_port = wx.ComboBox(self, -1, choices=["dummy1", "dummy2", "dummy3", "dummy4", "dummy5"], style=wx.CB_DROPDOWN)
- if self.show & SHOW_BAUDRATE:
- self.label_1 = wx.StaticText(self, -1, "Baudrate")
- self.choice_baudrate = wx.Choice(self, -1, choices=["choice 1"])
- if self.show & SHOW_FORMAT:
- self.label_3 = wx.StaticText(self, -1, "Data Bits")
- self.choice_databits = wx.Choice(self, -1, choices=["choice 1"])
- self.label_4 = wx.StaticText(self, -1, "Stop Bits")
- self.choice_stopbits = wx.Choice(self, -1, choices=["choice 1"])
- self.label_5 = wx.StaticText(self, -1, "Parity")
- self.choice_parity = wx.Choice(self, -1, choices=["choice 1"])
- if self.show & SHOW_TIMEOUT:
- self.checkbox_timeout = wx.CheckBox(self, -1, "Use Timeout")
- self.text_ctrl_timeout = wx.TextCtrl(self, -1, "")
- self.label_6 = wx.StaticText(self, -1, "seconds")
- if self.show & SHOW_FLOW:
- self.checkbox_rtscts = wx.CheckBox(self, -1, "RTS/CTS")
- self.checkbox_xonxoff = wx.CheckBox(self, -1, "Xon/Xoff")
- self.button_ok = wx.Button(self, -1, "OK")
- self.button_cancel = wx.Button(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 = wx.BoxSizer(wx.VERTICAL)
- sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
- sizer_basics = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Basics"), wx.VERTICAL)
- sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
- sizer_5.Add(self.label_2, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_5.Add(self.combo_box_port, 1, 0, 0)
- sizer_basics.Add(sizer_5, 0, wx.RIGHT|wx.EXPAND, 0)
- if self.show & SHOW_BAUDRATE:
- sizer_baudrate = wx.BoxSizer(wx.HORIZONTAL)
- sizer_baudrate.Add(self.label_1, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_baudrate.Add(self.choice_baudrate, 1, wx.ALIGN_RIGHT, 0)
- sizer_basics.Add(sizer_baudrate, 0, wx.EXPAND, 0)
- sizer_2.Add(sizer_basics, 0, wx.EXPAND, 0)
- if self.show & SHOW_FORMAT:
- sizer_8 = wx.BoxSizer(wx.HORIZONTAL)
- sizer_7 = wx.BoxSizer(wx.HORIZONTAL)
- sizer_6 = wx.BoxSizer(wx.HORIZONTAL)
- sizer_format = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Data Format"), wx.VERTICAL)
- sizer_6.Add(self.label_3, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_6.Add(self.choice_databits, 1, wx.ALIGN_RIGHT, 0)
- sizer_format.Add(sizer_6, 0, wx.EXPAND, 0)
- sizer_7.Add(self.label_4, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_7.Add(self.choice_stopbits, 1, wx.ALIGN_RIGHT, 0)
- sizer_format.Add(sizer_7, 0, wx.EXPAND, 0)
- sizer_8.Add(self.label_5, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_8.Add(self.choice_parity, 1, wx.ALIGN_RIGHT, 0)
- sizer_format.Add(sizer_8, 0, wx.EXPAND, 0)
- sizer_2.Add(sizer_format, 0, wx.EXPAND, 0)
- if self.show & SHOW_TIMEOUT:
- sizer_timeout = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Timeout"), wx.HORIZONTAL)
- sizer_timeout.Add(self.checkbox_timeout, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_timeout.Add(self.text_ctrl_timeout, 0, 0, 0)
- sizer_timeout.Add(self.label_6, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_2.Add(sizer_timeout, 0, 0, 0)
- if self.show & SHOW_FLOW:
- sizer_flow = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Flow Control"), wx.HORIZONTAL)
- sizer_flow.Add(self.checkbox_rtscts, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_flow.Add(self.checkbox_xonxoff, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
- sizer_flow.Add((10,10), 1, wx.EXPAND, 0)
- sizer_2.Add(sizer_flow, 0, wx.EXPAND, 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, wx.ALL|wx.ALIGN_RIGHT, 4)
- self.SetAutoLayout(1)
- self.SetSizer(sizer_2)
- sizer_2.Fit(self)
- sizer_2.SetSizeHints(self)
- self.Layout()
-
- def __attach_events(self):
- wx.EVT_BUTTON(self, self.button_ok.GetId(), self.OnOK)
- wx.EVT_BUTTON(self, self.button_cancel.GetId(), self.OnCancel)
- if self.show & SHOW_TIMEOUT:
- wx.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 = wx.MessageDialog(self, 'Timeout must be a numeric value',
- 'Value Error', wx.OK | wx.ICON_ERROR)
- dlg.ShowModal()
- dlg.Destroy()
- success = False
- else:
- self.serial.timeout = None
- if success:
- self.EndModal(wx.ID_OK)
-
- def OnCancel(self, events):
- self.EndModal(wx.ID_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(wx.App):
- """Test code"""
- def OnInit(self):
- wx.InitAllImageHandlers()
-
- 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 != wx.ID_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 != wx.ID_OK:
- break
- return 0
-
-# end of class MyApp
-
-if __name__ == "__main__":
- app = MyApp(0)
- app.MainLoop()
diff --git a/pyserial/examples/wxSerialConfigDialog.wxg b/pyserial/examples/wxSerialConfigDialog.wxg
deleted file mode 100644
index f5e92e0..0000000
--- a/pyserial/examples/wxSerialConfigDialog.wxg
+++ /dev/null
@@ -1,262 +0,0 @@
-<?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/pyserial/examples/wxTerminal.py b/pyserial/examples/wxTerminal.py
deleted file mode 100644
index 646c272..0000000
--- a/pyserial/examples/wxTerminal.py
+++ /dev/null
@@ -1,333 +0,0 @@
-#!/usr/bin/env python
-# generated by wxGlade 0.3.1 on Fri Oct 03 23:23:45 2003
-
-#from wxPython.wx import *
-import wx
-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 = wx.NewEventType()
-# bind to serial data receive events
-EVT_SERIALRX = wx.PyEventBinder(SERIALRX, 0)
-
-class SerialRxEvent(wx.PyCommandEvent):
- eventType = SERIALRX
- def __init__(self, windowID, data):
- wx.PyCommandEvent.__init__(self, self.eventType, windowID)
- self.data = data
-
- def Clone(self):
- self.__class__(self.GetId(), self.data)
-
-#----------------------------------------------------------------------
-
-ID_CLEAR = wx.NewId()
-ID_SAVEAS = wx.NewId()
-ID_SETTINGS = wx.NewId()
-ID_TERM = wx.NewId()
-ID_EXIT = wx.NewId()
-
-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(wx.Dialog):
- """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"] = wx.DEFAULT_DIALOG_STYLE
- wx.Dialog.__init__(self, *args, **kwds)
- self.checkbox_echo = wx.CheckBox(self, -1, "Local Echo")
- self.checkbox_unprintable = wx.CheckBox(self, -1, "Show unprintable characters")
- self.radio_box_newline = wx.RadioBox(self, -1, "Newline Handling", choices=["CR only", "LF only", "CR+LF"], majorDimension=0, style=wx.RA_SPECIFY_ROWS)
- self.button_ok = wx.Button(self, -1, "OK")
- self.button_cancel = wx.Button(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 = wx.BoxSizer(wx.VERTICAL)
- sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
- sizer_4 = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Input/Output"), wx.VERTICAL)
- sizer_4.Add(self.checkbox_echo, 0, wx.ALL, 4)
- sizer_4.Add(self.checkbox_unprintable, 0, wx.ALL, 4)
- sizer_4.Add(self.radio_box_newline, 0, 0, 0)
- sizer_2.Add(sizer_4, 0, wx.EXPAND, 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, wx.ALL|wx.ALIGN_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(wx.EVT_BUTTON, self.OnOK, id = self.button_ok.GetId())
- self.Bind(wx.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(wx.ID_OK)
-
- def OnCancel(self, events):
- """Do not update data but close dialog."""
- self.EndModal(wx.ID_CANCEL)
-
-# end of class TerminalSettingsDialog
-
-
-class TerminalFrame(wx.Frame):
- """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"] = wx.DEFAULT_FRAME_STYLE
- wx.Frame.__init__(self, *args, **kwds)
- self.text_ctrl_output = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_READONLY)
-
- # Menu Bar
- self.frame_terminal_menubar = wx.MenuBar()
- self.SetMenuBar(self.frame_terminal_menubar)
- wxglade_tmp_menu = wx.Menu()
- wxglade_tmp_menu.Append(ID_CLEAR, "&Clear", "", wx.ITEM_NORMAL)
- wxglade_tmp_menu.Append(ID_SAVEAS, "&Save Text As...", "", wx.ITEM_NORMAL)
- wxglade_tmp_menu.AppendSeparator()
- wxglade_tmp_menu.Append(ID_SETTINGS, "&Port Settings...", "", wx.ITEM_NORMAL)
- wxglade_tmp_menu.Append(ID_TERM, "&Terminal Settings...", "", wx.ITEM_NORMAL)
- wxglade_tmp_menu.AppendSeparator()
- wxglade_tmp_menu.Append(ID_EXIT, "&Exit", "", wx.ITEM_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.alive.set()
- self.thread.start()
-
- 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 = wx.BoxSizer(wx.VERTICAL)
- sizer_1.Add(self.text_ctrl_output, 1, wx.EXPAND, 0)
- self.SetAutoLayout(1)
- self.SetSizer(sizer_1)
- self.Layout()
- # end wxGlade
-
- def __attach_events(self):
- #register events at the controls
- self.Bind(wx.EVT_MENU, self.OnClear, id = ID_CLEAR)
- self.Bind(wx.EVT_MENU, self.OnSaveAs, id = ID_SAVEAS)
- self.Bind(wx.EVT_MENU, self.OnExit, id = ID_EXIT)
- self.Bind(wx.EVT_MENU, self.OnPortSettings, id = ID_SETTINGS)
- self.Bind(wx.EVT_MENU, self.OnTermSettings, id = ID_TERM)
- self.text_ctrl_output.Bind(wx.EVT_CHAR, self.OnKey)
- self.Bind(EVT_SERIALRX, self.OnSerialRead)
- self.Bind(wx.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 = wx.FileDialog(None, "Save Text As...", ".", "", "Text File|*.txt|All Files|*", wx.SAVE)
- if dlg.ShowModal() == wx.ID_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 == wx.ID_OK or event is not None:
- try:
- self.serial.open()
- except serial.SerialException, e:
- dlg = wx.MessageDialog(None, str(e), "Serial Port Error", wx.OK | wx.ICON_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(wx.App):
- def OnInit(self):
- wx.InitAllImageHandlers()
- 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/pyserial/examples/wxTerminal.wxg b/pyserial/examples/wxTerminal.wxg
deleted file mode 100644
index 183f876..0000000
--- a/pyserial/examples/wxTerminal.wxg
+++ /dev/null
@@ -1,127 +0,0 @@
-<?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/pyserial/serial/.cvsignore b/pyserial/serial/.cvsignore
deleted file mode 100644
index 7e99e36..0000000
--- a/pyserial/serial/.cvsignore
+++ /dev/null
@@ -1 +0,0 @@
-*.pyc \ No newline at end of file
diff --git a/pyserial/serial/__init__.py b/pyserial/serial/__init__.py
deleted file mode 100644
index 6e160e0..0000000
--- a/pyserial/serial/__init__.py
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/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
-
-VERSION = '2.4'
-
-import sys
-
-if sys.platform == 'cli':
- from serialcli import *
-else:
- import os
- # 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/pyserial/serial/serialcli.py b/pyserial/serial/serialcli.py
deleted file mode 100644
index d8eaf1e..0000000
--- a/pyserial/serial/serialcli.py
+++ /dev/null
@@ -1,271 +0,0 @@
-#! python
-# Python Serial Port Extension for Win32, Linux, BSD, Jython and .NET/Mono
-# serial driver for .NET/Mono (IronPython), .NET >= 2
-# see __init__.py
-#
-# (C) 2008 Chris Liechti <cliechti@gmx.net>
-# this is distributed under a free software license, see license.txt
-
-import clr
-import System
-import System.IO.Ports
-from serialutil import *
-
-
-def device(portnum):
- """Turn a port number into a device name"""
- return System.IO.Ports.SerialPort.GetPortNames()[portnum]
-
-
-# must invoke function with byte array, make a helper to convert strings
-# to byte arrays
-sab = System.Array[System.Byte]
-def as_byte_array(string):
- return sab([ord(x) for x in string]) # XXX will require adaption when run with a 3.x compatible IronPython
-
-class IronSerial(SerialBase):
- """Serial port implemenation for .NET/Mono."""
-
- 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.")
- try:
- self._port_handle = System.IO.Ports.SerialPort(self.portstr)
- except Exception, msg:
- self._port_handle = None
- raise SerialException("could not open port %s: %s" % (self.portstr, msg))
-
- self._reconfigurePort()
- self._port_handle.Open()
- self._isOpen = True
- if not self._rtscts:
- self.setRTS(True)
- self.setDTR(True)
- self.flushInput()
- self.flushOutput()
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port."""
- if not self._port_handle:
- raise SerialException("Can only operate on a valid port handle")
-
- #~ self._port_handle.ReceivedBytesThreshold = 1
-
- if self._timeout is None:
- self._port_handle.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
- else:
- self._port_handle.ReadTimeout = int(self._timeout*1000)
-
- # if self._timeout != 0 and self._interCharTimeout is not None:
- # timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
-
- if self._writeTimeout is None:
- self._port_handle.WriteTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
- else:
- self._port_handle.WriteTimeout = int(self._writeTimeout*1000)
-
-
- # Setup the connection info.
- try:
- self._port_handle.BaudRate = self._baudrate
- except IOError, e:
- # catch errors from illegal baudrate settings
- raise ValueError(str(e))
-
- if self._bytesize == FIVEBITS:
- self._port_handle.DataBits = 5
- elif self._bytesize == SIXBITS:
- self._port_handle.DataBits = 6
- elif self._bytesize == SEVENBITS:
- self._port_handle.DataBits = 7
- elif self._bytesize == EIGHTBITS:
- self._port_handle.DataBits = 8
- else:
- raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
-
- if self._parity == PARITY_NONE:
- self._port_handle.Parity = getattr(System.IO.Ports.Parity, 'None') # reserved keyword in Py3k
- elif self._parity == PARITY_EVEN:
- self._port_handle.Parity = System.IO.Ports.Parity.Even
- elif self._parity == PARITY_ODD:
- self._port_handle.Parity = System.IO.Ports.Parity.Odd
- elif self._parity == PARITY_MARK:
- self._port_handle.Parity = System.IO.Ports.Parity.Mark
- elif self._parity == PARITY_SPACE:
- self._port_handle.Parity = System.IO.Ports.Parity.Space
- else:
- raise ValueError("Unsupported parity mode: %r" % self._parity)
-
- if self._stopbits == STOPBITS_ONE:
- self._port_handle.StopBits = System.IO.Ports.StopBits.One
- elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
- self._port_handle.StopBits = System.IO.Ports.StopBits.OnePointFive
- elif self._stopbits == STOPBITS_TWO:
- self._port_handle.StopBits = System.IO.Ports.StopBits.Two
- else:
- raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
-
- if self._rtscts and self._xonxoff:
- self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff
- elif self._rtscts:
- self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSend
- elif self._xonxoff:
- self._port_handle.Handshake = System.IO.Ports.Handshake.XOnXOff
- else:
- self._port_handle.Handshake = getattr(System.IO.Ports.Handshake, 'None') # reserved keyword in Py3k
-
- #~ def __del__(self):
- #~ self.close()
-
- def close(self):
- """Close port"""
- if self._isOpen:
- if self._port_handle:
- try:
- self._port_handle.Close()
- except System.IO.Ports.InvalidOperationException:
- # ignore errors. can happen for unplugged USB serial devices
- pass
- self._port_handle = None
- self._isOpen = False
-
- def makeDeviceName(self, port):
- try:
- return device(port)
- except TypeError, e:
- raise SerialException(str(e))
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def inWaiting(self):
- """Return the number of characters currently in the input buffer."""
- if not self._port_handle: raise portNotOpenError
- return self._port_handle.BytesToRead
-
- 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._port_handle: raise portNotOpenError
- # must use single byte reads as this is the only way to read
- # without applying encodings
- data = bytearray()
- while size:
- try:
- data.append(self._port_handle.ReadByte())
- except System.TimeoutException, e:
- break
- else:
- size -= 1
- return bytes(data)
-
- def write(self, data):
- """Output the given string over the serial port."""
- if not self._port_handle: raise portNotOpenError
- if not isinstance(data, (bytes, bytearray)):
- raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
- try:
- # must call overloaded method with byte array argument
- # as this is the only one not applying encodings
- self._port_handle.Write(as_byte_array(data), 0, len(data))
- except System.TimeoutException, e:
- raise writeTimeoutError
- return len(data)
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.DiscardInBuffer()
-
- def flushOutput(self):
- """Clear output buffer, aborting the current output and
- discarding all that is in the buffer."""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.DiscardOutBuffer()
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given duration."""
- if not self._port_handle: raise portNotOpenError
- import time
- self._port_handle.BreakState = True
- time.sleep(duration)
- self._port_handle.BreakState = False
-
- def setBreak(self, level=True):
- """Set break: Controls TXD. When active, to transmitting is possible."""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.BreakState = bool(level)
-
- def setRTS(self, level=True):
- """Set terminal status line: Request To Send"""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.RtsEnable = bool(level)
-
- def setDTR(self, level=True):
- """Set terminal status line: Data Terminal Ready"""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.DtrEnable = bool(level)
-
- def getCTS(self):
- """Read terminal status line: Clear To Send"""
- if not self._port_handle: raise portNotOpenError
- return self._port_handle.CtsHolding
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready"""
- if not self._port_handle: raise portNotOpenError
- return self._port_handle.DsrHolding
-
- def getRI(self):
- """Read terminal status line: Ring Indicator"""
- if not self._port_handle: raise portNotOpenError
- #~ return self._port_handle.XXX
- return False #XXX an error would be better
-
- def getCD(self):
- """Read terminal status line: Carrier Detect"""
- if not self._port_handle: raise portNotOpenError
- return self._port_handle.CDHolding
-
- # - - platform specific - - - -
- # none
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(IronSerial, FileLike):
- pass
-else:
- # io library present
- class Serial(IronSerial, io.RawIOBase):
- pass
-
-
-# Nur Testfunktion!!
-if __name__ == '__main__':
- import sys
-
- s = Serial(0)
- sys.stdio.write('%s\n' % s)
-
- s = Serial()
- sys.stdio.write('%s\n' % s)
-
-
- s.baudrate = 19200
- s.databits = 7
- s.close()
- s.port = 0
- s.open()
- sys.stdio.write('%s\n' % s)
-
diff --git a/pyserial/serial/serialjava.py b/pyserial/serial/serialjava.py
deleted file mode 100644
index 2541534..0000000
--- a/pyserial/serial/serialjava.py
+++ /dev/null
@@ -1,260 +0,0 @@
-#!jython
-#
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# module for serial IO for Jython and JavaComm
-# see __init__.py
-#
-# (C) 2002-2008 Chris Liechti <cliechti@gmx.net>
-# this is distributed under a free software license, see license.txt
-
-from serialutil import *
-
-def my_import(name):
- mod = __import__(name)
- components = name.split('.')
- for comp in components[1:]:
- mod = getattr(mod, comp)
- return mod
-
-
-def detect_java_comm(names):
- """try given list of modules and return that imports"""
- for name in names:
- try:
- mod = my_import(name)
- mod.SerialPort
- return mod
- except (ImportError, AttributeError):
- pass
- raise ImportError("No Java Communications API implementation found")
-
-
-# Java Communications API implementations
-# http://mho.republika.pl/java/comm/
-
-comm = detect_java_comm([
- 'javax.comm', # Sun/IBM
- 'gnu.io', # RXTX
-])
-
-
-def device(portnumber):
- """Turn a port number into a device name"""
- enum = comm.CommPortIdentifier.getPortIdentifiers()
- ports = []
- while enum.hasMoreElements():
- el = enum.nextElement()
- if el.getPortType() == comm.CommPortIdentifier.PORT_SERIAL:
- ports.append(el)
- return ports[portnumber].getName()
-
-
-class JavaSerial(SerialBase):
- """Serial port class, implemented with Java Communications API 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 = comm.CommPortIdentifier.getPortIdentifier(self._port)
- else:
- portId = comm.CommPortIdentifier.getPortIdentifier(device(self._port)) # numbers are transformed to a comport id 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 communication 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 = comm.SerialPort.DATABITS_5
- elif self._bytesize == SIXBITS:
- jdatabits = comm.SerialPort.DATABITS_6
- elif self._bytesize == SEVENBITS:
- jdatabits = comm.SerialPort.DATABITS_7
- elif self._bytesize == EIGHTBITS:
- jdatabits = comm.SerialPort.DATABITS_8
- else:
- raise ValueError("unsupported bytesize: %r" % self._bytesize)
-
- if self._stopbits == STOPBITS_ONE:
- jstopbits = comm.SerialPort.STOPBITS_1
- elif stopbits == STOPBITS_ONE_POINT_FIVE:
- self._jstopbits = comm.SerialPort.STOPBITS_1_5
- elif self._stopbits == STOPBITS_TWO:
- jstopbits = comm.SerialPort.STOPBITS_2
- else:
- raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
-
- if self._parity == PARITY_NONE:
- jparity = comm.SerialPort.PARITY_NONE
- elif self._parity == PARITY_EVEN:
- jparity = comm.SerialPort.PARITY_EVEN
- elif self._parity == PARITY_ODD:
- jparity = comm.SerialPort.PARITY_ODD
- elif self._parity == PARITY_MARK:
- jparity = comm.SerialPort.PARITY_MARK
- elif self._parity == PARITY_SPACE:
- jparity = comm.SerialPort.PARITY_SPACE
- else:
- raise ValueError("unsupported parity type: %r" % self._parity)
-
- jflowin = jflowout = 0
- if self._rtscts:
- jflowin |= comm.SerialPort.FLOWCONTROL_RTSCTS_IN
- jflowout |= comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
- if self._xonxoff:
- jflowin |= comm.SerialPort.FLOWCONTROL_XONXOFF_IN
- jflowout |= comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
-
- self.sPort.setSerialPortParams(self._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 = bytearray()
- if size > 0:
- while len(read) < size:
- x = self._instream.read()
- if x == -1:
- if self.timeout >= 0:
- break
- else:
- read.append(x)
- return bytes(read)
-
- def write(self, data):
- """Output the given string over the serial port."""
- if not self.sPort: raise portNotOpenError
- if not isinstance(data, (bytes, bytearray)):
- raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
- self._outstream.write(data)
- return len(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, duration=0.25):
- """Send break condition. Timed, returns to idle state after given duration."""
- if not self.sPort: raise portNotOpenError
- self.sPort.sendBreak(duration*1000.0)
-
- def setBreak(self, level=1):
- """Set break: Controls TXD. When active, to transmitting is possible."""
- if self.fd is None: raise portNotOpenError
- raise SerialException("The setBreak function is not implemented in java.")
-
- def setRTS(self, level=1):
- """Set terminal status line: Request To Send"""
- if not self.sPort: raise portNotOpenError
- self.sPort.setRTS(level)
-
- def setDTR(self, level=1):
- """Set terminal status line: Data Terminal Ready"""
- if not self.sPort: raise portNotOpenError
- self.sPort.setDTR(level)
-
- 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()
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(JavaSerial, FileLike):
- pass
-else:
- # io library present
- class Serial(JavaSerial, io.RawIOBase):
- pass
-
-
-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')
- sys.stdio.write('%r\n' % s.read(5))
- sys.stdio.write('%s\n' % s.inWaiting())
- del s
-
-
diff --git a/pyserial/serial/serialposix.py b/pyserial/serial/serialposix.py
deleted file mode 100644
index bbf7fb9..0000000
--- a/pyserial/serial/serialposix.py
+++ /dev/null
@@ -1,612 +0,0 @@
-#!/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-2009 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 *
-
-# 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
-
-baudrate_constants = {
- 0: 0000000, # hang up
- 50: 0000001,
- 75: 0000002,
- 110: 0000003,
- 134: 0000004,
- 150: 0000005,
- 200: 0000006,
- 300: 0000007,
- 600: 0000010,
- 1200: 0000011,
- 1800: 0000012,
- 2400: 0000013,
- 4800: 0000014,
- 9600: 0000015,
- 19200: 0000016,
- 38400: 0000017,
- 57600: 0010001,
- 115200: 0010002,
- 230400: 0010003,
- 460800: 0010004,
- 500000: 0010005,
- 576000: 0010006,
- 921600: 0010007,
- 1000000: 0010010,
- 1152000: 0010011,
- 1500000: 0010012,
- 2000000: 0010013,
- 2500000: 0010014,
- 3000000: 0010015,
- 3500000: 0010016,
- 4000000: 0010017
-}
-
-# try to detect the OS so that a device can be selected...
-# this code block should supply a device() and set_special_baudrate() function
-# for the platform
-plat = sys.platform.lower()
-
-if plat[:5] == 'linux': # Linux (confirmed)
-
- def device(port):
- return '/dev/ttyS%d' % port
-
- ASYNC_SPD_MASK = 0x1030
- ASYNC_SPD_CUST = 0x0030
-
- def set_special_baudrate(port, baudrate):
- import array
- buf = array.array('i', [0] * 32)
-
- # get serial_struct
- FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf)
-
- # set custom divisor
- buf[6] = buf[7] / baudrate
-
- # update flags
- buf[4] &= ~ASYNC_SPD_MASK
- buf[4] |= ASYNC_SPD_CUST
-
- # set serial_struct
- try:
- res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf)
- except IOError:
- raise ValueError('Failed to set custom baud rate: %r' % baudrate)
-
-elif plat == 'cygwin': # cygwin/win32 (confirmed)
-
- def device(port):
- return '/dev/com%d' % (port + 1)
-
- ASYNC_SPD_MASK = 0x1030
- ASYNC_SPD_CUST = 0x0030
-
- # XXX untested!
- def set_special_baudrate(port, baudrate):
- import array
- buf = array.array('i', [0] * 32)
-
- # get serial_struct
- FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf)
-
- # set custom divisor
- buf[6] = buf[7] / baudrate
-
- # update flags
- buf[4] &= ~ASYNC_SPD_MASK
- buf[4] |= ASYNC_SPD_CUST
-
- # set serial_struct
- try:
- res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf)
- except IOError:
- raise ValueError('Failed to set custom baud rate: %r' % baudrate)
-
-elif plat == 'openbsd3': # BSD (confirmed)
-
- def device(port):
- return '/dev/ttyp%d' % port
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
-elif plat[:3] == 'bsd' or \
- plat[:7] == 'freebsd' or \
- plat[:7] == 'openbsd': # BSD (confirmed for freebsd4: cuaa%d)
-
- def device(port):
- return '/dev/cuad%d' % port
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
-elif plat[:6] == 'darwin': # OS X
-
- version = os.uname()[2].split('.')
- # Tiger or above can support arbitrary serial speeds
- if int(version[0]) >= 8:
- # remove all speeds not supported with TERMIOS so that pyserial never
- # attempts to use them directly
- for b in baudrate_constants.keys():
- if b > 230400:
- del baudrate_constants[b]
-
- def set_special_baudrate(port, baudrate):
- # use IOKit-specific call to set up high speeds
- import array, fcntl
- buf = array.array('i', [baudrate])
- IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t)
- fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1)
- else: # version < 8
- def set_special_baudrate(port, baudrate):
- raise ValueError("baud rate not supported")
-
- def device(port):
- return '/dev/cuad%d' % port
-
-
-elif plat[:6] == 'netbsd': # NetBSD 1.6 testing by Erk
-
- def device(port):
- return '/dev/dty%02d' % port
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
-elif plat[:4] == 'irix': # IRIX (partially tested)
-
- def device(port):
- return '/dev/ttyf%d' % (port+1) #XXX different device names depending on flow control
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
-elif plat[:2] == 'hp': # HP-UX (not tested)
-
- def device(port):
- return '/dev/tty%dp0' % (port+1)
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
-elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed)
-
- def device(port):
- return '/dev/tty%c' % (ord('a')+port)
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
-elif plat[:3] == 'aix': # AIX
-
- def device(port):
- return '/dev/tty%d' % (port)
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
-else:
- #platform detection has failed...
- sys.stderr.write("""\
-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 parameter.
- def device(portum):
- return '/dev/ttyS%d' % portnum
- def set_special_baudrate(port, baudrate):
- raise SerialException("sorry don't know how to handle non standard baud rate on this platform")
- #~ 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)
-
-TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427
-TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428
-
-
-class PosixSerial(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."""
- self.fd = None
- if self._port is None:
- raise SerialException("Port must be configured before it can be used.")
- # 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: %s" % (self._port, msg))
- #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) # set blocking
-
- try:
- self._reconfigurePort()
- except:
- try:
- os.close(self.fd)
- except:
- # ignore any exception when closing the port
- # also to keep original exception that happened when setting up
- pass
- self.fd = None
- raise
- else:
- self._isOpen = True
- #~ self.flushInput()
-
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port."""
- if self.fd is None:
- raise SerialException("Can only operate on a valid port handle")
- custom_baud = None
-
- vmin = vtime = 0 # timeout is done via select
- if self._interCharTimeout is not None:
- vmin = 1
- vtime = int(self._interCharTimeout * 10)
- 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 baud rate
- try:
- ispeed = ospeed = getattr(TERMIOS, 'B%s' % (self._baudrate))
- except AttributeError:
- try:
- ispeed = ospeed = baudrate_constants[self._baudrate]
- except KeyError:
- #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
- # may need custom baud rate, it isn't in our list.
- ispeed = ospeed = getattr(TERMIOS, 'B38400')
- try:
- custom_baud = int(self._baudrate) # store for later
- except ValueError:
- raise ValueError('Invalid baud rate: %r' % self._baudrate)
- else:
- if custom_baud < 0:
- 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_ONE_POINT_FIVE:
- cflag |= (TERMIOS.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
- elif self._stopbits == STOPBITS_TWO:
- cflag |= (TERMIOS.CSTOPB)
- else:
- raise ValueError('Invalid stop bit 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])
-
- # apply custom baud rate, if any
- if custom_baud is not None:
- set_special_baudrate(self, custom_baud)
-
- 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 = bytearray()
- 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.extend(buf)
- if ((self._timeout is not None and self._timeout >= 0) or
- (self._interCharTimeout is not None and self._interCharTimeout > 0)) and not buf:
- break # early abort on timeout
- return bytes(read)
-
- def write(self, data):
- """Output the given string over the serial port."""
- if self.fd is None: raise portNotOpenError
- if not isinstance(data, (bytes, bytearray)):
- raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
- 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
- return len(data)
-
- 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, duration=0.25):
- """Send break condition. Timed, returns to idle state after given duration."""
- if self.fd is None:
- raise portNotOpenError
- termios.tcsendbreak(self.fd, int(duration/0.25))
-
- def setBreak(self, level=1):
- """Set break: Controls TXD. When active, no transmitting is possible."""
- if self.fd is None: raise portNotOpenError
- if level:
- fcntl.ioctl(self.fd, TIOCSBRK)
- else:
- fcntl.ioctl(self.fd, TIOCCBRK)
-
- def setRTS(self, level=1):
- """Set terminal status line: Request To Send"""
- if self.fd is None: raise portNotOpenError
- if level:
- fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
- else:
- fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
-
- def setDTR(self, level=1):
- """Set terminal status line: Data Terminal Ready"""
- if self.fd is None: raise portNotOpenError
- if level:
- 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 use 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
-
-
-# assemble Serial class with the platform specifc implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derrive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(PosixSerial, FileLike):
- pass
-else:
- # io library present
- class Serial(PosixSerial, io.RawIOBase):
- pass
-
-
-if __name__ == '__main__':
- s = Serial(0,
- baudrate=19200, # baud rate
- bytesize=EIGHTBITS, # number of data bits
- parity=PARITY_EVEN, # enable parity checking
- stopbits=STOPBITS_ONE, # number of stop bits
- 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')
- sys.stdio.write('%r\n' % s.read(5))
- sys.stdio.write('%s\n' % s.inWaiting())
- del s
-
diff --git a/pyserial/serial/serialutil.py b/pyserial/serial/serialutil.py
deleted file mode 100644
index e568aa1..0000000
--- a/pyserial/serial/serialutil.py
+++ /dev/null
@@ -1,478 +0,0 @@
-#! python
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see __init__.py
-#
-# (C) 2001-2009 Chris Liechti <cliechti@gmx.net>
-# this is distributed under a free software license, see license.txt
-
-# compatibility folder Python < 2.6
-try:
- bytes
- bytearray
-except (NameError, AttributeError):
- # Python older than 2.6 do not have these types. Like for Python 2.6 they
- # should behave like str. For Python older than 3.0 we want to work with
- # strings anyway, only later versions have a true bytes type.
- bytes = str
- # bytearray is a mutable type that is easily turned into an instance of
- # bytes
- class bytearray(list):
- # for bytes(bytearray()) usage
- def __str__(self): return ''.join(self)
- # append automatically converts integers to characters
- def append(self, item):
- if isinstance(item, str):
- list.append(self, item)
- else:
- list.append(self, chr(item))
-
-# create control bytes, depending on true type of bytes
-# all Python versions prior 3.x convert str([17]) to '[17]' instead of '\x11'
-if bytes is str:
- XON = chr(17)
- XOFF = chr(19)
-else:
- XON = bytes([17])
- XOFF = bytes([19])
-
-
-PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
-STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
-FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
-
-PARITY_NAMES = {
- PARITY_NONE: 'None',
- PARITY_EVEN: 'Even',
- PARITY_ODD: 'Odd',
- PARITY_MARK: 'Mark',
- PARITY_SPACE: 'Space',
-}
-
-
-class SerialException(IOError):
- """Base class for serial port related exceptions."""
-
-
-class SerialTimeoutException(SerialException):
- """Write timeouts give an exception"""
-
-
-writeTimeoutError = SerialTimeoutException("Write timeout")
-portNotOpenError = ValueError('Attempting to use a port that is not open')
-
-
-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 __init__(self):
- self.closed = True
-
- def close(self):
- self.closed = True
-
- # so that ports are closed when objects are discarded
- def __del__(self):
- """Destructor. Calls close()."""
- # The try/except block is in case this is called at program
- # exit time, when it's possible that globals have already been
- # deleted, and then the close() call might fail. Since
- # there's nothing we can do about such failures and they annoy
- # the end users, we suppress the traceback.
- try:
- self.close()
- except:
- pass
-
- def writelines(self, sequence):
- for line in sequence:
- self.write(line)
-
- def flush(self):
- """flush of file like objects"""
- pass
-
- # iterator for e.g. "for line in Serial(0): ..." usage
- def next(self):
- line = self.readline()
- if not line: raise StopIteration
- return line
-
- def __iter__(self):
- return self
-
- # other functions of file-likes - not used by pySerial
-
- #~ readinto(b)
-
- def seek(self, pos, whence=0):
- raise IOError("file is not seekable")
-
- def tell(self):
- raise IOError("file is not seekable")
-
- def truncate(self, n=None):
- raise IOError("file is not seekable")
-
- def isatty(self):
- return False
-
-
-class SerialBase(object):
- """Serial port base class. Provides __init__ function and properties to
- get/set port settings."""
-
- # default values, may be overridden 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, PARITY_MARK, PARITY_SPACE)
- STOPBITS = (STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, 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, # baud rate
- bytesize=EIGHTBITS, # number of data bits
- parity=PARITY_NONE, # enable parity checking
- stopbits=STOPBITS_ONE, # number of stop bits
- 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
- interCharTimeout=None # Inter-character timeout, None to disable
- ):
- """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 through properties
- self._baudrate = None # correct value is assigned below through properties
- self._bytesize = None # correct value is assigned below through properties
- self._parity = None # correct value is assigned below through properties
- self._stopbits = None # correct value is assigned below through properties
- self._timeout = None # correct value is assigned below through properties
- self._writeTimeout = None # correct value is assigned below through properties
- self._xonxoff = None # correct value is assigned below through properties
- self._rtscts = None # correct value is assigned below through properties
- self._dsrdtr = None # correct value is assigned below through properties
- self._interCharTimeout = None # correct value is assigned below through 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
- self.interCharTimeout = interCharTimeout
-
- if port is not None:
- self.open()
-
- def isOpen(self):
- """Check if the port is opened."""
- return self._isOpen
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- # TODO: these are not really 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 isinstance(port, basestring):
- self.portstr = port
- else:
- self.portstr = self.makeDeviceName(port)
- else:
- self.portstr = None
- self._port = port
- self.name = self.portstr
- 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 baud rate. It raises a ValueError if the port is open and the
- baud rate is not possible. If the port is closed, then the value is
- accepted and the exception is raised when the port is opened."""
- 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 baud rate setting."""
- return self._baudrate
-
- baudrate = property(getBaudrate, setBaudrate, doc="Baud rate 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 stop bits size."""
- if stopbits not in self.STOPBITS: raise ValueError("Not a valid stop bit size: %r" % (stopbits,))
- self._stopbits = stopbits
- if self._isOpen: self._reconfigurePort()
-
- def getStopbits(self):
- """Get the current stop bits setting."""
- return self._stopbits
-
- stopbits = property(getStopbits, setStopbits, doc="Stop bits setting")
-
-
- def setTimeout(self, timeout):
- """Change timeout setting."""
- if timeout is not None:
- 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,))
- if timeout < 0: 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 XON/XOFF setting."""
- self._xonxoff = xonxoff
- if self._isOpen: self._reconfigurePort()
-
- def getXonXoff(self):
- """Get the current XON/XOFF setting."""
- return self._xonxoff
-
- xonxoff = property(getXonXoff, setXonXoff, doc="XON/XOFF setting")
-
- def setRtsCts(self, rtscts):
- """Change RTS/CTS flow control setting."""
- self._rtscts = rtscts
- if self._isOpen: self._reconfigurePort()
-
- def getRtsCts(self):
- """Get the current RTS/CTS 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 DSR/DTR flow control setting."""
- return self._dsrdtr
-
- dsrdtr = property(getDsrDtr, setDsrDtr, "DSR/DTR flow control setting")
-
- def setInterCharTimeout(self, interCharTimeout):
- """Change inter-character timeout setting."""
- if interCharTimeout is not None:
- if interCharTimeout < 0: raise ValueError("Not a valid timeout: %r" % interCharTimeout)
- try:
- interCharTimeout + 1 # test if it's a number, will throw a TypeError if not...
- except TypeError:
- raise ValueError("Not a valid timeout: %r" % interCharTimeout)
-
- self._interCharTimeout = interCharTimeout
- if self._isOpen: self._reconfigurePort()
-
- def getInterCharTimeout(self):
- """Get the current inter-character timeout setting."""
- return self._interCharTimeout
-
- interCharTimeout = property(getInterCharTimeout, setInterCharTimeout, doc="Inter-character timeout setting for read()")
-
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- 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,
- )
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- 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 bytes(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()
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
- # compatibility with io library
-
- def readable(self): return True
- def writable(self): return True
- def seekable(self): return False
- def readinto(self, b):
- data = self.read(len(b))
- n = len(data)
- try:
- b[:n] = data
- except TypeError, err:
- import array
- if not isinstance(b, array.array):
- raise err
- b[:n] = array.array('b', data)
- return n
-
-
-if __name__ == '__main__':
- import sys
- s = SerialBase()
- sys.stdout.write('port name: %s\n' % s.portstr)
- sys.stdout.write('baud rates: %s\n' % s.getSupportedBaudrates())
- sys.stdout.write('byte sizes: %s\n' % s.getSupportedByteSizes())
- sys.stdout.write('parities: %s\n' % s.getSupportedParities())
- sys.stdout.write('stop bits: %s\n' % s.getSupportedStopbits())
- sys.stdout.write('%s\n' % s)
diff --git a/pyserial/serial/serialwin32.py b/pyserial/serial/serialwin32.py
deleted file mode 100644
index af436bb..0000000
--- a/pyserial/serial/serialwin32.py
+++ /dev/null
@@ -1,383 +0,0 @@
-#! python
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# serial driver for win32
-# see __init__.py
-#
-# (C) 2001-2009 Chris Liechti <cliechti@gmx.net>
-# this is distributed under a free software license, see license.txt
-#
-# Initial patch to use ctypes by Giovanni Bajo <rasky@develer.com>
-
-import ctypes
-import win32
-
-from serialutil import *
-
-
-def device(portnum):
- """Turn a port number into a device name"""
- return 'COM%d' % (portnum+1) # numbers are transformed to a string
-
-
-class Win32Serial(SerialBase):
- """Serial port implementation for Win32 based on ctypes."""
-
- 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
- # the "\\.\COMx" format is required for devices other than COM1-COM8
- # not all versions of windows seem to support this properly
- # so that the first few ports are used with the DOS device name
- port = self.portstr
- try:
- if port.upper().startswith('COM') and int(port[3:]) > 8:
- port = '\\\\.\\' + port
- except ValueError:
- # for like COMnotanumber
- pass
- self.hComPort = win32.CreateFile(port,
- win32.GENERIC_READ | win32.GENERIC_WRITE,
- 0, # exclusive access
- None, # no security
- win32.OPEN_EXISTING,
- win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
- 0)
- if self.hComPort == win32.INVALID_HANDLE_VALUE:
- self.hComPort = None # 'cause __del__ is called anyway
- raise SerialException("could not open port %s: %s" % (self.portstr, ctypes.WinError()))
-
- # Setup a 4k buffer
- win32.SetupComm(self.hComPort, 4096, 4096)
-
- # Save original timeout values:
- self._orgTimeouts = win32.COMMTIMEOUTS()
- win32.GetCommTimeouts(self.hComPort, ctypes.byref(self._orgTimeouts))
-
- self._rtsState = win32.RTS_CONTROL_ENABLE
- self._dtrState = win32.DTR_CONTROL_ENABLE
-
- self._reconfigurePort()
-
- # Clear buffers:
- # Remove anything that was there
- win32.PurgeComm(self.hComPort,
- win32.PURGE_TXCLEAR | win32.PURGE_TXABORT |
- win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
-
- self._overlappedRead = win32.OVERLAPPED()
- self._overlappedRead.hEvent = win32.CreateEvent(None, 1, 0, None)
- self._overlappedWrite = win32.OVERLAPPED()
- #~ self._overlappedWrite.hEvent = win32.CreateEvent(None, 1, 0, None)
- self._overlappedWrite.hEvent = win32.CreateEvent(None, 0, 0, None)
- self._isOpen = True
-
- def _reconfigurePort(self):
- """Set communication 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 = (win32.MAXDWORD, 0, 0, 0, 0)
- else:
- timeouts = (0, 0, int(self._timeout*1000), 0, 0)
- if self._timeout != 0 and self._interCharTimeout is not None:
- timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
-
- if self._writeTimeout is None:
- pass
- elif self._writeTimeout == 0:
- timeouts = timeouts[:-2] + (0, win32.MAXDWORD)
- else:
- timeouts = timeouts[:-2] + (0, int(self._writeTimeout*1000))
- win32.SetCommTimeouts(self.hComPort, ctypes.byref(win32.COMMTIMEOUTS(*timeouts)))
-
- win32.SetCommMask(self.hComPort, win32.EV_ERR)
-
- # Setup the connection info.
- # Get state and modify it:
- comDCB = win32.DCB()
- win32.GetCommState(self.hComPort, ctypes.byref(comDCB))
- 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 = win32.NOPARITY
- comDCB.fParity = 0 # Disable Parity Check
- elif self._parity == PARITY_EVEN:
- comDCB.Parity = win32.EVENPARITY
- comDCB.fParity = 1 # Enable Parity Check
- elif self._parity == PARITY_ODD:
- comDCB.Parity = win32.ODDPARITY
- comDCB.fParity = 1 # Enable Parity Check
- elif self._parity == PARITY_MARK:
- comDCB.Parity = win32.MARKPARITY
- comDCB.fParity = 1 # Enable Parity Check
- elif self._parity == PARITY_SPACE:
- comDCB.Parity = win32.SPACEPARITY
- comDCB.fParity = 1 # Enable Parity Check
- else:
- raise ValueError("Unsupported parity mode: %r" % self._parity)
-
- if self._stopbits == STOPBITS_ONE:
- comDCB.StopBits = win32.ONESTOPBIT
- elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
- comDCB.StopBits = win32.ONE5STOPBITS
- elif self._stopbits == STOPBITS_TWO:
- comDCB.StopBits = win32.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 = win32.RTS_CONTROL_HANDSHAKE
- else:
- comDCB.fRtsControl = self._rtsState
- if self._dsrdtr:
- comDCB.fDtrControl = win32.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
-
- if not win32.SetCommState(self.hComPort, ctypes.byref(comDCB)):
- raise ValueError("Cannot configure port, some setting was wrong. Original message: %s" % ctypes.WinError())
-
- #~ def __del__(self):
- #~ self.close()
-
- def close(self):
- """Close port"""
- if self._isOpen:
- if self.hComPort:
- # Restore original timeout values:
- win32.SetCommTimeouts(self.hComPort, self._orgTimeouts)
- # Close COM-Port:
- win32.CloseHandle(self.hComPort)
- win32.CloseHandle(self._overlappedRead.hEvent)
- win32.CloseHandle(self._overlappedWrite.hEvent)
- 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 = win32.DWORD()
- comstat = win32.COMSTAT()
- if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
- raise SerialException('call to ClearCommError failed')
- 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:
- win32.ResetEvent(self._overlappedRead.hEvent)
- flags = win32.DWORD()
- comstat = win32.COMSTAT()
- if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
- raise SerialException('call to ClearCommError failed')
- if self.timeout == 0:
- n = min(comstat.cbInQue, size)
- if n > 0:
- buf = ctypes.create_string_buffer(n)
- rc = win32.DWORD()
- err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
- if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
- raise SerialException("ReadFile failed (%s)" % ctypes.WinError())
- err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE)
- read = buf.raw[:rc.value]
- else:
- read = bytes()
- else:
- buf = ctypes.create_string_buffer(size)
- rc = win32.DWORD()
- err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
- if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
- raise SerialException("ReadFile failed (%s)" % ctypes.WinError())
- err = win32.GetOverlappedResult(self.hComPort, ctypes.byref(self._overlappedRead), ctypes.byref(rc), True)
- read = buf.raw[:rc.value]
- else:
- read = bytes()
- return bytes(read)
-
- def write(self, data):
- """Output the given string over the serial port."""
- if not self.hComPort: raise portNotOpenError
- #~ if not isinstance(data, (bytes, bytearray)):
- #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
- # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
- data = bytes(data)
- if data:
- #~ win32event.ResetEvent(self._overlappedWrite.hEvent)
- n = win32.DWORD()
- err = win32.WriteFile(self.hComPort, data, len(data), ctypes.byref(n), self._overlappedWrite)
- if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
- raise SerialException("WriteFile failed (%s)" % ctypes.WinError())
- # Wait for the write to complete.
- #~ win32.WaitForSingleObject(self._overlappedWrite.hEvent, win32.INFINITE)
- err = win32.GetOverlappedResult(self.hComPort, self._overlappedWrite, ctypes.byref(n), True)
- if n.value != len(data):
- raise writeTimeoutError
- return n.value
- else:
- return 0
-
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self.hComPort: raise portNotOpenError
- win32.PurgeComm(self.hComPort, win32.PURGE_RXCLEAR | win32.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
- win32.PurgeComm(self.hComPort, win32.PURGE_TXCLEAR | win32.PURGE_TXABORT)
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given duration."""
- if not self.hComPort: raise portNotOpenError
- import time
- win32.SetCommBreak(self.hComPort)
- time.sleep(duration)
- win32.ClearCommBreak(self.hComPort)
-
- def setBreak(self, level=1):
- """Set break: Controls TXD. When active, to transmitting is possible."""
- if not self.hComPort: raise portNotOpenError
- if level:
- win32.SetCommBreak(self.hComPort)
- else:
- win32.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 = win32.RTS_CONTROL_ENABLE
- win32.EscapeCommFunction(self.hComPort, win32.SETRTS)
- else:
- self._rtsState = win32.RTS_CONTROL_DISABLE
- win32.EscapeCommFunction(self.hComPort, win32.CLRRTS)
-
- def setDTR(self, level=1):
- """Set terminal status line: Data Terminal Ready"""
- if not self.hComPort: raise portNotOpenError
- if level:
- self._dtrState = win32.DTR_CONTROL_ENABLE
- win32.EscapeCommFunction(self.hComPort, win32.SETDTR)
- else:
- self._dtrState = win32.DTR_CONTROL_DISABLE
- win32.EscapeCommFunction(self.hComPort, win32.CLRDTR)
-
- def _GetCommModemStatus(self):
- stat = win32.DWORD()
- win32.GetCommModemStatus(self.hComPort, ctypes.byref(stat))
- return stat.value
-
- def getCTS(self):
- """Read terminal status line: Clear To Send"""
- if not self.hComPort: raise portNotOpenError
- return win32.MS_CTS_ON & self._GetCommModemStatus() != 0
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready"""
- if not self.hComPort: raise portNotOpenError
- return win32.MS_DSR_ON & self._GetCommModemStatus() != 0
-
- def getRI(self):
- """Read terminal status line: Ring Indicator"""
- if not self.hComPort: raise portNotOpenError
- return win32.MS_RING_ON & self._GetCommModemStatus() != 0
-
- def getCD(self):
- """Read terminal status line: Carrier Detect"""
- if not self.hComPort: raise portNotOpenError
- return win32.MS_RLSD_ON & self._GetCommModemStatus() != 0
-
- # - - platform specific - - - -
-
- def setXON(self, level=True):
- """Platform specific - set flow state."""
- if not self.hComPort: raise portNotOpenError
- if level:
- win32.EscapeCommFunction(self.hComPort, win32.SETXON)
- else:
- win32.EscapeCommFunction(self.hComPort, win32.SETXOFF)
-
- def outWaiting(self):
- """return how many characters the in the outgoing buffer"""
- flags = win32.DWORD()
- comstat = win32.COMSTAT()
- if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
- raise SerialException('call to ClearCommError failed')
- return comstat.cbOutQue
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(Win32Serial, FileLike):
- pass
-else:
- # io library present
- class Serial(Win32Serial, io.RawIOBase):
- pass
-
-
-# Nur Testfunktion!!
-if __name__ == '__main__':
- s = Serial(0)
- sys.stdout.write("%s\n" % s)
-
- s = Serial()
- sys.stdout.write("%s\n" % s)
-
- s.baudrate = 19200
- s.databits = 7
- s.close()
- s.port = 0
- s.open()
- sys.stdout.write("%s\n" % s)
-
diff --git a/pyserial/serial/sermsdos.py b/pyserial/serial/sermsdos.py
deleted file mode 100644
index c3560d0..0000000
--- a/pyserial/serial/sermsdos.py
+++ /dev/null
@@ -1,200 +0,0 @@
-# sermsdos.py
-#
-# History:
-#
-# 3rd September 2002 Dave Haynes
-# 1. First defined
-#
-# Although this code should run under the latest versions of
-# Python, on DOS-based platforms such as Windows 95 and 98,
-# it has been specifically written to be compatible with
-# PyDOS, available at:
-# http://www.python.org/ftp/python/wpy/dos.html
-#
-# PyDOS is a stripped-down version of Python 1.5.2 for
-# DOS machines. Therefore, in making changes to this file,
-# please respect Python 1.5.2 syntax. In addition, please
-# limit the width of this file to 60 characters.
-#
-# Note also that the modules in PyDOS contain fewer members
-# than other versions, so we are restricted to using the
-# following:
-#
-# In module os:
-# -------------
-# environ, chdir, getcwd, getpid, umask, fdopen, close,
-# dup, dup2, fstat, lseek, open, read, write, O_RDONLY,
-# O_WRONLY, O_RDWR, O_APPEND, O_CREAT, O_EXCL, O_TRUNC,
-# access, F_OK, R_OK, W_OK, X_OK, chmod, listdir, mkdir,
-# remove, rename, renames, rmdir, stat, unlink, utime,
-# execl, execle, execlp, execlpe, execvp, execvpe, _exit,
-# system.
-#
-# In module os.path:
-# ------------------
-# curdir, pardir, sep, altsep, pathsep, defpath, linesep.
-#
-
-import os
-import sys
-import string
-import serialutil
-
-BAUD_RATES = {
- 110: "11",
- 150: "15",
- 300: "30",
- 600: "60",
- 1200: "12",
- 2400: "24",
- 4800: "48",
- 9600: "96",
- 19200: "19"}
-
-(PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK,
-PARITY_SPACE) = (0, 1, 2, 3, 4)
-(STOPBITS_ONE, STOPBITS_ONEANDAHALF,
-STOPBITS_TWO) = (1, 1.5, 2)
-FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
-(RETURN_ERROR, RETURN_BUSY, RETURN_RETRY, RETURN_READY,
-RETURN_NONE) = ('E', 'B', 'P', 'R', 'N')
-portNotOpenError = ValueError('port not open')
-
-def device(portnum):
- return 'COM%d' % (portnum+1)
-
-class Serial(serialutil.FileLike):
- """
- port: number of device; numbering starts at
- zero. if everything fails, the user can
- specify a device string, note that this
- isn't portable any more
- baudrate: baud rate
- bytesize: number of databits
- parity: enable parity checking
- stopbits: number of stopbits
- timeout: set a timeout (None for waiting forever)
- xonxoff: enable software flow control
- rtscts: enable RTS/CTS flow control
- retry: DOS retry mode
- """
- def __init__(self,
- port,
- baudrate = 9600,
- bytesize = EIGHTBITS,
- parity = PARITY_NONE,
- stopbits = STOPBITS_ONE,
- timeout = None,
- xonxoff = 0,
- rtscts = 0,
- retry = RETURN_RETRY
- ):
-
- if type(port) == type(''):
- # strings are taken directly
- self.portstr = port
- else:
- # numbers are transformed to a string
- self.portstr = device(port+1)
-
- self.baud = BAUD_RATES[baudrate]
- self.bytesize = str(bytesize)
-
- if parity == PARITY_NONE:
- self.parity = 'N'
- elif parity == PARITY_EVEN:
- self.parity = 'E'
- elif parity == PARITY_ODD:
- self.parity = 'O'
- elif parity == PARITY_MARK:
- self.parity = 'M'
- elif parity == PARITY_SPACE:
- self.parity = 'S'
-
- self.stop = str(stopbits)
- self.retry = retry
- self.filename = "sermsdos.tmp"
-
- self._config(self.portstr, self.baud, self.parity,
- self.bytesize, self.stop, self.retry, self.filename)
-
- def __del__(self):
- self.close()
-
- def close(self):
- pass
-
- def _config(self, port, baud, parity, data, stop, retry,
- filename):
- comString = string.join(("MODE ", port, ":"
- , " BAUD= ", baud, " PARITY= ", parity
- , " DATA= ", data, " STOP= ", stop, " RETRY= ",
- retry, " > ", filename ), '')
- os.system(comString)
-
- def setBaudrate(self, baudrate):
- self._config(self.portstr, BAUD_RATES[baudrate],
- self.parity, self.bytesize, self.stop, self.retry,
- self.filename)
-
- def inWaiting(self):
- """returns the number of bytes waiting to be read"""
- raise NotImplementedError
-
- def read(self, num = 1):
- """Read num bytes from serial port"""
- handle = os.open(self.portstr,
- os.O_RDONLY | os.O_BINARY)
- rv = os.read(handle, num)
- os.close(handle)
- return rv
-
- def write(self, s):
- """Write string to serial port"""
- handle = os.open(self.portstr,
- os.O_WRONLY | os.O_BINARY)
- rv = os.write(handle, s)
- os.close(handle)
- return rv
-
- def flushInput(self):
- raise NotImplementedError
-
- def flushOutput(self):
- raise NotImplementedError
-
- def sendBreak(self):
- raise NotImplementedError
-
- def setRTS(self,level=1):
- """Set terminal status line"""
- raise NotImplementedError
-
- def setDTR(self,level=1):
- """Set terminal status line"""
- raise NotImplementedError
-
- def getCTS(self):
- """Eead terminal status line"""
- raise NotImplementedError
-
- def getDSR(self):
- """Eead terminal status line"""
- raise NotImplementedError
-
- def getRI(self):
- """Eead terminal status line"""
- raise NotImplementedError
-
- def getCD(self):
- """Eead terminal status line"""
- raise NotImplementedError
-
- def __repr__(self):
- return string.join(( "<Serial>: ", self.portstr
- , self.baud, self.parity, self.bytesize, self.stop,
- self.retry , self.filename), ' ')
-
-if __name__ == '__main__':
- s = Serial(0)
- sys.stdio.write('%s %s\n' % (__name__, s))
diff --git a/pyserial/serial/win32.py b/pyserial/serial/win32.py
deleted file mode 100644
index 9b8c118..0000000
--- a/pyserial/serial/win32.py
+++ /dev/null
@@ -1,288 +0,0 @@
-from ctypes import *
-from ctypes.wintypes import HANDLE
-from ctypes.wintypes import BOOL
-from ctypes.wintypes import LPCWSTR
-_stdcall_libraries = {}
-_stdcall_libraries['kernel32'] = WinDLL('kernel32')
-from ctypes.wintypes import DWORD
-from ctypes.wintypes import WORD
-from ctypes.wintypes import BYTE
-
-INVALID_HANDLE_VALUE = HANDLE(-1).value
-
-class _SECURITY_ATTRIBUTES(Structure):
- pass
-LPSECURITY_ATTRIBUTES = POINTER(_SECURITY_ATTRIBUTES)
-
-CreateEventW = _stdcall_libraries['kernel32'].CreateEventW
-CreateEventW.restype = HANDLE
-CreateEventW.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR]
-CreateEvent = CreateEventW # alias
-
-CreateFileW = _stdcall_libraries['kernel32'].CreateFileW
-CreateFileW.restype = HANDLE
-CreateFileW.argtypes = [LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE]
-CreateFile = CreateFileW # alias
-
-class _OVERLAPPED(Structure):
- pass
-OVERLAPPED = _OVERLAPPED
-
-class _COMSTAT(Structure):
- pass
-COMSTAT = _COMSTAT
-
-class _DCB(Structure):
- pass
-DCB = _DCB
-
-class _COMMTIMEOUTS(Structure):
- pass
-COMMTIMEOUTS = _COMMTIMEOUTS
-
-GetLastError = _stdcall_libraries['kernel32'].GetLastError
-GetLastError.restype = DWORD
-GetLastError.argtypes = []
-
-LPOVERLAPPED = POINTER(_OVERLAPPED)
-LPDWORD = POINTER(DWORD)
-
-GetOverlappedResult = _stdcall_libraries['kernel32'].GetOverlappedResult
-GetOverlappedResult.restype = BOOL
-GetOverlappedResult.argtypes = [HANDLE, LPOVERLAPPED, LPDWORD, BOOL]
-
-ResetEvent = _stdcall_libraries['kernel32'].ResetEvent
-ResetEvent.restype = BOOL
-ResetEvent.argtypes = [HANDLE]
-
-LPCVOID = c_void_p
-
-WriteFile = _stdcall_libraries['kernel32'].WriteFile
-WriteFile.restype = BOOL
-WriteFile.argtypes = [HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED]
-
-LPVOID = c_void_p
-
-ReadFile = _stdcall_libraries['kernel32'].ReadFile
-ReadFile.restype = BOOL
-ReadFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED]
-
-CloseHandle = _stdcall_libraries['kernel32'].CloseHandle
-CloseHandle.restype = BOOL
-CloseHandle.argtypes = [HANDLE]
-
-ClearCommBreak = _stdcall_libraries['kernel32'].ClearCommBreak
-ClearCommBreak.restype = BOOL
-ClearCommBreak.argtypes = [HANDLE]
-
-LPCOMSTAT = POINTER(_COMSTAT)
-
-ClearCommError = _stdcall_libraries['kernel32'].ClearCommError
-ClearCommError.restype = BOOL
-ClearCommError.argtypes = [HANDLE, LPDWORD, LPCOMSTAT]
-
-SetupComm = _stdcall_libraries['kernel32'].SetupComm
-SetupComm.restype = BOOL
-SetupComm.argtypes = [HANDLE, DWORD, DWORD]
-
-EscapeCommFunction = _stdcall_libraries['kernel32'].EscapeCommFunction
-EscapeCommFunction.restype = BOOL
-EscapeCommFunction.argtypes = [HANDLE, DWORD]
-
-GetCommModemStatus = _stdcall_libraries['kernel32'].GetCommModemStatus
-GetCommModemStatus.restype = BOOL
-GetCommModemStatus.argtypes = [HANDLE, LPDWORD]
-
-LPDCB = POINTER(_DCB)
-
-GetCommState = _stdcall_libraries['kernel32'].GetCommState
-GetCommState.restype = BOOL
-GetCommState.argtypes = [HANDLE, LPDCB]
-
-LPCOMMTIMEOUTS = POINTER(_COMMTIMEOUTS)
-
-GetCommTimeouts = _stdcall_libraries['kernel32'].GetCommTimeouts
-GetCommTimeouts.restype = BOOL
-GetCommTimeouts.argtypes = [HANDLE, LPCOMMTIMEOUTS]
-
-PurgeComm = _stdcall_libraries['kernel32'].PurgeComm
-PurgeComm.restype = BOOL
-PurgeComm.argtypes = [HANDLE, DWORD]
-
-SetCommBreak = _stdcall_libraries['kernel32'].SetCommBreak
-SetCommBreak.restype = BOOL
-SetCommBreak.argtypes = [HANDLE]
-
-SetCommMask = _stdcall_libraries['kernel32'].SetCommMask
-SetCommMask.restype = BOOL
-SetCommMask.argtypes = [HANDLE, DWORD]
-
-SetCommState = _stdcall_libraries['kernel32'].SetCommState
-SetCommState.restype = BOOL
-SetCommState.argtypes = [HANDLE, LPDCB]
-
-SetCommTimeouts = _stdcall_libraries['kernel32'].SetCommTimeouts
-SetCommTimeouts.restype = BOOL
-SetCommTimeouts.argtypes = [HANDLE, LPCOMMTIMEOUTS]
-
-WaitForSingleObject = _stdcall_libraries['kernel32'].WaitForSingleObject
-WaitForSingleObject.restype = DWORD
-WaitForSingleObject.argtypes = [HANDLE, DWORD]
-
-ONESTOPBIT = 0 # Variable c_int
-TWOSTOPBITS = 2 # Variable c_int
-ONE5STOPBITS = 1
-
-NOPARITY = 0 # Variable c_int
-ODDPARITY = 1 # Variable c_int
-EVENPARITY = 2 # Variable c_int
-MARKPARITY = 3
-SPACEPARITY = 4
-
-RTS_CONTROL_HANDSHAKE = 2 # Variable c_int
-RTS_CONTROL_DISABLE = 0 # Variable c_int
-RTS_CONTROL_ENABLE = 1 # Variable c_int
-SETRTS = 3
-CLRRTS = 4
-
-DTR_CONTROL_HANDSHAKE = 2 # Variable c_int
-DTR_CONTROL_DISABLE = 0 # Variable c_int
-DTR_CONTROL_ENABLE = 1 # Variable c_int
-SETDTR = 5
-CLRDTR = 6
-
-MS_DSR_ON = 32 # Variable c_ulong
-EV_RING = 256 # Variable c_int
-EV_PERR = 512 # Variable c_int
-EV_ERR = 128 # Variable c_int
-SETXOFF = 1 # Variable c_int
-EV_RXCHAR = 1 # Variable c_int
-GENERIC_WRITE = 1073741824 # Variable c_long
-PURGE_TXCLEAR = 4 # Variable c_int
-FILE_FLAG_OVERLAPPED = 1073741824 # Variable c_int
-EV_DSR = 16 # Variable c_int
-MAXDWORD = 4294967295L # Variable c_uint
-EV_RLSD = 32 # Variable c_int
-ERROR_IO_PENDING = 997 # Variable c_long
-MS_CTS_ON = 16 # Variable c_ulong
-EV_EVENT1 = 2048 # Variable c_int
-EV_RX80FULL = 1024 # Variable c_int
-PURGE_RXABORT = 2 # Variable c_int
-FILE_ATTRIBUTE_NORMAL = 128 # Variable c_int
-PURGE_TXABORT = 1 # Variable c_int
-SETXON = 2 # Variable c_int
-OPEN_EXISTING = 3 # Variable c_int
-MS_RING_ON = 64 # Variable c_ulong
-EV_TXEMPTY = 4 # Variable c_int
-EV_RXFLAG = 2 # Variable c_int
-MS_RLSD_ON = 128 # Variable c_ulong
-GENERIC_READ = 2147483648L # Variable c_ulong
-EV_EVENT2 = 4096 # Variable c_int
-EV_CTS = 8 # Variable c_int
-EV_BREAK = 64 # Variable c_int
-PURGE_RXCLEAR = 8 # Variable c_int
-ULONG_PTR = c_ulong
-INFINITE = 0xFFFFFFFFL
-
-class N11_OVERLAPPED4DOLLAR_48E(Union):
- pass
-class N11_OVERLAPPED4DOLLAR_484DOLLAR_49E(Structure):
- pass
-N11_OVERLAPPED4DOLLAR_484DOLLAR_49E._fields_ = [
- ('Offset', DWORD),
- ('OffsetHigh', DWORD),
-]
-
-PVOID = c_void_p
-
-N11_OVERLAPPED4DOLLAR_48E._anonymous_ = ['_0']
-N11_OVERLAPPED4DOLLAR_48E._fields_ = [
- ('_0', N11_OVERLAPPED4DOLLAR_484DOLLAR_49E),
- ('Pointer', PVOID),
-]
-_OVERLAPPED._anonymous_ = ['_0']
-_OVERLAPPED._fields_ = [
- ('Internal', ULONG_PTR),
- ('InternalHigh', ULONG_PTR),
- ('_0', N11_OVERLAPPED4DOLLAR_48E),
- ('hEvent', HANDLE),
-]
-_SECURITY_ATTRIBUTES._fields_ = [
- ('nLength', DWORD),
- ('lpSecurityDescriptor', LPVOID),
- ('bInheritHandle', BOOL),
-]
-_COMSTAT._fields_ = [
- ('fCtsHold', DWORD, 1),
- ('fDsrHold', DWORD, 1),
- ('fRlsdHold', DWORD, 1),
- ('fXoffHold', DWORD, 1),
- ('fXoffSent', DWORD, 1),
- ('fEof', DWORD, 1),
- ('fTxim', DWORD, 1),
- ('fReserved', DWORD, 25),
- ('cbInQue', DWORD),
- ('cbOutQue', DWORD),
-]
-_DCB._fields_ = [
- ('DCBlength', DWORD),
- ('BaudRate', DWORD),
- ('fBinary', DWORD, 1),
- ('fParity', DWORD, 1),
- ('fOutxCtsFlow', DWORD, 1),
- ('fOutxDsrFlow', DWORD, 1),
- ('fDtrControl', DWORD, 2),
- ('fDsrSensitivity', DWORD, 1),
- ('fTXContinueOnXoff', DWORD, 1),
- ('fOutX', DWORD, 1),
- ('fInX', DWORD, 1),
- ('fErrorChar', DWORD, 1),
- ('fNull', DWORD, 1),
- ('fRtsControl', DWORD, 2),
- ('fAbortOnError', DWORD, 1),
- ('fDummy2', DWORD, 17),
- ('wReserved', WORD),
- ('XonLim', WORD),
- ('XoffLim', WORD),
- ('ByteSize', BYTE),
- ('Parity', BYTE),
- ('StopBits', BYTE),
- ('XonChar', c_char),
- ('XoffChar', c_char),
- ('ErrorChar', c_char),
- ('EofChar', c_char),
- ('EvtChar', c_char),
- ('wReserved1', WORD),
-]
-_COMMTIMEOUTS._fields_ = [
- ('ReadIntervalTimeout', DWORD),
- ('ReadTotalTimeoutMultiplier', DWORD),
- ('ReadTotalTimeoutConstant', DWORD),
- ('WriteTotalTimeoutMultiplier', DWORD),
- ('WriteTotalTimeoutConstant', DWORD),
-]
-__all__ = ['GetLastError', 'MS_CTS_ON', 'FILE_ATTRIBUTE_NORMAL',
- 'DTR_CONTROL_ENABLE', '_COMSTAT', 'MS_RLSD_ON',
- 'GetOverlappedResult', 'SETXON', 'PURGE_TXABORT',
- 'PurgeComm', 'N11_OVERLAPPED4DOLLAR_48E', 'EV_RING',
- 'ONESTOPBIT', 'SETXOFF', 'PURGE_RXABORT', 'GetCommState',
- 'RTS_CONTROL_ENABLE', '_DCB', 'CreateEvent',
- '_COMMTIMEOUTS', '_SECURITY_ATTRIBUTES', 'EV_DSR',
- 'EV_PERR', 'EV_RXFLAG', 'OPEN_EXISTING', 'DCB',
- 'FILE_FLAG_OVERLAPPED', 'EV_CTS', 'SetupComm',
- 'LPOVERLAPPED', 'EV_TXEMPTY', 'ClearCommBreak',
- 'LPSECURITY_ATTRIBUTES', 'SetCommBreak', 'SetCommTimeouts',
- 'COMMTIMEOUTS', 'ODDPARITY', 'EV_RLSD',
- 'GetCommModemStatus', 'EV_EVENT2', 'PURGE_TXCLEAR',
- 'EV_BREAK', 'EVENPARITY', 'LPCVOID', 'COMSTAT', 'ReadFile',
- 'PVOID', '_OVERLAPPED', 'WriteFile', 'GetCommTimeouts',
- 'ResetEvent', 'EV_RXCHAR', 'LPCOMSTAT', 'ClearCommError',
- 'ERROR_IO_PENDING', 'EscapeCommFunction', 'GENERIC_READ',
- 'RTS_CONTROL_HANDSHAKE', 'OVERLAPPED',
- 'DTR_CONTROL_HANDSHAKE', 'PURGE_RXCLEAR', 'GENERIC_WRITE',
- 'LPDCB', 'CreateEventW', 'SetCommMask', 'EV_EVENT1',
- 'SetCommState', 'LPVOID', 'CreateFileW', 'LPDWORD',
- 'EV_RX80FULL', 'TWOSTOPBITS', 'LPCOMMTIMEOUTS', 'MAXDWORD',
- 'MS_DSR_ON', 'MS_RING_ON',
- 'N11_OVERLAPPED4DOLLAR_484DOLLAR_49E', 'EV_ERR',
- 'ULONG_PTR', 'CreateFile', 'NOPARITY', 'CloseHandle']
diff --git a/pyserial/setup.py b/pyserial/setup.py
deleted file mode 100644
index b4a2fba..0000000
--- a/pyserial/setup.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# setup.py for pyserial
-#
-# windows installer:
-# python setup.py bdist_wininst
-
-import sys
-
-from distutils.core import setup
-
-try:
- from distutils.command.build_py import build_py_2to3 as build_py
-except ImportError:
- if sys.version_info >= (3, 0):
- raise ImportError("build_py_2to3 not found in distutils - it is required for Python 3.x")
- from distutils.command.build_py import build_py
- suffix = ""
-else:
- suffix = "-py3k"
-
-
-if sys.version < '2.3':
- # distutils that old can't cope with the "classifiers" or "download_url"
- # keywords and True/False constants and basestring are missing
- raise ValueError("Sorry Python versions older than 2.3 are no longer"
- "supported - check http://pyserial.sf.net for older "
- "releases or upgrade your Python installation.")
-
-setup(
- name = "pyserial" + suffix,
- description = "Python Serial Port Extension",
- version = "2.5-rc1",
- 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, IronPython",
- 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',
- #~ 'Operating System :: Microsoft :: Windows :: Windows CE', # could work due to new ctypes impl. someone needs to confirm that
- 'Programming Language :: Python',
- 'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.3',
- 'Programming Language :: Python :: 2.4',
- 'Programming Language :: Python :: 2.5',
- 'Programming Language :: Python :: 2.6',
- 'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.0',
- 'Programming Language :: Python :: 3.1',
- 'Topic :: Communications',
- 'Topic :: Software Development :: Libraries',
- 'Topic :: Software Development :: Libraries :: Python Modules',
- 'Topic :: Terminals :: Serial',
- ],
- platforms = 'any',
- cmdclass = {'build_py': build_py},
-
- scripts = ['examples/miniterm.py'],
-)