python : How to detect device name/id on a serial COM - python

I would like some indication on how to do this in python:
Identify the port named a specific name in the serial com (\Device\VCP0 and \Device\VCP1 these are get by browsing in regedit window)
And get the id of the device that is pluged
I can already identify the avalable COM with this pySerial code that scan up the active serial port 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
return available
if __name__=='__main__':
print "Found ports:"
for n,s in scan():
print "(%d) %s" % (n,s)
Thanks in advance

I am not sure what operating system you are using, but this is in Win7-x64
import win32com.client
wmi = win32com.client.GetObject("winmgmts:")
for serial in wmi.InstancesOf("Win32_SerialPort"):
print (serial.Name, serial.Description)
Using this information, you can parse it and get the COM numbers.
You can get other attributes of the Serial instances here:
http://msdn.microsoft.com/en-us/library/aa394413(v=vs.85).aspx

Two answer
1) Because this relies on the hardware available, it is perfectly possible that the test code worked in the environment it was written on, but doesn't work in your environment - may be quite likely if you are on Windows and this was written on Linux. The code uses port 0 - don't know how that maps to COM1 etc.
2) On Windows, COM ports used to have DOS names like COM1, COM2 - i.e. A string, not an int (they aren't like TCP/IP port numbers). More recently in Windows there is the \.\COMnotanumber format which allows a more generic name, I've seen these used by a USB to serial converter. Having had a quick look at the source code of pyserial SerialBase in serialutil.py, it's a bit odd IMO, because AFAICT self.name only gets set when you use an explicit port setting by calling self.port(portname). You might want to try intializing the serial port instance with serport = Serial(0) then explicitly calling serport.port('COM1') (or whatever your port name is instead of COM1).
Just corrected the code. its working fine... :)
import serial
def scan():
available = []
for i in range(256):
try:
s = serial.Serial('COM'+str(i))
available.append( (s.portstr))
s.close() # explicit close 'cause of delayed GC in java
except serial.SerialException:
pass
for s in available:
print "%s" % (s)
if __name__=='__main__':
print "Found ports:"
scan()

If you are using a USB to TTY serial adapter, a unique symbolic link to the device driver file will appear in /dev/serial/by-id. The folder will only appear if a serial device is plugged in. The file name displayed is created from the product information in the USB interface chip on the device and will be unique for that device.
For instance, a Korad KD3005P programmable power supply will show up as usb-Nuvoton_USB_Virtual_COM_A92014090305-if00. The symbolic link will resolve to '/../../ttyACM0'. The required device drive file is then '/dev/ttyACM0'.

Related

PySerial Attributes - Issues, Documentation Current Reference?

