PySerial and IronPython - get strange error
Question: I have a device connected to COM31. And the code that I need to create a
serial connection looks very simple

    
    
    port = 31
    trex_serial = serial.Serial(port - 1, baudrate=19200, stopbits=serial.STOPBITS_ONE, timeout=1)
    

The foollowing code works when I run it using Python2.6, but when executed by
IronPython2.6.1, this is what I get:

    
    
    Traceback (most recent call last):
      File "c:\Python26\lib\site-packages\serial\serialutil.py", line 188, in __init__
    
      File "c:\Python26\lib\site-packages\serial\serialutil.py", line 236, in setPort
    
      File "c:\Python26\lib\site-packages\serial\serialcli.py", line 139, in makeDeviceName
    
      File "c:\Python26\lib\site-packages\serial\serialcli.py", line 17, in device
    
    IndexError: index out of range: 30
    

I am not sure what is going on. PySerial clearly says that it is IronPython
compliant. Any ideas what am I doing wrong?


Answer: IronPython is asking .NET what the ports are. They are enumerated differently.
Most likely you are asking to open a connection that doesn't exist as far as
IronPython/.NET is concerned. To find out the "real" port number, use the
following code modified from the pySerial scan examples. Then use the number
next to the listed COM.

    
    
    import serial
    
    def scan():
    #scan for available ports. return a list of tuples (num, name)
    available = []
    for i in range(256):
        try:
            s = serial.Serial(i)
            available.append( (i, s.portstr))
            s.close()   # explicit close 'cause of delayed GC in java
        except serial.SerialException:
            pass
        #You must add this check, otherwise the scan won't complete
        except IndexError as Error:
            pass
    
    for n,s in available:
        print "(%d) %s" % (n,s)
    
    return available
    

The output looks like this for me:

(0) COM9

(1) COM15

(2) COM16

(3) COM1

(4) COM15

Then when you try to open the connection, use the number on the left NOT the
actual COMportNumber - 1. For instance I need to open a connection to COM15,
so using the above scan:

    
    
    def IOCardConnect():
    try:
        connection = serial.Serial(4, 115200, timeout=1, parity=serial.PARITY_NONE)
        print "Connection Succesful"
        return connection
    except serial.SerialException as Error:
        print Error
    

Also, once you are connected, pySerial will expect bytes to write to the
connectio, not strings. So make sure you send like this:

    
    
    #Use the built in bytes function to convert to a bytes array.
    connection.write(bytes('Data_To_Send'))
    

