Linux dev tty usb

команда для определения портов устройства (например, / dev / ttyUSB0)

У меня вопрос по поводу портов в Linux. Если я подключаю свое устройство через USB и хочу проверить его порт, я не могу сделать это с помощью команды lsusb, которая указывает только номер шины и номер устройства на этой шине:

Есть ли команда, которая сообщает мне порт, к которому устройство подключено напрямую? Единственный способ сделать это до сих пор заключался в том, чтобы отключить и повторно подключиться и использовать команду:

В последней строке видно, что мое устройство подключено к / dev / ttyUSB0 .

Я не совсем уверен, что вы спрашиваете. Вы упоминаете «порт» несколько раз, но затем в своем примере вы говорите, что ответом является /dev/ttyUSB0 путь устройства, а не порт. Таким образом, этот ответ о поиске пути разработки для каждого устройства.

Ниже приведен быстрый и грязный скрипт, который просматривает устройства в /sys поиске USB-устройств с ID_SERIAL атрибутом. Обычно только настоящие USB-устройства будут иметь этот атрибут, и мы можем фильтровать его. Если мы этого не сделаем, вы увидите в списке много вещей, которые не являются физическими устройствами.

В моей системе это приводит к следующему:

Объяснение:

Устройства, которые отображаются в, /dev имеют dev файл в своем /sys каталоге. Поэтому мы ищем каталоги, соответствующие этим критериям.

Нам нужен путь к каталогу, поэтому мы удалим его /dev .

Это дает нам путь, /dev который соответствует этому /sys устройству.

Это отфильтровывает вещи, которые не являются фактическими устройствами. В противном случае вы получите такие вещи, как USB-контроллеры и концентраторы.

Команда udevadm info -q property —export выводит список всех свойств устройства в формате, который может быть проанализирован оболочкой в ​​переменные. Поэтому мы просто призываем eval к этому. Это также причина, по которой мы заключаем код в круглые скобки, чтобы мы использовали подоболочку, а переменные стирались в каждом цикле.

Больше фильтрации вещей, которые не являются реальными устройствами.

Я надеюсь, что вы знаете, что делает эта строка 🙂

Источник

Выполнение AT/USSD команд к /dev/ttyUSB* модему из консоли Linux

Утилиты и скрипты для коммуникации с /dev/ttyUSB* устройством из shell консоли (bash скриптов).

Читайте также:  Как избавиться от windows system32

Теория

Отправить в /dev/ttyUSB* терминал AT команду не составляет проблем. Но результат вывода мы не увидим!

Мы можем читать поток stdout c /dev/ttyUSB2 (результат выполнения команд):

  1. Нужно получить только результат выполнения конкретной AT команды, а не весь поток вывода.
  2. Нужно использовать gsm7bit кодировку для кодирования параметров и получения ответа при выполнении USSD запросов:
  3. Ну и хочется простоты в работе)

Выполнение AT/USSD команд

Скрипт at.sh для отправки AT команды и получения ответа в переменную:

Но вы получите ответ вида:

minicom

Можно отправить AT команду и перенаправить весь вывод в файл:

После этого нужно закрыть терминал и разобрать/декодировать весь вывод из файла output.txt. Не круто..

ussd.py

В сети нашел python скрипт для отправки USSD запросов (немного поправил):

Кодировка GSM 7bit в USSD запросах

Кодирование в gsm7bit

При отправке USSD запросов нужно кодировать USSD-код в кодировку GSM 7bit (как я понял из-за того, что модем не поддерживает текстовый режим).

Следующие запросы вернут ERROR:

Python функция gsm7bitencode для кодирования utf8 строки в gsm7bit:

Примечание

Смотрите онлайн-сервис для работы с кодировками: http://smstools3.kekekasvi.com/topic.php?id=288

Пример USSD команд в кодировке 7bit gsm проверки баланса:

Кодированные ответы (ответ всегда приходит на устройство /dev/ttyUSB2):

Декодирование из gsm7bit

Python функция gsm7bitdecode для декодирования gsm7bit в utf8:

Источник

screen /dev/ttyUSB0 with different options such as databit, parity, etc

I am trying to use

to connect to a old computer(s) through a USB-serial interface.

I am hoping that registering on this site I will receive answers to my question. I have searched and searched, but have not figured out to put the correct options in my command line to get a non-gibberish feedback from my computer (the text received is all screwed up).

