]> git.sur5r.net Git - tio/commitdiff
New upstream version 2.0 upstream/2.0
authorJakob Haufe <sur5r@debian.org>
Sun, 2 Oct 2022 20:11:28 +0000 (22:11 +0200)
committerJakob Haufe <sur5r@debian.org>
Sun, 2 Oct 2022 20:11:28 +0000 (22:11 +0200)
28 files changed:
.gitignore
NEWS
README.md
TODO
example/tiorc
man/tio.1.in
man/tio.1.txt
meson.build
src/alert.c [new file with mode: 0644]
src/alert.h [new file with mode: 0644]
src/bash-completion/tio.in
src/configfile.c
src/error.c
src/main.c
src/meson.build
src/misc.c
src/misc.h
src/options.c
src/options.h
src/print.c
src/print.h
src/rs485.c [new file with mode: 0644]
src/rs485.h [new file with mode: 0644]
src/signals.c
src/socket.c
src/timestamp.c [new file with mode: 0644]
src/timestamp.h [new file with mode: 0644]
src/tty.c

index 1eef64ab4041d85db7fd976b7b20a49c8765275e..40120d6c74bfa1c5e6d2d8e9f8848894a7480a78 100644 (file)
@@ -1,3 +1,4 @@
 /build
 /subprojects/libinih
 *.swp
+.cache
diff --git a/NEWS b/NEWS
index e7305cc435d23a82b20e6354f97e6c4fdc7648c5..544f8a1c7ce12958b2bd0c507c4a6b1637316469 100644 (file)
--- a/NEWS
+++ b/NEWS
@@ -1,5 +1,117 @@
 
-=== 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.
 
 
 
@@ -700,7 +812,7 @@ Changes since tio v1.32:
  * 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
index a79bc159285e5809808b6b602ba1d6056372c453..8861b68819f92473d99395a201a673561b75e860 100644 (file)
--- a/README.md
+++ b/README.md
@@ -28,7 +28,9 @@ when used in combination with [tmux](https://tmux.github.io).
 
  * 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
@@ -43,17 +45,20 @@ when used in combination with [tmux](https://tmux.github.io).
  * 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
 
@@ -83,8 +88,13 @@ The command-line interface is straightforward as reflected in the output from
         --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
 
@@ -121,6 +131,18 @@ $ 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.
 
+
+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
@@ -202,7 +224,7 @@ Packages for various GNU/Linux distributions are available. Please consult your
 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)
 
@@ -218,11 +240,11 @@ If you have [brew](http://brew.sh) installed:
     $ 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
@@ -238,8 +260,7 @@ Install steps:
 
 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
diff --git a/TODO b/TODO
index 7801868f53db4c1445e1f9459b58b8bfff810542..14d80254653c4786cb4901dcbf17890980672493 100644 (file)
--- a/TODO
+++ b/TODO
@@ -1,19 +1,31 @@
 
  * 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.
index a1340e30ec85161347a6db7d1d70c90a6096083c..c555df1b834e28da7912bb572cfa42f1e54dd4bf 100644 (file)
@@ -16,7 +16,11 @@ output-line-delay = 0
 no-autoconnect = disable
 hexadecimal = disable
 timestamp = disable
+log = disable
+log-strip = disable
 color = bold
+rs-485 = disable
+alert = none
 
 # Sub-configuraions
 
@@ -30,6 +34,7 @@ color = 9
 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]
@@ -44,3 +49,9 @@ color = 11
 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
index 48623b23264dbee49b30044c883faee0b1d0d682..de87ea33478a64fe210c8e49cb122f7817b8ad43 100644 (file)
@@ -55,18 +55,24 @@ Set output delay [ms] inserted between each sent line (default: 0).
 .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.
 
@@ -118,15 +124,14 @@ Default format is \fB24hour\fR
 .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>
@@ -185,10 +190,12 @@ Default value is "bold".
 .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.
 
@@ -208,6 +215,58 @@ If port is 0 or no port is provided default port 3333 is used.
 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
 
@@ -288,7 +347,7 @@ Any options set via command-line will override options set in the configuration
 .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"
@@ -333,6 +392,16 @@ Enable hexadecimal mode
 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"
 
@@ -469,12 +538,24 @@ $ nc -N 10.0.0.42 4444
 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
index dc1072aa2d1525c367a27f1b92e58c1a55f3455a..0399b635a6707ce81e07d972849213248a3b5530 100644 (file)
@@ -1,4 +1,4 @@
-tio(1)                                                        User Commands                                                        tio(1)
+tio(1)                                                                                    User Commands                                                                                   tio(1)
 
 NAME
        tio - a simple serial device I/O tool
@@ -7,8 +7,7 @@ SYNOPSIS
        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>
@@ -31,8 +30,7 @@ OPTIONS
 
               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>
 
@@ -44,22 +42,21 @@ OPTIONS
 
            --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.
 
@@ -69,12 +66,10 @@ OPTIONS
 
               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
 
@@ -100,7 +95,7 @@ OPTIONS
 
        -L, --list-devices
 
-              List available serial devices.
+              List available serial devices by ID.
 
        -l, --log
 
@@ -144,8 +139,7 @@ OPTIONS
 
        -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.
 
@@ -153,9 +147,10 @@ OPTIONS
 
        -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.
 
@@ -171,6 +166,44 @@ OPTIONS
 
               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.
@@ -180,8 +213,7 @@ OPTIONS
               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
 
@@ -214,12 +246,10 @@ KEYS
 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
 
@@ -237,49 +267,59 @@ CONFIGURATION FILE
 
        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:
@@ -339,8 +379,7 @@ EXAMPLES
 
               $ 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:
 
@@ -377,14 +416,24 @@ EXAMPLES
 
               $ 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)