I am very new, learning Python specifically geared toward hardware (serial port and TCP/IP device) testing.
I have been trying to get PySerial based code to work and keep hitting roadblocks. Running Python 3.10.8 on Windows 10.
I worked through the 'import serial' problem (uninstalled and reinstalled Python); the serial.Serial problem (needed to add 'from serial import *). Now, it seems like all of the read syntax does not work. All I want to do at this point is open the port, read and print data - from here I will start working on which data I want).
Here is the code I am working with (this was found in a couple of places on the internet):
#test_sport
import serial
from serial import *
s = serial.Serial(port='COM9', baudrate=9600)
serial_string = ""
while(1):
# Wait until there is data waiting in the serial buffer
if(serialPort.in_waiting > 0):
# Read data out of the buffer until a carraige return / new line is found
serial_string = serial.readline()
# Print the contents of the serial data
print(serial_string.decode('Ascii'))
# Tell the device connected over the serial port that we recevied the data!
# The b at the beginning is used to indicate bytes!
#serialPort.write(b"Thank you for sending data \r\n")
Running this results in an error on serialPort.in_waiting (says serialPort not defined) if I change that to serial.in_waiting (says serial has no attribute 'in_waiting' (PySerial API site says this is correct(?). I've also tried simple commands like serial.read(), serial.readline(), ser.read(), etc. All fail for attributes.
Is the PySerial documentation online current? Does anyone know where to find basic serial port examples?
Thank you!

Crystal-lang Accessing Serial port

I want to access the serial port using Crystal lang.
I have following code in python. I want to write the equivalent Crystal-lang code for a pet project.
import serial
def readSerData():
s = ser.readline()
if s:
print(s)
result = something(s) #do other stuff
return result
if __name__ == '__main__':
ser = serial.Serial("/dev/ttyUSB0", 9600)
while True:
data = readSerData()
#do something with data
I couldn't find any library for accessing the serial port.
What is the proper way for accessing serial port in crystal-lang?
Thanks in advance.
It is easier to answer this question in multiple parts to really cover it all:
Q: How do I access a serial port on linux/bsd?
A: Open it as a file. On linux/bsd a serial connection is established the moment a device is plugged in, and is then listed somewhere under /dev/ (these days, usually as /dev/ttyUSB0). In order to access this connection you simply open it like you would a regular file. Sometimes this is actually good enough to start communicating with the device as modern hardware typically works with all baud rates and default flags.
Q: How do I configure a serial/tty device on linux/bsd?
A: Set termios flags on the file. If you do need to configure your connection to set things like baud rate, IXON/IXOFF etc, you can do it before even running your program using stty if it is available. Eg. to set the baud rate you could run: stty -F /dev/ttyUSB0 9600. And after this is set up you can just open it as a file and start using it.
You can spawn stty from crystal using Process.run if you wanted an easy way to configure the device from your app. I would probably recommend this approach over the next solution..
Q: How do I set termios flags from crystal, without using stty?
A: Use the termios posix functions directly.
Crystal actually provides FileDescriptor handles with a few common termios settings such as cooked, which means it has minimal termios bindings already. We can start by using the existing code for our inspiration:
require "termios" # See above link for contents
#Open the file
serial_file = File.open("/dev/ttyACM0")
raise "Oh no, not a TTY" unless serial_file.tty?
# Fetch the unix FD. It's just a number.
fd = serial_file.fd
# Fetch the file's existing TTY flags
raise "Can't access TTY?" unless LibC.tcgetattr(fd, out mode) == 0
# `mode` now contains a termios struct. Let's enable, umm.. ISTRIP and IXON
mode.c_iflag |= (Termios::InputMode::ISTRIP | Termios::InputMode::IXON).value
# Let's turn off IXOFF too.
mode.c_iflag &= ~Termios::InputMode::IXOFF.value
# Unfun discovery: Termios doesn't have cfset[io]speed available
# Let's add them so changing baud isn't so difficult.
lib LibC
fun cfsetispeed(termios_p : Termios*, speed : SpeedT) : Int
fun cfsetospeed(termios_p : Termios*, speed : SpeedT) : Int
end
# Use the above funcs to set the ispeed and ospeed to your nominated baud rate.
LibC.cfsetispeed(pointerof(mode), Termios::BaudRate::B9600)
LibC.cfsetospeed(pointerof(mode), Termios::BaudRate::B9600)
# Write your changes to the FD.
LibC.tcsetattr(fd, Termios::LineControl::TCSANOW, pointerof(mode))
# Done! Your serial_file handle is ready to use.
To set any other flags, refer to the termios manual, or this nice serial guide I just found.
Q: Is there a library to do all this for me?
A: No :( . Not that I can see, but it would be great if someone made it. It's probably not much work for someone to make one if they had a vested interest :)

Connecting via USB/Serial port to Newport CONEX-PP Motion Controller in Python

I'm having trouble getting my Windows 7 laptop to talk to a Newport CONEX-PP motion controller. I've tried python (Spyder/Anaconda) and a serial port streaming program called Termite and in either case the results are the same: no response from the device. The end goal is to communicate with the controller using python.
The controller connects to my computer via a USB cable they sold me that is explicitly for use with this device. The connector has a pair of lights that blink when the device receives data (red) or sends data (green). There is also a packaged GUI program that comes with the device that seems to work fine. I haven't tried every button, the ones I have tried have the expected result.
The documentation for accessing this device is next to non-existant. The CD in the box has one way to connect to it and the webpage linked above has a different way. The first way (CD from the box) creates a hierarchy of modules that ends in a module it does not recognize (this is a code snippet provided by Newport):
import sys
sys.path.append(r'C:\Newport\MotionControl\CONEX-PP\Bin')
import clr
clr.AddReference("Newport.CONEXPP.CommandInterface")
from CommandInterfaceConexPP import *
import System
instrument="COM5"
print 'Instrument Key=>', instrument
myPP = ConexPP()
ret = myPP.OpenInstrument(instrument)
print 'OpenInstrument => ', ret
result, response, errString = myPP.SR_Get(1)
That last line returns:
Traceback (most recent call last):
File "< ipython-input-2-5d824f156d8f >", line 2, in
result, response, errString = myPP.SR_Get(1)
TypeError: No method matches given arguments
I'm guessing this is because the various module references are screwy in some way. But I don't know, I'm relatively new to python and the only time I have used it for serial communication the example files provided by the vendor simply worked.
The second way to communicate with the controller is via the visa module (the CONEX_SMC_common module imports the visa module):
import sys
sys.path.append(r'C:\Newport\NewportPython')
class CONEX(CONEXSMC): def __init__(self):
super(CONEX,self).__init__() device_key = 'com5'
self.connect=self.rm.open_resource(device_key, baud_rate=57600, timeout=2000, data_bits=8, write_termination='\r\n',read_termination='\r\n')
mine.connect.read()
That last mine.connect.read() command returns:
VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
If, instead, I write to the port mine.connect.write('VE') the light on the connector flashes red as if it received some data and returns:
(4L, < StatusCode.success: 0 >)
If I ask for the dictionary of the "mine" object mine.__dict__, I get:
{'connect': <'SerialInstrument'(u'ASRL5::INSTR')>,
'device_key': u'ASRL5::INSTR',
'list_of_devices': (u'ASRL5::INSTR',),
'rm': )>}
The ASRL5::INSTR resource for VISA is at least related to the controller, because when I unplug the device from the laptop it disappears and the GUI program will stop working.
Maybe there is something simple I'm missing here. I have NI VISA installed and I'm not just running with the DLL that comes from the website. Oh, I found a Github question / answer with this exact problem but the end result makes no sense, the thread is closed after hgrecco tells him to use "open_resource" which is precisely what I am using.
Results with Termite are the same, I can apparently connect to the controller and get the light to flash red, but it never responds, either through Termite or by performing the requested action.
I've tried pySerial too:
import serial
ser = serial.Serial('com5')
ser.write('VE\r\n')
ser.read()
Python just waits there forever, I assume because I haven't set a timeout limit.
So, if anyone has any experience with this particular motion controller, Newport devices or with serial port communication in general and can shed some light on this problem I'd much appreciate it. After about 7 hours on this I'm out of ideas.
After coming back at this with fresh eyes and finding this GitHub discussion I decided to give pySerial another shot because neither of the other methods in my question are yet working. The following code works:
import serial
ser = serial.Serial('com5',baudrate=115200,timeout=1.0,parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
ser.write('1TS?\r\n')
ser.read(10)
and returns
'1TS000033\r'
The string is 9 characters long, so my arbitrarily chosen 10 character read ended up picking up one of the termination characters.
The problem is that python files that come with the device, or available on the website are at best incomplete and shouldn't be trusted for anything. The GUI manual has the baud rate required. I used Termite to figure out the stop bit settings - or at least one that works.
3.5 years later...
Here is a gist with a class that supports Conex-CC
It took me hours to solve this!
My device is Conex-CC, not PP, but it's seem to be the same idea.
For me, the serial solution didn't work because there was absolutely no response from the serial port, either through the code nor by direct TeraTerm access.
So I was trying to adapt your code to my device (because for Conex-CC, even the code you were trying was not given!).
It is important to say that import clr is based on pip install pythonnet and not pip install clr which will bring something related to colors.
After getting your error, I was looking for this Pythonnet error and have found this answer, which led me to the final solution:
import clr
# We assume Newport.CONEXCC.CommandInterface.dll is copied to our folder
clr.AddReference("Newport.CONEXCC.CommandInterface")
from CommandInterfaceConexCC import *
instrument="COM4"
print('Instrument Key=>', instrument)
myCC = ConexCC()
ret = myCC.OpenInstrument(instrument)
print('OpenInstrument => ', ret)
response = 0
errString = ''
result, response, errString = myCC.SR_Get(1, response, errString)
print('Positive SW Limit: result=%d,response=%.2f,errString=\'%s\''%(result,response,errString))
myCC.CloseInstrument()
And here is the result I've got:
Instrument Key=> COM4
OpenInstrument => 0
Positive SW Limit: result=0,response=25.00,errString=''�
For Conex-CC serial connections are possible using both pyvisa
import pyvisa
rm = pyvisa.ResourceManager()
inst = rm.open_resource('ASRL6::INSTR',baud_rate=921600, write_termination='\r\n',read_termination='\r\n')
pos = inst.query('01PA?').strip()
and serial
import serial
serial = serial.Serial(port='com6',baudrate=921600,bytesize=8,parity='N',stopbits=1,xonxoff=True)
serial.write('01PA?'.encode('ascii'))
serial.read_until(b'\r\n')
All the commands are according to the manual

Pyserial get the name of the device behind a COM Port

I want to get a list of the devices which are connected to a COM Port. Instead of having python -m serial.tools.list_ports with the output COM1 COM2 for example, I want to have an output like Arduino_Uno Arduino Due etc. (Like the Arduino Gui do it, for example).
I found some answers for listing the COM Ports (like Listing available com ports with Python ), but no answer for my problem.
#J.P. Petersen is right - the serial port does not by itself provide that information. But the USB specifications allows some information to be sneaked in, and
serial.tools.list_ports.comports() thankfully returns that. The following code snipped is from my ArduinoBase class that works under Windows and Linux and does what you are looking for, i.e. it gives you Arduino Uno and Arduino Due descriptions as appropriate
def listPorts():
"""!
#brief Provide a list of names of serial ports that can be opened as well as a
a list of Arduino models.
#return A tuple of the port list and a corresponding list of device descriptions
"""
ports = list( serial.tools.list_ports.comports() )
resultPorts = []
descriptions = []
for port in ports:
if not port.description.startswith( "Arduino" ):
# correct for the somewhat questionable design choice for the USB
# description of the Arduino Uno
if port.manufacturer is not None:
if port.manufacturer.startswith( "Arduino" ) and \
port.device.endswith( port.description ):
port.description = "Arduino Uno"
else:
continue
else:
continue
if port.device:
resultPorts.append( port.device )
rdescriptions.append( str( port.description ) )
return (resultPorts, descriptions)

Pyserial code to connect peripheral device to PC automatically when using USB- Serial cable

I have one peripheral device (say hardware circuit with microcontroller). I have to iput some commands to this peripheral device via serial communication. These commands are embedded into a python script.
I am using USB-Serial cable to connect peripheral device to PC.
Now I have to write the code in pyserial so that PC will automatically detect the com port on which Peripheral device is connected and connects the devide with PC successfully.(loop back can be possible)
Currently I am using following Code in Pyserial. I have explicitely mentioned that Peripheral is connected to PC on COM1 ---
try:
self.ser = serial.Serial(0)
#self.ser.port='/dev/ttyS1'
self.ser.baudrate = 9600
self.ser.bytesize = serial.EIGHTBITS
self.ser.parity = serial.PARITY_NONE
self.ser.stopbits = serial.STOPBITS_ONE
self.ser.timeout = 1
self.ser.xonxoff = False #disable software flow control
self.ser.rtscts = False #disable hardware (RTS/CTS) flow control
self.ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
self.ser.writeTimeout = 2 #timeout for write
except Exception, e:
print "error open serial port: " + str(e)
Please let me know that how can a COM port is automatically detected and gets connect afterwards?
This is a common issue and can be solved by checking for a specific return code (usually an identification string) from the peripheral device. Here's an example, using pyserial:
from serial.tools import list_ports
def locate_port():
"""Attempt to locate the serial port to which the device
is connected."""
status_request_string = 'OI;' # Output information
expected_response = 'DISPENSEMATE'
device_port = None
for port_name, port_desc, hw_id in list_ports.comports():
with serial.Serial(port=port_name, **device_serial_settings) as ser:
ser.write(status_request_string)
if ser.readline().startswith(expected_response):
device_port = port_name
break
if not device_port:
raise UserWarning('Could not find a serial port belonging to '
'the asymtek dispensemate.')
return device_port
Usually, the manual of the device you're communicating with has at least one command that does not change the state of the device, but merely echoes back your last line or returns its configuration, hardware ROM version or simply its name. It is this response (and the command that requests it), that you 'll need to fill in for expected_response and status_request_string respectively. The device_serial_settings is a dictionary that contains the parameters such as baudrate and parity bits; everything needed to connect properly to the device, except for its name.
As you can see, the code above was written for an Asymtek Dispensemate (an old one too and thus difficult to get support for).
If you call that function, you can use its return value to simply connect to the device:
port = locate_port()
my_device = serial.Serial(port, **device_serial_settings)
There is one caveat though: if the computer is connected to several serial devices that are all powered on, it is possible that you send an illegal command to the other devices. In the best case, they simply reply with an error code and their state will be unaffected, but the command could also make changes to these devices, so check all other peripherals for their dictionaries of "allowed opcodes".

Categories