My operating system is CentOs, Gnome 2.16.0. I see that there is a program called KPPP which has a «Terminal. «, but haven’t figured that one out either. So I am trying to use CLI with ‘screen’, but I am having trouble setting the correct parameters (obviously, I do not understand how to put these parameters to use with stty). It is not an option installing applications or doing anything with this computer, so I have to use what’s already there. ‘screen’ seems to do the job, but the text received is gibberish as mentioned earlier («$$@%idj ldj» etc.)

I need these parameters for computer one:

Baud: 9600 Databit: 8 Parity: No Stopbit: 2 Flow control: Hardware.

For computer two I need:

Baud: 9600 Databit: 7 Parity: Even Stopbit: 1 Flow control: Hardware

The baud rate is easy;

Читайте также:  Пропали значки громкости windows 10

But what to do with the rest, I do not know. . I have found the option for stop bits:

-cstopb (use one stop bits)

But how do I use it correctly?

So if someone could help me out connecting to the other computer through serial interface with all of the listed parameters I would be very thankfull!

Источник

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

What is the proper way to get a list of all available serial ports/devices on a Linux system?

In other words, when I iterate over all devices in /dev/ , how do I tell which ones are serial ports in the classic way, that is, those usually supporting baud rates and RTS/CTS flow control?

The solution would be coded in C.

I ask because I am using a third-party library that does this clearly wrong: It appears to only iterate over /dev/ttyS* . The problem is that there are, for instance, serial ports over USB (provided by USB-RS232 adapters), and those are listed under /dev/ttyUSB*. And reading the Serial-HOWTO at Linux.org, I get the idea that there’ll be other name spaces as well, as time comes.

So I need to find the official way to detect serial devices. The problem is that none appears to be documented, or I can’t find it.

I imagine one way would be to open all files from /dev/tty* and call a specific ioctl() on them that is only available on serial devices. Would that be a good solution, though?

Update

hrickards suggested to look at the source for «setserial». Its code does exactly what I had in mind:

First, it opens a device with:

Then it invokes:

If that call returns no error, then it’s a serial device, apparently.

I found similar code in Serial Programming/termios, which suggested to also add the O_NOCTTY option.

There is one problem with this approach, though:

When I tested this code on BSD Unix (that is, Mac OS X), it worked as well. However, serial devices that are provided through Bluetooth cause the system (driver) to try to connect to the Bluetooth device, which takes a while before it’ll return with a timeout error. This is caused by just opening the device. And I can imagine that similar things can happen on Linux as well — ideally, I should not need to open the device to figure out its type. I wonder if there’s also a way to invoke ioctl functions without an open, or open a device in a way that it does not cause connections to be made?

Читайте также:  Турбо режим для windows

Источник

command to determine ports of a device (like /dev/ttyUSB0)

I have a question regarding the ports in Linux. If I connect my device via USB and want to check its port I can’t do it using the command lsusb, which only specifies bus number and device number on this bus:

Is there a command that tells me the port the device is connected to directly? Only way to do this until now was to disconect and reconnect and using the command:

In the last line it can be seen that my device is connected to /dev/ttyUSB0.

6 Answers 6

I’m not quite certain what you’re asking. You mention ‘port’ several times, but then in your example, you say the answer is /dev/ttyUSB0 , which is a device dev path, not a port. So this answer is about finding the dev path for each device.

Below is a quick and dirty script which walks through devices in /sys looking for USB devices with a ID_SERIAL attribute. Typically only real USB devices will have this attribute, and so we can filter with it. If we don’t, you’ll see a lot of things in the list that aren’t physical devices.

On my system, this results in the following:

Explanation:

Devices which show up in /dev have a dev file in their /sys directory. So we search for directories matching this criteria.

We want the directory path, so we strip off /dev .

This gives us the path in /dev that corresponds to this /sys device.

This filters out things which aren’t actual devices. Otherwise you’ll get things like USB controllers & hubs. The exit exits the subshell, which flows to the next iteration of the loop.

The udevadm info -q property —export command lists all the device properties in a format that can be parsed by the shell into variables. So we simply call eval on this. This is also the reason why we wrap the code in the parenthesis, so that we use a subshell, and the variables get wiped on each loop.

More filtering of things that aren’t actual devices.

Источник

Оцените статью