Управление потоком xon xoff что это

от admin

From XON/XOFF to Forward Incremental Search

In the olden days of computing, software flow control with control codes XON and XOFF was a necessary feature that dumb terminals needed to support. When a terminal received more data than it could display, there needed to be a way for the terminal to tell the remote host to pause sending more data. The control code 19 was chosen for this. The control code 17 was chosen to tell the remote host to resume transmission of data.

The control code 19 is called Device Control 3 (DC3) in the ASCII chart. It is also known as «transmit off» (XOFF). The control code 17 is called Device Control 1 (DC1) as well as «transmit on» (XON). Now how does a user of the terminal really send these control codes? Well, how do they send any control code? Using the ctrl key of course.

Let us take a step back and see how a user can send familiar control codes on modern terminal emulators, like say, the terminal software we find on a Unix or Linux desktop environment. While any sane computer user would just type the tab key to insert a tab character, one could also type ctrl + i to insert a tab character. The character I has code 73 (binary 1001001) and holding the ctrl key while typing it results in a control code made by taking 73 (binary 1001001), keeping its five least significant bits, and discarding the rest to get the control code 9 (binary 1001) which is the code of the tab character. In other words, we get the control code by performing a bitwise AND operation on the code of the character being modified with binary code of 31 (binary 0011111).

In case you are wondering, if we get the same result if we choose the binary code of the lowercase i to perform the aforementioned operation, the answer is, yes. While the code of uppercase I is 73 (binary 1001001), that of lowercase i is 105 (binary 1101001). The right-most five bits are same for both. Thus when we preserve the five least significant bits and discard the rest, we get the control code 9 (binary 1001) in both cases. This is a neat result due to the fact that the five least significant bits of the code of a lowercase character is exactly the same as that of the corresponding uppercase character. They differ only in their sixth least significant bit. That bit is on for the lowercase character but off for the corresponding uppercase character. This is just an interesting observation as far as this post is concerned. The very early keyboards did not have lowercase letters. They only had uppercase letters and when the ctrl key is pressed together with a letter on such keyboards, the 7th bit of the character code was flipped to get the control code.

The bitwise operation mentioned earlier explains why typing ctrl + h sends a backspace, typing ctrl + j sends a newline, and typing ctrl + g plays a bell. In modern terminal emulators these days, the bell often manifests in the form of an audible beep or a visual flash. Here is a table that summarizes these control codes and a few more:

Key Modified Character Control Character
Binary Decimal Character Binary Decimal Character
ctrl + @ 1000000 64 @ 00000 0 Null
ctrl + g 1000111 71 G 00111 7 Bell
ctrl + h 1001000 72 H 01000 8 Backspace
ctrl + i 1001001 73 I 01001 9 Horizontal Tab
ctrl + j 1001010 74 I 01010 10 Line Feed
ctrl + m 1001101 77 M 01101 13 Carriage Return
ctrl + [ 1011011 91 [ 11011 27 Escape

The last row in the table above explains why we can also type ctrl + [ in Vim to escape from insert mode to normal mode. This is, in fact, one of the convenient ways for touch-typists to return to normal mode in Vim instead of clumsily stretching the left hand fingers out to reach the esc key which is usually poorly located at the corner of most keyboards.

There is a bit of oversimplication in the description above. Throughout the history of computing, different systems have used slightly different methods to compute the resulting control code when the ctrl modifier key is held. Toggling the 7th least significant bit was an early method. Turning off both the 6th and 7th least significant bits is another method. Subtracting 64 from the character code is yet another method. These are implementation details and these various implementation methods lead to the same results for the examples in the table above. Then there are some special rules too. For example, many terminals implement a special rule to make ctrl + space behave the same as ctrl + @ thus producing the null character. Further ctrl + ? produces the delete character in some terminals. These special rules are summarized in the table below.

Key Modified Character Resulting Character
Binary Decimal Character Binary Decimal Character
ctrl + space 0100000 32 Space 0 0 Null
ctrl + ? 0111111 63 ? 1111111 127 Delete

For the purpose of this blog post, we don’t need to worry about these special rules. Let us get back to the control codes 19 and 17 that represent XOFF and XON. Here is how the table looks for them:

Key Modified Character Resulting Character
Binary Decimal Character Binary Decimal Character
ctrl + q 1010001 81 Q 10001 17 DC1 (XON)
ctrl + s 1010011 83 S 10011 19 DC3 (XOFF)

We see that a user can type ctrl + s to send the control code XOFF and then ctrl + q to send the control code XON. Although we do not use dumb terminals anymore, these conventions have survived in various forms in our modern terminal emulators. To see a glimpse of it, launch the terminal that comes with a modern operating system, then run ping localhost and while this command is printing its output, type ctrl + s . The terminal should pause printing the output of the command. Then type ctrl + q and the terminal should resume printing the output.

Incremental Search in Bash/Zsh

Let us now take a look at the shells that run within the terminals. Both Bash and Zsh are very popular these days. Both these shells have excellent support for performing incremental searches through the input history. To see a quick demonstration of this, open a new terminal that runs either Bash or Zsh and run these commands:

Now type ctrl + r followed by echo . This should invoke the reverse search feature of the shell and automatically complete the partial command echo to echo baz . Type ctrl + r again to move back in the input history and autocomplete the command to echo bar . We can type enter anytime we use the reverse search feature to execute the automatically completed command. Typing ctrl + r yet another time should bring the echo foo command at the shell prompt.

What if we went too far back in the input history and now want to go forward? There is a good news and there is some bad news. The good news is that both Bash and Zsh support forward search using the ctrl + s key sequence. The bad news is that this key sequence may not reach the shell. Most terminal emulators consume this key sequence and interpret it as the control code XOFF.

The Conflict

In the previous two sections, we have seen that the ctrl + s key sequence is used to send the control code XOFF. But the same key sequence is also used for forward incremental search in Bash and Zsh. Since the terminal consumes this key sequence and interprets it as the control code XOFF, the shell never sees the key sequence. As a result, the forward incremental search functionality does not work when we type this key sequence in the shell.

Bash offers the incremental search facility via a wonderful piece of library known as the the GNU Readline Library. ZSH offers this facility with its own Zsh Line Editor (ZLE). So other tools that rely on these libraries to offer line editing and history capability are also affected by this conflict. For example, many builds of Python offer line editing and history capability using GNU Readline, so while ctrl + r works fine to perform reverse search in the Python interpreter, it is very likely that ctrl + s does not work to perform forward search.

Reclaim Forward Incremental Search

We can forfeit the usage of control codes XON/XOFF to reclaim forward incremental search. Here is the command to disable XON/XOFF output control in the terminal:

After running the command, ctrl + s is no longer consumed by the terminal to pause the output. To confirm that forward incremental search works now, first run the above command, and then run the following commands:

Now type ctrl + r followed by echo and the input line should be automatically completed to echo baz . Type ctrl + r again and echo bar should appear at the shell prompt. Type ctrl + r one more time to bring the command echo foo at the shell prompt.

Now type ctrl + s once and the search facility should switch itself to forward incremental search. The search prompt should change to show this. For example, in Bash the search prompt changes from reverse-i-search: to i-search: to indicate this. In Zsh, the search prompt changes from bck-i-search: to fwd-i-search: .

Now type ctrl + s again and the input line should be automatically completed to echo bar . Type ctrl + s again to bring back echo baz at the shell prompt. This is the forward incremental search in action.

Conclusion

I believe the forward incremental search facility offered in shells and other tools with line editing and history capabilities is a very useful feature that can make navigating the input history very convenient. However due to the default setting of most terminals, this rather splendid feature remains unusable.

I believe heavy terminal users should add the command stty -ixon to their

/.zshrc , so that the ctrl + s key sequence can be used for forward incremental search. Forfeit XON/XOFF to reclaim forward incremental search!

Русские Блоги

Управление последовательным потоком UART (управление потоком)

Как правило, при последовательной связи на некоторых компьютерах верхнего уровня мы увидим параметры RTS / CTS, DTR / DSR и XON / XOFF.Это параметр для управления потоком, который обычно применяется к интерфейсу RS232, который является данными от модема. Общение

1. Роль управления потоками

Упомянутый здесь «поток» относится к потоку данных; при передаче данныхУправление потокомЭто процесс управления скоростью передачи данных между двумя узлами для предотвращения заполнения буфера данных на принимающей стороне, в то время как отправляющая сторона продолжает отправлять данные, что приводит к потере данных.

2. Принцип работы

Когда буфер данных на принимающей стороне заполнен и данные не могут быть обработаны, он отправит сигнал «больше не принимает», а отправляющая сторона прекратит отправку, пока отправляющая сторона не получит сигнал «можно продолжить отправку» перед отправкой данных. В компьютерах обычно используются два типа управления потоком: аппаратное управление потоком (RTS / CTS, DTR / DSR и т. Д.) И программное управление потоком (XON / XOFF).

Три, определение контакта RS232

RS-232 изначально был разработан для подключения к модему для передачи, поэтому значение его контактов обычно связано с передачей модема. Оборудование RS-232 можно разделить на два типа: оконечное оборудование данных (DTE, оконечное оборудование данных, например, ПК) и оборудование передачи данных (DCE, оборудование передачи данных). Эта классификация определяет разные линии для передачи и приема. сигнал. Вообще говоря, компьютеры и оконечное оборудование имеют разъемы DTE, а модемы и принтеры — разъемы DCE. Но это не всегда строго правильно.Чтобы проверить соединение с разветвителем проводки или методом проб и ошибок определить, исправен ли кабель, часто необходимо обратиться к соответствующей документации.

RS-232 в настоящее время имеет разъемы типа DB-25 и DB-9, а интерфейсы типа DB-9 используются чаще.

Назначение контактов типа DB-9 в RS-232:

Описание его сигнального контакта:

Положение стопы Стенография значимость сигнал Описание
Pin1 DCD Data Carrier Detect Обнаружение носителя данных (DCD) Модем сообщает компьютеру об обнаружении носителя.
Pin2 RXD Receiver Получение данных (RD, RXD) Получите данные.
Pin3 TXD Transmit Отправить данные (TD, TXD) отправить данные.
Pin4 DTR Data Terminal Ready Подготовка терминала данных (DTR) Компьютер сообщает модему, что он может передавать.
Pin5 GND Ground Общие основания Провод заземления.
Pin6 DSR Data Set Ready Данные готовы (DSR) Модем сообщает компьютеру, что все готово.
Pin7 RTS Request To Send Запрос на отправку (RTS) Компьютер просит модем передать данные.
Pin8 CTS Clear To Send Очистить для отправки (CTS) Модем сообщает компьютеру, что он может отправлять данные.
Pin9 RI Ring Indicator Индикация звонка (RI) Модем сообщает компьютеру о входящем звонке.

4. Аппаратное управление потоком (в основном RTS / CTS)

RTS / CTS был первоначально разработан для полудуплексной совместной связи между телетайпом и модемом, и только один модем может отправлять данные одновременно. Терминал должен отправить запрос на отправку сигнала, а затем ждать, пока модем не ответит разрешением на отправку. Хотя в RTS / CTS квитирование осуществляется аппаратно, у него есть свои преимущества.

1. Стандартный метод подключения RS232

Когда оборудование на стороне A готово, сигнал DTR (оборудование для передачи данных готово) будет отправлен на RI (вызывной сигнал) и DSR (оборудование связи готово) на стороне B. Таким образом, пока A готов (DTR), B будет генерировать вызов (RI) и быть готовым (DSR).

Обратите внимание, что RTS (запрос на отправку), CTS (разрешена отправка) и CD (обнаружение несущей) на стороне B соединены вместе, что означает, что как только A запрашивает отправку (RTS), он будет немедленно разрешен (CTS) и сделает обнаружение B Несущий сигнал (CD). TXD терминала A соединен с RXD терминала B, и A отправляет, а B принимает.

2. Упрощенный способ подключения RS232.

Исходные RTS и CTS используются, чтобы спросить и ответить, можно ли передавать данные. Но в этом режиме соединения он просто сообщает другой стороне, могут ли они общаться. В настоящее время для управления потоком данных могут использоваться как RTS, так и DTR.

DTR (готовность устройства данных) на стороне A. Когда сторона B готова, DTR (готовность устройства данных) на стороне B отправляет сигнал DSR (устройство связи готово) на стороне A. Затем вы можете контролировать связь через RTS (запрос на отправку) и DTR (разрешить отправку).

3. Дальнейшее упрощение (то есть на основе RTS / CTS)

Как видно из вышеупомянутого процесса, аппаратное управление потоком в основном контролируется RTS / CTS и DTR / DSR, но люди ленивы и ленивы, поэтому теперь часто они просто используют RTS / CTS, чтобы сообщить другой стороне, могут ли они общаться. , И пропустить определение состояния готовности DTR / DSR напрямую

При использовании RTS / CTS они оба активны на низком уровне.Поэтому после открытия последовательного порта на главном компьютере RTS выберет высокий уровень, а затем дождется отправки данных, чтобы сделать низкий уровень действительным.

Стоит отметить, что аппаратное управление потоком данных зависит не только от оборудования, оно также требует программного обеспечения для обработки идентификации, поскольку аппаратное управление потоком данных дает только уровни сигналов, а реальный контроль разрешения отправки зависит от программной обработки.

Пять, программное управление потоком

Программный контроль потока(Программное управление потоком) — это метод управления потоком в канале компьютерных данных, особенно подходящий для последовательной связи RS-232; он использует специальные символы для передачи внутриполосной сигнализации, а также вызываются специальные кодированные символы.XOFFпротив XON(Соответственно расшифровываются "передача выключена" и "передача включена"). Поэтому его также называют «управление потоком XON / XOFF»;

Используйте набор символов ASCII, XOFF — обычно байтовое значение 19 (десятичное), XON — байтовое значение 17

Кодовое имя смысл ASCII Десятичный Шестнадцатеричный
XOFF Приостановить передачу DC3 19 13
XON Возобновить передачу DC1 17 11

Стоит отметить, что получатель отправляет отправителю сигналы XON / XOFF, чтобы контролировать, когда отправитель отправляет данные.Эти сигналы противоположны направлению передачи отправленных данных.

Его обработка в основном заключается в следующем: получатель использует сигнал XON, чтобы сообщить отправителю, что я готов принять больше данных, и использует сигнал XOFF, чтобы сказать отправителю прекратить отправку данных, пока получатель не отправит сигнал XON, чтобы сообщить отправителю, что я снова готов. .

XON / XOFF — это внутриполосный метод, который работает между терминалами, но оба конца должны поддерживать этот протокол, и при его внезапном запуске может возникнуть путаница; XON / XOFF может работать на 3-проводных интерфейсах.

Программное управление потоком широко используется в низкоскоростных устройствах, особенно в принтерах и немых терминалах, чтобы указать, что они временно приостанавливают получение данных; преимущество программного управления потоком данных состоит в том, что оно уменьшает количество проводников цепи между отправляющей и принимающей сторонами и при наличии общей цепи заземления, Для отправки и приема необходимы только две схемы, и никакой дополнительной конкретной аппаратной реализации не требуется; недостаток состоит в том, что для отправки XOFF требуется хотя бы один символ, и его необходимо обрабатывать после данных, которые получила другая сторона.

XON / XOFF, как правило, не рекомендуются. Рекомендуется заменить их потоком управления RTS / CTS. Потому что, если вы передаете двоичные данные, в отправляемых вами данных могут быть двоичные значения, соответствующие XON и XOFF, что может привести к неправильной работе. Это дефект программного управления потоком, и аппаратное управление потоком не будет иметь этой проблемы; конечно, вы Вы также можете избежать XON и XOFF

Шесть, управление нижним уровнем UART

Как упоминалось выше, окончательная реализация аппаратного управления потоком все еще связана с программным обеспечением. Если вы собираетесь написать управление хост-компьютером с последовательным портом, вы можете просмотреть ссылку ниже, чтобы понять соответствующие регистры

XON/XOFF Flow Control

XON/XOFF flow control is selected by setting the FLO bits to ‘ 01 ’.

XON/XOFF is a data-based flow control method. The signals to suspend and resume transmission are special characters sent by the receiver to the transmitter. The advantage is that additional hardware lines are not needed.

XON/XOFF flow control requires full-duplex operation because the transmitter must be able to receive the signal to suspend transmitting while the transmission is in progress. Although XON and XOFF are not defined in the ASCII code, the generally accepted values are 13h for XOFF and 11h for XON. The UART uses those codes.

The transmitter defaults to XON, or transmitter enabled. This state is also indicated by the read-only XON bit.

When an XOFF character is received, the transmitter stops transmitting after completing the character actively being transmitted. The transmitter remains disabled until an XON character is received.

XON will be forced on when software toggles the TXEN bit.

When the RUNOVF bit is set, the XON and XOFF characters continue to be received and processed without the need to clear the input FIFO by reading UxRXB. However, if the RUNOVF bit is clear then UxRXB must be read to avoid a receive overflow which will suspend flow control when the receive buffer overflows.

Управление потоком xon xoff что это

USR IOT коммуникационные серверы

  1. Что такое программное управление потоком Xon/Xoff?

Xon/Xoff — это программный механизм управления потоком.

Его можно использовать только в символьно-ориентированной передаче данных (не в двоичной передаче), поскольку он основан на использовании предварительно определенных символов Xon и Xoff. Основная идея проста: когда буфер приемника заполняется до такой степени, что он больше не может принимать данные, он выдает Xoff (отключение передачи) передатчику. Когда передатчик видит символ Xoff, он прекращает передачу. Он возобновится только после того, как увидит соответствующий Xon.

Недостатком такой системы является то, что если выданный символ будет поврежден при транспортировке, отправитель не предпримет никаких действий.

Читать:
D link des 1005c что это

Похожие публикации