- Виртуальный последовательный порт для Linux
- JustChecking’s Weblog On All
- Life, science, programming, and all… convincing and meaningless.
- HowTo: Virtual Serial Ports on Linux using socat, and more
- To create a pair of VSP’s
- Connecting executable and VSP
- Virtual network interfaces
- Ubuntu Documentation
- Introduction
- Installing prerequisites
- Creating ports
- Checking file names
- Using socat
- Using lsof
- External Links
- Linux virtual com ports
- Настраиваем виртуальный компорт в Ubuntu
Виртуальный последовательный порт для Linux
Мне нужно протестировать приложение последовательного порта в Linux, однако моя тестовая машина имеет только один последовательный порт.
Есть ли способ добавить виртуальный последовательный порт в Linux и протестировать мое приложение, эмулируя устройство через оболочку или скрипт?
Примечание: я не могу переназначить порт, он жестко запрограммирован на ttys2, и мне нужно протестировать приложение, как оно написано.
Для этого вы можете использовать pty («псевдотелетайп», где последовательный порт является «настоящим телетайпом»). С одного конца откройте /dev/ptyp5 , а затем прикрепите свою программу к /dev/ttyp5 ; ttyp5 будет действовать так же, как последовательный порт, но будет отправлять / получать все, что он делает, через / dev / ptyp5.
Если вам действительно нужно, чтобы он разговаривал с файлом с именем /dev/ttys2 , просто уберите старый /dev/ttys2 и создайте символическую ссылку с ptyp5 на ttys2 .
Конечно, вы можете использовать другое число, кроме ptyp5 . Возможно, выберите один с большим числом, чтобы избежать дублирования, поскольку все ваши терминалы входа также будут использовать ptys.
В Википедии есть дополнительная информация о ptys: http://en.wikipedia.org/wiki/Pseudo_terminal
Дополняя ответ @ slonik.
Вы можете протестировать socat для создания виртуального последовательного порта, выполнив следующую процедуру (проверено на Ubuntu 12.04):
Откройте терминал (назовем его Terminal 0) и запустите его:
Приведенный выше код возвращает:
Откройте другой терминал и напишите (Терминал 1):
имя порта этой команды может быть изменено в зависимости от компьютера. это зависит от предыдущего вывода.
вы должны использовать номер, доступный в выделенной области.
Откройте другой терминал и напишите (Терминал 2):
Теперь вернитесь в Терминал 1, и вы увидите строку «Тест».
Для этого используйте socat:
Также существует tty0tty http://sourceforge.net/projects/tty0tty/, который является настоящим эмулятором нуль-модема для Linux.
Это простой модуль ядра — небольшой исходный файл. Я не знаю, почему он получил отрицательные отзывы на sourceforge, но мне он подходит. Самое лучшее в нем то, что он также эмулирует аппаратные контакты (RTC / CTS DSR / DTR). Он даже реализует команды TIOCMGET / TIOCMSET и TIOCMIWAIT iotcl!
В недавнем ядре вы можете получить ошибки компиляции. Это легко исправить. Просто вставьте несколько строк вверху источника module / tty0tty.c (после включений):
Когда модуль загружен, он создает 4 пары последовательных портов. Устройства: от / dev / tnt0 до / dev / tnt7, где tnt0 подключен к tnt1, tnt2 подключен к tnt3 и т. Д. Вам может потребоваться исправить права доступа к файлам, чтобы иметь возможность использовать устройства.
Думаю, я немного поторопился со своим энтузиазмом. Хотя драйвер выглядит многообещающе, он кажется нестабильным. Я не знаю наверняка, но думаю, что это разбило машину в офисе, над которым я работал из дома. Я не могу проверить, пока не вернусь в офис в понедельник.
Во-вторых, TIOCMIWAIT не работает. Код, кажется, скопирован из какого-то примера кода «крошечного терминала». Обработка TIOCMIWAIT кажется на месте, но она никогда не просыпается, потому что соответствующий вызов wake_up_interruptible () отсутствует.
Авария в офисе действительно произошла по вине водителя. Отсутствовала инициализация, и полностью непроверенный код TIOCMIWAIT вызвал сбой машины.
Вчера и сегодня потратил на переписывание драйвера. Было много проблем, но теперь у меня все хорошо. По-прежнему отсутствует код для аппаратного управления потоком данных, управляемого драйвером, но он мне не нужен, потому что я сам буду управлять контактами, используя TIOCMGET / TIOCMSET / TIOCMIWAIT из кода пользовательского режима.
Если кому-то интересна моя версия кода, напишите мне, и я отправлю его вам.
Источник
JustChecking’s Weblog On All
Life, science, programming, and all… convincing and meaningless.
HowTo: Virtual Serial Ports on Linux using socat, and more
socat (SOcket CAT) – multipurpose relay – is a command line based utility that establishes two bidirectional byte streams and transfers data between them.
socat is #4 on the Top 100 Network Security Tools list, available in most distro repositories (on Debian/Ubuntu sudo apt-get install socat does the trick), really light on resources, and very efficient.
Sounds simple, does wonders!
Sidenote: socat is actually #71 on the mentioned list, but since socat is a much enhanced version of netcat, which is #4, it seems to me logical to count socat as #4 also.
One of the wonders you can do is creating pairs of “virtual” ports/interfaces/sockets etc., even hybrid pairs like port-socket, etc., where one (or both) ends of the pair can also be real objects. See socat man page for more details.
Creating pairs of virtual serial ports (VSP), is quite often wanted feature, yet it’s hard to find a solution online (try Googling it)… Pair of VSP’s is very useful to have esp. if you’re into embedded device programming, where many embedded development kits support debugging via serial link – PharLap in my case. Yes, it does have Ethernet debugging since ETS 14, but it’s a very unstable option.
Even if you’re using Ethernet debugging, it’s often much easier to have your embedded system in a virtual machine (VirtualBox, VMWare etc.), and do the debugging via virtual NIC.
To cut the talk short, many thanks to Gerhard Rieger, author of socat, for the following tips!
To create a pair of VSP’s
and that’s it! As long as the socat is running, you have a pair of VSP’s open (their names are printed by socat on initialization). See socat man page for more details on what the above command does.
Connecting executable and VSP
where the executable myprog will be connected with the VSP through stdio.
Virtual network interfaces
In a similar fashion, you can create pairs of virtual network interfaces – tun/tap devices (again, this pair exists as long as the master process – socat – is alive):
Yes, that’s it, you’ve got a pair of virtual network interfaces!
Источник
Ubuntu Documentation
Introduction
Virtual serial ports are commonly used in development of programs using serial connection as well as debugging existing applications — to check what kind of data is transmitted over a serial connection.
The idea of virtual serial port is to create two virtual serial ports linked with a null modem cable, attaching one end to tested application and the other end to (usually) serial terminal (e.g. Cutecom).
Installing prerequisites
To create a pair of ports you will need a utility called «socat». It is located in «universe» repository, so you should be able to find it in Synaptic. Alternatively install using
Creating ports
After installing socat you have to execute following command:
That should create and link the virtual port pair for as long as socat is running.
If you are like me and want a little more feedback on what is happening instead of a command line that is hanging, use verbose mode instead:
You can put the -d argument up to four times, increasing the information fed back to you each time.
Checking file names
Using socat
The easiest way to tell which file names are assigned to these virtual ports is to tell socat to print information about opened pseudo terminals during initialization using following options (verbose mode):
Your applicantion should connect to these files.
Using lsof
Another way is to list socat’s open files:
You should notice file /dev/ptmx, that is pseudo terminal multiplexer and directly below each entry should be listed /dev/pts/X file, which are the ends of created pair.
External Links
VirtualSerialPort (последним исправлял пользователь janisozaur 2010-10-28 11:21:26)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Источник
Linux virtual com ports
Virtual Serial Port driver for Linux
This kernel module allows userspace programs to create virtual serial ports under /dev/ttyV#.
This is somewhat similar to the regular pseudo-tty interface, but vtty also emulates characteristics such as baud rate & modem line state. This allows users to create a fully-functional serial port driver completely in userspace.
- forward a serial port over the network. There are several Linux implementations of a RFC2217 server. VTTY allows you to write a RFC2217 client exposing a native-looking serial port to other software.
- quickly prototype a driver for an USB-to-serial converter using VTTY & libusb
- split one physical serial port in two, allowing two apps to access it without conflict (for example gdb & minicom, or esptool & minicom)
The module creates a /dev/vtmx «master» device, which is used to create the virtual serial ports in a manner similar to the pseudo-tty master device /dev/ptmx. Opening the /dev/vtmx device causes a /dev/ttyV# device to be allocated. The index of the virtual port can be obtained by issuing a VTMX_GET_VTTY_NUM (equal to TIOCGPTN) ioctl on the vtmx file descriptor.
Any writes on the vtmx file descriptor will appear as incoming data on the virtual TTY, subject to the regular in-kernel processing (line disciplines, echoing, and so on). Reading from vtmx will return data in a «packetized» format, inspired by the obscure pseudo-tty «packet» mode. On each successful read() call, the first byte returned will indicate the type of packet returned.
Currently supported packet formats:
- TAG_UART_RX (0), followed by the «serial port» data coming in from the virtual TTY (processed by the kernel as usual)
- TAG_SET_TERMIOS (1), followed by a ‘struct termios2’ structure representing the serial port configuration requested on the virtual TTY (TCSETS/TCSETS2)
- TAG_SET_MODEM (2), followed by a 32-bit integer representing the modem line state requested on the virtual TTY (TIOCMSET/TIOCMBIC/TIOCMBIS)
- TAG_BREAK_CTL (3), followed by a 32-bit integer representing the requested «break» state. A «break» state is a special condition on the serial port, during which the «low» signal state is sent for a period longer than the byte duration. A positive number indicates the duration of the requested break state (in milliseconds). Negative numbers indicate a request to set the break state indefinitely. Zero terminates the break state.
The master side can also use the VTMX_SET_MODEM_LINES ioctl (equal to TIOCMSET) to manipulate the modem line state of the virtual serial port. Only the «input» lines (such as CTS) can be changed this way. If the master process needs to change the «output» lines (such as RTS), it needs to open the ttyV# device and issue the regular tty ioctls there.
The test/ directory contains testing/example apps demonstrating the use of the interface.
Comparison with PTY
Most of the functionality of VTTY is inspired by and follows the PTY interfaces. Most notable differences include:
The «master» side of the pseudo-tty is a tty. I’m not really sure why and what would be the reason to (for example) configure the line discipline on the master side. After all, it’s only used to read & write some bytes. In VTTY, the master side is a simple character device.
PTY does not inform the master of the «termios» settings on the slave
PTY does not support setting modem lines on the slave
VTTY reads on the master side return the data prefixed with a «tag» byte. This is similar to the (rarely used) «packet» mode of the pseudo-ttys.
PTY supports locking/unlocking access to the pseudo-tty using TIOCSPTLCK. This is not supported in VTTY
Any kinds of flow control were not tested. I assume that XON/XOFF will not work.
The module is mostly stable, but I wouldn’t recommend running it on any «important» systems. I wouldn’t be surprised if there were some subtle locking bugs remaining (the linux tty layer is. complex).
Also see FIXME/TODO markers in the source code.
Some tty ioctls are not supported (notably TIOCMIWAIT & TIOCGICOUNT).
tty0tty emulates pairs of serial ports, connected in a null-modem fashion. The modem status lines are properly emulated, but the «termios» settings are not.
Источник
Настраиваем виртуальный компорт в Ubuntu
Удобно работать с виртуальной машиной XPSP3 в VirtualBox’е: когда надо включаешь её, когда не надо – выключаешь, всё очень быстро, и вирусы прочно экранируются. Но вот понадобилось внести изменения в отлаживаемую «виндовую» программу, работающую со старыми добрыми компортами. И тут обнаруживается: не работает компорт виртуальной машины. В ЛОРе нет хорошего ответа. Всё сводится к рекомендации создания новой машины, а это время. Западные пользователи на форумах тоже дают немало пустых советов. А на самом деле всё не так уж и сложно.
Сначала надо установить утилиту настройки аппаратного компорта хост-машины. Называется она setserial, в дистрибутивах Ubuntu её нет, но зато она есть в репозиториях, поэтому воспользуемся командой терминала:
sudo apt-get install setserial
И, конечно, запустим эту утилиту, чтобы посмотреть, присутствует ли на материнской плате, что собой представляет и как настроен аппаратный порт хозяйки (далее в примере исследуем COM1):
sudo setserial -g /dev/ttyS0
Учтите, что ttyS0 соответствует COM1, ttyS1 соответствует COM2 и т.д. согласно терминологии Линукса. Подставьте нужное. После ввода пароля суперпользователя в норме должен быть получен ответ:
/dev/ttyS0, UART: 16550A, Port: 0x03f8, IRQ: 4
Иначе компорт отсутствует или отключен на уровне BIOS’а хост-машины. Выключенный порт включаем. В случае отсутствия на материнской плате аппаратного компорта придётся поставить «костыль» из дополнительной PCI-платы расширения и добавить модуль его драйвера из прилагаемого к ней диска. Проверено: для Линукса драйверы раюотоспособны, но уточните номер появившегося компорта командой терминала
При необходимости параметры настройки коммуникационного порта можно откорректировать ( как именно – см. терминальной командой man setserial).
Настраиваем проключение виртуального COMn в аппаратный COMn, то бишь в файл ttySn+1. Для этого запускаем VirtualBox, НЕ ЗАПУСКАЯ ВИРТУАЛЬНУЮ МАШИНУ, и настраиваем параметры её компорта, как показано на этом скриншоте:
Здесь важно, чтобы номер порта, номер прерывания и адрес ввода-вывода совпадали бы с теми, которые проиндицировала утилита setserial. Если не совпадают, то утилита setserial поможет перенастроить параметры аппаратного компорта.
Но если вы сейчас попытаетесь запустить виртуальную машину, то с очень большой вероятностью получите ошибку. А всего-то надо сделать ещё две вещи.
Во-первых, вы, хотя и являетесь «главным администратором», не обязательно автоматически являетесь членом группы пользователей виртуальной машины. Удивительно? Но бывает нередко. Впрочем, эта нелепость устраняется легко. Чтобы не заморачиваться с CLI, установите с помощью эмулятора терминала великолепную утилиту gnome-system-tools (она есть в репозиториях) командой
sudo apt-get install gnome-system-tools
Данную утилиту рекомендую для многократного употребления, поэтому скопируйте из папки /usr/share/applications значок «Пользователи и группы» на рабочий стол и запустите эту утилиту из рабочего стола. Откроется окно «Параметры пользователей». Жмите кнопку «Управление группами», в открывшемся окне «Параметры групп» скроллингом отыщите группу vboxusers, выберите её и дважды щёлкните по ней. Откроется окно «Свойства группы vboxusers». Внутри панели «Члены группы» пометьте чекбокс напротив своего имени, отражающего вас, как пользователя системы.
Во вторых, реальному порту следует присвоить права «666», что означает разрешение дуплексного обмена через компорт на уровнях владельца, членов его группы и остальных пользователей. Делается это командой
sudo chmod 666 /dev/ttyS0
Вместо ttyS0 подставьте обозначение нужного аппаратного компорта хост-машины. Вcё, теперь можно смело запускать виртуальную машину, включать привычный «виндовый» гипертерминал и с помощью виртуальной Windows настраивать модемы, управлять программаторами и т.д. Словом, делать всё то, как будто бы вы работали с реальной Windows XP или «семёркой». Успехов!
Источник