index 6f11ea41c5d9b2eea3ed91b4c2ae5fcdbe9410da..0291474a0e24b1e378b916934c0aec42083e74c2 100644 (file)
@@ -1,12 +1,12 @@
 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')
@@ -71,5 +71,13 @@ foreach rate : test_baudrates
   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')
diff --git a/src/alert.c b/src/alert.c
new file mode 100644 (file)
index 0000000..4cb0132
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ * 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;
+    }
+}
diff --git a/src/alert.h b/src/alert.h
new file mode 100644 (file)
index 0000000..cb26eff
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * 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);
index 3d87cb690f28d91604e62fcecf34250b3f9b3ca6..ca115e600cbbcba25c7f562f1e0c41bc0105c311 100644 (file)
@@ -30,6 +30,11 @@ _tio()
           -c --color \
           -S --socket \
           -x --hexadecimal \
+          -r --response-wait \
+             --response-timeout \
+             --rs-485 \
+             --rs-485-config \
+             --alert \
           -v --version \
           -h --help"
 
@@ -116,6 +121,26 @@ _tio()
             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
index b8a16492ea2513f5b3c57813a3c8aa383b1914db..864380e04a79d3235a5e12e1acc30cdde6c19836 100644 (file)
@@ -42,6 +42,9 @@
 #include "options.h"
 #include "error.h"
 #include "print.h"
+#include "rs485.h"
+#include "timestamp.h"
+#include "alert.h"
 
 static struct config_t *c;
 
@@ -249,8 +252,42 @@ static int data_handler(void *user, const char *section, const char *name,
                 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;
 }
 
index 4e0142fc8f639beb56d00f7e3bf1f752d2226488..43da8dd728f74b2a9517ce2c5809a11ede67d6f0 100644 (file)
@@ -31,6 +31,7 @@
 #include "options.h"
 #include "print.h"
 #include "error.h"
+#include "timestamp.h"
 
 static char error[2][1000];
 static bool in_session = false;
@@ -54,7 +55,7 @@ void error_printf_(const char *format, ...)
     {
       putchar('\n');
     }
