Giter VIP home page Giter VIP logo

pyserial's Introduction

pySerial Build status Documentation

Overview

This module encapsulates the access for the serial port. It provides backends for Python running on Windows, OSX, Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named "serial" automatically selects the appropriate backend.

BSD license, (C) 2001-2020 Chris Liechti <[email protected]>

Documentation

For API documentation, usage and examples see files in the "documentation" directory. The ".rst" files can be read in any text editor or being converted to HTML or PDF using Sphinx. An HTML version is online at https://pythonhosted.org/pyserial/

Examples

Examples and unit tests are in the directory examples.

Installation

pip install pyserial should work for most users.

Detailed information can be found in documentation/pyserial.rst.

The usual setup.py for Python libraries is used for the source distribution. Windows installers are also available (see download link above).

or

To install this package with conda run:

conda install -c conda-forge pyserial

conda builds are available for linux, mac and windows.

pyserial's People

Contributors

akiomik avatar brendansimon avatar bufferoverflow avatar carlosperate avatar cefn avatar csboling avatar cweeks12 avatar davidhowlett avatar dhoomakethu avatar drugo72 avatar eliotb avatar erikbgithub avatar flameeyes avatar hardkrash avatar henzef avatar hoihu avatar jdpatt avatar jwilk avatar keisisqrl avatar klanmiko avatar machinaut avatar mindw avatar renha avatar rob-smallshire avatar ryan-summers avatar shaunwbell avatar topnotcher avatar waveform80 avatar wisdompill avatar zsquareplusc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyserial's Issues

Windows can not find my COM port after it briefly disappeared

I'm writing a Python script to test a device we are creating that has a virtual USB serial port on board.
In my test I'm rebooting the device, which causes the serial port to briefly be disrupted.
So I close my port as soon as I can after receiving the ACK to my command.

Unfortunately I can not reopen the port after that (not directly after it but also not after a minute or so).
Strange thing is that serial.tools.list_ports.comports() does show the port.
However when trying to connect I get the following exception:

WindowsError(2, 'The system cannot find the file specified.')

Unplugging the device and plugging it back in again allows me to connect to the device again.
However, that is not a do-able situation for an automated test.

Is there a workaround or fix for this problem?

Better Asyncio Support

I noticed there's an aio.py module in this project that uses the nonblocking mode of the serial connection in order to support use with asyncio. I tried using this on my Mac and my desktop (running Ubuntu 14.04) and got mixed results. For some reason, on my Mac it could only read in a single garbage character b'0xfe' or b'0xff' and it didn't seem to write correctly. That may or may not be an issue with the aio.py code but might have been some other problem.

Either way, I didn't like that the nonblocking mode doesn't support windows so I wrote my own asyncio adapter layer over pyserial using a separate worker thread to handle the blocking serial calls. You can see the code in this gist: https://gist.github.com/dummerbd/75316ab8c109b5bbc46b

If my code looks like a good addition for this library, I can clean it up a bit (like add some logging statements) and make a pull request. If not, let me know what you don't like!

Read does not honor the timeout on Linux

Hello,
Reading from the serial port with a timeout is not reliable on my system:

  • Linux Mint Nadia
  • Python 2.7.3
  • pyserial 2.7 (but also 2.5) installed both with pip and the latest tar.gz

I have a CDC-ACM dongle that transmits data periodically.

This simple program does not respect the timeout:

import serial
import time

ser = serial.Serial(
                    port        = '/dev/ttyACM0',
                    baudrate    = 460800,
                    bytesize    = serial.EIGHTBITS,
                    parity      = serial.PARITY_NONE,
                    stopbits    = serial.STOPBITS_ONE,
                    timeout     = 0.1
                   )

while True:
   length = 1000000

   t0 = time.time()
   print str(len(ser.read(length))) + ' ' + str((time.time() - t0))

Running the above I get:

123 0.109111070633
246 0.205754995346
123 0.106971025467
369 0.310961008072
123 0.106863975525
369 0.309740066528
246 0.214066982269

Data is read but with an higher latency.
Things go worst if the timeout is set to 1s, in which case data is read with higher latencies (>> 1s).

What's going on? For comparison I've tried the following program that mimics what pyserial should do:

import serial
import time
import select

ser = serial.Serial(
                    port        = '/dev/ttyACM0',
                    baudrate    = 460800,
                    bytesize    = serial.EIGHTBITS,
                    parity      = serial.PARITY_NONE,
                    stopbits    = serial.STOPBITS_ONE,
                    timeout     = None, #block forever
                   )

def read(ser, length, timeout):
   n = 0
   b = bytearray()
   ser.timeout = 0 #non-blocking
   while timeout >= 0 and n < length:
       t0 = time.time()
       ready = select.select([ser], [], [], timeout)
       timeout -= (time.time() - t0)
       if len(ready[0]) != 0:
           bb = ser.read(length - n)
           n += len(bb)
           b.extend(bb)
   return b

while True:
   timeout = 0.1 #seconds
   length = 1000000

   t0 = time.time()
   b = read(ser, length, timeout)
   print str(len(b)) + ' ' + str((time.time() - t0))

Whose output is:

123 0.101263999939
123 0.101146936417
123 0.101223945618
123 0.100612163544
123 0.100650072098
123 0.101171016693
123 0.10132598877

As you can see data is consistently read with the specified latency.
Other runs:

timeout=2.0:

2460 2.0148499012
2337 2.01164889336
2340 2.01203608513
2337 2.01602220535
2337 2.01417803764
2337 2.01304197311

timeout=2.0, length=10:

10 0.000165939331055
10 0.000646114349365
10 0.000133991241455
10 9.58442687988e-05
10 0.000693082809448
10 0.000132083892822
10 0.000753879547119

[improvement] Add feature to list all serial ports available on the system (multi-platform)

I saw a good answer @tfeldmann for a generic issue of pyserial here

import sys
import glob

import serial


def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result


if __name__ == '__main__':
    print(serial_ports())

