summaryrefslogtreecommitdiff
path: root/serial/tools
diff options
context:
space:
mode:
Diffstat (limited to 'serial/tools')
-rw-r--r--serial/tools/__init__.py0
-rw-r--r--serial/tools/list_ports.py103
-rw-r--r--serial/tools/list_ports_linux.py143
-rw-r--r--serial/tools/list_ports_osx.py208
-rw-r--r--serial/tools/list_ports_posix.py101
-rw-r--r--serial/tools/list_ports_windows.py240
-rw-r--r--serial/tools/miniterm.py694
7 files changed, 1489 insertions, 0 deletions
diff --git a/serial/tools/__init__.py b/serial/tools/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/serial/tools/__init__.py
diff --git a/serial/tools/list_ports.py b/serial/tools/list_ports.py
new file mode 100644
index 0000000..d373a55
--- /dev/null
+++ b/serial/tools/list_ports.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python
+
+# portable serial port access with python
+# this is a wrapper module for different platform implementations of the
+# port enumeration feature
+#
+# (C) 2011-2013 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+"""\
+This module will provide a function called comports that returns an
+iterable (generator or list) that will enumerate available com ports. Note that
+on some systems non-existent ports may be listed.
+
+Additionally a grep function is supplied that can be used to search for ports
+based on their descriptions or hardware ID.
+"""
+
+import sys, os, re
+
+# chose an implementation, depending on os
+#~ if sys.platform == 'cli':
+#~ else:
+import os
+# chose an implementation, depending on os
+if os.name == 'nt': #sys.platform == 'win32':
+ from serial.tools.list_ports_windows import *
+elif os.name == 'posix':
+ from serial.tools.list_ports_posix import *
+#~ elif os.name == 'java':
+else:
+ raise ImportError("Sorry: no implementation for your platform ('%s') available" % (os.name,))
+
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+def grep(regexp):
+ """\
+ Search for ports using a regular expression. Port name, description and
+ hardware ID are searched. The function returns an iterable that returns the
+ same tuples as comport() would do.
+ """
+ r = re.compile(regexp, re.I)
+ for port, desc, hwid in comports():
+ if r.search(port) or r.search(desc) or r.search(hwid):
+ yield port, desc, hwid
+
+
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+def main():
+ import optparse
+
+ parser = optparse.OptionParser(
+ usage = "%prog [options] [<regexp>]",
+ description = "Miniterm - A simple terminal program for the serial port."
+ )
+
+ parser.add_option("--debug",
+ help="print debug messages and tracebacks (development mode)",
+ dest="debug",
+ default=False,
+ action='store_true')
+
+ parser.add_option("-v", "--verbose",
+ help="show more messages (can be given multiple times)",
+ dest="verbose",
+ default=1,
+ action='count')
+
+ parser.add_option("-q", "--quiet",
+ help="suppress all messages",
+ dest="verbose",
+ action='store_const',
+ const=0)
+
+ (options, args) = parser.parse_args()
+
+
+ hits = 0
+ # get iteraror w/ or w/o filter
+ if args:
+ if len(args) > 1:
+ parser.error('more than one regexp not supported')
+ print "Filtered list with regexp: %r" % (args[0],)
+ iterator = sorted(grep(args[0]))
+ else:
+ iterator = sorted(comports())
+ # list them
+ for port, desc, hwid in iterator:
+ print("%-20s" % (port,))
+ if options.verbose > 1:
+ print(" desc: %s" % (desc,))
+ print(" hwid: %s" % (hwid,))
+ hits += 1
+ if options.verbose:
+ if hits:
+ print("%d ports found" % (hits,))
+ else:
+ print("no ports found")
+
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+# test
+if __name__ == '__main__':
+ main()
diff --git a/serial/tools/list_ports_linux.py b/serial/tools/list_ports_linux.py
new file mode 100644
index 0000000..0a23e09
--- /dev/null
+++ b/serial/tools/list_ports_linux.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python
+
+# portable serial port access with python
+#
+# This is a module that gathers a list of serial ports including details on
+# GNU/Linux systems
+#
+# (C) 2011-2013 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+import glob
+import sys
+import os
+import re
+
+try:
+ import subprocess
+except ImportError:
+ def popen(argv):
+ try:
+ si, so = os.popen4(' '.join(argv))
+ return so.read().strip()
+ except:
+ raise IOError('lsusb failed')
+else:
+ def popen(argv):
+ try:
+ return subprocess.check_output(argv, stderr=subprocess.STDOUT).strip()
+ except:
+ raise IOError('lsusb failed')
+
+
+# The comports function is expected to return an iterable that yields tuples of
+# 3 strings: port name, human readable description and a hardware ID.
+#
+# as currently no method is known to get the second two strings easily, they
+# are currently just identical to the port name.
+
+# try to detect the OS so that a device can be selected...
+plat = sys.platform.lower()
+
+def read_line(filename):
+ """help function to read a single line from a file. returns none"""
+ try:
+ f = open(filename)
+ line = f.readline().strip()
+ f.close()
+ return line
+ except IOError:
+ return None
+
+def re_group(regexp, text):
+ """search for regexp in text, return 1st group on match"""
+ if sys.version < '3':
+ m = re.search(regexp, text)
+ else:
+ # text is bytes-like
+ m = re.search(regexp, text.decode('ascii', 'replace'))
+ if m: return m.group(1)
+
+
+# try to extract descriptions from sysfs. this was done by experimenting,
+# no guarantee that it works for all devices or in the future...
+
+def usb_sysfs_hw_string(sysfs_path):
+ """given a path to a usb device in sysfs, return a string describing it"""
+ bus, dev = os.path.basename(os.path.realpath(sysfs_path)).split('-')
+ snr = read_line(sysfs_path+'/serial')
+ if snr:
+ snr_txt = ' SNR=%s' % (snr,)
+ else:
+ snr_txt = ''
+ return 'USB VID:PID=%s:%s%s' % (
+ read_line(sysfs_path+'/idVendor'),
+ read_line(sysfs_path+'/idProduct'),
+ snr_txt
+ )
+
+def usb_lsusb_string(sysfs_path):
+ base = os.path.basename(os.path.realpath(sysfs_path))
+ bus = base.split('-')[0]
+ try:
+ dev = int(read_line(os.path.join(sysfs_path, 'devnum')))
+ desc = popen(['lsusb', '-v', '-s', '%s:%s' % (bus, dev)])
+ # descriptions from device
+ iManufacturer = re_group('iManufacturer\s+\w+ (.+)', desc)
+ iProduct = re_group('iProduct\s+\w+ (.+)', desc)
+ iSerial = re_group('iSerial\s+\w+ (.+)', desc) or ''
+ # descriptions from kernel
+ idVendor = re_group('idVendor\s+0x\w+ (.+)', desc)
+ idProduct = re_group('idProduct\s+0x\w+ (.+)', desc)
+ # create descriptions. prefer text from device, fall back to the others
+ return '%s %s %s' % (iManufacturer or idVendor, iProduct or idProduct, iSerial)
+ except IOError:
+ return base
+
+def describe(device):
+ """\
+ Get a human readable description.
+ For USB-Serial devices try to run lsusb to get a human readable description.
+ For USB-CDC devices read the description from sysfs.
+ """
+ base = os.path.basename(device)
+ # USB-Serial devices
+ sys_dev_path = '/sys/class/tty/%s/device/driver/%s' % (base, base)
+ if os.path.exists(sys_dev_path):
+ sys_usb = os.path.dirname(os.path.dirname(os.path.realpath(sys_dev_path)))
+ return usb_lsusb_string(sys_usb)
+ # USB-CDC devices
+ sys_dev_path = '/sys/class/tty/%s/device/interface' % (base,)
+ if os.path.exists(sys_dev_path):
+ return read_line(sys_dev_path)
+ return base
+
+def hwinfo(device):
+ """Try to get a HW identification using sysfs"""
+ base = os.path.basename(device)
+ if os.path.exists('/sys/class/tty/%s/device' % (base,)):
+ # PCI based devices
+ sys_id_path = '/sys/class/tty/%s/device/id' % (base,)
+ if os.path.exists(sys_id_path):
+ return read_line(sys_id_path)
+ # USB-Serial devices
+ sys_dev_path = '/sys/class/tty/%s/device/driver/%s' % (base, base)
+ if os.path.exists(sys_dev_path):
+ sys_usb = os.path.dirname(os.path.dirname(os.path.realpath(sys_dev_path)))
+ return usb_sysfs_hw_string(sys_usb)
+ # USB-CDC devices
+ if base.startswith('ttyACM'):
+ sys_dev_path = '/sys/class/tty/%s/device' % (base,)
+ if os.path.exists(sys_dev_path):
+ return usb_sysfs_hw_string(sys_dev_path + '/..')
+ return 'n/a' # XXX directly remove these from the list?
+
+def comports():
+ devices = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*')
+ return [(d, describe(d), hwinfo(d)) for d in devices]
+
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+# test
+if __name__ == '__main__':
+ for port, desc, hwid in sorted(comports()):
+ print "%s: %s [%s]" % (port, desc, hwid)
diff --git a/serial/tools/list_ports_osx.py b/serial/tools/list_ports_osx.py
new file mode 100644
index 0000000..c9ed615
--- /dev/null
+++ b/serial/tools/list_ports_osx.py
@@ -0,0 +1,208 @@
+#!/usr/bin/env python
+
+# portable serial port access with python
+#
+# This is a module that gathers a list of serial ports including details on OSX
+#
+# code originally from https://github.com/makerbot/pyserial/tree/master/serial/tools
+# with contributions from cibomahto, dgs3, FarMcKon, tedbrandston
+# and modifications by cliechti
+#
+# this is distributed under a free software license, see license.txt
+
+
+
+# List all of the callout devices in OS/X by querying IOKit.
+
+# See the following for a reference of how to do this:
+# http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/WorkingWSerial/WWSerial_SerialDevs/SerialDevices.html#//apple_ref/doc/uid/TP30000384-CIHGEAFD
+
+# More help from darwin_hid.py
+
+# Also see the 'IORegistryExplorer' for an idea of what we are actually searching
+
+import ctypes
+from ctypes import util
+import re
+
+iokit = ctypes.cdll.LoadLibrary(ctypes.util.find_library('IOKit'))
+cf = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))
+
+kIOMasterPortDefault = ctypes.c_void_p.in_dll(iokit, "kIOMasterPortDefault")
+kCFAllocatorDefault = ctypes.c_void_p.in_dll(cf, "kCFAllocatorDefault")
+
+kCFStringEncodingMacRoman = 0
+
+iokit.IOServiceMatching.restype = ctypes.c_void_p
+
+iokit.IOServiceGetMatchingServices.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
+iokit.IOServiceGetMatchingServices.restype = ctypes.c_void_p
+
+iokit.IORegistryEntryGetParentEntry.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
+
+iokit.IORegistryEntryCreateCFProperty.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32]
+iokit.IORegistryEntryCreateCFProperty.restype = ctypes.c_void_p
+
+iokit.IORegistryEntryGetPath.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
+iokit.IORegistryEntryGetPath.restype = ctypes.c_void_p
+
+iokit.IORegistryEntryGetName.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+iokit.IORegistryEntryGetName.restype = ctypes.c_void_p
+
+iokit.IOObjectGetClass.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+iokit.IOObjectGetClass.restype = ctypes.c_void_p
+
+iokit.IOObjectRelease.argtypes = [ctypes.c_void_p]
+
+
+cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int32]
+cf.CFStringCreateWithCString.restype = ctypes.c_void_p
+
+cf.CFStringGetCStringPtr.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
+cf.CFStringGetCStringPtr.restype = ctypes.c_char_p
+
+cf.CFNumberGetValue.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p]
+cf.CFNumberGetValue.restype = ctypes.c_void_p
+
+def get_string_property(device_t, property):
+ """ Search the given device for the specified string property
+
+ @param device_t Device to search
+ @param property String to search for.
+ @return Python string containing the value, or None if not found.
+ """
+ key = cf.CFStringCreateWithCString(
+ kCFAllocatorDefault,
+ property.encode("mac_roman"),
+ kCFStringEncodingMacRoman
+ )
+
+ CFContainer = iokit.IORegistryEntryCreateCFProperty(
+ device_t,
+ key,
+ kCFAllocatorDefault,
+ 0
+ );
+
+ output = None
+
+ if CFContainer:
+ output = cf.CFStringGetCStringPtr(CFContainer, 0)
+
+ return output
+
+def get_int_property(device_t, property):
+ """ Search the given device for the specified string property
+
+ @param device_t Device to search
+ @param property String to search for.
+ @return Python string containing the value, or None if not found.
+ """
+ key = cf.CFStringCreateWithCString(
+ kCFAllocatorDefault,
+ property.encode("mac_roman"),
+ kCFStringEncodingMacRoman
+ )
+
+ CFContainer = iokit.IORegistryEntryCreateCFProperty(
+ device_t,
+ key,
+ kCFAllocatorDefault,
+ 0
+ );
+
+ number = ctypes.c_uint16()
+
+ if CFContainer:
+ output = cf.CFNumberGetValue(CFContainer, 2, ctypes.byref(number))
+
+ return number.value
+
+def IORegistryEntryGetName(device):
+ pathname = ctypes.create_string_buffer(100) # TODO: Is this ok?
+ iokit.IOObjectGetClass(
+ device,
+ ctypes.byref(pathname)
+ )
+
+ return pathname.value
+
+def GetParentDeviceByType(device, parent_type):
+ """ Find the first parent of a device that implements the parent_type
+ @param IOService Service to inspect
+ @return Pointer to the parent type, or None if it was not found.
+ """
+ # First, try to walk up the IOService tree to find a parent of this device that is a IOUSBDevice.
+ while IORegistryEntryGetName(device) != parent_type:
+ parent = ctypes.c_void_p()
+ response = iokit.IORegistryEntryGetParentEntry(
+ device,
+ "IOService".encode("mac_roman"),
+ ctypes.byref(parent)
+ )
+
+ # If we weren't able to find a parent for the device, we're done.
+ if response != 0:
+ return None
+
+ device = parent
+
+ return device
+
+def GetIOServicesByType(service_type):
+ """
+ """
+ serial_port_iterator = ctypes.c_void_p()
+
+ response = iokit.IOServiceGetMatchingServices(
+ kIOMasterPortDefault,
+ iokit.IOServiceMatching(service_type),
+ ctypes.byref(serial_port_iterator)
+ )
+
+ services = []
+ while iokit.IOIteratorIsValid(serial_port_iterator):
+ service = iokit.IOIteratorNext(serial_port_iterator)
+ if not service:
+ break
+ services.append(service)
+
+ iokit.IOObjectRelease(serial_port_iterator)
+
+ return services
+
+def comports():
+ # Scan for all iokit serial ports
+ services = GetIOServicesByType('IOSerialBSDClient')
+
+ ports = []
+ for service in services:
+ info = []
+
+ # First, add the callout device file.
+ info.append(get_string_property(service, "IOCalloutDevice"))
+
+ # If the serial port is implemented by a
+ usb_device = GetParentDeviceByType(service, "IOUSBDevice")
+ if usb_device != None:
+ info.append(get_string_property(usb_device, "USB Product Name"))
+
+ info.append(
+ "USB VID:PID=%x:%x SNR=%s"%(
+ get_int_property(usb_device, "idVendor"),
+ get_int_property(usb_device, "idProduct"),
+ get_string_property(usb_device, "USB Serial Number"))
+ )
+ else:
+ info.append('n/a')
+ info.append('n/a')
+
+ ports.append(info)
+
+ return ports
+
+# test
+if __name__ == '__main__':
+ for port, desc, hwid in sorted(comports()):
+ print "%s: %s [%s]" % (port, desc, hwid)
+
diff --git a/serial/tools/list_ports_posix.py b/serial/tools/list_ports_posix.py
new file mode 100644
index 0000000..9d96e93
--- /dev/null
+++ b/serial/tools/list_ports_posix.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python
+
+# portable serial port access with python
+
+# This is a module that gathers a list of serial ports on POSIXy systems.
+# For some specific implementations, see also list_ports_linux, list_ports_osx
+#
+# this is a wrapper module for different platform implementations of the
+# port enumeration feature
+#
+# (C) 2011-2013 Chris Liechti <cliechti@gmx.net>
+# this is distributed under a free software license, see license.txt
+
+"""\
+The ``comports`` function is expected to return an iterable that yields tuples
+of 3 strings: port name, human readable description and a hardware ID.
+
+As currently no method is known to get the second two strings easily, they are
+currently just identical to the port name.
+"""
+
+import glob
+import sys
+import os
+
+# try to detect the OS so that a device can be selected...
+plat = sys.platform.lower()
+
+if plat[:5] == 'linux': # Linux (confirmed)
+ from serial.tools.list_ports_linux import comports
+
+elif plat == 'cygwin': # cygwin/win32
+ def comports():
+ devices = glob.glob('/dev/com*')
+ return [(d, d, d) for d in devices]
+
+elif plat[:7] == 'openbsd': # OpenBSD
+ def comports():
+ devices = glob.glob('/dev/cua*')
+ return [(d, d, d) for d in devices]
+
+elif plat[:3] == 'bsd' or \
+ plat[:7] == 'freebsd':
+
+ def comports():
+ devices = glob.glob('/dev/cuad*')
+ return [(d, d, d) for d in devices]
+
+elif plat[:6] == 'darwin': # OS X (confirmed)
+ from serial.tools.list_ports_osx import comports
+
+elif plat[:6] == 'netbsd': # NetBSD
+ def comports():
+ """scan for available ports. return a list of device names."""
+ devices = glob.glob('/dev/dty*')
+ return [(d, d, d) for d in devices]
+
+elif plat[:4] == 'irix': # IRIX
+ def comports():
+ """scan for available ports. return a list of device names."""
+ devices = glob.glob('/dev/ttyf*')
+ return [(d, d, d) for d in devices]
+
+elif plat[:2] == 'hp': # HP-UX (not tested)
+ def comports():
+ """scan for available ports. return a list of device names."""
+ devices = glob.glob('/dev/tty*p0')
+ return [(d, d, d) for d in devices]
+
+elif plat[:5] == 'sunos': # Solaris/SunOS
+ def comports():
+ """scan for available ports. return a list of device names."""
+ devices = glob.glob('/dev/tty*c')
+ return [(d, d, d) for d in devices]
+
+elif plat[:3] == 'aix': # AIX
+ def comports():
+ """scan for available ports. return a list of device names."""
+ devices = glob.glob('/dev/tty*')
+ return [(d, d, d) for d in devices]
+
+else:
+ # platform detection has failed...
+ sys.stderr.write("""\
+don't know how to enumerate ttys on this system.
+! I you know how the serial ports are named send this information to
+! the author of this module:
+
+sys.platform = %r
+os.name = %r
+pySerial version = %s
+
+also add the naming scheme of the serial ports and with a bit luck you can get
+this module running...
+""" % (sys.platform, os.name, serial.VERSION))
+ raise ImportError("Sorry: no implementation for your platform ('%s') available" % (os.name,))
+
+# test
+if __name__ == '__main__':
+ for port, desc, hwid in sorted(comports()):
+ print "%s: %s [%s]" % (port, desc, hwid)
diff --git a/serial/tools/list_ports_windows.py b/serial/tools/list_ports_windows.py
new file mode 100644
index 0000000..cc770f7
--- /dev/null
+++ b/serial/tools/list_ports_windows.py
@@ -0,0 +1,240 @@
+import ctypes
+import re
+
+def ValidHandle(value, func, arguments):
+ if value == 0:
+ raise ctypes.WinError()
+ return value
+
+import serial
+from serial.win32 import ULONG_PTR, is_64bit
+from ctypes.wintypes import HANDLE
+from ctypes.wintypes import BOOL
+from ctypes.wintypes import HWND
+from ctypes.wintypes import DWORD
+from ctypes.wintypes import WORD
+from ctypes.wintypes import LONG
+from ctypes.wintypes import ULONG
+from ctypes.wintypes import LPCSTR
+from ctypes.wintypes import HKEY
+from ctypes.wintypes import BYTE
+
+NULL = 0
+HDEVINFO = ctypes.c_void_p
+PCTSTR = ctypes.c_char_p
+PTSTR = ctypes.c_void_p
+CHAR = ctypes.c_char
+LPDWORD = PDWORD = ctypes.POINTER(DWORD)
+#~ LPBYTE = PBYTE = ctypes.POINTER(BYTE)
+LPBYTE = PBYTE = ctypes.c_void_p # XXX avoids error about types
+
+ACCESS_MASK = DWORD
+REGSAM = ACCESS_MASK
+
+
+def byte_buffer(length):
+ """Get a buffer for a string"""
+ return (BYTE*length)()
+
+def string(buffer):
+ s = []
+ for c in buffer:
+ if c == 0: break
+ s.append(chr(c & 0xff)) # "& 0xff": hack to convert signed to unsigned
+ return ''.join(s)
+
+
+class GUID(ctypes.Structure):
+ _fields_ = [
+ ('Data1', DWORD),
+ ('Data2', WORD),
+ ('Data3', WORD),
+ ('Data4', BYTE*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)
+
+PSP_DEVICE_INTERFACE_DETAIL_DATA = ctypes.c_void_p
+
+setupapi = ctypes.windll.LoadLibrary("setupapi")
+SetupDiDestroyDeviceInfoList = setupapi.SetupDiDestroyDeviceInfoList
+SetupDiDestroyDeviceInfoList.argtypes = [HDEVINFO]
+SetupDiDestroyDeviceInfoList.restype = BOOL
+
+SetupDiClassGuidsFromName = setupapi.SetupDiClassGuidsFromNameA
+SetupDiClassGuidsFromName.argtypes = [PCTSTR, ctypes.POINTER(GUID), DWORD, PDWORD]
+SetupDiClassGuidsFromName.restype = BOOL
+
+SetupDiEnumDeviceInfo = setupapi.SetupDiEnumDeviceInfo
+SetupDiEnumDeviceInfo.argtypes = [HDEVINFO, DWORD, PSP_DEVINFO_DATA]
+SetupDiEnumDeviceInfo.restype = BOOL
+
+SetupDiGetClassDevs = setupapi.SetupDiGetClassDevsA
+SetupDiGetClassDevs.argtypes = [ctypes.POINTER(GUID), PCTSTR, HWND, DWORD]
+SetupDiGetClassDevs.restype = HDEVINFO
+SetupDiGetClassDevs.errcheck = ValidHandle
+
+SetupDiGetDeviceRegistryProperty = setupapi.SetupDiGetDeviceRegistryPropertyA
+SetupDiGetDeviceRegistryProperty.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, DWORD, PDWORD, PBYTE, DWORD, PDWORD]
+SetupDiGetDeviceRegistryProperty.restype = BOOL
+
+SetupDiGetDeviceInstanceId = setupapi.SetupDiGetDeviceInstanceIdA
+SetupDiGetDeviceInstanceId.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, PTSTR, DWORD, PDWORD]
+SetupDiGetDeviceInstanceId.restype = BOOL
+
+SetupDiOpenDevRegKey = setupapi.SetupDiOpenDevRegKey
+SetupDiOpenDevRegKey.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, DWORD, DWORD, DWORD, REGSAM]
+SetupDiOpenDevRegKey.restype = HKEY
+
+advapi32 = ctypes.windll.LoadLibrary("Advapi32")
+RegCloseKey = advapi32.RegCloseKey
+RegCloseKey.argtypes = [HKEY]
+RegCloseKey.restype = LONG
+
+RegQueryValueEx = advapi32.RegQueryValueExA
+RegQueryValueEx.argtypes = [HKEY, LPCSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD]
+RegQueryValueEx.restype = LONG
+
+
+DIGCF_PRESENT = 2
+DIGCF_DEVICEINTERFACE = 16
+INVALID_HANDLE_VALUE = 0
+ERROR_INSUFFICIENT_BUFFER = 122
+SPDRP_HARDWAREID = 1
+SPDRP_FRIENDLYNAME = 12
+DICS_FLAG_GLOBAL = 1
+DIREG_DEV = 0x00000001
+KEY_READ = 0x20019
+
+# workaround for compatibility between Python 2.x and 3.x
+Ports = serial.to_bytes([80, 111, 114, 116, 115]) # "Ports"
+PortName = serial.to_bytes([80, 111, 114, 116, 78, 97, 109, 101]) # "PortName"
+
+def comports():
+ GUIDs = (GUID*8)() # so far only seen one used, so hope 8 are enough...
+ guids_size = DWORD()
+ if not SetupDiClassGuidsFromName(
+ Ports,
+ GUIDs,
+ ctypes.sizeof(GUIDs),
+ ctypes.byref(guids_size)):
+ raise ctypes.WinError()
+
+ # repeat for all possible GUIDs
+ for index in range(guids_size.value):
+ g_hdi = SetupDiGetClassDevs(
+ ctypes.byref(GUIDs[index]),
+ None,
+ NULL,
+ DIGCF_PRESENT) # was DIGCF_PRESENT|DIGCF_DEVICEINTERFACE which misses CDC ports
+
+ devinfo = SP_DEVINFO_DATA()
+ devinfo.cbSize = ctypes.sizeof(devinfo)
+ index = 0
+ while SetupDiEnumDeviceInfo(g_hdi, index, ctypes.byref(devinfo)):
+ index += 1
+
+ # get the real com port name
+ hkey = SetupDiOpenDevRegKey(
+ g_hdi,
+ ctypes.byref(devinfo),
+ DICS_FLAG_GLOBAL,
+ 0,
+ DIREG_DEV, # DIREG_DRV for SW info
+ KEY_READ)
+ port_name_buffer = byte_buffer(250)
+ port_name_length = ULONG(ctypes.sizeof(port_name_buffer))
+ RegQueryValueEx(
+ hkey,
+ PortName,
+ None,
+ None,
+ ctypes.byref(port_name_buffer),
+ ctypes.byref(port_name_length))
+ RegCloseKey(hkey)
+
+ # unfortunately does this method also include parallel ports.
+ # we could check for names starting with COM or just exclude LPT
+ # and hope that other "unknown" names are serial ports...
+ if string(port_name_buffer).startswith('LPT'):
+ continue
+
+ # hardware ID
+ szHardwareID = byte_buffer(250)
+ # try to get ID that includes serial number
+ if not SetupDiGetDeviceInstanceId(
+ g_hdi,
+ ctypes.byref(devinfo),
+ ctypes.byref(szHardwareID),
+ ctypes.sizeof(szHardwareID) - 1,
+ None):
+ # fall back to more generic hardware ID if that would fail
+ 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()
+ # stringify
+ szHardwareID_str = string(szHardwareID)
+
+ # in case of USB, make a more readable string, similar to that form
+ # that we also generate on other platforms
+ if szHardwareID_str.startswith('USB'):
+ m = re.search(r'VID_([0-9a-f]{4})&PID_([0-9a-f]{4})(\\(\w+))?', szHardwareID_str, re.I)
+ if m:
+ if m.group(4):
+ szHardwareID_str = 'USB VID:PID=%s:%s SNR=%s' % (m.group(1), m.group(2), m.group(4))
+ else:
+ szHardwareID_str = 'USB VID:PID=%s:%s' % (m.group(1), m.group(2))
+
+ # friendly name
+ szFriendlyName = byte_buffer(250)
+ if not SetupDiGetDeviceRegistryProperty(
+ g_hdi,
+ ctypes.byref(devinfo),
+ SPDRP_FRIENDLYNAME,
+ #~ SPDRP_DEVICEDESC,
+ None,
+ ctypes.byref(szFriendlyName),
+ ctypes.sizeof(szFriendlyName) - 1,
+ None):
+ # Ignore ERROR_INSUFFICIENT_BUFFER
+ #~ if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
+ #~ raise IOError("failed to get details for %s (%s)" % (devinfo, szHardwareID.value))
+ # ignore errors and still include the port in the list, friendly name will be same as port name
+ yield string(port_name_buffer), 'n/a', szHardwareID_str
+ else:
+ yield string(port_name_buffer), string(szFriendlyName), szHardwareID_str
+
+ SetupDiDestroyDeviceInfoList(g_hdi)
+
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+# test
+if __name__ == '__main__':
+ import serial
+
+ for port, desc, hwid in sorted(comports()):
+ print "%s: %s [%s]" % (port, desc, hwid)
diff --git a/serial/tools/miniterm.py b/serial/tools/miniterm.py
new file mode 100644
index 0000000..274c7fb
--- /dev/null
+++ b/serial/tools/miniterm.py
@@ -0,0 +1,694 @@
+#!/usr/bin/env python
+
+# Very simple serial terminal
+# (C)2002-2011 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
+try:
+ from serial.tools.list_ports import comports
+except ImportError:
+ comports = None
+
+EXITCHARCTER = serial.to_bytes([0x1d]) # GS/CTRL+]
+MENUCHARACTER = serial.to_bytes([0x14]) # Menu: CTRL+T
+
+DEFAULT_PORT = None
+DEFAULT_BAUDRATE = 9600
+DEFAULT_RTS = None
+DEFAULT_DTR = None
+
+
+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 (%(version)s) - miniterm - help
+---
+--- %(exit)-8s Exit program
+--- %(menu)-8s Menu escape key, followed by:
+--- Menu keys:
+--- %(itself)-7s Send the menu character itself to remote
+--- %(exchar)-7s Send the exit character itself to remote
+--- %(info)-7s Show info
+--- %(upload)-7s Upload file (prompt will be shown)
+--- Toggles:
+--- %(rts)-7s RTS %(echo)-7s local echo
+--- %(dtr)-7s DTR %(break)-7s BREAK
+--- %(lfm)-7s line feed %(repr)-7s Cycle repr mode
+---
+--- Port settings (%(menu)s followed by the following):
+--- p change port
+--- 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
+""" % {
+ 'version': getattr(serial, 'VERSION', 'unknown version'),
+ '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),
+}
+
+if sys.version_info >= (3, 0):
+ def character(b):
+ return b.decode('latin1')
+else:
+ def character(b):
+ return b
+
+LF = serial.to_bytes([10])
+CR = serial.to_bytes([13])
+CRLF = serial.to_bytes([13, 10])
+
+X00 = serial.to_bytes([0])
+X0E = serial.to_bytes([0x0e])
+
+# first choose a platform dependant way to read single characters from the console
+global console
+
+if os.name == 'nt':
+ import msvcrt
+ class Console(object):
+ def __init__(self):
+ pass
+
+ def setup(self):
+ pass # Do nothing for 'nt'
+
+ def cleanup(self):
+ pass # Do nothing for 'nt'
+
+ def getkey(self):
+ while True:
+ z = msvcrt.getch()
+ if z == X00 or z == X0E: # functions keys, ignore
+ msvcrt.getch()
+ else:
+ if z == CR:
+ return LF
+ return z
+
+ console = Console()
+
+elif os.name == 'posix':
+ import termios, sys, os
+ class Console(object):
+ def __init__(self):
+ self.fd = sys.stdin.fileno()
+ self.old = None
+
+ 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)
+
+ def getkey(self):
+ c = os.read(self.fd, 1)
+ return c
+
+ def cleanup(self):
+ if self.old is not None:
+ termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
+
+ console = Console()
+
+ def cleanup_console():
+ console.cleanup()
+
+ sys.exitfunc = cleanup_console # terminal modes have to be restored on exit...
+
+else:
+ raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
+
+
+def dump_port_list():
+ if comports:
+ sys.stderr.write('\n--- Available ports:\n')
+ for port, desc, hwid in sorted(comports()):
+ #~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
+ sys.stderr.write('--- %-20s %s\n' % (port, desc))
+
+
+CONVERT_CRLF = 2
+CONVERT_CR = 1
+CONVERT_LF = 0
+NEWLINE_CONVERISON_MAP = (LF, CR, CRLF)
+LF_MODES = ('LF', 'CR', 'CR/LF')
+
+REPR_MODES = ('raw', 'some control', 'all control', 'hex')
+
+class Miniterm(object):
+ def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
+ try:
+ self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
+ except AttributeError:
+ # happens when the installed pyserial is older than 2.5. use the
+ # Serial class directly then.
+ self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
+ 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_reader(self):
+ """Start reader thread"""
+ self._reader_alive = True
+ # start serial->console thread
+ self.receiver_thread = threading.Thread(target=self.reader)
+ self.receiver_thread.setDaemon(True)
+ self.receiver_thread.start()
+
+ def _stop_reader(self):
+ """Stop reader thread only, wait for clean exit of thread"""
+ self._reader_alive = False
+ self.receiver_thread.join()
+
+
+ def start(self):
+ self.alive = True
+ self._start_reader()
+ # enter console->serial loop
+ self.transmitter_thread = threading.Thread(target=self.writer)
+ self.transmitter_thread.setDaemon(True)
+ 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: %-8s DTR: %-8s BREAK: %-8s\n' % (
+ (self.rts_state and 'active' or 'inactive'),
+ (self.dtr_state and 'active' or 'inactive'),
+ (self.break_state and 'active' or 'inactive')))
+ try:
+ sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
+ (self.serial.getCTS() and 'active' or 'inactive'),
+ (self.serial.getDSR() and 'active' or 'inactive'),
+ (self.serial.getRI() and 'active' or 'inactive'),
+ (self.serial.getCD() and 'active' or 'inactive')))
+ except serial.SerialException:
+ # on RFC 2217 ports it can happen to no modem state notification was
+ # yet received. ignore this error.
+ pass
+ 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 linefeed: %s\n' % (
+ REPR_MODES[self.repr_mode],
+ LF_MODES[self.convert_outgoing]))
+
+ def reader(self):
+ """loop and copy serial->console"""
+ try:
+ while self.alive and self._reader_alive:
+ data = character(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 c in data:
+ sys.stdout.write("%s " % c.encode('hex'))
+ sys.stdout.flush()
+ except serial.SerialException, e:
+ self.alive = False
+ # would be nice if the console reader could be interruptted at this
+ # point...
+ raise
+
+
+ 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:
+ b = console.getkey()
+ except KeyboardInterrupt:
+ b = serial.to_bytes([3])
+ c = character(b)
+ if menu_active:
+ if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
+ self.serial.write(b) # 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
+ dump_port_list()
+ sys.stderr.write('--- Enter port name: ')
+ sys.stderr.flush()
+ console.cleanup()
+ try:
+ port = sys.stdin.readline().strip()
+ except KeyboardInterrupt:
+ port = None
+ console.setup()
+ if port and port != self.serial.port:
+ # reader thread needs to be shut down
+ self._stop_reader()
+ # save settings
+ settings = self.serial.getSettingsDict()
+ try:
+ try:
+ new_serial = serial.serial_for_url(port, do_not_open=True)
+ except AttributeError:
+ # happens when the installed pyserial is older than 2.5. use the
+ # Serial class directly then.
+ new_serial = serial.Serial()
+ new_serial.port = port
+ # restore settings and open
+ new_serial.applySettingsDict(settings)
+ new_serial.open()
+ new_serial.setRTS(self.rts_state)
+ new_serial.setDTR(self.dtr_state)
+ new_serial.setBreak(self.break_state)
+ except Exception, e:
+ sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
+ new_serial.close()
+ else:
+ self.serial.close()
+ self.serial = new_serial
+ sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
+ # and restart the reader thread
+ self._start_reader()
+ 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(b) # send byte
+ 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."
+ )
+
+ group = optparse.OptionGroup(parser, "Port settings")
+
+ group.add_option("-p", "--port",
+ dest = "port",
+ help = "port, a number or a device name. (deprecated option, use parameter instead)",
+ default = DEFAULT_PORT
+ )
+
+ group.add_option("-b", "--baud",
+ dest = "baudrate",
+ action = "store",
+ type = 'int',
+ help = "set baud rate, default %default",
+ default = DEFAULT_BAUDRATE
+ )
+
+ group.add_option("--parity",
+ dest = "parity",
+ action = "store",
+ help = "set parity, one of [N, E, O, S, M], default=N",
+ 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 = DEFAULT_RTS
+ )
+
+ group.add_option("--dtr",
+ dest = "dtr_state",
+ action = "store",
+ type = 'int',
+ help = "set initial DTR line state (possible values: 0, 1)",
+ default = DEFAULT_DTR
+ )
+
+ parser.add_option_group(group)
+
+ group = optparse.OptionGroup(parser, "Data handling")
+
+ group.add_option("-e", "--echo",
+ dest = "echo",
+ action = "store_true",
+ help = "enable local echo (default off)",
+ default = False
+ )
+
+ group.add_option("--cr",
+ dest = "cr",
+ action = "store_true",
+ help = "do not send CR+LF, send CR only",
+ default = False
+ )
+
+ group.add_option("--lf",
+ dest = "lf",
+ action = "store_true",
+ help = "do not send CR+LF, send LF only",
+ default = False
+ )
+
+ group.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_group(group)
+
+
+ group = optparse.OptionGroup(parser, "Hotkeys")
+
+ group.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
+ )
+
+ group.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
+ )
+
+ parser.add_option_group(group)
+
+ group = optparse.OptionGroup(parser, "Diagnostics")
+
+ group.add_option("-q", "--quiet",
+ dest = "quiet",
+ action = "store_true",
+ help = "suppress non-error messages",
+ default = False
+ )
+
+ parser.add_option_group(group)
+
+
+ (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.menu_char == options.exit_char:
+ 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:
+ # noport given on command line -> ask user now
+ if port is None:
+ dump_port_list()
+ port = raw_input('Enter port name:')
+
+ 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, e:
+ sys.stderr.write("could not open port %r: %s\n" % (port, e))
+ 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
+
+ console.setup()
+ miniterm.start()
+ try:
+ miniterm.join(True)
+ except KeyboardInterrupt:
+ pass
+ if not options.quiet:
+ sys.stderr.write("\n--- exit ---\n")
+ miniterm.join()
+ #~ console.cleanup()
+
+# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+if __name__ == '__main__':
+ main()