/build
/subprojects/libinih
*.swp
+.cache
-=== tio v1.47 ===
+=== tio v2.0 ===
+
+
+
+Changes since tio v1.47:
+
+ * Handle stale unix socket file
+
+ Delete existing unix socket file if it is tested to be stale, meaning no
+ one is listening on it.
+
+ * Add visual or audible alert support on connect/disconnect
+
+ The feature is detailed via the following option:
+
+ --alert none|bell|blink
+
+ Set alert action on connect/disconnect.
+
+ It will sound the bell once or blink once on successful connect.
+ Likewise it will sound the bell twice or blink twice on disconnect.
+
+ Default value is "none" for no alert.
+
+ * Add experimental RS-485 support
+
+ Many modern RS-485 serial devices such as the ones from FTDI already
+ operate in RS-485 mode by default and will work with tio out of the box.
+ However, there are some RS-232/485 devices which need to be switched
+ from e.g. RS-232 to RS-485 mode to operate accordingly on the physical
+ level.
+
+ This commit implements the switching mechanism and interface required to
+ enable RS-485 mode. It only works on Linux and with serial devices which
+ use device drivers that support the Linux RS-485 control interface.
+
+ The RS-485 feature is detailed via the following options:
+
+ --rs-485 Enable RS-485 mode
+ --rs-485-config <config> Set RS-485 configuration
+
+ Set the RS-485 configuration using the following key or key value pair
+ format in the configuration field:
+
+ RTS_ON_SEND=value Set logical level (0 or 1) for RTS pin when sending
+ RTS_AFTER_SEND=value Set logical level (0 or 1) for RTS pin after sending
+ RTS_DELAY_BEFORE_SEND=value Set RTS delay (ms) before sending
+ RTS_DELAY_AFTER_SEND=value Set RTS delay (ms) after sending
+ RX_DURING_TX Receive data even while sending data
+
+ If defining more than one key or key value pair, they must be comma
+ separated.
+
+ Example use:
+
+ $ tio /dev/ttyUSB0 --rs-485 --rs-r485-config=RTS_DELAY_AFTER_SEND=50,RX_DURING_TX
+
+ * Add line response feature
+
+ Add a simple line response feature to make it possible to send e.g. a
+ command string to your serial device and easily receive and parse a line
+ response.
+
+ This is a convenience feature for simple request/response interaction
+ based on lines. For more advanced interaction the socket feature should
+ be used instead.
+
+ The line response feature is detailed via the following options:
+
+ -r, --response-wait
+
+ Wait for line response then quit. A line is considered any string ending
+ with either CR or NL character. If no line is received tio will quit
+ after response timeout.
+
+ Any tio text is automatically muted when piping a string to tio while in
+ response mode to make it easy to parse the response.
+
+ --response-timeout <ms>
+
+ Set timeout [ms] of line response (default: 100).
+
+ Example:
+
+ Sending a string (SCPI command) to a test instrument (Korad PSU) and
+ print line response:
+
+ $ echo "*IDN?" | tio /dev/ttyACM0 --response-wait
+ KORAD KD3305P V4.2 SN:32477045
+
+ * Fix potential sscanf() overflow
+
+ * Only print version on '--version'
+
+ * Remove duplicate show config entry of DTR pulse duration
+
+ * Remove MacPorts instructions
+
+ Remove instructions for MacPorts because the port has no maintainer and
+ the port build definition is broken (missing dependency on libinih etc.).
+
+ It is recommended to use brew instead.
+
+Peter Collingbourne:
+
+ * Ignore SIGPIPE signals
+
+ If the remote end of a socket is closed between when an input character
+ is received from the serial port and when it is written to the socket,
+ tio will receive a SIGPIPE signal when writing the character to the
+ socket, which will terminate the program. To prevent this, ignore the
+ signal, which will cause write(2) to return -EPIPE, causing tio to close
+ the socket.
* Rename option -i to -L
* Shorten timestamp
-
+
* Shorten timestamp description
We do not need the date part of the timestamp. It simply takes up too
* Easily connect to serial TTY devices
* Automatic connect and reconnect
- * Support for arbitrary baud rates
+ * Sensible defaults
+ * Support for non-standard baud rates
+ * Support for RS-485 mode
* List available serial devices by ID
* Show RX/TX statistics
* Toggle serial lines
* Autogeneration of log filename
* Configuration file support
* Activate sub-configurations by name or pattern
- * Redirect I/O to file or network socket for scripting or TTY sharing
+ * Redirect I/O to UNIX socket or IPv4/v6 network socket for scripting or TTY sharing
* Pipe input and/or output
+ * Support for simple line request/response handling
* Bash completion
* Color support
+ * Visual or audible alert on connect/disconnect
* Remapping of prefix key
* Man page documentation
+ * Plays nicely with [tmux](https://tmux.github.io)
## 3. Usage
For more usage details please see the man page documentation
-[here](man/tio.1.txt).
+[here](https://raw.githubusercontent.com/tio/tio/master/man/tio.1.txt).
### 3.1 Command-line
--log-strip Strip control characters and escape sequences
-m, --map <flags> Map characters
-c, --color 0..255|bold|none|list Colorize tio text (default: bold)
- -S, --socket <socket> Redirect I/O to file or network socket
+ -S, --socket <socket> Redirect I/O to socket
-x, --hexadecimal Enable hexadecimal mode
+ -r, --response-wait Wait for line response then quit
+ --response-timeout <ms> Response timeout (default: 100)
+ --rs-485 Enable RS-485 mode
+ --rs-485-config <config> Set RS-485 configuration
+ --alert bell|blink|none Alert on connect/disconnect (default: none)
-v, --version Display version
-h, --help Display help
Using serial devices by ID ensures that tio automatically reconnects to the
correct serial device if it is disconnected and then reconnected.
+
+Inject data to the serial device:
+```
+$ cat data.bin | tio /dev/ttyUSB0
+```
+
+Send command to serial device and wait for line response:
+```
+$ echo "*IDN?" | tio /dev/ttyACM0 --response-wait
+KORAD KD3305P V4.2 SN:32475045
+```
+
### 3.2 Key commands
Various in session key commands are supported. When tio is started, press
package manager tool to find and install tio.
If you would like to see tio included in your favorite distribution, please
-reach out to their package maintainers team.
+reach out to its package maintainers team.
### 4.2 Installation using snap (Linux)
$ brew install tio
```
-### 4.4 Installation using MacPorts (MacOS)
+### 4.4 Installation using MSYS2 (Windows)
-If you have [MacPorts](https://www.macports.org) installed:
+If you have [MSYS2](https://www.msys2.org) installed:
```
- $ sudo port install tio
+ $ pacman -S tio
```
### 4.5 Installation from source
See meson\_options.txt for tio specific build options.
-Note: It is recommended to only try to install from source if you are familiar
-with how to build stuff using meson.
+Note: The meson install steps may differ depending on your specific system.
## 5. Contributing
* Split I/O feature
- Allow to split input and output so that it is possible to manage these independently.
+ Allow to split input and output so that it is possible to manage these
+ independently.
The general idea is to redirect the output stream on the socket port number
specified but then redirect the input stream on the same port number + 1.
Example:
- tio /dev/ttyUSB0 --socket inet:4444,split-io
+ $ tio /dev/ttyUSB0 --socket inet:4444,split-io
- Will result in output stream being hosted on port 4444 and input stream hosted on port 4445.
+ Will result in output stream being hosted on port 4444 and input stream
+ hosted on port 4445.
For file sockets something similar can be arranged:
- tio /dev/ttyUSB0 --socket unix:/tmp/tio-socket-0,split-io
+ $ tio /dev/ttyUSB0 --socket unix:/tmp/tio-socket-0,split-io
- Will result in output stream being hosted via /tmp/tio-socket-0 and input stream hosted via /tmp/tio-socket-0_input
+ Will result in output stream being hosted via /tmp/tio-socket-0 and input
+ stream hosted via /tmp/tio-socket-0_input
+
+ * Websocket support
+
+ Extend the socket feature to redirect serial I/O to websocket on e.g. port
+ 1234 like so:
+
+ $ tio --socket ws:1234
+
+ Use libwesockets to implement feature.
no-autoconnect = disable
hexadecimal = disable
timestamp = disable
+log = disable
+log-strip = disable
color = bold
+rs-485 = disable
+alert = none
# Sub-configuraions
baudrate = 115200
tty = /dev/serial/by-id/usb-Silicon_Labs_CP2105_Dual_USB_to_UART_Bridge_Controller_01093176-if01-port0
line-pulse-duration = DTR=200,RTS=300,RI=50
+alert = bell
color = 10
[tincan]
pattern = usb([0-9]*)
tty = /dev/ttyUSB%s
color = 12
+
+[rs-485-device]
+tty = /dev/ttyUSB0
+rs-485 = enable
+rs-485-config = RTS_ON_SEND=1,RTS_AFTER_SEND=1,RTS_DELAY_BEFORE_SEND=60,RTS_DELAY_AFTER_SEND=80,RX_DURING_TX
+color = 13
.BR " \-\-line\-pulse\-duration " \fI<duration>
Set the pulse duration [ms] of each serial port line using the following key
-valur pair format in the duration field: <key>=<value>
+value pair format in the duration field: <key>=<value>
Each key represents a serial line. The following keys are available:
.RS
-.TP 12n
-.IP "\fBDTR - Data Terminal Ready"
-.IP "\fBRTS - Request To Send"
-.IP "\fBCTS - Clear To Send"
-.IP "\fBDSR - Data Set Ready"
-.IP "\fBDCD - Data Carrier Detect"
-.IP "\fBRI - Ring Indicator"
+.TP 8n
+.IP \fBDTR
+Data Terminal Ready
+.IP \fBRTS
+Request To Send
+.IP \fBCTS
+Clear To Send
+.IP \fBDSR
+Data Set Ready
+.IP \fBDCD
+Data Carrier Detect
+.IP \fBRI
+Ring Indicator
.P
If defining more than one key value pair, the pairs must be comma separated.
.TP
.BR \-L ", " \-\-list\-devices
-List available serial devices.
+List available serial devices by ID.
.TP
.BR \-l ", " \-\-log
Enable log to file.
-If no filename is provided the filename will be
-automatically generated.
+If no filename is provided the filename will be automatically generated.
.TP
.BR " \-\-log-file \fI<filename>
.TP
.BR \-S ", " "\-\-socket \fI<socket>\fR\fB
-Redirect I/O to socket. Any input from clients connected to the socket is sent
-on the serial port as if entered at the terminal where tio is running (except
-that \fBctrl-t\fR sequences are not recognized), and any input from the serial
-port is multiplexed to the terminal and all connected clients.
+Redirect I/O to socket.
+
+Any input from clients connected to the socket is sent on the serial port as if
+entered at the terminal where tio is running (except that \fBctrl-t\fR sequences
+are not recognized), and any input from the serial port is multiplexed to the
+terminal and all connected clients.
Sockets remain open while the serial port is disconnected, and writes will block.
At present there is a hardcoded limit of 16 clients connected at one time.
.RE
+.TP
+.BR \-r ", " \-\-response-wait
+
+Wait for line response then quit. A line is considered any string ending with
+either CR or NL character. If no line is received tio will quit after response
+timeout.
+
+Any tio text is automatically muted when piping a string to tio while in
+response mode to make it easy to parse the response.
+
+.TP
+.BR " \-\-response\-timeout " \fI<ms>
+
+Set timeout [ms] of line response (default: 100).
+
+.TP
+.BR " \-\-rs\-485"
+
+Enable RS-485 mode.
+
+.TP
+.BR " \-\-rs\-485\-config " \fI<config>
+
+Set the RS-485 configuration using the following key or key value pair format in
+the configuration field:
+
+.RS
+.TP 30n
+.IP \fBRTS_ON_SEND=value
+Set logical level (0 or 1) for RTS pin when sending
+.IP \fBRTS_AFTER_SEND=value
+Set logical level (0 or 1) for RTS pin after sending
+.IP \fBRTS_DELAY_BEFORE_SEND=value
+Set RTS delay (ms) before sending
+.IP \fBRTS_DELAY_AFTER_SEND=value
+Set RTS delay (ms) after sending
+.IP \fBRX_DURING_TX
+Receive data even while sending data
+.P
+If defining more than one key or key value pair, they must be comma separated.
+.RE
+
+.TP
+.BR "\-\-alert none|bell|blink"
+
+Set alert action on connect/disconnect.
+
+It will sound the bell once or blink once on successful connect. Likewise it
+will sound the bell twice or blink twice on disconnect.
+
+Default value is "none".
+
.TP
.BR \-v ", " \-\-version
.PP
The following configuration file options are available:
-.TP 21n
+.TP 25n
.IP "\fBpattern"
Pattern matching user input. This pattern can be an extended regular expression with a single group.
.IP "\fBtty"
Set socket to redirect I/O to
.IP "\fBprefix-ctrl-key"
Set prefix ctrl key (a..z, default: t)
+.IP "\fBresponse-wait"
+Enable wait for line response
+.IP "\fBresponse-timeout"
+Set line response timeout
+.IP "\fBrs-485"
+Enable RS-485 mode
+.IP "\fBrs-485-config"
+Set RS-485 configuration
+.IP "\fBalert"
+Set alert action on connect/disconnect
.SH "CONFIGURATION FILE EXAMPLES"
Pipe command to the serial device:
$ echo "ls -la" | tio /dev/serial/by\-id/usb\-FTDI_TTL232R-3V3_FTGQVXBL\-if00\-port0
-
+
+.TP
+Pipe command to the serial device and wait for line response (string ending with CR or NL):
+
+$ echo "*IDN?" | tio /dev/ttyACM0 --response-wait
+.TP
+In this mode, only the response will be printed.
+
.TP
Likewise, to pipe data from file to the serial device:
$ cat data.bin | tio /dev/serial/by\-id/usb\-FTDI_TTL232R-3V3_FTGQVXBL\-if00\-port0
+.TP
+Enable RS-485 mode:
+
+$ tio --rs-485 --rs-485-config=RTS_ON_SEND=1,RX_DURING_TX /dev/ttyUSB0
+
.SH "WEBSITE"
.PP
Visit https://tio.github.io
-tio(1) User Commands tio(1)
+tio(1) User Commands tio(1)
NAME
tio - a simple serial device I/O tool
tio [<options>] <tty-device|sub-config>
DESCRIPTION
- tio is a simple serial device tool which features a straightforward command-line and configuration file interface to easily con‐
- nect to serial TTY devices for basic I/O operations.
+ tio is a simple serial device tool which features a straightforward command-line and configuration file interface to easily connect to serial TTY devices for basic I/O operations.
OPTIONS
-b, --baudrate <bps>
Set parity (default: none).
- Note: With mark parity the parity bit is always 0. With space parity the parity bit is always 1. Not all platforms support
- mark and space parity.
+ Note: With mark parity the parity bit is always 0. With space parity the parity bit is always 1. Not all platforms support mark and space parity.
-o, --output-delay <ms>
--line-pulse-duration <duration>
- Set the pulse duration [ms] of each serial port line using the following key valur pair format in the duration field:
- <key>=<value>
+ Set the pulse duration [ms] of each serial port line using the following key value pair format in the duration field: <key>=<value>
Each key represents a serial line. The following keys are available:
- DTR - Data Terminal Ready
+ DTR Data Terminal Ready
- RTS - Request To Send
+ RTS Request To Send
- CTS - Clear To Send
+ CTS Clear To Send
- DSR - Data Set Ready
+ DSR Data Set Ready
- DCD - Data Carrier Detect
+ DCD Data Carrier Detect
- RI - Ring Indicator
+ RI Ring Indicator
If defining more than one key value pair, the pairs must be comma separated.
Disable automatic connect.
- By default tio automatically connects to the provided device if present. If the device is not present, it will wait for it
- to appear and then connect. If the connection is lost (eg. device disconnects), it will wait for the device to reappear and
- then reconnect.
+ By default tio automatically connects to the provided device if present. If the device is not present, it will wait for it to appear and then connect. If the connection is lost
+ (eg. device disconnects), it will wait for the device to reappear and then reconnect.
- However, if the --no-autoconnect option is provided, tio will exit if the device is not present or an established connec‐
- tion is lost.
+ However, if the --no-autoconnect option is provided, tio will exit if the device is not present or an established connection is lost.
-e, --local-echo
-L, --list-devices
- List available serial devices.
+ List available serial devices by ID.
-l, --log
-c, --color 0..255|bold|none|list
- Colorize tio text using ANSI color code value ranging from 0 to 255 or use "none" for no color or use "bold" to apply bold
- formatting to existing system color.
+ Colorize tio text using ANSI color code value ranging from 0 to 255 or use "none" for no color or use "bold" to apply bold formatting to existing system color.
Use "list" to print a list of available ANSI color codes.
-S, --socket <socket>
- Redirect I/O to socket. Any input from clients connected to the socket is sent on the serial port as if entered at the ter‐
- minal where tio is running (except that ctrl-t sequences are not recognized), and any input from the serial port is multi‐
- plexed to the terminal and all connected clients.
+ Redirect I/O to socket.
+
+ Any input from clients connected to the socket is sent on the serial port as if entered at the terminal where tio is running (except that ctrl-t sequences are not recognized),
+ and any input from the serial port is multiplexed to the terminal and all connected clients.
Sockets remain open while the serial port is disconnected, and writes will block.
At present there is a hardcoded limit of 16 clients connected at one time.
+ -r, --response-wait
+
+ Wait for line response then quit. A line is considered any string ending with either CR or NL character. If no line is received tio will quit after response timeout.
+
+ Any tio text is automatically muted when piping a string to tio while in response mode to make it easy to parse the response.
+
+ --response-timeout <ms>
+
+ Set timeout [ms] of line response (default: 100).
+
+ --rs-485
+
+ Enable RS-485 mode.
+
+ --rs-485-config <config>
+
+ Set the RS-485 configuration using the following key or key value pair format in the configuration field:
+
+ RTS_ON_SEND=value Set logical level (0 or 1) for RTS pin when sending
+
+ RTS_AFTER_SEND=value Set logical level (0 or 1) for RTS pin after sending
+
+ RTS_DELAY_BEFORE_SEND=value Set RTS delay (ms) before sending
+
+ RTS_DELAY_AFTER_SEND=value Set RTS delay (ms) after sending
+
+ RX_DURING_TX Receive data even while sending data
+
+ If defining more than one key or key value pair, they must be comma separated.
+
+ --alert none|bell|blink
+
+ Set alert action on connect/disconnect.
+
+ It will sound the bell once or blink once on successful connect. Likewise it will sound the bell twice or blink twice on disconnect.
+
+ Default value is "none".
+
-v, --version
Display program version.
Display help.
KEYS
- In session, the following key sequences, a prefix key (default: ctrl-t) followed by a command key, are intercepted as tio com‐
- mands:
+ In session, the following key sequences, a prefix key (default: ctrl-t) followed by a command key, are intercepted as tio commands:
ctrl-t ? List available key commands
HEXADECIMAL MODE
In hexadecimal mode each incoming byte is printed out as a hexadecimal value.
- Bytes can be sent in this mode by typing the two-character hexadecimal representation of the value, e.g.: to send 0xA you must
- type 0a or 0A.
+ Bytes can be sent in this mode by typing the two-character hexadecimal representation of the value, e.g.: to send 0xA you must type 0a or 0A.
CONFIGURATION FILE
- Options can be set via configuration file using the INI format. tio uses the configuration file first found in the following loca‐
- tions in the order listed:
+ Options can be set via configuration file using the INI format. tio uses the configuration file first found in the following locations in the order listed:
$XDG_CONFIG_HOME/tio/tiorc
The following configuration file options are available:
- pattern Pattern matching user input. This pattern can be an extended regular expression with a single group.
+ pattern Pattern matching user input. This pattern can be an extended regular expression with a single group.
+
+ tty tty device to open. If it contains a "%s" it is substituted with the first group match.
+
+ baudrate Set baud rate
+
+ databits Set data bits
- tty tty device to open. If it contains a "%s" it is substituted with the first group match.
+ flow Set flow control
- baudrate Set baud rate
+ stopbits Set stop bits
- databits Set data bits
+ parity Set parity
- flow Set flow control
+ output-delay Set output character delay
- stopbits Set stop bits
+ output-line-delay Set output line delay
- parity Set parity
+ line-pulse-duration Set line pulse duration
- output-delay Set output character delay
+ no-autoconnect Disable automatic connect
- output-line-delay Set output line delay
+ log Enable log to file
- line-pulse-duration Set line pulse duration
+ log-file Set log filename
- no-autoconnect Disable automatic connect
+ log-strip Enable strip of control and escape sequences from log
- log Enable log to file
+ local-echo Enable local echo
- log-file Set log filename
+ timestamp Enable line timestamp
- log-strip Enable strip of control and escape sequences from log
+ timestamp-format Set timestamp format
- local-echo Enable local echo
+ map Map characters on input or output
- timestamp Enable line timestamp
+ color Colorize tio text using ANSI color code ranging from 0 to 255
- timestamp-format Set timestamp format
+ hexadecimal Enable hexadecimal mode
- map Map characters on input or output
+ socket Set socket to redirect I/O to
- color Colorize tio text using ANSI color code ranging from 0 to 255
+ prefix-ctrl-key Set prefix ctrl key (a..z, default: t)
- hexadecimal Enable hexadecimal mode
+ response-wait Enable wait for line response
- socket Set socket to redirect I/O to
+ response-timeout Set line response timeout
- prefix-ctrl-key Set prefix ctrl key (a..z, default: t)
+ rs-485 Enable RS-485 mode
+
+ rs-485-config Set RS-485 configuration
+
+ alert Set alert action on connect/disconnect
CONFIGURATION FILE EXAMPLES
To change the default configuration simply set options like so:
$ tio /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
- Using serial devices by ID ensures that tio automatically reconnects to the correct serial device if it is disconnected and then
- reconnected.
+ Using serial devices by ID ensures that tio automatically reconnects to the correct serial device if it is disconnected and then reconnected.
Redirect serial device I/O to Unix file socket for scripting:
$ echo "ls -la" | tio /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
+ Pipe command to the serial device and wait for line response (string ending with CR or NL):
+
+ $ echo "*IDN?" | tio /dev/ttyACM0 --response-wait
+
+ In this mode, only the response will be printed.
+
Likewise, to pipe data from file to the serial device:
$ cat data.bin | tio /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
+ Enable RS-485 mode:
+
+ $ tio --rs-485 --rs-485-config=RTS_ON_SEND=1,RX_DURING_TX /dev/ttyUSB0
+
WEBSITE
Visit https://tio.github.io
AUTHOR
Created by Martin Lund <martin.lund@keep-it-simple.com>.
-tio 1.46 2022-07-15 tio(1)
+tio 2.0 2022-09-11 tio(1)
project('tio', 'c',
- version : '1.47',
+ version : '2.0',
license : [ 'GPL-2'],
meson_version : '>= 0.53.2',
default_options : [ 'warning_level=2', 'buildtype=release', 'c_std=gnu99' ]
)
# The tag date of the project_version(), update when the version bumps.
-version_date = '2022-07-23'
+version_date = '2022-09-11'
# Test for dynamic baudrate configuration interface
compiler = meson.get_compiler('c')
endif
endforeach
+# Test for RS-485 support on Linux
+enable_rs485 = false
+if host_machine.system() == 'linux'
+ if compiler.check_header('linux/serial.h')
+ enable_rs485 = compiler.has_header_symbol('sys/ioctl.h', 'TIOCSRS485')
+ endif
+endif
+
subdir('src')
subdir('man')
--- /dev/null
+/*
+ * tio - a simple serial terminal I/O tool
+ *
+ * Copyright (c) 2014-2022 Martin Lund
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "config.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include "error.h"
+#include "print.h"
+#include "options.h"
+
+enum alert_t alert_option_parse(const char *arg)
+{
+ enum alert_t alert = option.alert; // Default
+
+ if (arg != NULL)
+ {
+ if (strcmp(arg, "none") == 0)
+ {
+ return ALERT_NONE;
+ }
+ else if (strcmp(arg, "bell") == 0)
+ {
+ return ALERT_BELL;
+ }
+ else if (strcmp(arg, "blink") == 0)
+ {
+ return ALERT_BLINK;
+ }
+ }
+
+ return alert;
+}
+
+void blink_background(void)
+{
+ // Turn on reverse video
+ printf("\e[?5h");
+ fflush(stdout);
+
+ usleep(200*1000);
+
+ // Turn on normal video
+ printf("\e[?5l");
+ fflush(stdout);
+}
+
+void sound_bell(void)
+{
+ // Audio bell
+ printf("\a");
+ fflush(stdout);
+}
+
+void alert_connect(void)
+{
+ switch (option.alert)
+ {
+ case ALERT_NONE:
+ break;
+ case ALERT_BELL:
+ sound_bell();
+ break;
+ case ALERT_BLINK:
+ blink_background();
+ break;
+ default:
+ break;
+ }
+}
+
+void alert_disconnect(void)
+{
+ switch (option.alert)
+ {
+ case ALERT_NONE:
+ break;
+ case ALERT_BELL:
+ sound_bell();
+ usleep(200*1000);
+ sound_bell();
+ break;
+ case ALERT_BLINK:
+ blink_background();
+ usleep(200*1000);
+ blink_background();
+ break;
+ default:
+ break;
+ }
+}
--- /dev/null
+/*
+ * tio - a simple serial terminal I/O tool
+ *
+ * Copyright (c) 2014-2022 Martin Lund
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#pragma once
+
+enum alert_t
+{
+ ALERT_NONE,
+ ALERT_BELL,
+ ALERT_BLINK,
+ ALERT_END,
+};
+
+enum alert_t alert_option_parse(const char *arg);
+void alert_connect(void);
+void alert_disconnect(void);
-c --color \
-S --socket \
-x --hexadecimal \
+ -r --response-wait \
+ --response-timeout \
+ --rs-485 \
+ --rs-485-config \
+ --alert \
-v --version \
-h --help"
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
+ -r | --response-wait)
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ return 0
+ ;;
+ --response-timeout)
+ COMPREPLY=( $(compgen -W "1 10 100" -- ${cur}) )
+ return 0
+ ;;
+ --rs-485)
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ return 0
+ ;;
+ --rs-485-config)
+ COMPREPLY=( $(compgen -W "RTS_ON_SEND RTS_AFTER_SEND RTS_DELAY_BEFORE_SEND RTS_DELAY_AFTER_SEND RX_DURING_TX" -- ${cur}) )
+ return 0
+ ;;
+ --alert)
+ COMPREPLY=( $(compgen -W "none bell blink" -- ${cur}) )
+ return 0
+ ;;
-v | --version)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
#include "options.h"
#include "error.h"
#include "print.h"
+#include "rs485.h"
+#include "timestamp.h"
+#include "alert.h"
static struct config_t *c;
option.prefix_key = value[0];
}
}
-
+ else if (!strcmp(name, "response-wait"))
+ {
+ if (!strcmp(value, "enable"))
+ {
+ option.response_wait = true;
+ }
+ else if (!strcmp(value, "disable"))
+ {
+ option.response_wait = false;
+ }
+ }
+ else if (!strcmp(name, "response-timeout"))
+ {
+ option.response_timeout = atoi(value);
+ }
+ else if (!strcmp(name, "rs-485"))
+ {
+ if (!strcmp(value, "enable"))
+ {
+ option.rs485 = true;
+ }
+ else if (!strcmp(value, "disable"))
+ {
+ option.rs485 = false;
+ }
+ }
+ else if (!strcmp(name, "rs-485-config"))
+ {
+ rs485_parse_config(value);
+ }
+ else if (!strcmp(name, "alert"))
+ {
+ option.alert = alert_option_parse(value);
+ }
}
+
return 0;
}
#include "options.h"
#include "print.h"
#include "error.h"
+#include "timestamp.h"
static char error[2][1000];
static bool in_session = false;
{
putchar('\n');
}
- ansi_error_printf("[%s] %s", current_time(), line);
+ ansi_error_printf("[%s] %s", timestamp_current_time(), line);
}
else
{
{
// Enter non interactive mode
interactive_mode = false;
+
+ // Mute tio text in response mode
+ if (option.response_wait)
+ {
+ option.mute = true;
+ }
}
/* Configure output terminal */
'configfile.c',
'signals.c',
'socket.c',
- 'setspeed.c'
+ 'setspeed.c',
+ 'rs485.c',
+ 'timestamp.c',
+ 'alert.c'
]
tio_dep = dependency('inih', required: true,
tio_c_args += '-DHAVE_IOSSIOSPEED'
endif
+if enable_rs485
+ tio_c_args += '-DHAVE_RS485'
+endif
+
executable('tio',
tio_sources,
c_args: tio_c_args,
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
+#include <unistd.h>
#include <string.h>
#include <time.h>
-#include <sys/time.h>
#include <errno.h>
#include "error.h"
#include "print.h"
#include "options.h"
-#define TIME_STRING_SIZE_MAX 24
-
-char *current_time(void)
-{
- static char time_string[TIME_STRING_SIZE_MAX];
- static struct timeval tv, tv_now, tv_start, tv_previous;
- static bool first = true;
- struct tm *tm;
- size_t len;
-
- // Get current time value
- gettimeofday(&tv_now, NULL);
-
- if (first)
- {
- tv_start = tv_now;
- first = false;
- }
-
- // Add formatted timestap
- switch (option.timestamp)
- {
- case TIMESTAMP_NONE:
- case TIMESTAMP_24HOUR:
- // "hh:mm:ss.sss" (24 hour format)
- tv = tv_now;
- tm = localtime(&tv.tv_sec);
- len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm);
- break;
- case TIMESTAMP_24HOUR_START:
- // "hh:mm:ss.sss" (24 hour format relative to start time)
- timersub(&tv_now, &tv_start, &tv);
- tm = gmtime(&tv.tv_sec);
- len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm);
- break;
- case TIMESTAMP_24HOUR_DELTA:
- // "hh:mm:ss.sss" (24 hour format relative to previous time stamp)
- timersub(&tv_now, &tv_previous, &tv);
- tm = gmtime(&tv.tv_sec);
- len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm);
- break;
- case TIMESTAMP_ISO8601:
- // "YYYY-MM-DDThh:mm:ss.sss" (ISO-8601)
- tv = tv_now;
- tm = localtime(&tv.tv_sec);
- len = strftime(time_string, sizeof(time_string), "%Y-%m-%dT%H:%M:%S", tm);
- break;
- default:
- return NULL;
- }
-
- // Append milliseconds to all timestamps
- if (len)
- {
- len = snprintf(time_string + len, TIME_STRING_SIZE_MAX - len, ".%03ld", (long)tv.tv_usec / 1000);
- }
-
- // Save previous time value for next run
- tv_previous = tv_now;
-
- return (len < TIME_STRING_SIZE_MAX) ? time_string : NULL;
-}
-
void delay(long ms)
{
struct timespec ts;
void delay(long ms);
long string_to_long(char *string);
int ctrl_key_code(unsigned char key);
+void alert_connect(void);
+void alert_disconnect(void);
#include "misc.h"
#include "print.h"
#include "tty.h"
+#include "rs485.h"
+#include "timestamp.h"
+#include "alert.h"
enum opt_t
{
OPT_LOG_FILE,
OPT_LOG_STRIP,
OPT_LINE_PULSE_DURATION,
+ OPT_RESPONSE_TIMEOUT,
+ OPT_RS485,
+ OPT_RS485_CONFIG,
+ OPT_ALERT,
};
/* Default options */
.hex_mode = false,
.prefix_code = 20, // ctrl-t
.prefix_key = 't',
+ .response_wait = false,
+ .response_timeout = 100,
+ .mute = false,
+ .rs485 = false,
+ .rs485_config_flags = 0,
+ .rs485_delay_rts_before_send = -1,
+ .rs485_delay_rts_after_send = -1,
+ .alert = ALERT_NONE,
};
void print_help(char *argv[])
printf(" -e, --local-echo Enable local echo\n");
printf(" -t, --timestamp Enable line timestamp\n");
printf(" --timestamp-format <format> Set timestamp format (default: 24hour)\n");
- printf(" -L, --list-devices List available serial devices\n");
+ printf(" -L, --list-devices List available serial devices by ID\n");
printf(" -l, --log Enable log to file\n");
printf(" --log-file <filename> Set log filename\n");
printf(" --log-strip Strip control characters and escape sequences\n");
printf(" -m, --map <flags> Map characters\n");
printf(" -c, --color 0..255|bold|none|list Colorize tio text (default: bold)\n");
- printf(" -S, --socket <socket> Redirect I/O to file or network socket\n");
+ printf(" -S, --socket <socket> Redirect I/O to socket\n");
printf(" -x, --hexadecimal Enable hexadecimal mode\n");
+ printf(" -r, --response-wait Wait for line response then quit\n");
+ printf(" --response-timeout <ms> Response timeout (default: 100)\n");
+ printf(" --rs-485 Enable RS-485 mode\n");
+ printf(" --rs-485-config <config> Set RS-485 configuration\n");
+ printf(" --alert bell|blink|none Alert on connect/disconnect (default: none)\n");
printf(" -v, --version Display version\n");
printf(" -h, --help Display help\n");
printf("\n");
printf("See the man page for more details.\n");
}
-const char* timestamp_state_to_string(enum timestamp_t timestamp)
-{
- switch (timestamp)
- {
- case TIMESTAMP_NONE:
- return "disabled";
- break;
-
- case TIMESTAMP_24HOUR:
- return "24hour";
- break;
-
- case TIMESTAMP_24HOUR_START:
- return "24hour-start";
- break;
-
- case TIMESTAMP_24HOUR_DELTA:
- return "24hour-delta";
- break;
-
- case TIMESTAMP_ISO8601:
- return "iso8601";
- break;
-
- default:
- return "unknown";
- break;
- }
-}
-
-enum timestamp_t timestamp_option_parse(const char *arg)
-{
- enum timestamp_t timestamp = TIMESTAMP_24HOUR; // Default
-
- if (arg != NULL)
- {
- if (strcmp(arg, "24hour") == 0)
- {
- return TIMESTAMP_24HOUR;
- }
- else if (strcmp(arg, "24hour-start") == 0)
- {
- return TIMESTAMP_24HOUR_START;
- }
- else if (strcmp(arg, "24hour-delta") == 0)
- {
- return TIMESTAMP_24HOUR_DELTA;
- }
- else if (strcmp(arg, "iso8601") == 0)
- {
- return TIMESTAMP_ISO8601;
- }
- }
-
- return timestamp;
-}
-
void line_pulse_duration_option_parse(const char *arg)
{
bool token_found = true;
if (token != NULL)
{
- char keyname[10];
+ char keyname[11];
unsigned int value;
sscanf(token, "%10[^=]=%d", keyname, &value);
}
}
free(buffer);
-
}
void options_print()
tio_printf(" Timestamp: %s", timestamp_state_to_string(option.timestamp));
tio_printf(" Output delay: %d", option.output_delay);
tio_printf(" Output line delay: %d", option.output_line_delay);
- tio_printf(" DTR pulse duration: %d", option.dtr_pulse_duration);
tio_printf(" Auto connect: %s", option.no_autoconnect ? "disabled" : "enabled");
tio_printf(" Pulse duration: DTR=%d RTS=%d CTS=%d DSR=%d DCD=%d RI=%d", option.dtr_pulse_duration,
option.rts_pulse_duration,
option.dsr_pulse_duration,
option.dcd_pulse_duration,
option.ri_pulse_duration);
+ tio_printf(" Hexadecimal mode: %s", option.hex_mode ? "enabled" : "disabled");
if (option.map[0] != 0)
tio_printf(" Map flags: %s", option.map);
if (option.log)
{"map", required_argument, 0, 'm' },
{"color", required_argument, 0, 'c' },
{"hexadecimal", no_argument, 0, 'x' },
+ {"response-wait", no_argument, 0, 'r' },
+ {"response-timeout", required_argument, 0, OPT_RESPONSE_TIMEOUT },
+ {"rs-485", no_argument, 0, OPT_RS485 },
+ {"rs-485-config", required_argument, 0, OPT_RS485_CONFIG },
+ {"alert", required_argument, 0, OPT_ALERT },
{"version", no_argument, 0, 'v' },
{"help", no_argument, 0, 'h' },
{0, 0, 0, 0 }
int option_index = 0;
/* Parse argument using getopt_long */
- c = getopt_long(argc, argv, "b:d:f:s:p:o:O:netLlS:m:c:xvh", long_options, &option_index);
+ c = getopt_long(argc, argv, "b:d:f:s:p:o:O:netLlS:m:c:xrvh", long_options, &option_index);
/* Detect the end of the options */
if (c == -1)
break;
case OPT_LOG_FILE:
- option.log = true;
option.log_filename = optarg;
break;
option.hex_mode = true;
break;
+ case 'r':
+ option.response_wait = true;
+ break;
+
+ case OPT_RESPONSE_TIMEOUT:
+ option.response_timeout = string_to_long(optarg);
+ break;
+
+ case OPT_RS485:
+ option.rs485 = true;
+ break;
+
+ case OPT_RS485_CONFIG:
+ rs485_parse_config(optarg);
+ break;
+
+ case OPT_ALERT:
+ option.alert = alert_option_parse(optarg);
+ break;
+
case 'v':
printf("tio v%s\n", VERSION);
- printf("Copyright (c) 2014-2022 Martin Lund\n");
- printf("\n");
- printf("License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl-2.0.html>.\n");
- printf("This is free software: you are free to change and redistribute it.\n");
- printf("There is NO WARRANTY, to the extent permitted by law.\n");
exit(EXIT_SUCCESS);
break;
#pragma once
+#include <stdint.h>
#include <stdbool.h>
#include <limits.h>
#include <termios.h>
#include <sys/param.h>
-
-enum timestamp_t
-{
- TIMESTAMP_NONE,
- TIMESTAMP_24HOUR,
- TIMESTAMP_24HOUR_START,
- TIMESTAMP_24HOUR_DELTA,
- TIMESTAMP_ISO8601,
- TIMESTAMP_END,
-};
-
-enum timestamp_t timestamp_option_parse(const char *arg);
+#include "timestamp.h"
+#include "alert.h"
/* Options */
struct option_t
bool hex_mode;
unsigned char prefix_code;
unsigned char prefix_key;
+ bool response_wait;
+ int response_timeout;
+ bool mute;
+ bool rs485;
+ uint32_t rs485_config_flags;
+ int32_t rs485_delay_rts_before_send;
+ int32_t rs485_delay_rts_after_send;
+ enum alert_t alert;
};
extern struct option_t option;
*/
#include <stdio.h>
+#include <stdlib.h>
#include <stdbool.h>
+#include <string.h>
#include "options.h"
#include "print.h"
sprintf(ansi_format, "\e[1;38;5;%dm", option.color);
}
}
+
+void tio_printf_array(const char *array)
+{
+ int i = 0, j = 0;
+
+ tio_printf("");
+
+ while (array[i])
+ {
+ if (array[i] == '\n')
+ {
+ const char *line = &array[j];
+ char *line_copy = strndup(line, i-j);
+ tio_printf_raw("%s\r", line_copy);
+ free(line_copy);
+ j = i;
+ }
+ i++;
+ }
+ tio_printf("");
+}
#pragma once
+#include <stdio.h>
#include <stdbool.h>
#include "misc.h"
#include "error.h"
#include "options.h"
+#include "timestamp.h"
extern bool print_tainted;
extern char ansi_format[];
#define ansi_printf(format, args...) \
{ \
+ if (!option.mute) { \
if (option.color < 0) \
fprintf (stdout, "\r" format "\r\n", ## args); \
else \
fprintf (stdout, "\r%s" format ANSI_RESET "\r\n", ansi_format, ## args); \
+ } \
}
#define ansi_error_printf(format, args...) \
{ \
+ if (!option.mute) { \
if (option.color < 0) \
fprintf (stderr, "\r" format "\r\n", ## args); \
else \
fprintf (stderr, "\r%s" format ANSI_RESET "\r\n", ansi_format, ## args); \
fflush(stderr); \
+ } \
}
#define ansi_printf_raw(format, args...) \
{ \
+ if (!option.mute) { \
if (option.color < 0) \
fprintf (stdout, format, ## args); \
else \
fprintf (stdout, "%s" format ANSI_RESET, ansi_format, ## args); \
+ } \
}
#define tio_warning_printf(format, args...) \
{ \
+ if (!option.mute) { \
if (print_tainted) \
putchar('\n'); \
if (option.color < 0) \
- fprintf (stdout, "\r[%s] Warning: " format "\r\n", current_time(), ## args); \
+ fprintf (stdout, "\r[%s] Warning: " format "\r\n", timestamp_current_time(), ## args); \
else \
- ansi_printf("[%s] Warning: " format, current_time(), ## args); \
+ ansi_printf("[%s] Warning: " format, timestamp_current_time(), ## args); \
+ } \
}
#define tio_printf(format, args...) \
{ \
+ if (!option.mute) { \
if (print_tainted) \
putchar('\n'); \
- ansi_printf("[%s] " format, current_time(), ## args); \
+ ansi_printf("[%s] " format, timestamp_current_time(), ## args); \
print_tainted = false; \
+ } \
+}
+
+#define tio_printf_raw(format, args...) \
+{ \
+ if (!option.mute) { \
+ if (print_tainted) \
+ putchar('\n'); \
+ ansi_printf_raw("[%s] " format, timestamp_current_time(), ## args); \
+ print_tainted = false; \
+ } \
}
#ifdef DEBUG
void print_hex(char c);
void print_normal(char c);
void print_init_ansi_formatting(void);
+void tio_printf_array(const char *array);
--- /dev/null
+/*
+ * tio - a simple serial device I/O tool
+ *
+ * Copyright (c) 2022 Martin Lund
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/ioctl.h>
+#include <stdbool.h>
+#include "options.h"
+#include "print.h"
+#include "error.h"
+
+#ifdef HAVE_RS485
+
+#include <linux/serial.h>
+
+static struct serial_rs485 rs485_config_saved;
+static struct serial_rs485 rs485_config;
+static bool rs485_config_written = false;
+
+void rs485_parse_config(const char *arg)
+{
+ bool token_found = true;
+ char *token = NULL;
+ char *buffer = strdup(arg);
+
+ while (token_found == true)
+ {
+ if (token == NULL)
+ {
+ token = strtok(buffer,",");
+ }
+ else
+ {
+ token = strtok(NULL, ",");
+ }
+
+ if (token != NULL)
+ {
+ char keyname[31];
+ unsigned int value;
+ sscanf(token, "%30[^=]=%d", keyname, &value);
+
+ if (!strcmp(keyname, "RTS_ON_SEND"))
+ {
+ if (value)
+ {
+
+ /* Set logical level for RTS pin equal to 1 when sending */
+ option.rs485_config_flags |= SER_RS485_RTS_ON_SEND;
+ }
+ else
+ {
+ /* Set logical level for RTS pin equal to 0 when sending */
+ option.rs485_config_flags &= ~(SER_RS485_RTS_ON_SEND);
+ }
+ }
+ else if (!strcmp(keyname, "RTS_AFTER_SEND"))
+ {
+ if (value)
+ {
+ /* Set logical level for RTS pin equal to 1 after sending */
+ option.rs485_config_flags |= SER_RS485_RTS_AFTER_SEND;
+ }
+ else
+ {
+ /* Set logical level for RTS pin equal to 0 after sending */
+ option.rs485_config_flags &= ~(SER_RS485_RTS_AFTER_SEND);
+ }
+ }
+ else if (!strcmp(keyname, "RTS_DELAY_BEFORE_SEND"))
+ {
+ /* Set RTS delay before send */
+ option.rs485_delay_rts_before_send = value;
+ }
+ else if (!strcmp(keyname, "RTS_DELAY_AFTER_SEND"))
+ {
+ /* Set RTS delay after send */
+ option.rs485_delay_rts_after_send = value;
+ }
+ else if (!strcmp(keyname, "RX_DURING_TX"))
+ {
+ /* Receive data even while sending data */
+ option.rs485_config_flags |= SER_RS485_RX_DURING_TX;
+ }
+ }
+ else
+ {
+ token_found = false;
+ }
+ }
+ free(buffer);
+}
+
+void rs485_print_config(void)
+{
+ tio_printf(" RS-485 Configuration:");
+ tio_printf(" RTS_ON_SEND: %s", (rs485_config.flags & SER_RS485_RTS_ON_SEND) ? "high" : "low");
+ tio_printf(" RTS_AFTER_SEND: %s", (rs485_config.flags & SER_RS485_RTS_AFTER_SEND) ? "high" : "low");
+ tio_printf(" RTS_DELAY_BEFORE_SEND = %d", rs485_config.delay_rts_before_send);
+ tio_printf(" RTS_DELAY_AFTER_SEND = %d", rs485_config.delay_rts_after_send);
+ tio_printf(" RX_DURING_TX: %s", (rs485_config.flags & SER_RS485_RX_DURING_TX) ? "enabled" : "disabled");
+}
+
+int rs485_mode_enable(int fd)
+{
+ /* Save existing RS-485 configuration */
+ ioctl (fd, TIOCGRS485, &rs485_config_saved);
+
+ /* Prepare new RS-485 configuration */
+ rs485_config.flags = SER_RS485_ENABLED;
+ rs485_config.flags |= option.rs485_config_flags;
+
+ if (option.rs485_delay_rts_before_send > 0)
+ {
+ rs485_config.delay_rts_before_send = option.rs485_delay_rts_before_send;
+ }
+ else
+ {
+ rs485_config.delay_rts_before_send = rs485_config_saved.delay_rts_before_send;
+ }
+
+ if (option.rs485_delay_rts_after_send > 0)
+ {
+ rs485_config.delay_rts_after_send = option.rs485_delay_rts_after_send;
+ }
+ else
+ {
+ rs485_config.delay_rts_after_send = rs485_config_saved.delay_rts_after_send;
+ }
+
+ /* Write new RS-485 configuration */
+ if (ioctl(fd, TIOCSRS485, &rs485_config) < 0)
+ {
+ tio_warning_printf("RS-485 mode is not supported by your device (%s)", strerror(errno));
+ return -1;
+ }
+
+ rs485_config_written = true;
+
+ return 0;
+}
+
+void rs485_mode_restore(int fd)
+{
+ if (rs485_config_written)
+ {
+ /* Write saved RS-485 configuration */
+ if (ioctl(fd, TIOCSRS485, &rs485_config_saved) < 0)
+ {
+ tio_warning_printf("TIOCGRS485 ioctl failed (%s)", strerror(errno));
+ }
+ }
+}
+
+#else
+
+void rs485_parse_config(const char *arg)
+{
+ UNUSED(arg);
+ return;
+}
+
+void rs485_print_config(void)
+{
+ return;
+}
+
+int rs485_mode_enable(int fd)
+{
+ UNUSED(fd);
+ tio_error_printf("RS485 mode is not supported on your system");
+ exit(EXIT_FAILURE);
+}
+
+void rs485_mode_restore(int fd)
+{
+ UNUSED(fd);
+ return;
+}
+
+#endif
--- /dev/null
+/*
+ * tio - a simple serial device I/O tool
+ *
+ * Copyright (c) 2022 Martin Lund
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#pragma once
+
+void rs485_parse_config(const char *arg);
+int rs485_mode_enable(int fd);
+void rs485_mode_restore(int fd);
+void rs485_print_config(void);
{
signal(SIGHUP, signal_handler);
signal(SIGINT, signal_handler);
+ signal(SIGPIPE, SIG_IGN);
}
}
}
+static bool socket_stale(const char *path)
+{
+ struct sockaddr_un addr;
+ bool stale = false;
+ int sockfd;
+
+ /* Test if socket file exists */
+ if (access(path, F_OK) == 0)
+ {
+ /* Create test socket */
+ sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (sockfd < 0)
+ {
+ tio_warning_printf("Failure opening socket (%s)", strerror(errno));
+ return false;
+ }
+
+ /* Prepare address */
+ addr.sun_family = AF_UNIX;
+ strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
+
+ /* Perform connect to test if socket is active */
+ if (connect(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)) == -1)
+ {
+ if (errno == ECONNREFUSED)
+ {
+ // No one is listening on socket file
+ stale = true;
+ }
+ }
+
+ /* Cleanup */
+ close(sockfd);
+ }
+
+ return stale;
+}
+
void socket_configure(void)
{
struct sockaddr_un sockaddr_unix = {};
tio_error_printf("%s: Invalid socket scheme, must be prefixed with 'unix:', 'inet:', or 'inet6:'", option.socket);
exit(EXIT_FAILURE);
}
-
+
/* Configure socket */
switch (socket_family)
strncpy(sockaddr_unix.sun_path, socket_filename(), sizeof(sockaddr_unix.sun_path) - 1);
sockaddr_p = (struct sockaddr *) &sockaddr_unix;
socklen = sizeof(sockaddr_unix);
+
+ /* Test for stale unix socket file */
+ if (socket_stale(socket_filename()))
+ {
+ tio_printf("Cleaning up old socket file");
+ unlink(socket_filename());
+ }
+
break;
case AF_INET:
--- /dev/null
+/*
+ * tio - a simple serial terminal I/O tool
+ *
+ * Copyright (c) 2014-2022 Martin Lund
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#include "config.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/time.h>
+#include <time.h>
+#include "error.h"
+#include "print.h"
+#include "options.h"
+#include "timestamp.h"
+
+#define TIME_STRING_SIZE_MAX 24
+
+char *timestamp_current_time(void)
+{
+ static char time_string[TIME_STRING_SIZE_MAX];
+ static struct timeval tv, tv_now, tv_start, tv_previous;
+ static bool first = true;
+ struct tm *tm;
+ size_t len;
+
+ // Get current time value
+ gettimeofday(&tv_now, NULL);
+
+ if (first)
+ {
+ tv_start = tv_now;
+ first = false;
+ }
+
+ // Add formatted timestap
+ switch (option.timestamp)
+ {
+ case TIMESTAMP_NONE:
+ case TIMESTAMP_24HOUR:
+ // "hh:mm:ss.sss" (24 hour format)
+ tv = tv_now;
+ tm = localtime(&tv.tv_sec);
+ len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm);
+ break;
+ case TIMESTAMP_24HOUR_START:
+ // "hh:mm:ss.sss" (24 hour format relative to start time)
+ timersub(&tv_now, &tv_start, &tv);
+ tm = gmtime(&tv.tv_sec);
+ len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm);
+ break;
+ case TIMESTAMP_24HOUR_DELTA:
+ // "hh:mm:ss.sss" (24 hour format relative to previous time stamp)
+ timersub(&tv_now, &tv_previous, &tv);
+ tm = gmtime(&tv.tv_sec);
+ len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm);
+ break;
+ case TIMESTAMP_ISO8601:
+ // "YYYY-MM-DDThh:mm:ss.sss" (ISO-8601)
+ tv = tv_now;
+ tm = localtime(&tv.tv_sec);
+ len = strftime(time_string, sizeof(time_string), "%Y-%m-%dT%H:%M:%S", tm);
+ break;
+ default:
+ return NULL;
+ }
+
+ // Append milliseconds to all timestamps
+ if (len)
+ {
+ len = snprintf(time_string + len, TIME_STRING_SIZE_MAX - len, ".%03ld", (long)tv.tv_usec / 1000);
+ }
+
+ // Save previous time value for next run
+ tv_previous = tv_now;
+
+ return (len < TIME_STRING_SIZE_MAX) ? time_string : NULL;
+}
+
+const char* timestamp_state_to_string(enum timestamp_t timestamp)
+{
+ switch (timestamp)
+ {
+ case TIMESTAMP_NONE:
+ return "disabled";
+ break;
+
+ case TIMESTAMP_24HOUR:
+ return "24hour";
+ break;
+
+ case TIMESTAMP_24HOUR_START:
+ return "24hour-start";
+ break;
+
+ case TIMESTAMP_24HOUR_DELTA:
+ return "24hour-delta";
+ break;
+
+ case TIMESTAMP_ISO8601:
+ return "iso8601";
+ break;
+
+ default:
+ return "unknown";
+ break;
+ }
+}
+
+enum timestamp_t timestamp_option_parse(const char *arg)
+{
+ enum timestamp_t timestamp = TIMESTAMP_24HOUR; // Default
+
+ if (arg != NULL)
+ {
+ if (strcmp(arg, "24hour") == 0)
+ {
+ return TIMESTAMP_24HOUR;
+ }
+ else if (strcmp(arg, "24hour-start") == 0)
+ {
+ return TIMESTAMP_24HOUR_START;
+ }
+ else if (strcmp(arg, "24hour-delta") == 0)
+ {
+ return TIMESTAMP_24HOUR_DELTA;
+ }
+ else if (strcmp(arg, "iso8601") == 0)
+ {
+ return TIMESTAMP_ISO8601;
+ }
+ }
+
+ return timestamp;
+}
--- /dev/null
+/*
+ * tio - a simple serial terminal I/O tool
+ *
+ * Copyright (c) 2014-2022 Martin Lund
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301, USA.
+ */
+
+#pragma once
+
+enum timestamp_t
+{
+ TIMESTAMP_NONE,
+ TIMESTAMP_24HOUR,
+ TIMESTAMP_24HOUR_START,
+ TIMESTAMP_24HOUR_DELTA,
+ TIMESTAMP_ISO8601,
+ TIMESTAMP_END,
+};
+
+char *timestamp_current_time(void);
+const char* timestamp_state_to_string(enum timestamp_t timestamp);
+enum timestamp_t timestamp_option_parse(const char *arg);
#include "error.h"
#include "socket.h"
#include "setspeed.h"
+#include "rs485.h"
+#include "alert.h"
+#include "timestamp.h"
+#include "misc.h"
-#ifdef __APPLE__
+#if defined(__APPLE__)
+#define PATH_SERIAL_DEVICES "/dev/"
+#define PREFIX_TTY_DEVICES "tty."
+#elif defined(__CYGWIN__)
#define PATH_SERIAL_DEVICES "/dev/"
+#define PREFIX_TTY_DEVICES "ttyS"
#else
#define PATH_SERIAL_DEVICES "/dev/serial/by-id/"
+#define PREFIX_TTY_DEVICES ""
#endif
#ifndef CMSPAR
#define KEY_G 0x67
#define KEY_H 0x68
#define KEY_L 0x6C
+#define KEY_SHIFT_L 0x4C
#define KEY_P 0x70
#define KEY_Q 0x71
#define KEY_S 0x73
#define KEY_T 0x74
#define KEY_U 0x55
#define KEY_V 0x76
-#define KEY_SHIFT_L 0x4C
-
-#define NORMAL 0
-#define HEX 1
+#define KEY_Z 0x7a
enum line_mode_t
{
LINE_PULSE
};
+const char random_array[] =
+{
+0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x20, 0x28, 0x0A, 0x20,
+0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x29, 0x20, 0x29, 0x0A, 0x20,
+0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E,
+0x2E, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7C, 0x20, 0x20, 0x20,
+0x20, 0x20, 0x20, 0x7C, 0x5D, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+0x5C, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2F, 0x0A, 0x20, 0x20, 0x20, 0x20,
+0x20, 0x20, 0x20, 0x20, 0x60, 0x2D, 0x2D, 0x2D, 0x2D, 0x27, 0x0A, 0x0A, 0x54,
+0x69, 0x6D, 0x65, 0x20, 0x66, 0x6F, 0x72, 0x20, 0x61, 0x20, 0x63, 0x6F, 0x66,
+0x66, 0x65, 0x65, 0x20, 0x62, 0x72, 0x65, 0x61, 0x6B, 0x21, 0x0A, 0x20, 0x0A,
+0x00
+};
+
bool interactive_mode = true;
static struct termios tio, tio_old, stdout_new, stdout_old, stdin_new, stdin_old;
static unsigned long rx_total = 0, tx_total = 0;
static bool connected = false;
-static bool print_mode = NORMAL;
static bool standard_baudrate = true;
static void (*print)(char c);
static int fd;
tio_printf("Configuration:");
config_file_print();
options_print();
+ if (option.rs485)
+ {
+ rs485_print_config();
+ }
break;
case KEY_E:
case KEY_H:
/* Toggle hexadecimal printing mode */
- if (print_mode == NORMAL)
+ if (!option.hex_mode)
{
print = print_hex;
- print_mode = HEX;
+ option.hex_mode = true;
tio_printf("Switched to hexadecimal mode");
}
else
{
print = print_normal;
- print_mode = NORMAL;
+ option.hex_mode = false;
tio_printf("Switched to normal mode");
}
break;
tio_printf("tio v%s", VERSION);
break;
+ case KEY_Z:
+ tio_printf_array(random_array);
+ break;
+
default:
/* Ignore unknown ctrl-t escaped keys */
break;
flock(fd, LOCK_UN);
close(fd);
connected = false;
+
+ /* Fire alert action */
+ alert_disconnect();
}
}
{
tcsetattr(fd, TCSANOW, &tio_old);
+ if (option.rs485)
+ {
+ /* Restore original RS-485 mode */
+ rs485_mode_restore(fd);
+ }
+
if (connected)
{
tty_disconnect();
}
else
{
- if (print_mode == HEX)
+ if (option.hex_mode)
{
output_hex(output_char);
}
int status;
bool next_timestamp = false;
char* now = NULL;
+ struct timeval tv;
+ struct timeval *tv_p = &tv;
+ bool ignore_stdin = false;
/* Open tty device */
fd = open(option.tty_device, O_RDWR | O_NOCTTY | O_NONBLOCK);
connected = true;
print_tainted = false;
+ /* Fire alert action */
+ alert_connect();
+
if (option.timestamp)
{
next_timestamp = true;
if (option.hex_mode)
{
print = print_hex;
- print_mode = HEX;
}
else
{
print = print_normal;
- print_mode = NORMAL;
}
/* Save current port settings */
}
#endif
+ /* Manage RS-485 mode */
+ if (option.rs485)
+ {
+ rs485_mode_enable(fd);
+ }
+
/* Make sure we restore tty settings on exit */
if (first)
{
{
FD_ZERO(&rdfs);
FD_SET(fd, &rdfs);
- FD_SET(STDIN_FILENO, &rdfs);
+ if (!ignore_stdin)
+ {
+ FD_SET(STDIN_FILENO, &rdfs);
+ }
maxfd = MAX(fd, STDIN_FILENO);
maxfd = MAX(maxfd, socket_add_fds(&rdfs, true));
+ /* Manage timeout */
+ if ((option.response_wait) && (option.response_timeout != 0))
+ {
+ // Set response timeout
+ tv_p->tv_sec = 0;
+ tv_p->tv_usec = option.response_timeout * 1000;
+ }
+ else
+ {
+ // No timeout
+ tv_p = NULL;
+ }
+
/* Block until input becomes available */
- status = select(maxfd + 1, &rdfs, NULL, NULL, NULL);
+ status = select(maxfd + 1, &rdfs, NULL, NULL, tv_p);
if (status > 0)
{
bool forward = false;
/* Print timestamp on new line if enabled */
if (next_timestamp && input_char != '\n' && input_char != '\r')
{
- now = current_time();
+ now = timestamp_current_time();
if (now)
{
ansi_printf_raw("[%s] ", now);
{
next_timestamp = true;
}
+
+ if (option.response_wait)
+ {
+ if ((input_char == '\r') || (input_char == '\n'))
+ {
+ tty_sync(fd);
+ exit(EXIT_SUCCESS);
+ }
+ }
}
}
else if (FD_ISSET(STDIN_FILENO, &rdfs))
else if (bytes_read == 0)
{
/* Reached EOF (when piping to stdin) */
- tty_sync(fd);
- exit(EXIT_SUCCESS);
+ if (option.response_wait)
+ {
+ /* Stdin pipe closed but not blocking so stop listening
+ * to stdin in response mode.
+ *
+ * Note: select() really indicates not if data is ready
+ * but if file descriptor is non-blocking for I/O
+ * operation. */
+ ignore_stdin = true;
+ }
+ else
+ {
+ tty_sync(fd);
+ exit(EXIT_SUCCESS);
+ }
}
/* Process input byte by byte */
/* Save previous key */
previous_char = input_char;
- if ((print_mode == HEX) && (forward))
+ if ((option.hex_mode) && (forward))
{
if (!is_valid_hex(input_char))
{
tio_error_printf("select() failed (%s)", strerror(errno));
exit(EXIT_FAILURE);
}
+ else
+ {
+ // Timeout (only happens in response wait mode)
+ exit(EXIT_FAILURE);
+ }
}
return TIO_SUCCESS;
{
if ((strcmp(dir->d_name, ".")) && (strcmp(dir->d_name, "..")))
{
-#ifdef __APPLE__
-#define TTY_DEVICES_PREFIX "tty."
- if (!strncmp(dir->d_name, TTY_DEVICES_PREFIX, sizeof(TTY_DEVICES_PREFIX) - 1))
-#endif
- printf("%s%s\n", PATH_SERIAL_DEVICES, dir->d_name);
+ if (!strncmp(dir->d_name, PREFIX_TTY_DEVICES, sizeof(PREFIX_TTY_DEVICES) - 1))
+ {
+ printf("%s%s\n", PATH_SERIAL_DEVICES, dir->d_name);
+ }
}
}
closedir(d);