My question for pyserial board is:
Will accept a PR with these feature?
Or Do you prefer a separated pypi package for just this feature?

Suggestion: Integration of the FTDI D2XX Driver (or alternatively libftdi)

This is a proposal to merge in a Serial class which uses the FTDI D2XX driver which has a much better performance (at least on my laptop) compared with the default Virtual COM Port implementation.

How to integrate:

Something like this would be nice:

  1. Check if the d2xx dll or libftdi is available.
  2. If the neither is available switch to the currently used classes
  3. If the user want's to connect and d2xx is available, check if the comport is also available through d2xx.
  4. If the device is available, use the d2xx class, otherwise the serial class.

Existing implementations:

There exist different Versions, but the one I worked with is ft232 which works perfectly out of the box on my machine.
https://github.com/lsgunth/pyft232

Raise TimeoutError on timeout

When I set a timeout like this:

ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)

pyserial just retries reads like this:

character = ser.read()

I need to be able to know, when the read has timed out to resend my last message. Please raise a TimeoutError, so I can use pyserial like this:

while True:
    try:
        character = console.read()
    except TimeoutError:
        console.write(message)
        character = console.read()

I think that it is unpythonic to silently drop errors like a timeout. When a user of pyserial invokes a read(), the expected outcome is that it returns the data that has been read. So hitting the timeout is an error.

Update version numbering scheme to pep 440

Version 3.x should be changed to something more like 3.0a0

This will allow pip and friends to understand versions currently 3.x is unknown to these tools and evaluates to 0.0

write error with eagain (resource temporarily unavailable)

I have a program which when I run with threads (on multiple ports at same time) it hangs the python script. Doing an strace it is hanging on the write('AT\r') with error EAGAIN (resource temporarily unavailable). I removed the threaded call to function and it works but worry it is because of a timing issue rather than treading issue.

Is this a bug in pyserial? Is there something I can do to work around, not it never timed out!

Thanks

