Меню Рубрики

Linux virtual serial port

/dev/blog

25 июн. 2013 г.

Проброс последовательного порта по сети в Linux (serial over ip)

Ссылки

Входные данные

Способ 1: socat

Самый простой способ – использовать socat. С его помощью можно соединить последовательное устройство и сокет.
На server создаем сокет на tcp-порту 12345, привязанный к /dev/ttyS0 :
На client создаем виртуальный терминал в /dev/pts/N и привязываем его к сокету server:12345 :
При такой схеме передаются данные, но не управляющая информация. Настройка виртуального терминала на хосте client никак не отражается на реальном терминале на хосте server. Это значит, что приложения, которые используют ioctl(2) или termios(3) , не будут работать так, как ожидается.

Способ 2: RFC 2217

Сервер

  • ser2net
    ser2net реализует телнет-сервер RFC 2217.
    Запускаем на хосте server на порту 23:
    ser2net можно также запускать в режиме демона или с помощью inetd .

  • sredird
    sredird – другая реализация сервера RFC 2217. Он лучше совместим с клиентом cyclades-serial-client .
    Запускаем на хосте server на порту 23 с помощью netcat:
    sredird можно также запускать с помощью inetd .

  • sercd
    sercd – еще одна реализация. Он основан на sredird .

Клиент

  • telnet
    После запуска сервера к удаленному терминалу можно подключиться по телнет:

  • ckermit
    Вместо telnet можно использовать C-Kermit, который поддерживает RFC 2217:
    С ним помимо телнет будут также доступны команды для конфигурирования порта.

  • cyclades-serial-client

    cyclades-serial-client – клиент для сервера RFC 2217. Он работает с помощью трюка с LD_PRELOAD .

    Для каждого удаленного терминала создается:

    1. Виртуальный терминал /dev/pts/N .
    2. Символическая ссылка на него /dev/NAME .
    3. Локальный сокет /dev/NAME.control .

    Затем пользователь с помощью LD_PRELOAD может заставить приложение, использующее терминал /dev/NAME , перенаправлять вызовы ioctl(2) и tcsetattr(3) в сокет /dev/NAME.control , откуда они будут прочитаны демоном cyclades-ser-cli и отправлены в удаленный терминал.

    Настраиваем конфиг клиента /etc/cyclades-devices (без этого не будет работать трюк с LD_PRELOAD ):
    Запускаем демон, обслуживающий виртуальный терминал:
    Можно также запускать демон с помощью cyclades-serial-client .
    Проверяем передачу данных:
    Cообщение hello должен получить тот, кто подключен к порту /dev/ttyS0 на хосте server .
    Проверяем настройку baud rate :
    На хосте server у терминала /dev/ttyS0 должно обновиться значение:
    У меня этот клиент работает с сервером sredird , но не работает с ser2net .

    Другие проблемы:

    • Не все параметры ioctl() реализованы.
    • Подход с использованием LD_PRELOAD для ioctl() и tcgetattr() работает не для всех приложений. У меня так и не заработала команда setserial(8) .

  • Network Virtual Terminal
    nvtty – это драйвер ядра, реализующий виртуальный терминал, перенаправляющий все запросы удаленному серверу RFC 2217. Патч основан на cyclades-serial-client .

    And this is still something that should be done in userspace if necessary
    by fixing up the tty layer to support pty/tty pair modem lines and
    termios change reporting, or some kind of generic vt that can also
    expose all the config other net protocols might need.

    TTYredirector

    Способ 3: Serial to Ethernet Converter

    Serial to Ethernet Converter – устройство, преобразующее RS-232 (и/или другие протоколы) в Ethernet и обратно.

    Есть как минимум два производителя, поставляющие вместе со своими преобразователями драйвер для Linux, который создает виртуальный COM-порт и перенаправляет все запросы к нему в сеть:

    • Tibbo VSPDL (Virtual Serial Port Driver for LINUX)
    • Perle TruePort

    Источник

    Virtual Serial Port for Linux

    I need to test a serial port application on Linux, however, my test machine only has one serial port.

    Is there a way to add a virtual serial port to Linux and test my application by emulating a device through a shell or script?

    Note: I cannot remap the port, it hard coded on ttys2 and I need to test the application as it is written.

    8 Answers 8

    You can use a pty («pseudo-teletype», where a serial port is a «real teletype») for this. From one end, open /dev/ptyp5 , and then attach your program to /dev/ttyp5 ; ttyp5 will act just like a serial port, but will send/receive everything it does via /dev/ptyp5.

    If you really need it to talk to a file called /dev/ttys2 , then simply move your old /dev/ttys2 out of the way and make a symlink from ptyp5 to ttys2 .

    Of course you can use some number other than ptyp5 . Perhaps pick one with a high number to avoid duplicates, since all your login terminals will also be using ptys.

    Complementing the @slonik’s answer.

    You can test socat to create Virtual Serial Port doing the following procedure (tested on Ubuntu 12.04):

    Open a terminal (let’s call it Terminal 0) and execute it:

    The code above returns:

    Open another terminal and write (Terminal 1):

    this command’s port name can be changed according to the pc. it’s depends on the previous output.

    you should use the number available on highlighted area.

    Open another terminal and write (Terminal 2):

    Now back to Terminal 1 and you’ll see the string «Test».

    Use socat for this:

    There is also tty0tty http://sourceforge.net/projects/tty0tty/ which is a real null modem emulator for linux.

    It is a simple kernel module — a small source file. I don’t know why it only got thumbs down on sourceforge, but it works well for me. The best thing about it is that is also emulates the hardware pins (RTC/CTS DSR/DTR). It even implements TIOCMGET/TIOCMSET and TIOCMIWAIT iotcl commands!

    On a recent kernel you may get compilation errors. This is easy to fix. Just insert a few lines at the top of the module/tty0tty.c source (after the includes):

    When the module is loaded, it creates 4 pairs of serial ports. The devices are /dev/tnt0 to /dev/tnt7 where tnt0 is connected to tnt1, tnt2 is connected to tnt3, etc. You may need to fix the file permissions to be able to use the devices.

    I guess I was a little quick with my enthusiasm. While the driver looks promising, it seems unstable. I don’t know for sure but I think it crashed a machine in the office I was working on from home. I can’t check until I’m back in the office on monday.

    The second thing is that TIOCMIWAIT does not work. The code seems to be copied from some «tiny tty» example code. The handling of TIOCMIWAIT seems in place, but it never wakes up because the corresponding call to wake_up_interruptible() is missing.

    The crash in the office really was the driver’s fault. There was an initialization missing, and the completely untested TIOCMIWAIT code caused a crash of the machine.

    I spent yesterday and today rewriting the driver. There were a lot of issues, but now it works well for me. There’s still code missing for hardware flow control managed by the driver, but I don’t need it because I’ll be managing the pins myself using TIOCMGET/TIOCMSET/TIOCMIWAIT from user mode code.

    If anyone is interested in my version of the the code, send me a message and I’ll send it to you.

    Источник

    Linux virtual serial port

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.md

    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.

    Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Ubuntu gnome mac os
  • Txt mac os кодировка
  • Twonky для mac os
  • Twixtor pro mac os
  • Tuxera ntfs для mac os sierra