-    ansi_error_printf("[%s] %s", current_time(), line);
+    ansi_error_printf("[%s] %s", timestamp_current_time(), line);
   }
   else
   {
index 7f31645ddb229bd48577ce5cc6e8127fc13b1bb4..02f8a47f9ebb399cc6a32010f9876c0b23978201 100644 (file)
@@ -63,6 +63,12 @@ int main(int argc, char *argv[])
     {
         // Enter non interactive mode
         interactive_mode = false;
+
+        // Mute tio text in response mode
+        if (option.response_wait)
+        {
+            option.mute = true;
+        }
     }
 
     /* Configure output terminal */
index 464f4f3ea9ab8f40cd5cbed03db346f76ee44a02..00777330ce96020ea80bcdfa099bc8e583c5601f 100644 (file)
@@ -14,7 +14,10 @@ tio_sources = [
   'configfile.c',
   'signals.c',
   'socket.c',
-  'setspeed.c'
+  'setspeed.c',
+  'rs485.c',
+  'timestamp.c',
+  'alert.c'
 ]
 
 tio_dep = dependency('inih', required: true,
@@ -31,6 +34,10 @@ if enable_iossiospeed
   tio_c_args += '-DHAVE_IOSSIOSPEED'
 endif
 
+if enable_rs485
+  tio_c_args += '-DHAVE_RS485'
+endif
+
 executable('tio',
   tio_sources,
   c_args: tio_c_args,
index c519c4610bf68b408dd9319c644b7b43708167c1..1983950d1bff29d35abfd684bd60ecd62219ed39 100644 (file)
 #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;
index 23208a653b860a9a061c61e79885b19610370303..6fe5368c2606e9e093290a34312e3e7844d15394 100644 (file)
@@ -27,3 +27,5 @@ char * current_time(void);
 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);
index 49646745359c755c4394b5994bcd04dc9b209314..d21ed87d87beb148a1c655d19b2b5d5bc0d965e6 100644 (file)
@@ -35,6 +35,9 @@
 #include "misc.h"
 #include "print.h"
 #include "tty.h"
+#include "rs485.h"
+#include "timestamp.h"
+#include "alert.h"
 
 enum opt_t
 {
@@ -43,6 +46,10 @@ 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 */
@@ -74,6 +81,14 @@ struct option_t option =
     .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[])
@@ -95,14 +110,19 @@ 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");
@@ -111,63 +131,6 @@ void print_help(char *argv[])
     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;
@@ -187,7 +150,7 @@ void line_pulse_duration_option_parse(const char *arg)
 
         if (token != NULL)
         {
-            char keyname[10];
+            char keyname[11];
             unsigned int value;
             sscanf(token, "%10[^=]=%d", keyname, &value);
 
@@ -222,7 +185,6 @@ void line_pulse_duration_option_parse(const char *arg)
         }
     }
     free(buffer);
-
 }
 
 void options_print()
@@ -237,7 +199,6 @@ 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,
@@ -245,6 +206,7 @@ void options_print()
                                                                             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)
@@ -287,6 +249,11 @@ void options_parse(int argc, char *argv[])
             {"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                     }
@@ -296,7 +263,7 @@ void options_parse(int argc, char *argv[])
         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)
@@ -372,7 +339,6 @@ void options_parse(int argc, char *argv[])
                 break;
 
             case OPT_LOG_FILE:
-                option.log = true;
                 option.log_filename = optarg;
                 break;
 
@@ -422,13 +388,28 @@ void options_parse(int argc, char *argv[])
                 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;
 
index ed8a4fa0fb2194a3474029ca1284f693e5d99e97..22ec236b7b7fc2dfe7cced64bbab6cb5d446d42b 100644 (file)
 
 #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
@@ -67,6 +58,14 @@ 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;
index 359c0785ff04e155bdb8070788af3c02a6d118e8..cf130f0afee1208df5f6a1dea75507d4bf0a6806 100644 (file)
@@ -20,7 +20,9 @@
  */
 
 #include <stdio.h>
+#include <stdlib.h>
 #include <stdbool.h>
+#include <string.h>
 #include "options.h"
 #include "print.h"
 
@@ -50,3 +52,24 @@ void print_init_ansi_formatting()
     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("");
+}
index c212a7c875cd82bdc04cc40a87f0745eebad8e99..e3f61939f32a7ecad9347465373be03f0bbc5bed 100644 (file)
 
 #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[];
@@ -33,45 +35,65 @@ 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
@@ -87,3 +109,4 @@ extern char ansi_format[];
 void print_hex(char c);
 void print_normal(char c);
 void print_init_ansi_formatting(void);