def TestForATPort(self,comport):
try:
port=serial.Serial(comport,115200,timeout=5,writeTimeout=3)

        self.logger.info("trying port %s %s" % (comport, str(port)))
        if port.isOpen():
            try:
                fcntl.flock(port.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError:
                print('Port %s is busy' % comport)
                port.close()
                return False
        else:
            return False
        port.flushInput()
        port.flushOutput()
        port.write('AT\r')         
        s=""
        found=False
        time.sleep(1) #dleay ot have response
        t=time.time()
        while(time.time()-t)<3:
            if (port.inWaiting()>0):
                try:
                    c=port.read()
                    s=s+c
                    if (c=='\r'):
                        if "\nOK\r" in s:
                            found= True
                            print("found port %s" % comport)
                            break;
                        s=""
                except Exception as e:
                    self.logger.error("exception %s" % str(e))
                    pass   
        fcntl.flock(port.fileno(), fcntl.LOCK_UN)   
        port.close()
        return found
    except Exception as e:        
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        s=str(exc_type) + " " + fname +" "+ str(exc_tb.tb_lineno)
        self.logger.error(s)
        return False
    return False

interCharTimeout kwarg doesn't work

I'm running Ubuntu 14.04 and just did:

sudo pip3 install --upgrade pyserial

which installed
and now the interCharTimeout kwarg no longer works.

507 >python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> serial.VERSION
'3.0'
>>> ser = serial.Serial('/dev/ttyACM0', baudrate=115200, interCharTimeout=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'interCharTimeout'
>>> 

PySerial having problems with Arduino Yun

Hello, I've already had some discussion on this issue on PlatformIO Github - please look at trace log below:
(platformio/platformio-core#294 (comment))

python -m serial.tools.list_ports -v returns:
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/private/tmp/piotest/lib/python2.7/site-packages/serial/tools/list_ports.py", line 102, in <module> main() File "/private/tmp/piotest/lib/python2.7/site-packages/serial/tools/list_ports.py", line 84, in main iterator = sorted(comports()) File "/private/tmp/piotest/lib/python2.7/site-packages/serial/tools/list_ports_osx.py", line 233, in comports serial_interfaces = scan_interfaces() File "/private/tmp/piotest/lib/python2.7/site-packages/serial/tools/list_ports_osx.py", line 209, in scan_interfaces device = get_string_property(service, "IOCalloutDevice") File "/private/tmp/piotest/lib/python2.7/site-packages/serial/tools/list_ports_osx.py", line 101, in get_string_property output = cf.CFStringGetCStringPtr(CFContainer, 0).decode('mac_roman') AttributeError: 'NoneType' object has no attribute 'decode'

Pyserial write hangs

I tried to pass a command on to my DUT using pyserial write API. Its hanging there and the next step of my script is not executed.

If I want to continue my script, then I have to give any of the keystokes on the prompt where script is running.

Example

If my script is as follows

  1. serial.write('pwd')
  2. serial.write('pwd')
  3. serial.write('pwd')

Observed Behavior

After Step # 1, script is not trying to run step#2.
If the script has to run step#2, then I have to give "Enter" key on my DOS prompt.

serialjava.py can't handle non-contiguous COM port numbers

I have COM1, COM2, COM3, COM200 and tried to open COM200 using the command:

ser = serial.Serial( port=199, baudrate=1500000, timeout=30 )

I received an index error

    ser = serial.Serial( port=199, baudrate=1500000, timeout=30 )
  File "C:\jython2.7.0\Lib\site-packages\serial\serialutil.py", line 269, in __init__
    self.port     = port
  File "C:\jython2.7.0\Lib\site-packages\serial\serialutil.py", line 317, in setPort
    self.portstr = self.makeDeviceName(port)
  File "C:\jython2.7.0\Lib\site-packages\serial\serialjava.py", line 143, in makeDeviceName
    return device(port)
  File "C:\jython2.7.0\Lib\site-packages\serial\serialjava.py", line 49, in device
    return ports[portnumber].getName()
IndexError: index out of range: 199

I believe the error is on line 48 of serialjava.py. Change ports.append(el) to something else.

EDIT: I'm using pyserial 2.7

Listing serial ports on python3 (Mac OS X)

I tried to use the built-in port listing function but got different results depending on the python version. I'm using Mac OS X 10.11.

Python 2.7.5 (default, Nov  4 2013, 18:04:45) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from serial.tools import list_ports
>>> list_ports.comports()
[['/dev/cu.Bluetooth-Incoming-Port', 'n/a', 'n/a'], ['/dev/cu.Bluetooth-Modem', 'n/a', 'n/a']]

Python 3.3.5 (default, Mar 10 2014, 13:25:50) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from serial.tools import list_ports
>>> list_ports.comports()
[]

A patch seems to be available here: http://sourceforge.net/p/pyserial/patches/38/
Stackoverflow discussion: http://stackoverflow.com/q/22467683/300783

Edit: I'm using the pyserial version from pypi but will give the beta a try soon!

Problem with inter_byte_timeout

When run the instructions below:
(...)
self.port = serial.Serial(port, baudrate, timeout = 0.5, write_timeout = 0.5, inter_byte_timeout = 0.5)
print(self.port.get_settings())
(...)
result:
{'dsrdtr': False, 'rtscts': False, 'bytesize': 8, 'timeout': 0.5, 'inter_byte_timeout': None, 'baudrate': 115200, 'xonxoff': False, 'parity': 'N', 'write_timeout': 0.5, 'stopbits': 1}

I get as a result:
'inter_byte_timeout': None
instead of the
'inter_byte_timeout': 0.5

Problem with Ubuntu 14.04

Hi to all,
i'm writing a simple application that send and receive command over the USB Port. I use pySerial python library and I open a connection to the USB device. All go fine but after a while (1/2 hours) a strange behavior happen:
i receive the following error
write failed: [Errno 5] input/output error

Have you ever had the same problem?

NOTE: if I remove the device from the USB and than I reinsert it its name change (for example: /dev/ttyACM0 -> /dev/ttyACM1)

thanks to all!

Add open() and close() to SerialBase

The SerialBase should have the open() and close() Method implemented with a raise NotImplementedError() like this:

class SerialBase(io.RawIOBase):
    # All the existing code ...

    def open(self):
        """Opens the Port"""
        raise NotImplementedError("This function must be implemented in the subclass")

    def close(self):
        """Closes the Port"""
        raise NotImplementedError("This function must be implemented in the subclass")

This way it is immediatly clear that this functions must be implemented in subclasses and if somenone is looking at the code of SerialBase its obvious where these methods are doing.

pyserial 3 not working in windows 10

Hey folks, I've got three lcd screens communicating with each other and the host computer via pyserial and python under Windows 7. To utilize another piece of hardware, I was required to upgrade the host computer to windows 10. Now, I'm not getting my python script to work correctly in windows 10. This is the error I'm getting.

Traceback (most recent call last):
File "runscript.py line 13, in
ser = serial.Serial(port = 6, baudrate = 9600, timeout = 0)
File "C:\Python27\lib\site-packages\serial\serialWin32.py", line 38, in init
SerialBase.init(self, "args, ""kwargs)
File "C:\Python27\lib\site-packages\serial\serialutil.py", line 282, in init
self.open()
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinErrorr()))
serial.serialutil.SerialException: could not open port 'COM7': WindowsError(2, 'The system cannot find the file specified.')

My python code to call the serial port is just this...

5 import sys, re, os, time, serial, pygame, winsound

13 ser = serial.Serial(port=6, baudrate=9600, timeout=999)
14 serRightScreen = serial.Serial(port=3, baudrate=9600, timeout=999)
15 serLeftScreen = serial.Serial(port= 5, baudrate=9600, timeout=999)

Again, the screens themselves and the code works fine with python interface which was working fine under Windows 7, but not under Windows 10. I'd love to have your input.

Barry

Overlapped I/O objects not cancelled properly in Windows

The _close() method in serialwin32.py does not close out pending overlapped I/O objects (self._overlappedRead and self._overlappedWrite) correctly. These I/O events should be cancelled before they are destroyed. The current implementation can cause Python to crash with "Segmentation fault" if .close() is called while an I/O event is still pending. This happens because the library attempts to access memory that has already been garbage collected.

I wrote an implementation of _close() based on this MSDN article (https://msdn.microsoft.com/en-us/library/windows/desktop/aa363789(v=vs.85).aspx) that seems to fix the issue:

def _close(self):
    """internal close port helper"""
    if self.hComPort:
        # Restore original timeout values:
        win32.SetCommTimeouts(self.hComPort, self._orgTimeouts)

        if self._overlappedRead is not None:
            rc = win32.DWORD()
            err = win32.GetOverlappedResult(self.hComPort,
                                         ctypes.byref(self._overlappedRead),
                                         ctypes.byref(rc),
                                         False)
            if not err:
                win32.GetLastError()

                err = CancelIoEx(self.hComPort, self._overlappedRead)
                if not err:
                    win32.GetLastError()
                    raise SerialException("CancelIoEx failed (%r)" % \
                                          ctypes.WinError())

            self._overlappedRead = None

        if self._overlappedWrite is not None:
            wc = win32.DWORD()
            err = win32.GetOverlappedResult(self.hComPort,
                                        ctypes.byref(self._overlappedWrite),
                                        ctypes.byref(wc),
                                        False)
            if not err:
                win32.GetLastError()

                err = CancelIoEx(self.hComPort, self._overlappedWrite)
                if not err:
                    win32.GetLastError()
                    raise SerialException("CancelIoEx failed (%r)" % \
                                          ctypes.WinError())
                else:
                    err = win32.GetOverlappedResult(self.hComPort,
                                        ctypes.byref(self._overlappedWrite),
                                        ctypes.byref(wc),
                                        True)

            self._overlappedWrite = None

        # Close COM-Port:
        win32.CloseHandle(self.hComPort)
        self.hComPort = None

Not able to connect after last kernel upgrade

Hi
I upgraded ubuntu today, which included a new kernel, and since then, I haven't been able to connect to a 3D printer using pyserial. I receive

SerialException: device reports readiness to read but returned no data (device disconnected?)

Just in case, the fact that this is a 3D printer is transparent. It just publishes a virtual serial device the printer connects to.
My environment is:

Python 2.7.6
Kernel 3.13.0-65-generic #105-Ubuntu SMP Mon Sep 21 18:51:54 UTC 2015 i686 i686 i686 GNU/Linux
$ dpkg -l | fgrep pyserial
ii  python-serial                                                             2.6-1build1                                         all          pyserial - module encapsulating access for the serial port

The device is connected using the USB to serial driver. Tried both using a tipical USB and an additional FTDI programmer to ensure it was not because of the cable or the board input.
I'm not sure if this is a pyserial bug, but decided it would be better if you evaluated it. I could connect using screen command executing:
screen /dev/ttyACM0 115200
or using the external FTDI programmer
screen /dev/ttyUSB0 115200
In both cases I could connect. so, it doesn't seem to be a global scale problem. However, I couldn't connect using pyserial applications, like printrun/pronterface (a python based 3D printer client) or miniterm.py.
As a workaround, I modified the file serialposix.py, and commented a few lines:

            if not ready:
                break   # timeout
            buf = os.read(self.fd, size-len(read))
            # read should always return some data as select reported it was
            # ready to read when we get to this point.
            if not buf:
                # Disconnected devices, at least on Linux, show the
                # behavior that they are always ready to read immediately
                # but reading returns nothing.
                raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
            read.extend(buf)
        return bytes(read)

Changed those to:

            if not ready:
                break   # timeout
            buf = os.read(self.fd, size-len(read))
            # read should always return some data as select reported it was
            # ready to read when we get to this point.
            #if not buf:
                # Disconnected devices, at least on Linux, show the
                # behavior that they are always ready to read immediately
                # but reading returns nothing.
                #raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
            read.extend(buf)
        return bytes(read)

and then it worked.
I know those lines should be there, but they seem to be related to the symptoms of not being able to connect to the device. Maybe this helps you to find out what the problem is, and if this has to do with pyserial, the kernel or another project.
Thanks in advance!

Hardware IDs for FTDI devices are not parsed correctly on Windows

When using serial.tools.list_ports.comports() to retrieve a list of ListPortInfo objects on windows. Those objects does not have the correct vid/pid/serial_number attributes.
For reference the FTDI serial number should be A600ARJH and should be VID:PID 0403:6001

PS C:\Users\sxu> python -m serial.tools.list_ports -v
COM1
    desc: Communications Port (COM1)
    hwid: ACPI\PNP0501\1
COM6
    desc: USB Serial Port (COM6)
    hwid: FTDIBUS\VID_0403+PID_6001+A600ARJHA\0000
COM7
    desc: KitProg USB-UART (COM7)
    hwid: USB VID:PID=04B4:F139 LOCATION=1-1
3 ports found

comports returns:

Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from serial.tools.list_ports import comports
>>> ports = comports()
>>> for port in ports:
...     print port.hwid
...
ACPI\PNP0501\1
FTDIBUS\VID_0403+PID_6001+A600ARJHA\0000
USB VID:PID=04B4:F139 LOCATION=1-1
>>> ports = comports()
>>> for port in ports:
...     print port.serial_number
...
None
None
None
>>>

list_ports_common.py:usb_description should not return None

The update to 3.0 caused list_ports.grep to stop working for me on a Linux system. I am using a CDC USB serial device. Example output from python3 -m serial.tools.list_ports -v
On 3.0

/dev/ttyACM0
    desc: None
    hwid: USB VID:PID=03EB:2404 LOCATION=1-1.1.1

On 2.7

/dev/ttyACM0
    desc: ttyACM0
    hwid: USB VID:PID=03eb:2404

Patch that behaves the same way on my system as 2.7.

diff --git a/serial/tools/list_ports_common.py b/serial/tools/list_ports_common.py
index e5b0394..640b2a1 100644
--- a/serial/tools/list_ports_common.py
+++ b/serial/tools/list_ports_common.py
@@ -46,8 +46,10 @@ class ListPortInfo(object):
     def usb_description(self):
         if self.interface is not None:
             return '{} - {}'.format(self.product, self.interface)
-        else:
+        elif self.product is not None:
             return self.product
+        else:
+            return self.name

     def usb_info(self):
         return 'USB VID:PID={:04X}:{:04X}{}{}'.format(
-- 
2.3.0

getTimeout not available in pyserial 3.0

Hi

I just upgraded to pyserial 3.0 on archlinux the other day, this broke a software package I use called Chirp.

The error I get from Chirp is:

$ chirpw 
ERROR: -- Exception: --
ERROR: Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/chirp/ui/clone.py", line 238, in run
    self.__radio.sync_in()
  File "/usr/lib/python2.7/site-packages/chirp/drivers/uv5r.py", line 705, in sync_in
    raise errors.RadioError("Failed to communicate with radio: %s" % e)
RadioError: Failed to communicate with radio: 'Serial' object has no attribute 'setTimeout'

ERROR: ----------------
ERROR: Clone failed: Failed to communicate with radio: 'Serial' object has no attribute 'setTimeout'
ERROR: --- Exception Dialog: Failed to communicate with radio: 'Serial' object has no attribute 'setTimeout' ---
ERROR: None

ERROR: ----------------------------

I traced it back to this commit which removed that method:
779b1a2#diff-6565967c29e370a01030e6dcbc5acee8L232

I would ask to get those methods back, to maintain backwards compatibility.

This issue is similar to the API breakage mentioned in #55.

Reading garbage after reconnect

After closing the serial connection and reconnecting again, reading, using readline(), gives garbage hex.

I've tested this using python 3.4 on ubuntu 14.04 and an Arduino nano that writes to the serial port once connected. The arduino is connected to /dev/ttyUSB0. Both pyserial 2.7 and 3.0b1 show the problem, but pyserial 2.5 works nicely in this case. See console log below, for what was tested.

martin@martin-htpc:~/Dev/pymysensors$ mkvirtualenv -p /usr/bin/python3 pyserial
Running virtualenv with interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in pyserial/bin/python3
Also creating executable in pyserial/bin/python
Installing setuptools, pip, wheel...done.
virtualenvwrapper.user_scripts creating /home/martin/.virtualenvs/pyserial/bin/predeactivate
virtualenvwrapper.user_scripts creating /home/martin/.virtualenvs/pyserial/bin/postdeactivate
virtualenvwrapper.user_scripts creating /home/martin/.virtualenvs/pyserial/bin/preactivate
virtualenvwrapper.user_scripts creating /home/martin/.virtualenvs/pyserial/bin/postactivate
virtualenvwrapper.user_scripts creating /home/martin/.virtualenvs/pyserial/bin/get_env_details
(pyserial)martin@martin-htpc:~/Dev/pymysensors$ pip install file:///home/martin/Skrivbord/pyserial-3.0b1.zip 
Processing /home/martin/Skrivbord/pyserial-3.0b1.zip
Building wheels for collected packages: pyserial
  Running setup.py bdist_wheel for pyserial
  Stored in directory: /home/martin/.cache/pip/wheels/04/84/58/182c41f54077fd565291d425f3bb4c3213693a1a3988571de6
Successfully built pyserial
Installing collected packages: pyserial
Successfully installed pyserial-3.0b1
(pyserial)martin@martin-htpc:~/Dev/pymysensors$ pip show pyserial

---
Metadata-Version: 2.0
Name: pyserial
Version: 3.0b1
Summary: Python Serial Port Extension
Home-page: https://github.com/pyserial/pyserial
Author: Chris Liechti
Author-email: [email protected]
License: Python
Location: /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages
Requires: 
(pyserial)martin@martin-htpc:~/Dev/pymysensors$ pip3 install ipython
Collecting ipython
  Using cached ipython-4.0.0-py3-none-any.whl
Collecting traitlets (from ipython)
  Using cached traitlets-4.0.0-py2.py3-none-any.whl
Collecting pickleshare (from ipython)
Collecting decorator (from ipython)
  Using cached decorator-4.0.4-py2.py3-none-any.whl
Collecting pexpect (from ipython)
Collecting simplegeneric>0.8 (from ipython)
Collecting ipython-genutils (from traitlets->ipython)
  Using cached ipython_genutils-0.1.0-py2.py3-none-any.whl
Collecting path.py (from pickleshare->ipython)
  Using cached path.py-8.1.2-py2.py3-none-any.whl
Collecting ptyprocess>=0.5 (from pexpect->ipython)
Installing collected packages: decorator, ipython-genutils, traitlets, path.py, pickleshare, ptyprocess, pexpect, simplegeneric, ipython
Successfully installed decorator-4.0.4 ipython-4.0.0 ipython-genutils-0.1.0 path.py-8.1.2 pexpect-4.0.1 pickleshare-0.5 ptyprocess-0.5 simplegeneric-0.8.1 traitlets-4.0.0
(pyserial)martin@martin-htpc:~/Dev/pymysensors$ ipython
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
Type "copyright", "credits" or "license" for more information.

IPython 4.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import serial

In [2]: port = '/dev/ttyUSB0'

In [3]: baud = 115200

In [4]: ser = serial.Serial(port, baud, timeout=1)

In [5]: ser
Out[5]: Serial<id=0x7f99d4f50208, open=True>(port='/dev/ttyUSB0', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, dsrdtr=False)

In [6]: ser.name
Out[6]: '/dev/ttyUSB0'

In [7]: ser.isOpen()
Out[7]: True

In [8]: ser.readline()
Out[8]: b'0;0;3;0;9;gateway started, id=0, parent=0, distance=0\n'

In [9]: ser.readline()
Out[9]: b'0;0;3;0;14;Gateway startup complete.\n'

In [10]: ser.readline()
Out[10]: b''

In [11]: ser.close()

In [12]: ser.isOpen()
Out[12]: False

In [13]: ser = serial.Serial(port, baud, timeout=1)

In [14]: ser.isOpen()
Out[14]: True

In [15]: ser.readline()
Out[15]: b'\xe9\x0b8\xdf\xcb\xbb\xf2'

In [16]: ser.readline()
Out[16]: b''

In [17]: ser.close()

In [18]: ser.isOpen()
Out[18]: False

In [19]: quit()
(pyserial)martin@martin-htpc:~/Dev/pymysensors$ pip uninstall pyserial
Uninstalling pyserial-3.0b1:
  /home/martin/.virtualenvs/pyserial/bin/__pycache__/miniterm.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/bin/miniterm.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/pyserial-3.0b1.dist-info/DESCRIPTION.rst
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/pyserial-3.0b1.dist-info/METADATA
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/pyserial-3.0b1.dist-info/RECORD
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/pyserial-3.0b1.dist-info/WHEEL
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/pyserial-3.0b1.dist-info/metadata.json
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/pyserial-3.0b1.dist-info/top_level.txt
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__init__.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/__init__.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/aio.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/rfc2217.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/rs485.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/serialcli.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/serialjava.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/serialposix.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/serialutil.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/serialwin32.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/__pycache__/win32.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/aio.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/rfc2217.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/rs485.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/serialcli.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/serialjava.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/serialposix.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/serialutil.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/serialwin32.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__init__.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/__init__.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/hexlify_codec.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/list_ports.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/list_ports_common.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/list_ports_linux.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/list_ports_osx.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/list_ports_posix.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/list_ports_windows.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/__pycache__/miniterm.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/hexlify_codec.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/list_ports.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/list_ports_common.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/list_ports_linux.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/list_ports_osx.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/list_ports_posix.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/list_ports_windows.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/tools/miniterm.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/__init__.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/__pycache__/__init__.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/__pycache__/protocol_alt.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/__pycache__/protocol_hwgrep.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/__pycache__/protocol_loop.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/__pycache__/protocol_rfc2217.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/__pycache__/protocol_socket.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/__pycache__/protocol_spy.cpython-34.pyc
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/protocol_alt.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/protocol_hwgrep.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/protocol_loop.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/protocol_rfc2217.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/protocol_socket.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/urlhandler/protocol_spy.py
  /home/martin/.virtualenvs/pyserial/lib/python3.4/site-packages/serial/win32.py
Proceed (y/n)? y
  Successfully uninstalled pyserial-3.0b1
(pyserial)martin@martin-htpc:~/Dev/pymysensors$ cd ..
(pyserial)martin@martin-htpc:~/Dev$ atom .
(pyserial)martin@martin-htpc:~/Dev$ pip3 install -r /home/martin/Dev/requirements.txt 
Collecting pyserial<=2.5.9 (from -r /home/martin/Dev/requirements.txt (line 1))
  Downloading pyserial-2.5.tar.gz (106kB)
    100% |████████████████████████████████| 106kB 2.5MB/s 
Building wheels for collected packages: pyserial
  Running setup.py bdist_wheel for pyserial
  Stored in directory: /home/martin/.cache/pip/wheels/5c/57/e3/77e68f591edf4fdccdc8b2753a0eb641ebcdcee287f97a71ec
Successfully built pyserial
Installing collected packages: pyserial
Successfully installed pyserial
(pyserial)martin@martin-htpc:~/Dev$ pip show pyserial
(pyserial)martin@martin-htpc:~/Dev$ pip3 show pyserial
(pyserial)martin@martin-htpc:~/Dev$ ipython
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
Type "copyright", "credits" or "license" for more information.

IPython 4.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import serial

In [2]: port = '/dev/ttyUSB0'

In [3]: baud = 115200

In [4]: ser = serial.Serial(port, baud, timeout=1)

In [5]: ser
Out[5]: Serial<id=0x7f07d0060e48, open=True>(port='/dev/ttyUSB0', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, dsrdtr=False)

In [6]: ser.isOpen()
Out[6]: True

In [7]: ser.readline()
Out[7]: b'\xaae\xd1\xb9\xf10;0;3;0;9;gateway started, id=0, parent=0, distance=0\n'

In [8]: ser.readline()
Out[8]: b'0;0;3;0;14;Gateway startup complete.\n'

In [9]: ser.readline()
Out[9]: b''

In [10]: ser.close()

In [11]: ser.isOpen()
Out[11]: False

In [12]: ser = serial.Serial(port, baud, timeout=1)

In [13]: ser.readline()
Out[13]: b'0;0;3;0;9;gateway started, id=0, parent=0, distance=0\n'

In [14]: ser.readline()
Out[14]: b'0;0;3;0;14;Gateway startup complete.\n'

In [15]: ser.readline()
Out[15]: b''

In [16]: ser.readline()
Out[16]: b''

In [17]: ser.close()

In [18]: ser.isOpen()
Out[18]: False

Python 3.4 compatibility issue

Hi!
Trying to use the PySerial 3.0a which has Py3.4 compatibility. However, it seems there is till issues.

I used it with newest code from master branch of:
https://github.com/faucamp/python-gsmmodem/

DEBUG: write: ATZ
Traceback (most recent call last):
File "modempool.py", line 180, in
server.main()
File "modempool.py", line 139, in main
modem.connect(PIN)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/python_gsmmodem-0.9-py3.4.egg/gsmmodem/modem.py", line 177, in connect
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/python_gsmmodem-0.9-py3.4.egg/gsmmodem/modem.py", line 413, in write

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/python_gsmmodem-0.9-py3.4.egg/gsmmodem/serial_comms.py", line 127, in write

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pyserial-3.0a0-py3.4.egg/serial/serialposix.py", line 513, in write

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pyserial-3.0a0-py3.4.egg/serial/serialutil.py", line 57, in to_bytes
TypeError: an integer is required

Compatibility to Python 2.6

Hey,

I'm developing using Python 2.7 but a user uses 2.6.

Some Modules throw errors because the usage of the str.format() function:
On Python 2.7 an index between the {} is optional, on 2.6 it is not.

I'm on my work PC without git so i can't submit the fix, and I also can't append a zip so you could merge, so sadly I can't do my part beside hinting you.

To fix:
Open IDE, search for every '{}' and replace with '{0}' (or '{0} - {1}') where needed.

Eg:
Your str from list_ports_common.py:

def __str__(self):
    return '{} - {}'.format(self.device, self.description)

My version:

def __str__(self):
    return '{0} - {1}'.format(self.device, self.description)

I love your work! Keep it up!

Feature request: open() methods support for context manager

I found a use case where I'm only interested in managing a pre-configured pyserial object.

I'd like to do it that way:

import serial

# My pre-configured serial object
ser = serial.Serial()
ser.baudrate = 115200
ser.port = '/dev/ttyUSB0'

with ser.open():
    assert ser.isOpen()

assert not ser.isOpen()

It seems the only changes required in PySerial to do this would be to return the serial object itself when calling any of the open() method implementations (posix, ironpython, etc.).

Could this be considered for inclusion in PySerial?

[miniterm] My reworking with additional features diverged from your recent changes.

I just finished a few features for miniterm on my fork and discovered that you also were reworking miniterm.

While I agree with the bulk of the changes, switching the reader and writer to bytes from str I believe is too high in the stack. My rework involved splitting out the representation engine to functions and applying them to both the input from the serial port and to the local echo function. These operations are in the unicode world. When leaving the console world then the conversion to bytes is appropriate.

Please see https://github.com/hardkrash/pyserial/commits/feature/miniterm_features
Features include:

  • Pretty printing of ASCII C) codes.
  • Color mapping of local and remote text. (Should be turned into a runtime option, default off)
  • File input bugfixes.

On a side note:
It would be interesting to take the local echo concept from Mosh. https://mosh.mit.edu
Where the text is locally echoed and highlighted until the remote echos the text.

pyserial on raspberry pi with socat raises IOError on open

using socat on Raspberry Pi (wheezy), Python 2.7, pyserial 3.0, doing an open on a socat serial port raises the following exception:

serial.Serial(port="/dev/ttyVapor002")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/serial/serialutil.py", line 171, in __init__
    self.open()
  File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 311, in open
    self._update_dtr_state()
  File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 605, in _update_dtr_state
    fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
IOError: [Errno 22] Invalid argument

/dev/ttyVapor002 is hooked up to /dev/ttyVapor001 for a serial emulator setup using socat. We were using pyserial 2.7 previously and quite happily without error; on upgrade to pyserial 3.0, it appears the switch in how DTR state is updated does not work on this platform. Happy to dig around to help find a fix - it doesn't appear DTR state is set during open in pyserial-legacy, though setDTR does exist in serialposix.py there.

Bug in escape function of rfc2217 with Python 3

Python 3 handles bytes differently and 0xFF are not escaped correctly when they are read by the Serial object. In file rfc2217.py, line 1010, instead of:

for byte in data:
    if byte == IAC:
        yield IAC
        yield IAC

It should be:

for byte in data:
    if byte == ord(IAC):
        yield IAC
        yield IAC

I'm not sure how it should be done to work with both Python 2 and Python 3...

serial_for_url with do_not_open on loop://

Hi all,

I just realise that I cant use serial_for_url on loop:// if I instanciate with do_not_open=True option and configure port and open() later.
The error message is: could not open port loop:// [Errno2] Aucun fichier ou dossier de ce type: 'loop://'
Tested on 3.0a0 and 3.0b1

edit:
init of serial_for_url(None, do_not_open=True)
a try with serial_for_url("loop://", do_not_open=True) work on open() but you cant change port anymore...

Import serial breaks Python executable built with Nuitka

I'm attempting to build a very simple Python standalone executable using Nuitka:

import serial
print 'hello'

Building the executable using nuitka --standalone --portable app.py works, but if the PC's C:\Python27 directory is missing then the program fails with:

Traceback (most recent call last):
  File "C:\app\app.dist\app.py", line 6, in <module>
  File "C:\app\app.dist\serial\__init__.py", line 26, in serial

  File "C:\app\app.dist\serial\serialwin32.py", line 12, in serialwin32
  File "C:\Python27\lib\ctypes\__init__.py", line 10, in <module>

ImportError: No module named _ctypes

I suppose technically this is an issue with Nuitka not properly finding dependencies (I will post there too), but many other modules do work. I haven't checked yet if serial/ctypes does some sort of tricky importing.

In the meantime the workaround on the pyserial side is to simply add import _ctypes at the top of serialwin32.py. If it helps I can make a pull request for this.

Provide a way to disable read timeout on sockets

The socket class doesn't seem to have a way to disable the timeout on reads, this would be a very useful feature. I've worked around it by setting _timeout to a very small value in the meantime, but official support to disable this would be great.

[WxTerminal] Fail to run WxTerminal.py on Python3 with invalid column index

My environment (Windows 7 64bit):
Python3.4.3 (64bit)
pySerial: 3.0a
wxPython_Phoenix-3.0.3 (64bit)

Try to run example wxTerminal.py
Get first exception:

Traceback (most recent call last):
  File ".\wxTerminal.py", line 361, in OnInit
    frame_terminal = TerminalFrame(None, -1, "")
  File ".\wxTerminal.py", line 170, in __init__
    self.OnPortSettings(None)       # call setup dialog on startup, opens port
  File ".\wxTerminal.py", line 265, in OnPortSettings
    serial=self.serial) as dialog_serial_cfg:
  File "R:\pyserial-master\examples\wxSerialConfigDialog.py", line 37, in __init__
    if kwds.has_key('show'):
AttributeError: 'dict' object has no attribute 'has_key'
OnInit returned false, exiting...

In Python3, there is no dict,has_key, then I change has_key to dict.get.

Then meet below exception:

Traceback (most recent call last):
  File ".\wxTerminal.py", line 361, in OnInit
    frame_terminal = TerminalFrame(None, -1, "")
  File ".\wxTerminal.py", line 170, in __init__
    self.OnPortSettings(None)       # call setup dialog on startup, opens port
  File ".\wxTerminal.py", line 265, in OnPortSettings
    serial=self.serial) as dialog_serial_cfg:
  File "R:\pyserial-master\examples\wxSerialConfigDialog.py", line 69, in __init__
    self.__do_layout()
  File "R:\pyserial-master\examples\wxSerialConfigDialog.py", line 172, in __do_layout
    sizer_basics.AddGrowableCol(1)
wx._core.wxAssertionError: C++ assertion "!m_cols || idx < (size_t)m_cols" failed at ..\..\src\common\sizer.cpp(1980) in wxFlexGridSizer::AddGrowableCol(): invalid column index
OnInit returned false, exiting...

Serial read() function throwing error when used with inWaiting() in serialposix.py

As part of script development, I have used pyserial module for accessing the DUT. I have started using inWaiting() API for reading the data displayed on DUT.

But, during some instances, I have faced the following issue while reading the data.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
res=s.read(s.inWaiting)
File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 468, in read
buf = os.read(self.fd, size-len(read))
TypeError: unsupported operand type(s) for -: 'instancemethod' and 'int'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

For some reason, inWaiting has no data and the function tries to read the difference of size and the len(read) data.
buf = os.read(self.fd, size-len(read))

As a work around, I have added the following snippet in serialposix.py file @ line 468.
try:

                    buf = os.read(self.fd, size-len(read))
            except:
                    buf = os.read(self.fd, 3000)

Unable to open /dev/ttyUSB1 after upgrade to v3.0.1

Upgraded pyserial to v 3.0.1
list available COM ports:

$ python -m serial.tools.list_ports
/dev/ttyAMA0
/dev/ttyUSB0
/dev/ttyUSB1
3 ports found

running
$ python -m serial.tools.miniterm /dev/ttyUSB0
opens miniterm:

--- Miniterm on /dev/ttyUSB0  9600,8,N,1 ---
--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
at
OK

works fine.

However running
$ python -m serial.tools.miniterm /dev/ttyUSB1
returns

Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/local/lib/python2.7/dist-packages/serial/tools/miniterm.py", line 878, in <module>
    main()
  File "/usr/local/lib/python2.7/dist-packages/serial/tools/miniterm.py", line 834, in main
    serial_instance.open()
  File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 311, in open
    self._update_dtr_state()
  File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 605, in _update_dtr_state
    fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
IOError: [Errno 32] Broken pipe

After downgrade to pyserial 2.7 everything works fine:

$  python -m serial.tools.miniterm /dev/ttyUSB1
--- Miniterm on /dev/ttyUSB1: 9600,8,N,1 ---
--- Quit: Ctrl+]  |  Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
at
OK

^BOOT:31506079,0,0,0,77

^RSSI:18

^RSSI:18

^BOOT:31506079,0,0,0,77

In my case The ttyUSB1 is the status serial port of a USB 3g modem Huawei K3565, which the modem uses to report its states and other events (signal strengts, received calls etc)

Add baud rate 74880

Would it be possible to add support for the 74880 baud rate? I know it is non-standard, but unfortunately it is used by the ESP 8266 module for it's bootloader, so it would be nice to have.

For context, the Arduino IDE recently added it because of this: arduino/Arduino@db75e67

Thanks

Throw SerialException if can't open port

OS: Windows 7 64-bit
Python: v2.7.8
PySerial: v2.7

If I try to open a COM port that doesn't exist on the system, e.g.:

    port = Serial(
        port='COM66', baudrate=500000, bytesize=8,
        parity=serial.PARITY_NONE, stopbits=1, timeout=None)

I get an exception:

ERROR:   File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 38, in __init__
ERROR: SerialBase.__init__(self, *args, **kwargs)
ERROR:   File "C:\Python27\lib\site-packages\serial\serialutil.py", line 282, in __init__
ERROR: self.open()
ERROR:   File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 82, in open
ERROR: self._reconfigurePort()
ERROR:   File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 202, in _reconfigurePort
ERROR: raise ValueError("Cannot configure port, some setting was wrong. Original message: %r" % ctypes.WinError())
ERROR: ValueError
ERROR: :
ERROR: Cannot configure port, some setting was wrong. Original message: WindowsError(87, 'The parameter is incorrect.')