+void tio_printf_array(const char *array);
diff --git a/src/rs485.c b/src/rs485.c
new file mode 100644 (file)
index 0000000..e364b13
--- /dev/null
@@ -0,0 +1,200 @@
+/*
+ * 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
diff --git a/src/rs485.h b/src/rs485.h
new file mode 100644 (file)
index 0000000..b7a4882
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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);
index 02ccbbe5b71c1ae6d112fe05caa87f8880955b73..6829b448625471c9be1ce254e5a23b10b79ea301 100644 (file)
@@ -47,4 +47,5 @@ void signal_handlers_install(void)
 {
     signal(SIGHUP, signal_handler);
     signal(SIGINT, signal_handler);
+    signal(SIGPIPE, SIG_IGN);
 }
index c21904f15dd327cb2b200f7560cf5094d951b7f7..16d962189540a7ce44c343bace3fa4104ecf83dc 100644 (file)
@@ -78,6 +78,44 @@ static void socket_exit(void)
     }
 }
 
+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 = {};
@@ -136,7 +174,7 @@ void socket_configure(void)
         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)
@@ -146,6 +184,14 @@ void socket_configure(void)
             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:
diff --git a/src/timestamp.c b/src/timestamp.c
new file mode 100644 (file)
index 0000000..b8a2198
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+ * 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;
+}
diff --git a/src/timestamp.h b/src/timestamp.h
new file mode 100644 (file)
index 0000000..ee23ce6
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * 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);
index 43cfb9125cb32981fafc13ee22d61ca7a70f7810..4165017b93e0204e9ba4d8fc8bbec51310015158 100644 (file)
--- a/src/tty.c
+++ b/src/tty.c
 #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
 {
@@ -92,12 +99,25 @@ 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;
@@ -445,6 +465,10 @@ void handle_command_sequence(char input_char, char previous_char, char *output_c
                 tio_printf("Configuration:");
                 config_file_print();
                 options_print();
+                if (option.rs485)
+                {
+                    rs485_print_config();
+                }
                 break;
 
             case KEY_E:
@@ -454,16 +478,16 @@ void handle_command_sequence(char input_char, char previous_char, char *output_c
 
             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;
@@ -517,6 +541,10 @@ void handle_command_sequence(char input_char, char previous_char, char *output_c
                 tio_printf("tio v%s", VERSION);
                 break;
 
+            case KEY_Z:
+                tio_printf_array(random_array);
+                break;
+
             default:
                 /* Ignore unknown ctrl-t escaped keys */
                 break;
@@ -925,6 +953,9 @@ void tty_disconnect(void)
         flock(fd, LOCK_UN);
         close(fd);
         connected = false;
+
+        /* Fire alert action */
+        alert_disconnect();
     }
 }
 
@@ -932,6 +963,12 @@ void tty_restore(void)
 {
     tcsetattr(fd, TCSANOW, &tio_old);
 
+    if (option.rs485)
+    {
+        /* Restore original RS-485 mode */
+        rs485_mode_restore(fd);
+    }
+
     if (connected)
     {
         tty_disconnect();
@@ -969,7 +1006,7 @@ void forward_to_tty(int fd, char output_char)
     }
     else
     {
-        if (print_mode == HEX)
+        if (option.hex_mode)
         {
             output_hex(output_char);
         }
@@ -1000,6 +1037,9 @@ int tty_connect(void)
     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);
@@ -1032,6 +1072,9 @@ int tty_connect(void)
     connected = true;
     print_tainted = false;
 
+    /* Fire alert action */
+    alert_connect();
+
     if (option.timestamp)
     {
         next_timestamp = true;
@@ -1041,12 +1084,10 @@ int tty_connect(void)
     if (option.hex_mode)
     {
         print = print_hex;
-        print_mode = HEX;
     }
     else
     {
         print = print_normal;
-        print_mode = NORMAL;
     }
 
     /* Save current port settings */
@@ -1065,6 +1106,12 @@ int tty_connect(void)
     }
 #endif
 
+    /* Manage RS-485 mode */
+    if (option.rs485)
+    {
+        rs485_mode_enable(fd);
+    }
+
     /* Make sure we restore tty settings on exit */
     if (first)
     {
@@ -1095,12 +1142,28 @@ int tty_connect(void)
     {
         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;
@@ -1126,7 +1189,7 @@ int tty_connect(void)
                     /* 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);
@@ -1168,6 +1231,15 @@ int tty_connect(void)
                     {
                         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))
@@ -1182,8 +1254,21 @@ int tty_connect(void)
                 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 */
@@ -1209,7 +1294,7 @@ int tty_connect(void)
                         /* Save previous key */
                         previous_char = input_char;
 
-                        if ((print_mode == HEX) && (forward))
+                        if ((option.hex_mode) && (forward))
                         {
                             if (!is_valid_hex(input_char))
                             {
@@ -1244,6 +1329,11 @@ int tty_connect(void)
             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;
@@ -1267,11 +1357,10 @@ void list_serial_devices(void)
         {
             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);