But shouldn't it throw a SerialException rather than a ValueError? Why a ValueError?

PS: Huge thank you for this great library :)

RFC: Update API for list_ports.comports()

The list of lists that is returned by serial.tools.list_ports.comports() is inflexible and prone to error.

Code and responses are from Python 3.4.3 running on OS X

For example in this invocation of comports() I get back a reply of

[['/dev/cu.Bluetooth-Incoming-Port', 'n/a', 'n/a'],
 ['/dev/cu.Bluetooth-Modem', 'n/a', 'n/a'],
 ['/dev/cu.usbserial', 'USB-Serial Controller', 'USB VID:PID=67b:2303 SNR=None']]

Now I can try matching with a grep on element 2 of each possible port but this is fragile across operating systems. On OS X we have some os specific USB properties such as location ID and if the device is considered a modem or a plain RS232 serial stream.

Location ID is a 32bit number that maps to a specific location on the USB bus that will not change if the hub topology is not changed upstream of the device. i.e. if you leave your USB bus alone the location ID will not change. This is useful for working with USB micro controllers that switch modes. e.g. from a USB-CDC interface you could issue a command to your part to enter a USB-DFU mode. If you knew your location ID before, you could attach to a DFU interface at that location ID.

As different systems have different serial port metadata, I propose a list of dictionaries to be returned by comports().

the above example would become

[
  {'device': '/dev/cu.Bluetooth-Incoming-Port'},
  {'device': '/dev/cu.Bluetooth-Modem'},
  {'device': '/dev/cu.usbserial',
    'USB PID': 8963,
    'USB VID': 1659, 
    'name': 'USB-Serial Controller',
    'location_id': 0xfa130000,
  },
]

Clearly this dictionary only includes keys that are populated. We could use the collections.DefaultDict to default non existent keys to None for convenience.

Alternatively we could use a named tuple and make the return more static.

Function name could change to maintain compatibly.
Thoughts?

serial.VERSION missing!!!

Hi all,

I don't know if it come from my setup but serial.VERSION is missing... (on 3.0b1 release)

Aio - Exception loop when serial device dissapears

When in Protocol serial device dissapears, in my case Bluetooth RFComm died, neverending exception loop started:

Traceback (most recent call last):
  File "/usr/lib/python3.4/asyncio/events.py", line 120, in _run
  File "/usr/lib/python3.4/site-packages/serial/aio.py", line 48, in _read_ready
  File "/usr/lib/python3.4/site-packages/serial/serialposix.py", line 505, in read
serial.serialutil.SerialException: read failed: device reports readiness to read but returned no data (device disconnected or multiple access on port?)

During handling of the above exception, another exception occurred:

--||--

Update documentation - KB2999226 required on Win 7 SP1

In order to run the win32 installer (2015-12-29) from pypi, I had to install KB299226 from MSDN. This fixed an error that I was missing api-ms-win-crt-string-l1-1-0.dll. I didn't see this mentioned in the docs, but I'm not sure where to add it - would you be willing to update appropriately, or let me know which file to update in a pull request? Thanks!

Sourceforge status

This is the current official development of pyserial, right?

If so, could the sourceforge page be updated/removed or at least indicate that sourceforge is no longer used and link to here? I think it's quite confusing right now.

The website link on PyPI could be updated too.

Happy to see active development on pyserial lately!

Thanks!

Raspberry Pi pyserial need constant reboot

Hi!

I am doing an application where I need to read a RS485 stream, I tried with pyserial and the program is working once but needs reboot between each uses. Doing the same in C does not poses any problem.

The problem is more described here. Apparently I am not the first to have this issue.

Can you tell something about this issue?

Thanks for the work!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.