This commit is contained in:
Peter van Dijk 2023-03-20 19:13:09 +00:00
commit a31bce5175
47 changed files with 8225 additions and 0 deletions

27
.circleci/config.yml Normal file
View file

@ -0,0 +1,27 @@
# Use the latest 2.1 version of CircleCI pipeline process engine.
# See: https://circleci.com/docs/2.0/configuration-reference
version: 2.1
# Define a job to be invoked later in a workflow.
# See: https://circleci.com/docs/2.0/configuration-reference/#jobs
jobs:
build-tio:
# Specify the execution environment. You can specify an image from Dockerhub or use one of our Convenience Images from CircleCI's Developer Hub.
# See: https://circleci.com/docs/2.0/configuration-reference/#docker-machine-macos-windows-executor
docker:
- image: cimg/base:edge
# Add steps to the job
# See: https://circleci.com/docs/2.0/configuration-reference/#steps
steps:
- checkout
- run: sudo apt-get -qq update
- run: sudo apt-get install -y bash-completion git meson libinih-dev
- run: git clone https://github.com/tio/tio.git
- run: cd tio && meson build --prefix $HOME/test/tio && ninja -C build install
# Invoke jobs via workflows
# See: https://circleci.com/docs/2.0/configuration-reference/#workflows
workflows:
build-tio-workflow:
jobs:
- build-tio

1
.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1 @@
custom: ["https://www.paypal.me/lundmar"]

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
/build
/subprojects/libinih
*.swp
.cache

46
AUTHORS Normal file
View file

@ -0,0 +1,46 @@
Maintainer:
Martin Lund <martin.lund@keep-it-simple.com>
Co-maintainer:
Sylvain LAFRASSE <slymacdev@free.fr>
Contributors:
Jesper Larsen <knorr.jesper@gmail.com>
Jeppe Ledet-Pedersen <jlp@gomspace.com>
Jakob Haufe <sur5r@sur5r.net>
Jakub Wilk <jwilk@jwilk.net>
Martin Hundeboll <martin@hundeboll.net>
Nick Østergaard <oe.nick@gmail.com>
Adam Borowski <kilobyte@angband.pl>
Robert Scheck <robert@fedoraproject.org>
Dmitri Goutnik <dg@syrec.org>
Daniel Engberg <daniel.engberg.lists@pyret.net>
Petr Vaněk <pv@excello.cz>
qianfan Zhao <qianfanguijin@163.com>
Henner Zeller <h.zeller@acm.org>
Robey Pointer <robey@afero.io>
Lars Kellogg-Stedman <lars@oddbit.com>
arichi <sergey.korabanov@gmail.com>
George Stark <george-u@yandex.com>
Erik Moqvist <erik.moqvist@gmail.com>
Fabrice Fontaine <fontaine.fabrice@gmail.com>
Alban Bedel <alban.bedel@aerq.com>
Björn Stenberg <bjorn@haxx.se>
Henner Zeller <h.zeller@acm.org>
Henrik Brix Andersen <henrik@brixandersen.dk>
Mariusz Midor <dexlab@o2.pl>
attila-v <attila_v@index.hu>
Yin Fengwei <fengwei.yin@intel.com>
Liam Beguin <liambeguin@gmail.com>
Peter Collingbourne <pcc@google.com>
g0mb4 <gomba007@gmail.com>
ZeroMemoryEx on GitHub
George Joseph <g.devel@wxy78.net>
Robert Snell <rcsnell@ncf.ca>
Rui Chen <rui@chenrui.dev>
Ralph Siemsen <ralphs@netwinder.org>
Victor Oliveira <rhapsodyv@gmail.com>
Attila Veghelyi <aveghelyi@dension.com>
Vyacheslav Patkov <slava@patkov.ru>
Thanks to everyone who has contributed to this project.

15
LICENSE Normal file
View file

@ -0,0 +1,15 @@
Copyright (c) 2014-2022 Martin Lund <martin.lund@keep-it-simple.com>
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 version 2
along with tio, in a file named COPYING. If not, see
<http://www.gnu.org/licenses/>.

1730
NEWS Normal file

File diff suppressed because it is too large Load diff

326
README.md Normal file
View file

@ -0,0 +1,326 @@
# tio - a simple serial device I/O tool
[![](https://img.shields.io/circleci/build/gh/tio/tio?token=da7e7fd0d0ee99b9f986f8877dcdbe28f73d9e06)](https://circleci.com/gh/tio/tio/tree/master)
[![](https://img.shields.io/github/v/release/tio/tio?sort=semver)](https://github.com/tio/tio/releases)
[![](https://img.shields.io/repology/repositories/tio)](https://repology.org/project/tio/versions)
[![](https://img.shields.io/tokei/lines/github/tio/tio)](https://github.com/tio/tio)
## 1. Introduction
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.
<p align="center">
<img src="images/tio-demo.gif">
</p>
### 1.1 Motivation
To make a simpler serial device tool for talking with serial TTY devices with
less focus on classic terminal/modem features and more focus on the needs of
embedded developers and hackers.
tio was originally created to replace
[screen](https://www.gnu.org/software/screen) for connecting to serial devices
when used in combination with [tmux](https://tmux.github.io).
## 2. Features
* Easily connect to serial TTY devices
* Automatic connect and reconnect
* Sensible defaults
* Support for non-standard baud rates
* Support for RS-485 mode
* Support for mark and space parity
* List available serial devices by ID
* Show RX/TX statistics
* Toggle serial lines
* Pulse serial lines with configurable pulse duration
* Local echo support
* Remapping of characters (nl, cr-nl, bs, lowercase to uppercase, etc.)
* Line timestamps
* Support for delayed output per character
* Support for delayed output per line
* Hexadecimal mode
* Log to file
* Autogeneration of log filename
* Configuration file support
* Activate sub-configurations by name or pattern
* 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 on options, serial device names, and sub-configuration names
* Configurable text color
* 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](https://raw.githubusercontent.com/tio/tio/master/man/tio.1.txt).
### 3.1 Command-line
The command-line interface is straightforward as reflected in the output from
'tio --help':
```
Usage: tio [<options>] <tty-device|sub-config>
Connect to TTY device directly or via sub-configuration.
Options:
-b, --baudrate <bps> Baud rate (default: 115200)
-d, --databits 5|6|7|8 Data bits (default: 8)
-f, --flow hard|soft|none Flow control (default: none)
-s, --stopbits 1|2 Stop bits (default: 1)
-p, --parity odd|even|none|mark|space Parity (default: none)
-o, --output-delay <ms> Output character delay (default: 0)
-O, --output-line-delay <ms> Output line delay (default: 0)
--line-pulse-duration <duration> Set line pulse duration
-n, --no-autoconnect Disable automatic connect
-e, --local-echo Enable local echo
-t, --timestamp Enable line timestamp
--timestamp-format <format> Set timestamp format (default: 24hour)
-L, --list-devices List available serial devices
-l, --log Enable log to file
--log-file <filename> Set log filename
--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 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
Options and sub-configurations may be set via configuration file.
See the man page for more details.
```
By default tio automatically connects to the provided TTY 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 is unplugged), 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 connection is lost.
tio features full bash autocompletion.
#### 3.1.1 Examples
Typical use is without options:
```
$ tio /dev/ttyUSB0
```
Which corresponds to the commonly used default options:
```
$ tio -b 115200 -d 8 -f none -s 1 -p none /dev/ttyUSB0
```
It is recommended to connect serial TTY devices by ID:
```
$ 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.
List available serial devices by ID:
```
$ tio --list-devices
```
Note: One can also use tio shell completion on /dev which will automatically
list all available serial TTY devices.
Log to file with autogenerated filename:
```
$ tio --log /dev/ttyUSB0
```
Enable ISO8601 timestamps per line:
```
$ tio --timestamp --timestamp-format iso8601 /dev/ttyUSB0
```
Redirect I/O to IPv4 network socket on port 4242:
```
$ tio --socket inet:4242 /dev/ttyUSB0
```
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
ctrl-t ? to list the available key commands.
```
[20:19:12.040] Key commands:
[20:19:12.040] ctrl-t ? List available key commands
[20:19:12.040] ctrl-t b Send break
[20:19:12.040] ctrl-t c Show configuration
[20:19:12.040] ctrl-t e Toggle local echo mode
[20:19:12.040] ctrl-t f Toggle log to file
[20:19:12.040] ctrl-t g Toggle serial port line
[20:19:12.040] ctrl-t h Toggle hexadecimal mode
[20:19:12.040] ctrl-t l Clear screen
[20:19:12.040] ctrl-t L Show line states
[20:19:12.040] ctrl-t p Pulse serial port line
[20:19:12.040] ctrl-t q Quit
[20:19:12.041] ctrl-t s Show statistics
[20:19:12.041] ctrl-t t Toggle line timestamp mode
[20:19:12.041] ctrl-t U Toggle conversion to uppercase
[20:19:12.041] ctrl-t v Show version
[20:19:12.041] ctrl-t ctrl-t Send ctrl-t character
```
If needed, the prefix key (ctrl-t) can be remapped via configuration file.
### 3.3 Configuration file
Options can be set via the configuration file first found in any of the
following locations in the order listed:
- $XDG_CONFIG_HOME/tio/config
- $HOME/.config/tio/config
- $HOME/.tioconfig
The configuration file supports sub-configurations using named sections which can
be activated via the command-line by name or pattern. A sub-configuration
specifies which TTY device to connect to and other options.
Example configuration file:
```
# Defaults
baudrate = 9600
databits = 8
parity = none
stopbits = 1
color = 10
[rpi3]
device = /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
baudrate = 115200
no-autoconnect = enable
log = enable
log-file = rpi3.log
line-pulse-duration = DTR=200,RTS=150
color = 12
[usb devices]
pattern = usb([0-9]*)
device = /dev/ttyUSB%s
color = 13
```
To use a specific sub-configuration by name simply start tio like so:
```
$ tio rpi3
```
Or by pattern match:
```
$ tio usb12
```
Another more elaborate configuration file example is available [here](example/config).
## 4. Installation
### 4.1 Installation using package manager (Linux)
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 its package maintainers team.
### 4.2 Installation using snap (Linux)
Install latest stable version:
```
$ snap install tio
```
### 4.3 Installation using brew (MacOS, Linux)
If you have [brew](http://brew.sh) installed:
```
$ brew install tio
```
### 4.4 Installation using MSYS2 (Windows)
If you have [MSYS2](https://www.msys2.org) installed:
```
$ pacman -S tio
```
### 4.5 Installation from source
The latest source releases can be found [here](https://github.com/tio/tio/releases).
Install steps:
```
$ meson build
$ meson compile -C build
$ meson install -C build
```
See meson\_options.txt for tio specific build options.
Note: The meson install steps may differ depending on your specific system.
## 5. Contributing
tio is open source. If you want to help out with the project please feel free
to join in.
All contributions (bug reports, code, doc, ideas, etc.) are welcome.
Please use the github issue tracker and pull request features.
Also, if you find this free open source software useful please feel free to
consider making a donation of your choice:
[![Donate](images/paypal.png)](https://www.paypal.me/lundmar)
## 6. Support
Submit bug reports via GitHub: https://github.com/tio/tio/issues
## 7. Website
Visit [tio.github.io](https://tio.github.io)
## 8. License
tio is GPLv2+. See LICENSE file for more details.
## 9. Authors
Created by Martin Lund \<martin.lund@keep-it-simple.com>
See the AUTHORS file for full list of contributors.

60
TODO Normal file
View file

@ -0,0 +1,60 @@
* Allow tio to connect to socket
After some more consideration I think it makes sense to support connecting to a
socket as that will make tio be able to both serve a serial port via a socket
and connect to it - it will be an end to end solution. In short we will be able
to do the following:
Host serial port on socket (existing feature):
$ tio --socket unix:/tmp/tio-socket-0 /dev/ttyUSB0
Connect to same socket (new feature):
$ tio unix:/tmp/tio-socket-0
Besides a bit of refactoring the following required changes spring to mind:
* Socket mode and type of socket should be activated via device name prefix. For example:
* UNIX socket: tio unix:<filename>
* TCPv4 socket: tio inet:<ip>:<port>
* TCPv6 socket: tio inet6:<ip>:<port>
* If no port number defined default to 3333
* Mapping flags INLCR, IGNCR, ICRNL needs implementation for socket mode
* Error messages should just say "device" instead of "tty device" etc.
* Remove other tty'isms (tty_write() should be device_write() etc.)
* In session key commands that do not work in socket mode should either not be listed or print an error messages if used.
* All non-tty features should continue work (auto-connect etc.)
* Shell completion script update
* Man page update
* Split I/O feature
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
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
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.

64
example/config Normal file
View file

@ -0,0 +1,64 @@
###############################
# tio - https://tio.github.io #
###############################
# Example tio configuration file
#
# Place file in any of the following locations:
# $XDG_CONFIG_HOME/tio/config
# $HOME/.config/tio/config
# $HOME/.tioconfig
# Defaults
baudrate = 115200
databits = 8
flow = none
stopbits = 1
parity = none
prefix-ctrl-key = t
output-delay = 0
output-line-delay = 0
no-autoconnect = disable
hexadecimal = disable
timestamp = disable
log = disable
log-strip = disable
local-echo = disable
color = bold
rs-485 = disable
response-wait = disable
alert = none
# Sub-configuraions
[rpi3]
baudrate = 115200
device = /dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A6009HU3-if00-port0
socket = unix:/tmp/tio-socket-0
color = 9
[am64-evm]
baudrate = 115200
device = /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]
baudrate = 9600
device = /dev/serial/by-id/usb-TinCanTools_Flyswatter2_FS20000-if00-port0
log = enable
log-file = tincan.log
log-strip = enable
color = 11
[usb]
pattern = usb([0-9]*)
device = /dev/ttyUSB%s
color = 12
[rs-485-device]
device = /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

BIN
images/paypal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
images/tio-demo.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 MiB

15
man/meson.build Normal file
View file

@ -0,0 +1,15 @@
mandir = join_paths(get_option('prefix'), get_option('mandir'))
man1dir = join_paths(mandir, 'man1')
conf = configuration_data()
conf.set('version', meson.project_version())
conf.set('version_date', version_date)
manpage = configure_file(
input: files('tio.1.in'),
output: 'tio.1',
configuration: conf)
install_man(
manpage,
install_dir: man1dir)

573
man/tio.1.in Normal file
View file

@ -0,0 +1,573 @@
.TH "tio" "1" "@version_date@" "tio @version@" "User Commands"
.SH "NAME"
tio \- a simple serial device I/O tool
.SH "SYNOPSIS"
.PP
.B tio
.RI "[" <options> "] " "<tty-device|sub-config>"
.SH "DESCRIPTION"
.PP
\fBtio\fR 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.
.SH "OPTIONS"
.TP
.BR \-b ", " "\-\-baudrate " \fI<bps>
Set baud rate [bps] (default: 115200).
.TP
.BR \-d ", " "\-\-databits 5" | 6 | 7 | 8
Set data bits (default: 8).
.TP
.BR \-f ", " "\-\-flow hard" | soft | none
Set flow control (default: none).
.TP
.BR \-s ", " "\-\-stopbits 1" | 2
Set stop bits (default: 1).
.TP
.BR \-p ", " "\-\-parity odd" | even | none | mark | space
Set parity (default: none).
Note: With \fBmark\fR parity the parity bit is always 0. With \fBspace\fR
parity the parity bit is always 1. Not all platforms support \fBmark\fR and
\fBspace\fR parity.
.TP
.BR \-o ", " "\-\-output\-delay " \fI<ms>
Set output delay [ms] inserted between each sent character (default: 0).
.TP
.BR \-O ", " "\-\-output\-line\-delay " \fI<ms>
Set output delay [ms] inserted between each sent line (default: 0).
.TP
.BR " \-\-line\-pulse\-duration " \fI<duration>
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:
.RS
.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.
The default pulse duration for each line is 100 ms.
.RE
.TP
.BR \-n ", " \-\-no\-autoconnect
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.
However, if the \fB\-\-no\-autoconnect\fR option is provided, tio will exit if
the device is not present or an established connection is lost.
.TP
.BR \-e ", " "\-\-local\-echo
Enable local echo.
.TP
.BR \-t ", " \-\-timestamp
Enable line timestamp.
.TP
.BR " \-\-timestamp-format \fI<format>
Set timestamp format to any of the following timestamp formats:
.RS
.TP 16n
.IP "\fB24hour"
24-hour format ("hh:mm:ss.sss")
.IP "\fB24hour-start"
24-hour format relative to start time
.IP "\fB24hour-delta"
24-hour format relative to previous timestamp
.IP "\fBiso8601"
ISO8601 format ("YYYY-MM-DDThh:mm:ss.sss")
.PP
Default format is \fB24hour\fR
.RE
.TP
.BR \-L ", " \-\-list\-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.
.TP
.BR " \-\-log-file \fI<filename>
Set log filename.
.TP
.BR " \-\-log-strip
Strip control characters and escape sequences from log.
.TP
.BR \-m ", " "\-\-map " \fI<flags>
Map (replace, translate) characters on input or output. The following mapping
flags are supported:
.RS
.TP 12n
.IP "\fBICRNL"
Map CR to NL on input (unless IGNCR is set)
.IP "\fBIGNCR"
Ignore CR on input
.IP "\fBINLCR"
Map NL to CR on input
.IP "\fBINLCRNL"
Map NL to CR-NL on input
.IP "\fBOCRNL"
Map CR to NL on output
.IP "\fBODELBS"
Map DEL to BS on output
.IP "\fBONLCRNL"
Map NL to CR-NL on output
.IP "\fBOLTU"
Map lowercase characters to uppercase on output
.IP "\fBMSB2LSB"
Map MSB bit order to LSB on output
.P
If defining more than one flag, the flags must be comma separated.
.RE
.TP
.BR \-x ", " \-\-hexadecimal
Enable hexadecimal mode.
.TP
.BR \-c ", " "\-\-color " \fI0..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.
Use "list" to print a list of available ANSI color codes.
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.
Sockets remain open while the serial port is disconnected, and writes will block.
Various socket types are supported using the following prefixes in the socket field:
.RS
.TP 20n
.IP "\fBunix:<filename>"
Unix Domain Socket (file)
.IP "\fBinet:<port>"
Internet Socket (network)
.IP "\fBinet6:<port>"
Internet IPv6 Socket (network)
.P
If port is 0 or no port is provided default port 3333 is used.
.P
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
Display program version.
.TP
.BR \-h ", " \-\-help
Display help.
.SH "KEYS"
.PP
.TP 16n
In session, the following key sequences, a prefix key (default: ctrl-t) followed by a command key, are intercepted as tio commands:
.IP "\fBctrl-t ?"
List available key commands
.IP "\fBctrl-t b"
Send serial break (triggers SysRq on Linux, etc.)
.IP "\fBctrl-t c"
Show configuration (baudrate, databits, etc.)
.IP "\fBctrl-t e"
Toggle local echo mode
.IP "\fBctrl-t f"
Toggle log to file
.IP "\fBctrl-t F"
Flush data I/O buffers (discard data written but not transmitted and data received but not read)
.IP "\fBctrl-t g"
Toggle serial port line
.IP "\fBctrl-t h"
Toggle hexadecimal mode
.IP "\fBctrl-t l"
Clear screen
.IP "\fBctrl-t L"
Show line states (DTR, RTS, CTS, DSR, DCD, RI)
.IP "\fBctrl-t p"
Pulse serial port line
.IP "\fBctrl-t q"
Quit
.IP "\fBctrl-t s"
Show TX/RX statistics
.IP "\fBctrl-t t"
Toggle line timestamp mode
.IP "\fBctrl-t U"
Toggle conversion to uppercase on output
.IP "\fBctrl-t v"
Show version
.IP "\fBctrl-t ctrl-t"
Send ctrl-t character
.SH "HEXADECIMAL MODE"
.PP
In hexadecimal mode each incoming byte is printed out as a hexadecimal value.
.PP
Bytes can be sent in this mode by typing the \fBtwo-character hexadecimal\fR
representation of the value, e.g.: to send \fI0xA\fR you must type \fI0a\fR or
\fI0A\fR.
.SH "CONFIGURATION FILE"
.PP
Options can be set via configuration file using the INI format. \fBtio\fR uses
the configuration file first found in the following locations in the order
listed:
.PP
.I $XDG_CONFIG_HOME/tio/config
.PP
.I $HOME/.config/tio/config
.PP
.I $HOME/.tioconfig
.PP
Labels can be used to group settings into named sub-configurations which can be
activated from the command-line when starting tio.
.PP
\fBtio\fR will try to match the user input to a sub-configuration by name or by
pattern to get the TTY device and other options.
.PP
Options without any label change the default options.
.PP
Any options set via command-line will override options set in the configuration file.
.PP
The following configuration file options are available:
.TP 25n
.IP "\fBpattern"
Pattern matching user input. This pattern can be an extended regular expression with a single group.
.IP "\fBdevice"
TTY device to open. If it contains a "%s" it is substituted with the first group match.
.IP "\fBbaudrate"
Set baud rate
.IP "\fBdatabits"
Set data bits
.IP "\fBflow"
Set flow control
.IP "\fBstopbits"
Set stop bits
.IP "\fBparity"
Set parity
.IP "\fBoutput-delay"
Set output character delay
.IP "\fBoutput-line-delay"
Set output line delay
.IP "\fBline-pulse-duration"
Set line pulse duration
.IP "\fBno-autoconnect"
Disable automatic connect
.IP "\fBlog"
Enable log to file
.IP "\fBlog-file"
Set log filename
.IP "\fBlog-strip"
Enable strip of control and escape sequences from log
.IP "\fBlocal-echo"
Enable local echo
.IP "\fBtimestamp"
Enable line timestamp
.IP "\fBtimestamp-format"
Set timestamp format
.IP "\fBmap"
Map characters on input or output
.IP "\fBcolor"
Colorize tio text using ANSI color code ranging from 0 to 255
.IP "\fBhexadecimal"
Enable hexadecimal mode
.IP "\fBsocket"
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"
.TP
To change the default configuration simply set options like so:
.RS
.nf
.eo
# Defaults
baudrate = 9600
databits = 8
parity = none
stopbits = 1
color = 10
line-pulse-duration = DTR=200,RTS=400
.ec
.fi
.RE
.TP
Named sub-configurations can be added via labels:
.RS
.nf
.eo
[rpi3]
device = /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
baudrate = 115200
color = 11
.ec
.fi
.RE
.TP
Activate the sub-configuration by name:
$ tio rpi3
.TP
Which is equivalent to:
$ tio -b 115200 -c 11 /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
.TP
A sub-configuration can also be activated by its pattern which supports regular expressions:
.RS
.nf
.eo
[usb device]
pattern = usb([0-9]*)
device = /dev/ttyUSB%s
baudrate = 115200
.ec
.fi
.RE
.TP
Activate the sub-configuration by pattern match:
$ tio usb12
.TP
Which is equivalent to:
$ tio -b 115200 /dev/ttyUSB12
.TP
It is also possible to combine use of sub-configuration and command-line options. For example:
$ tio -l -t usb12
.SH "EXAMPLES"
.TP
Typical use is without options:
$ tio /dev/ttyUSB0
.TP
Which corresponds to the commonly used default options:
$ tio \-b 115200 \-d 8 \-f none \-s 1 \-p none /dev/ttyUSB0
.TP
It is recommended to connect serial TTY devices by ID:
$ tio /dev/serial/by\-id/usb\-FTDI_TTL232R-3V3_FTGQVXBL\-if00\-port0
.PP
Using serial devices by ID ensures that tio automatically reconnects to the
correct serial device if it is disconnected and then reconnected.
.TP
Redirect serial device I/O to Unix file socket for scripting:
$ tio -S unix:/tmp/tmux-socket0 /dev/ttyUSB0
.TP
Then, to issue a command via the file socket simply do:
$ echo "ls -la" | nc -UN /tmp/tmux-socket0 > /dev/null
.TP
Or use the expect command to script an interaction:
.RS
.nf
.eo
#!/usr/bin/expect -f
set timeout -1
log_user 0
spawn nc -UN /tmp/tio-socket0
set uart $spawn_id
send -i $uart "date\n"
expect -i $uart "prompt> "
send -i $uart "ls -la\n"
expect -i $uart "prompt> "
.ec
.fi
.RE
.TP
Redirect device I/O to network file socket for remote TTY sharing:
$ tio --socket inet:4444 /dev/ttyUSB0
.TP
Then, use netcat to connect to the shared TTY session over network (assuming tio is hosted on IP 10.0.0.42):
$ nc -N 10.0.0.42 4444
.TP
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
.SH "AUTHOR"
.PP
Created by Martin Lund <martin.lund@keep\-it\-simple.com>.

447
man/tio.1.txt Normal file
View file

@ -0,0 +1,447 @@
tio(1) User Commands tio(1)
NAME
tio - a simple serial device I/O tool
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 connect to serial TTY devices for basic I/O operations.
OPTIONS
-b, --baudrate <bps>
Set baud rate [bps] (default: 115200).
-d, --databits 5|6|7|8
Set data bits (default: 8).
-f, --flow hard|soft|none
Set flow control (default: none).
-s, --stopbits 1|2
Set stop bits (default: 1).
-p, --parity odd|even|none|mark|space
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.
-o, --output-delay <ms>
Set output delay [ms] inserted between each sent character (default: 0).
-O, --output-line-delay <ms>
Set output delay [ms] inserted between each sent line (default: 0).
--line-pulse-duration <duration>
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
RTS Request To Send
CTS Clear To Send
DSR Data Set Ready
DCD Data Carrier Detect
RI Ring Indicator
If defining more than one key value pair, the pairs must be comma separated.
The default pulse duration for each line is 100 ms.
-n, --no-autoconnect
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.
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
Enable local echo.
-t, --timestamp
Enable line timestamp.
--timestamp-format <format>
Set timestamp format to any of the following timestamp formats:
24hour 24-hour format ("hh:mm:ss.sss")
24hour-start 24-hour format relative to start time
24hour-delta 24-hour format relative to previous timestamp
iso8601 ISO8601 format ("YYYY-MM-DDThh:mm:ss.sss")
Default format is 24hour
-L, --list-devices
List available serial devices by ID.
-l, --log
Enable log to file.
If no filename is provided the filename will be automatically generated.
--log-file <filename>
Set log filename.
--log-strip
Strip control characters and escape sequences from log.
-m, --map <flags>
Map (replace, translate) characters on input or output. The following mapping flags are supported:
ICRNL Map CR to NL on input (unless IGNCR is set)
IGNCR Ignore CR on input
INLCR Map NL to CR on input
INLCRNL Map NL to CR-NL on input
OCRNL Map CR to NL on output
ODELBS Map DEL to BS on output
ONLCRNL Map NL to CR-NL on output
OLTU Map lowercase characters to uppercase on output
MSB2LSB Map MSB bit order to LSB on output
If defining more than one flag, the flags must be comma separated.
-x, --hexadecimal
Enable hexadecimal mode.
-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.
Use "list" to print a list of available ANSI color codes.
Default value is "bold".
-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 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.
Various socket types are supported using the following prefixes in the socket field:
unix:<filename> Unix Domain Socket (file)
inet:<port> Internet Socket (network)
inet6:<port> Internet IPv6 Socket (network)
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.
-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.
-h, --help
Display help.
KEYS
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
ctrl-t b Send serial break (triggers SysRq on Linux, etc.)
ctrl-t c Show configuration (baudrate, databits, etc.)
ctrl-t e Toggle local echo mode
ctrl-t f Toggle log to file
ctrl-t F Flush data I/O buffers (discard data written but not transmitted and data received but not read)
ctrl-t g Toggle serial port line
ctrl-t h Toggle hexadecimal mode
ctrl-t l Clear screen
ctrl-t L Show line states (DTR, RTS, CTS, DSR, DCD, RI)
ctrl-t p Pulse serial port line
ctrl-t q Quit
ctrl-t s Show TX/RX statistics
ctrl-t t Toggle line timestamp mode
ctrl-t U Toggle conversion to uppercase on output
ctrl-t v Show version
ctrl-t ctrl-t Send ctrl-t character
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.
CONFIGURATION FILE
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/config
$HOME/.config/tio/config
$HOME/.tioconfig
Labels can be used to group settings into named sub-configurations which can be activated from the command-line when starting tio.
tio will try to match the user input to a sub-configuration by name or by pattern to get the TTY device and other options.
Options without any label change the default options.
Any options set via command-line will override options set in the 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.
device 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
flow Set flow control
stopbits Set stop bits
parity Set parity
output-delay Set output character delay
output-line-delay Set output line delay
line-pulse-duration Set line pulse duration
no-autoconnect Disable automatic connect
log Enable log to file
log-file Set log filename
log-strip Enable strip of control and escape sequences from log
local-echo Enable local echo
timestamp Enable line timestamp
timestamp-format Set timestamp format
map Map characters on input or output
color Colorize tio text using ANSI color code ranging from 0 to 255
hexadecimal Enable hexadecimal mode
socket Set socket to redirect I/O to
prefix-ctrl-key Set prefix ctrl key (a..z, default: t)
response-wait Enable wait for line response
response-timeout Set line response timeout
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:
# Defaults
baudrate = 9600
databits = 8
parity = none
stopbits = 1
color = 10
line-pulse-duration = DTR=200,RTS=400
Named sub-configurations can be added via labels:
[rpi3]
device = /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
baudrate = 115200
color = 11
Activate the sub-configuration by name:
$ tio rpi3
Which is equivalent to:
$ tio -b 115200 -c 11 /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
A sub-configuration can also be activated by its pattern which supports regular expressions:
[usb device]
pattern = usb([0-9]*)
device = /dev/ttyUSB%s
baudrate = 115200
Activate the sub-configuration by pattern match:
$ tio usb12
Which is equivalent to:
$ tio -b 115200 /dev/ttyUSB12
It is also possible to combine use of sub-configuration and command-line options. For example:
$ tio -l -t usb12
EXAMPLES
Typical use is without options:
$ tio /dev/ttyUSB0
Which corresponds to the commonly used default options:
$ tio -b 115200 -d 8 -f none -s 1 -p none /dev/ttyUSB0
It is recommended to connect serial TTY devices by ID:
$ 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.
Redirect serial device I/O to Unix file socket for scripting:
$ tio -S unix:/tmp/tmux-socket0 /dev/ttyUSB0
Then, to issue a command via the file socket simply do:
$ echo "ls -la" | nc -UN /tmp/tmux-socket0 > /dev/null
Or use the expect command to script an interaction:
#!/usr/bin/expect -f
set timeout -1
log_user 0
spawn nc -UN /tmp/tio-socket0
set uart $spawn_id
send -i $uart "date\n"
expect -i $uart "prompt> "
send -i $uart "ls -la\n"
expect -i $uart "prompt> "
Redirect device I/O to network file socket for remote TTY sharing:
$ tio --socket inet:4444 /dev/ttyUSB0
Then, use netcat to connect to the shared TTY session over network (assuming tio is hosted on IP 10.0.0.42):
$ 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
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 2.5 2022-11-02 tio(1)

83
meson.build Normal file
View file

@ -0,0 +1,83 @@
project('tio', 'c',
version : '2.5',
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-12-17'
# Test for dynamic baudrate configuration interface
compiler = meson.get_compiler('c')
enable_setspeed2 = false
enable_iossiospeed = false
if host_machine.system() != 'darwin'
if compiler.check_header('asm-generic/ioctls.h')
enable_setspeed2 = compiler.has_header_symbol('asm-generic/ioctls.h', 'TCGETS2')
endif
else
if compiler.check_header('IOKit/serial/ioss.h')
enable_iossiospeed = compiler.has_header_symbol('IOKit/serial/ioss.h', 'IOSSIOSPEED')
endif
endif
# Test for supported baudrates
test_baudrates = [
0,
50,
75,
110,
134,
150,
200,
300,
600,
1200,
1800,
2400,
4800,
7200,
9600,
14400,
19200,
28800,
38400,
57600,
76800,
115200,
230400,
460800,
500000,
576000,
921600,
1000000,
1152000,
1500000,
2000000,
2500000,
3000000,
3500000,
4000000 ]
baudrates = ''
baudrate_cases = ''
foreach rate : test_baudrates
baudrate = rate.to_string()
value = compiler.get_define('B' + baudrate, prefix: '#include <termios.h>')
if value != ''
baudrates = baudrates + baudrate + ' '
baudrate_cases = baudrate_cases + ' case ' + baudrate + ': baudrate = B' + baudrate + '; break;'
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')

3
meson_options.txt Normal file
View file

@ -0,0 +1,3 @@
option('bashcompletiondir',
type : 'string',
description : 'Directory for bash completion scripts ["no" disables]')

110
src/alert.c Normal file
View file

@ -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;
}
}

34
src/alert.h Normal file
View file

@ -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);

View file

@ -0,0 +1,18 @@
conf = configuration_data()
conf.set('baudrates', baudrates)
completion_file = configure_file( input: files('tio.in'),
output: 'tio',
configuration: conf )
bashcompletiondir = get_option('bashcompletiondir')
if bashcompletiondir == ''
bash_completion_dep = dependency('bash-completion', required: false)
if bash_completion_dep.found()
bashcompletiondir = join_paths(get_option('datadir'), 'bash-completion', 'completions')
endif
endif
if (bashcompletiondir != 'no') and (bashcompletiondir != '')
install_data(completion_file, install_dir: bashcompletiondir)
endif

179
src/bash-completion/tio.in Normal file
View file

@ -0,0 +1,179 @@
#
# Bash completion script for tio.
#
_tio()
{
local cur prev opts base ttys
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
# The options we'll complete.
opts="-b --baudrate \
-d --databits \
-f --flow \
-s --stopbits \
-p --parity \
-o --output-delay \
-o --output-line-delay \
--line-pulse-duration \
-n --no-autoconnect \
-e --local-echo \
-l --log \
--log-file \
--log-strip \
-m --map \
-t --timestamp \
--timestamp-format \
-L --list-devices \
-c --color \
-S --socket \
-x --hexadecimal \
-r --response-wait \
--response-timeout \
--rs-485 \
--rs-485-config \
--alert \
--mute \
-v --version \
-h --help"
# Complete the arguments to the options.
case "${prev}" in
-b | --baudrate)
local baudrates="@baudrates@"
COMPREPLY=( $(compgen -W "$baudrates" -- ${cur}) )
return 0
;;
-d | --databits)
COMPREPLY=( $(compgen -W "5 6 7 8" -- ${cur}) )
return 0
;;
-f | --flow)
COMPREPLY=( $(compgen -W "hard soft none" -- ${cur}) )
return 0
;;
-s | --stopbits)
COMPREPLY=( $(compgen -W "1 2" -- ${cur}) )
return 0
;;
-p | --parity)
COMPREPLY=( $(compgen -W "even odd none" -- ${cur}) )
return 0
;;
-o | --output-delay)
COMPREPLY=( $(compgen -W "1 10 100" -- ${cur}) )
return 0
;;
-O | --output-line-delay)
COMPREPLY=( $(compgen -W "1 10 100" -- ${cur}) )
return 0
;;
--line-pulse-duration)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-n | --no-autoconnect)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-e | --local-echo)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-l | --log)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
--log-file)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
--log-strip)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-m | --map)
COMPREPLY=( $(compgen -W "ICRNL IGNCR INLCR INLCRNL OCRNL ODELBS ONLCRNL MSB2LSB" -- ${cur}) )
return 0
;;
-t | --timestamp)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
--timestamp-format)
COMPREPLY=( $(compgen -W "24hour 24hour-start 24hour-delta iso8601" -- ${cur}) )
return 0
;;
-L | --list-devices)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-c | --color)
COMPREPLY=( $(compgen -W "$(seq 0 255) none list" -- ${cur}) )
return 0
;;
-S | --socket)
COMPREPLY=( $(compgen -W "unix: inet: inet6:" -- ${cur}) )
return 0
;;
-x | --hexadecimal)
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
;;
--mute)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-v | --version)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-h | --help)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
*)
;;
esac
case "${cur}" in
-*)
COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
return 0
;;
esac
sub_configs="`tio --complete-sub-configs`"
if [ -d /dev/serial/by-id ]; then
ttys=$(printf '%s\n' /dev/tty* /dev/serial/by-id/*)
else
ttys=$(printf '%s\n' /dev/tty*)
fi
COMPREPLY=( $(compgen -W "${ttys} ${sub_configs}" -- ${cur}) )
return 0
}
# Bind completion to tio command
complete -o default -F _tio tio

493
src/configfile.c Normal file
View file

@ -0,0 +1,493 @@
/*
* tio - a simple serial terminal I/O tool
*
* Copyright (c) 2020-2022 Liam Beguin
* 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.
*/
#define _GNU_SOURCE
#include "config.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <getopt.h>
#include <termios.h>
#include <limits.h>
#include <unistd.h>
#include <regex.h>
#include <ini.h>
#include "options.h"
#include "configfile.h"
#include "misc.h"
#include "options.h"
#include "error.h"
#include "print.h"
#include "rs485.h"
#include "timestamp.h"
#include "alert.h"
struct config_t
{
const char *user;
char *path;
char *section_name;
char *match;
char *tty;
char *flow;
char *parity;
char *log_filename;
char *socket;
char *map;
};
static struct config_t c;
static int get_match(const char *input, const char *pattern, char **match)
{
int ret;
int len = 0;
regex_t re;
regmatch_t m[2];
char err[128];
/* compile a regex with the pattern */
ret = regcomp(&re, pattern, REG_EXTENDED);
if (ret)
{
regerror(ret, &re, err, sizeof(err));
tio_error_printf("Regex failure: %s", err);
return ret;
}
/* try to match on input */
ret = regexec(&re, input, 2, m, 0);
if (!ret)
{
len = m[1].rm_eo - m[1].rm_so;
}
regfree(&re);
if (len)
{
asprintf(match, "%s", &input[m[1].rm_so]);
}
return len;
}
static bool read_boolean(const char *value, const char *name)
{
const char *true_values[] = { "true", "enable", "on", "yes", "1", NULL };
const char *false_values[] = { "false", "disable", "off", "no", "0", NULL };
for (int i = 0; true_values[i] != NULL; i++)
if (strcmp(value, true_values[i]) == 0)
return true;
for (int i = 0; false_values[i] != NULL; i++)
if (strcmp(value, false_values[i]) == 0)
return false;
tio_error_printf("Invalid value '%s' for option '%s' in configuration file",
value, name);
exit(EXIT_FAILURE);
}
static long read_integer(const char *value, const char *name, long min_value, long max_value)
{
errno = 0;
char *endptr;
long result = strtol(value, &endptr, 10);
if (errno || endptr == value || *endptr != '\0' || result < min_value || result > max_value)
{
tio_error_printf("Invalid value '%s' for option '%s' in configuration file",
value, name);
exit(EXIT_FAILURE);
}
return result;
}
/**
* data_handler() - walk config file to load parameters matching user input
*
* INIH handler used to get all parameters from a given section
*/
static int data_handler(void *user, const char *section, const char *name,
const char *value)
{
UNUSED(user);
// If section matches current section being parsed
if (!strcmp(section, c.section_name))
{
// Set configuration parameter if found
if (!strcmp(name, "device") || !strcmp(name, "tty"))
{
asprintf(&c.tty, value, c.match);
option.tty_device = c.tty;
}
else if (!strcmp(name, "baudrate"))
{
option.baudrate = read_integer(value, name, 0, LONG_MAX);
}
else if (!strcmp(name, "databits"))
{
option.databits = read_integer(value, name, 5, 8);
}
else if (!strcmp(name, "flow"))
{
asprintf(&c.flow, "%s", value);
option.flow = c.flow;
}
else if (!strcmp(name, "stopbits"))
{
option.stopbits = read_integer(value, name, 1, 2);
}
else if (!strcmp(name, "parity"))
{
asprintf(&c.parity, "%s", value);
option.parity = c.parity;
}
else if (!strcmp(name, "output-delay"))
{
option.output_delay = read_integer(value, name, 0, LONG_MAX);
}
else if (!strcmp(name, "output-line-delay"))
{
option.output_line_delay = read_integer(value, name, 0, LONG_MAX);
}
else if (!strcmp(name, "line-pulse-duration"))
{
line_pulse_duration_option_parse(value);
}
else if (!strcmp(name, "no-autoconnect"))
{
option.no_autoconnect = read_boolean(value, name);
}
else if (!strcmp(name, "log"))
{
option.log = read_boolean(value, name);
}
else if (!strcmp(name, "log-file"))
{
asprintf(&c.log_filename, "%s", value);
option.log_filename = c.log_filename;
}
else if (!strcmp(name, "log-strip"))
{
option.log_strip = read_boolean(value, name);
}
else if (!strcmp(name, "local-echo"))
{
option.local_echo = read_boolean(value, name);
}
else if (!strcmp(name, "hexadecimal"))
{
option.hex_mode = read_boolean(value, name);
}
else if (!strcmp(name, "timestamp"))
{
option.timestamp = read_boolean(value, name) ?
TIMESTAMP_24HOUR : TIMESTAMP_NONE;
}
else if (!strcmp(name, "timestamp-format"))
{
option.timestamp = timestamp_option_parse(value);
}
else if (!strcmp(name, "map"))
{
asprintf(&c.map, "%s", value);
option.map = c.map;
}
else if (!strcmp(name, "color"))
{
if (!strcmp(value, "list"))
{
// Ignore
return 0;
}
else if (!strcmp(value, "none"))
{
option.color = -1; // No color
return 0;
}
else if (!strcmp(value, "bold"))
{
option.color = 256; // Bold
return 0;
}
option.color = atoi(value);
if ((option.color < 0) || (option.color > 255))
{
option.color = -1; // No color
}
}
else if (!strcmp(name, "socket"))
{
asprintf(&c.socket, "%s", value);
option.socket = c.socket;
}
else if (!strcmp(name, "prefix-ctrl-key"))
{
if (ctrl_key_code(value[0]) > 0)
{
option.prefix_code = ctrl_key_code(value[0]);
option.prefix_key = value[0];
}
}
else if (!strcmp(name, "response-wait"))
{
option.response_wait = read_boolean(value, name);
}
else if (!strcmp(name, "response-timeout"))
{
option.response_timeout = read_integer(value, name, 0, LONG_MAX);
}
else if (!strcmp(name, "rs-485"))
{
option.rs485 = read_boolean(value, name);
}
else if (!strcmp(name, "rs-485-config"))
{
rs485_parse_config(value);
}
else if (!strcmp(name, "alert"))
{
option.alert = alert_option_parse(value);
}
else if (!strcmp(name, "mute"))
{
option.mute = read_boolean(value, name);
}
else
{
tio_warning_printf("Unknown option '%s' in configuration file, ignored", name);
}
}
return 0;
}
/**
* section_pattern_search_handler() - walk config file to find section matching user input
*
* INIH handler used to resolve the section matching the user's input.
* This will look for the pattern element of each section and try to match it
* with the user input.
*/
static int section_pattern_search_handler(void *user, const char *section, const char *varname,
const char *varval)
{
UNUSED(user);
if (strcmp(varname, "pattern"))
return 0;
if (!strcmp(varval, c.user))
{
/* pattern matches as plain text */
asprintf(&c.section_name, "%s", section);
}
else if (get_match(c.user, varval, &c.match) > 0)
{
/* pattern matches as regex */
asprintf(&c.section_name, "%s", section);
}
return 0;
}
/**
* section_pattern_search_handler() - walk config file to find section matching user input
*
* INIH handler used to resolve the section matching the user's input.
* This will try to match the user input against a section with the name of the user input.
*/
static int section_name_search_handler(void *user, const char *section, const char *varname,
const char *varval)
{
UNUSED(user);
UNUSED(varname);
UNUSED(varval);
if (!strcmp(section, c.user))
{
/* section name matches as plain text */
asprintf(&c.section_name, "%s", section);
}
return 0;
}
static int section_name_print_handler(void *user, const char *section, const char *varname,
const char *varval)
{
UNUSED(user);
UNUSED(varname);
UNUSED(varval);
static char *section_previous = "";
if (strcmp(section, section_previous) != 0)
{
printf("%s ", section);
section_previous = strdup(section);
}
return 0;
}
static int resolve_config_file(void)
{
char *xdg = getenv("XDG_CONFIG_HOME");
if (xdg)
{
asprintf(&c.path, "%s/tio/config", xdg);
if (access(c.path, F_OK) == 0)
{
return 0;
}
free(c.path);
}
char *home = getenv("HOME");
if (home)
{
asprintf(&c.path, "%s/.config/tio/config", home);
if (access(c.path, F_OK) == 0)
{
return 0;
}
free(c.path);
asprintf(&c.path, "%s/.tioconfig", home);
if (access(c.path, F_OK) == 0)
{
return 0;
}
free(c.path);
}
c.path = NULL;
return -EINVAL;
}
void config_file_show_sub_configurations(void)
{
memset(&c, 0, sizeof(struct config_t));
// Find config file
if (resolve_config_file() != 0)
{
// None found - stop parsing
return;
}
ini_parse(c.path, section_name_print_handler, NULL);
}
void config_file_parse(void)
{
int ret;
memset(&c, 0, sizeof(struct config_t));
// Find config file
if (resolve_config_file() != 0)
{
// None found - stop parsing
return;
}
// Set user input which may be tty device or sub config
c.user = option.tty_device;
if (!c.user)
{
return;
}
// Parse default (unnamed) settings
asprintf(&c.section_name, "%s", "");
ret = ini_parse(c.path, data_handler, NULL);
if (ret < 0)
{
tio_error_printf("Unable to parse configuration file (%d)", ret);
exit(EXIT_FAILURE);
}
free(c.section_name);
c.section_name = NULL;
// Find matching section
ret = ini_parse(c.path, section_pattern_search_handler, NULL);
if (!c.section_name)
{
ret = ini_parse(c.path, section_name_search_handler, NULL);
if (!c.section_name)
{
tio_debug_printf("Unable to match user input to configuration section (%d)", ret);
return;
}
}
// Parse settings of found section (sub config)
ret = ini_parse(c.path, data_handler, NULL);
if (ret < 0)
{
tio_error_printf("Unable to parse configuration file (%d)", ret);
exit(EXIT_FAILURE);
}
atexit(&config_exit);
}
void config_exit(void)
{
free(c.tty);
free(c.flow);
free(c.parity);
free(c.log_filename);
free(c.map);
free(c.match);
free(c.section_name);
free(c.path);
}
void config_file_print(void)
{
if (c.path != NULL)
{
tio_printf(" Active configuration file: %s", c.path);
if (c.section_name != NULL)
{
tio_printf(" Active sub-configuration: %s", c.section_name);
}
}
}

28
src/configfile.h Normal file
View file

@ -0,0 +1,28 @@
/*
* tio - a simple serial terminal I/O tool
*
* Copyright (c) 2020 Liam Beguin
* 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 config_file_print(void);
void config_file_parse(void);
void config_exit(void);
void config_file_show_sub_configurations(void);

101
src/error.c Normal file
View file

@ -0,0 +1,101 @@
/*
* 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.
*/
#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include "options.h"
#include "print.h"
#include "error.h"
#include "timestamp.h"
static char error[2][1000];
static bool in_session = false;
void error_enter_session_mode(void)
{
in_session = true;
}
void error_printf_(const char *format, ...)
{
va_list args;
char *line;
va_start(args, format);
vasprintf(&line, format, args);
if (in_session)
{
if (print_tainted)
{
putchar('\n');
}
ansi_error_printf("[%s] %s", timestamp_current_time(), line);
}
else
{
fprintf(stderr, "%s\n", line);
}
va_end(args);
print_tainted = false;
free(line);
}
void tio_error_printf(const char *format, ...)
{
va_list args;
va_start(args, format);
vsnprintf(error[0], 1000, format, args);
va_end(args);
}
void tio_error_printf_silent(const char *format, ...)
{
va_list args;
va_start(args, format);
vsnprintf(error[1], 1000, format, args);
va_end(args);
}
void error_exit(void)
{
if (error[0][0] != 0)
{
/* Print error */
error_printf_("Error: %s", error[0]);
}
else if ((error[1][0] != 0) && (option.no_autoconnect))
{
/* Print silent error */
error_printf_("Error: %s", error[1]);
}
}

30
src/error.h Normal file
View file

@ -0,0 +1,30 @@
/*
* 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
#define TIO_SUCCESS 0
#define TIO_ERROR 1
void tio_error_printf(const char *format, ...);
void tio_error_printf_silent(const char *format, ...);
void error_exit(void);
void error_enter_session_mode(void);

206
src/log.c Normal file
View file

@ -0,0 +1,206 @@
/*
* 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.
*/
#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <libgen.h>
#include "options.h"
#include "print.h"
#include "error.h"
#define IS_ESC_CSI_INTERMEDIATE_CHAR(c) ((c >= 0x20) && (c <= 0x3F))
#define IS_ESC_END_CHAR(c) ((c >= 0x30) && (c <= 0x7E))
#define IS_CTRL_CHAR(c) ((c >= 0x00) && (c <= 0x1F))
static FILE *fp = NULL;
static char file_buffer[BUFSIZ];
static const char *log_filename = NULL;
static char *date_time(void)
{
static char date_time_string[50];
struct tm *tm;
struct timeval tv;
gettimeofday(&tv, NULL);
tm = localtime(&tv.tv_sec);
strftime(date_time_string, sizeof(date_time_string), "%Y-%m-%dT%H:%M:%S", tm);
return date_time_string;
}
int log_open(const char *filename)
{
static char automatic_filename[400];
if (filename == NULL)
{
// Generate filename if none provided ("tio_DEVICE_YYYY-MM-DDTHH:MM:SS.log")
sprintf(automatic_filename, "tio_%s_%s.log", basename((char *)option.tty_device), date_time());
filename = automatic_filename;
}
log_filename = filename;
// Open log file in append write mode
fp = fopen(filename, "a+");
if (fp == NULL)
{
tio_warning_printf("Could not open log file %s (%s)", filename, strerror(errno));
return -1;
}
// Enable line buffering
setvbuf(fp, file_buffer, _IOLBF, BUFSIZ);
return 0;
}
bool log_strip(char c)
{
static char previous_char = 0;
static bool esc_sequence = false;
bool strip = false;
/* Detect if character should be stripped or not */
switch (c)
{
case 0xa:
/* Line feed / new line */
/* Reset ESC sequence just in case something went wrong with the
* escape sequence parsing. */
esc_sequence = false;
break;
case 0x1b:
/* Escape */
strip = true;
break;
case 0x5b:
/* Left bracket */
if (previous_char == 0x1b)
{
// Start of ESC sequence
esc_sequence = true;
strip = true;
}
break;
default:
if (IS_CTRL_CHAR(c))
{
/* Strip ASCII control characters */
strip = true;
break;
}
else
if ((esc_sequence) && (IS_ESC_CSI_INTERMEDIATE_CHAR(c)))
{
strip = true;
break;
}
else
if ((esc_sequence) && (IS_ESC_END_CHAR(c)))
{
esc_sequence = false;
strip = true;
break;
}
break;
}
previous_char = c;
return strip;
}
void log_printf(const char *format, ...)
{
if (fp == NULL)
{
return;
}
char *line;
va_list(args);
va_start(args, format);
vasprintf(&line, format, args);
va_end(args);
fwrite(line, strlen(line), 1, fp);
free(line);
}
void log_putc(char c)
{
if (fp == NULL)
{
return;
}
if (option.log_strip)
{
if (!log_strip(c))
{
fputc(c, fp);
}
}
else
{
fputc(c, fp);
}
}
void log_close(void)
{
if (fp != NULL)
{
fclose(fp);
fp = NULL;
log_filename = NULL;
}
}
void log_exit(void)
{
if (option.log)
{
tio_printf("Saved log to file %s", log_filename);
log_close();
}
}
const char *log_get_filename(void)
{
return log_filename;
}

29
src/log.h Normal file
View file

@ -0,0 +1,29 @@
/*
* 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
int log_open(const char *filename);
void log_printf(const char *format, ...);
void log_putc(char c);
void log_close(void);
void log_exit(void);
const char * log_get_filename(void);

145
src/main.c Normal file
View file

@ -0,0 +1,145 @@
/*
* 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 "options.h"
#include "configfile.h"
#include "tty.h"
#include "log.h"
#include "error.h"
#include "print.h"
#include "signals.h"
#include "socket.h"
int main(int argc, char *argv[])
{
int status = 0;
/* Handle received signals */
signal_handlers_install();
/* Add error exit handler */
atexit(&error_exit);
/* Parse command-line options (1st pass) */
options_parse(argc, argv);
if (option.complete_sub_configs)
{
config_file_show_sub_configurations();
return status;
}
/* Parse configuration file */
config_file_parse();
/* Parse command-line options (2nd pass) */
options_parse_final(argc, argv);
/* Configure tty device */
tty_configure();
/* Configure input terminal */
if (isatty(fileno(stdin)))
{
stdin_configure();
}
else
{
// Enter non interactive mode
interactive_mode = false;
// Mute tio text in response mode
if (option.response_wait)
{
option.mute = true;
}
}
/* Configure output terminal */
if (isatty(fileno(stdout)))
{
stdout_configure();
}
else
{
// No color when piping
option.color = -1;
}
/* Add log exit handler */
atexit(&log_exit);
/* Create log file */
if (option.log)
{
log_open(option.log_filename);
}
/* Initialize ANSI text formatting (colors etc.) */
print_init_ansi_formatting();
/* Change error printing mode */
error_enter_session_mode();
/* Print launch hints */
tio_printf("tio v%s", VERSION);
if (interactive_mode)
{
tio_printf("Press ctrl-%c q to quit", option.prefix_key);
} else
{
tio_printf("Non-interactive mode enabled");
tio_printf("Press ctrl-c to quit");
}
/* Open socket */
if (option.socket)
{
socket_configure();
}
/* Spawn input handling into separate thread */
tty_input_thread_create();
/* Wait for input to be ready */
tty_input_thread_wait_ready();
/* Connect to tty device */
if (option.no_autoconnect)
{
status = tty_connect();
}
else
{
/* Enter connect loop */
while (true)
{
tty_wait_for_device();
status = tty_connect();
}
}
return status;
}

50
src/meson.build Normal file
View file

@ -0,0 +1,50 @@
config_h = configuration_data()
config_h.set_quoted('VERSION', meson.project_version())
config_h.set('BAUDRATE_CASES', baudrate_cases)
configure_file(output: 'config.h', configuration: config_h)
tio_sources = [
'error.c',
'log.c',
'main.c',
'options.c',
'misc.c',
'tty.c',
'print.c',
'configfile.c',
'signals.c',
'socket.c',
'setspeed.c',
'rs485.c',
'timestamp.c',
'alert.c'
]
tio_dep = [
dependency('threads', required: true),
dependency('inih', required: true,
fallback : ['libinih', 'inih_dep'],
default_options: ['default_library=static', 'distro_install=false'])
]
tio_c_args = ['-Wno-unused-result']
if enable_setspeed2
tio_c_args += '-DHAVE_TERMIOS2'
endif
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,
dependencies: tio_dep,
install: true )
subdir('bash-completion')

72
src/misc.c Normal file
View file

@ -0,0 +1,72 @@
/*
* 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 <time.h>
#include <errno.h>
#include "error.h"
#include "print.h"
#include "options.h"
void delay(long ms)
{
struct timespec ts;
if (ms <= 0)
{
return;
}
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000;
nanosleep(&ts, NULL);
}
long string_to_long(char *string)
{
long result;
char *end_token;
errno = 0;
result = strtol(string, &end_token, 10);
if ((errno != 0) || (*end_token != 0))
{
printf("Error: Invalid digit\n");
exit(EXIT_FAILURE);
}
return result;
}
int ctrl_key_code(unsigned char key)
{
if ((key >= 'a') && (key <= 'z'))
{
return key & ~0x60;
}
return -1;
}

31
src/misc.h Normal file
View file

@ -0,0 +1,31 @@
/*
* 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
#define UNUSED(expr) do { (void)(expr); } while (0)
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);

489
src/options.c Normal file
View file

@ -0,0 +1,489 @@
/*
* 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 <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <getopt.h>
#include <termios.h>
#include <limits.h>
#include "options.h"
#include "error.h"
#include "misc.h"
#include "print.h"
#include "tty.h"
#include "rs485.h"
#include "timestamp.h"
#include "alert.h"
#include "log.h"
enum opt_t
{
OPT_NONE,
OPT_TIMESTAMP_FORMAT,
OPT_LOG_FILE,
OPT_LOG_STRIP,
OPT_LINE_PULSE_DURATION,
OPT_RESPONSE_TIMEOUT,
OPT_RS485,
OPT_RS485_CONFIG,
OPT_ALERT,
OPT_COMPLETE_SUB_CONFIGS,
OPT_MUTE,
};
/* Default options */
struct option_t option =
{
.tty_device = "",
.baudrate = 115200,
.databits = 8,
.flow = "none",
.stopbits = 1,
.parity = "none",
.output_delay = 0,
.output_line_delay = 0,
.dtr_pulse_duration = 100,
.rts_pulse_duration = 100,
.cts_pulse_duration = 100,
.dsr_pulse_duration = 100,
.dcd_pulse_duration = 100,
.ri_pulse_duration = 100,
.no_autoconnect = false,
.log = false,
.log_filename = NULL,
.log_strip = false,
.local_echo = false,
.timestamp = TIMESTAMP_NONE,
.socket = NULL,
.map = "",
.color = 256, // Bold
.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,
.complete_sub_configs = false,
};
void print_help(char *argv[])
{
UNUSED(argv);
printf("Usage: tio [<options>] <tty-device|sub-config>\n");
printf("\n");
printf("Connect to TTY device directly or via sub-configuration.\n");
printf("\n");
printf("Options:\n");
printf(" -b, --baudrate <bps> Baud rate (default: 115200)\n");
printf(" -d, --databits 5|6|7|8 Data bits (default: 8)\n");
printf(" -f, --flow hard|soft|none Flow control (default: none)\n");
printf(" -s, --stopbits 1|2 Stop bits (default: 1)\n");
printf(" -p, --parity odd|even|none|mark|space Parity (default: none)\n");
printf(" -o, --output-delay <ms> Output character delay (default: 0)\n");
printf(" -O, --output-line-delay <ms> Output line delay (default: 0)\n");
printf(" --line-pulse-duration <duration> Set line pulse duration\n");
printf(" -n, --no-autoconnect Disable automatic connect\n");
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 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 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(" --mute Mute tio\n");
printf(" -v, --version Display version\n");
printf(" -h, --help Display help\n");
printf("\n");
printf("Options and sub-configurations may be set via configuration file.\n");
printf("\n");
printf("See the man page for more details.\n");
}
void line_pulse_duration_option_parse(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[11];
unsigned int value;
sscanf(token, "%10[^=]=%d", keyname, &value);
if (!strcmp(keyname, "DTR"))
{
option.dtr_pulse_duration = value;
}
else if (!strcmp(keyname, "RTS"))
{
option.rts_pulse_duration = value;
}
else if (!strcmp(keyname, "CTS"))
{
option.cts_pulse_duration = value;
}
else if (!strcmp(keyname, "DSR"))
{
option.dsr_pulse_duration = value;
}
else if (!strcmp(keyname, "DCD"))
{
option.dcd_pulse_duration = value;
}
else if (!strcmp(keyname, "RI"))
{
option.ri_pulse_duration = value;
}
}
else
{
token_found = false;
}
}
free(buffer);
}
void options_print()
{
tio_printf(" Device: %s", option.tty_device);
tio_printf(" Baudrate: %u", option.baudrate);
tio_printf(" Databits: %d", option.databits);
tio_printf(" Flow: %s", option.flow);
tio_printf(" Stopbits: %d", option.stopbits);
tio_printf(" Parity: %s", option.parity);
tio_printf(" Local echo: %s", option.local_echo ? "enabled" : "disabled");
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(" 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.cts_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)
tio_printf(" Log file: %s", log_get_filename());
if (option.socket)
tio_printf(" Socket: %s", option.socket);
}
void options_parse(int argc, char *argv[])
{
int c;
if (argc == 1)
{
print_help(argv);
exit(EXIT_SUCCESS);
}
while (1)
{
static struct option long_options[] =
{
{"baudrate", required_argument, 0, 'b' },
{"databits", required_argument, 0, 'd' },
{"flow", required_argument, 0, 'f' },
{"stopbits", required_argument, 0, 's' },
{"parity", required_argument, 0, 'p' },
{"output-delay", required_argument, 0, 'o' },
{"output-line-delay" , required_argument, 0, 'O' },
{"line-pulse-duration", required_argument, 0, OPT_LINE_PULSE_DURATION },
{"no-autoconnect", no_argument, 0, 'n' },
{"local-echo", no_argument, 0, 'e' },
{"timestamp", no_argument, 0, 't' },
{"timestamp-format", required_argument, 0, OPT_TIMESTAMP_FORMAT },
{"list-devices", no_argument, 0, 'L' },
{"log", no_argument, 0, 'l' },
{"log-file", required_argument, 0, OPT_LOG_FILE },
{"log-strip", no_argument, 0, OPT_LOG_STRIP },
{"socket", required_argument, 0, 'S' },
{"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 },
{"mute", no_argument, 0, OPT_MUTE },
{"version", no_argument, 0, 'v' },
{"help", no_argument, 0, 'h' },
{"complete-sub-configs", no_argument, 0, OPT_COMPLETE_SUB_CONFIGS},
{0, 0, 0, 0 }
};
/* getopt_long stores the option index here */
int option_index = 0;
/* Parse argument using getopt_long */
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;
switch (c)
{
case 0:
/* If this option sets a flag, do nothing else now */
if (long_options[option_index].flag != 0)
break;
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case 'b':
option.baudrate = string_to_long(optarg);
break;
case 'd':
option.databits = string_to_long(optarg);
break;
case 'f':
option.flow = optarg;
break;
case 's':
option.stopbits = string_to_long(optarg);
break;
case 'p':
option.parity = optarg;
break;
case 'o':
option.output_delay = string_to_long(optarg);
break;
case 'O':
option.output_line_delay = string_to_long(optarg);
break;
case OPT_LINE_PULSE_DURATION:
line_pulse_duration_option_parse(optarg);
break;
case 'n':
option.no_autoconnect = true;
break;
case 'e':
option.local_echo = true;
break;
case 't':
option.timestamp = TIMESTAMP_24HOUR;
break;
case OPT_TIMESTAMP_FORMAT:
option.timestamp = timestamp_option_parse(optarg);
break;
case 'L':
list_serial_devices();
exit(EXIT_SUCCESS);
break;
case 'l':
option.log = true;
break;
case OPT_LOG_FILE:
option.log_filename = optarg;
break;
case OPT_LOG_STRIP:
option.log_strip = true;
break;
case 'S':
option.socket = optarg;
break;
case 'm':
option.map = optarg;
break;
case 'c':
if (!strcmp(optarg, "list"))
{
// Print available color codes
printf("Available color codes:\n");
for (int i=0; i<=255; i++)
{
printf(" \e[1;38;5;%dmThis is color code %d\e[0m\n", i, i);
}
exit(EXIT_SUCCESS);
}
else if (!strcmp(optarg, "none"))
{
option.color = -1; // No color
break;
}
else if (!strcmp(optarg, "bold"))
{
option.color = 256; // Bold
break;
}
option.color = string_to_long(optarg);
if ((option.color < 0) || (option.color > 255))
{
tio_error_printf("Invalid color code");
exit(EXIT_FAILURE);
}
break;
case 'x':
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 OPT_MUTE:
option.mute = true;
break;
case 'v':
printf("tio v%s\n", VERSION);
exit(EXIT_SUCCESS);
break;
case 'h':
print_help(argv);
exit(EXIT_SUCCESS);
break;
case OPT_COMPLETE_SUB_CONFIGS:
option.complete_sub_configs = true;
break;
case '?':
/* getopt_long already printed an error message */
exit(EXIT_FAILURE);
break;
default:
exit(EXIT_FAILURE);
}
}
/* Assume first non-option is the tty device name */
if (strcmp(option.tty_device, ""))
optind++;
else if (optind < argc)
option.tty_device = argv[optind++];
if (option.complete_sub_configs)
{
return;
}
if (strlen(option.tty_device) == 0)
{
tio_error_printf("Missing tty device or sub-configuration name");
exit(EXIT_FAILURE);
}
/* Print any remaining command line arguments (unknown options) */
if (optind < argc)
{
fprintf(stderr, "Error: Unknown argument ");
while (optind < argc)
{
fprintf(stderr, "%s ", argv[optind++]);
}
fprintf(stderr, "\n");
exit(EXIT_FAILURE);
}
}
void options_parse_final(int argc, char *argv[])
{
/* Preserve tty device which may have been set by configuration file */
const char *tty_device = option.tty_device;
/* Do 2nd pass to override settings set by configuration file */
optind = 1; // Reset option index to restart scanning of argv
options_parse(argc, argv);
/* Restore tty device */
option.tty_device = tty_device;
}

78
src/options.h Normal file
View file

@ -0,0 +1,78 @@
/*
* 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
#include <stdint.h>
#include <stdbool.h>
#include <limits.h>
#include <termios.h>
#include <sys/param.h>
#include "timestamp.h"
#include "alert.h"
/* Options */
struct option_t
{
const char *tty_device;
unsigned int baudrate;
int databits;
char *flow;
int stopbits;
char *parity;
int output_delay;
int output_line_delay;
unsigned int dtr_pulse_duration;
unsigned int rts_pulse_duration;
unsigned int cts_pulse_duration;
unsigned int dsr_pulse_duration;
unsigned int dcd_pulse_duration;
unsigned int ri_pulse_duration;
bool no_autoconnect;
bool log;
bool log_strip;
bool local_echo;
enum timestamp_t timestamp;
const char *log_filename;
const char *map;
const char *socket;
int color;
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;
bool complete_sub_configs;
};
extern struct option_t option;
void options_print();
void options_parse(int argc, char *argv[]);
void options_parse_final(int argc, char *argv[]);
void line_pulse_duration_option_parse(const char *arg);

75
src/print.c Normal file
View file

@ -0,0 +1,75 @@
/*
* 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 <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "options.h"
#include "print.h"
bool print_tainted = false;
char ansi_format[30];
void print_hex(char c)
{
printf("%02x ", (unsigned char) c);
}
void print_normal(char c)
{
putchar(c);
}
void print_init_ansi_formatting()
{
if (option.color == 256)
{
// Set bold text with no color changes
sprintf(ansi_format, "\e[1m");
}
else
{
// Set bold text with user defined ANSI color
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("");
}

118
src/print.h Normal file
View file

@ -0,0 +1,118 @@
/*
* 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
#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_RESET "\e[0m"
#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", timestamp_current_time(), ## args); \
else \
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, 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
#define tio_debug_printf(format, args...) \
fprintf(stdout, "[debug] " format, ## args)
#define tio_debug_printf_raw(format, args...) \
fprintf(stdout, "" format, ## args)
#else
#define tio_debug_printf(format, args...)
#define tio_debug_printf_raw(format, args...)
#endif
void print_hex(char c);
void print_normal(char c);
void print_init_ansi_formatting(void);
void tio_printf_array(const char *array);

200
src/rs485.c Normal file
View file

@ -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

27
src/rs485.h Normal file
View file

@ -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);

68
src/setspeed.c Normal file
View file

@ -0,0 +1,68 @@
/*
* tio - a simple serial terminal I/O tool
*
* Copyright (c) 2017-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 <errno.h>
#ifdef HAVE_TERMIOS2
#define termios asmtermios
#include <sys/ioctl.h>
#undef termios
#include <asm-generic/ioctls.h>
#include <asm-generic/termbits.h>
#elif HAVE_IOSSIOSPEED
#include <sys/ioctl.h>
#include <IOKit/serial/ioss.h>
#endif
#ifdef HAVE_TERMIOS2
int setspeed(int fd, int baudrate)
{
struct termios2 tio;
int status;
status = ioctl(fd, TCGETS2, &tio);
// Set baudrate speed using termios2 interface
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = baudrate;
tio.c_ospeed = baudrate;
status = ioctl(fd, TCSETS2, &tio);
return status;
}
#elif HAVE_IOSSIOSPEED
int setspeed(int fd, int baudrate)
{
return ioctl(fd, IOSSIOSPEED, (char *)&baudrate);
}
#else
int setspeed(int fd, int baudrate)
{
errno = EINVAL;
return -1;
}
#endif

24
src/setspeed.h Normal file
View file

@ -0,0 +1,24 @@
/*
* tio - a simple serial terminal 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
int setspeed(int fd, int baudrate);

51
src/signals.c Normal file
View file

@ -0,0 +1,51 @@
/*
* tio - a simple serial terminal 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 "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include "error.h"
#include "print.h"
#include "misc.h"
#include "tty.h"
static void signal_handler(int signum)
{
switch (signum)
{
case SIGHUP:
tio_printf("Received SIGHUP signal!");
break;
case SIGINT:
tio_printf("Received SIGINT signal!");
break;
}
exit(EXIT_FAILURE);
}
void signal_handlers_install(void)
{
signal(SIGHUP, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGPIPE, SIG_IGN);
}

24
src/signals.h Normal file
View file

@ -0,0 +1,24 @@
/*
* tio - a simple serial terminal 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 signal_handlers_install();

352
src/socket.c Normal file
View file

@ -0,0 +1,352 @@
/*
* tio - a simple serial terminal I/O tool
*
* Copyright (c) 2014-2022 Martin Lund
* Copyright (c) 2022 Google LLC
*
* 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 <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include "socket.h"
#include "options.h"
#include "print.h"
#define MAX_SOCKET_CLIENTS 16
#define SOCKET_PORT_DEFAULT 3333
static int sockfd;
static int clientfds[MAX_SOCKET_CLIENTS];
static int socket_family = AF_UNSPEC;
static int port_number = SOCKET_PORT_DEFAULT;
static const char *socket_filename(void)
{
/* skip 'unix:' */
return option.socket + 5;
}
static int socket_inet_port(void)
{
/* skip 'inet:' */
int port_number = atoi(option.socket + 5);
if (port_number == 0)
{
port_number = SOCKET_PORT_DEFAULT;
}
return port_number;
}
static int socket_inet6_port(void)
{
/* skip 'inet6:' */
int port_number = atoi(option.socket + 6);
if (port_number == 0)
{
port_number = SOCKET_PORT_DEFAULT;
}
return port_number;
}
static void socket_exit(void)
{
if (socket_family == AF_UNIX)
{
unlink(socket_filename());
}
}
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 = {};
struct sockaddr_in sockaddr_inet = {};
struct sockaddr_in6 sockaddr_inet6 = {};
struct sockaddr *sockaddr_p;
socklen_t socklen;
/* Parse socket string */
if (strncmp(option.socket, "unix:", 5) == 0)
{
socket_family = AF_UNIX;
if (strlen(socket_filename()) == 0)
{
tio_error_printf("Missing socket filename");
exit(EXIT_FAILURE);
}
if (strlen(socket_filename()) > sizeof(sockaddr_unix.sun_path) - 1)
{
tio_error_printf("Socket file path %s too long", option.socket);
exit(EXIT_FAILURE);
}
}
if (strncmp(option.socket, "inet:", 5) == 0)
{
socket_family = AF_INET;
port_number = socket_inet_port();
if (port_number < 0)
{
tio_error_printf("Invalid port number: %d", port_number);
exit(EXIT_FAILURE);
}
}
if (strncmp(option.socket, "inet6:", 6) == 0)
{
socket_family = AF_INET6;
port_number = socket_inet6_port();
if (port_number < 0)
{
tio_error_printf("Invalid port number: %d", port_number);
exit(EXIT_FAILURE);
}
}
if (socket_family == AF_UNSPEC)
{
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)
{
case AF_UNIX:
sockaddr_unix.sun_family = AF_UNIX;
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:
sockaddr_inet.sin_family = AF_INET;
sockaddr_inet.sin_addr.s_addr = INADDR_ANY;
sockaddr_inet.sin_port = htons(port_number);
sockaddr_p = (struct sockaddr *) &sockaddr_inet;
socklen = sizeof(sockaddr_inet);
break;
case AF_INET6:
sockaddr_inet6.sin6_family = AF_INET6;
sockaddr_inet6.sin6_addr = in6addr_any;
sockaddr_inet6.sin6_port = htons(port_number);
sockaddr_p = (struct sockaddr *) &sockaddr_inet6;
socklen = sizeof(sockaddr_inet6);
break;
default:
tio_error_printf("Invalid socket family (%d)", socket_family);
exit(EXIT_FAILURE);
break;
}
/* Create socket */
sockfd = socket(socket_family, SOCK_STREAM, 0);
if (sockfd < 0)
{
tio_error_printf("Failed to create socket (%s)", strerror(errno));
exit(EXIT_FAILURE);
}
/* Bind */
if (bind(sockfd, sockaddr_p, socklen) < 0)
{
tio_error_printf("Failed to bind to socket (%s)", strerror(errno));
exit(EXIT_FAILURE);
}
/* Listen */
if (listen(sockfd, MAX_SOCKET_CLIENTS) < 0)
{
tio_error_printf("Failed to listen on socket (%s)", strerror(errno));
exit(EXIT_FAILURE);
}
memset(clientfds, -1, sizeof(clientfds));
atexit(socket_exit);
if (socket_family == AF_UNIX)
{
tio_printf("Listening on socket %s", socket_filename());
}
else
{
tio_printf("Listening on socket port %d", port_number);
}
}
void socket_write(char input_char)
{
if (!option.socket)
{
return;
}
for (int i = 0; i != MAX_SOCKET_CLIENTS; ++i)
{
if (clientfds[i] != -1)
{
if (write(clientfds[i], &input_char, 1) <= 0)
{
tio_error_printf_silent("Failed to write to socket (%s)", strerror(errno));
close(clientfds[i]);
clientfds[i] = -1;
}
}
}
}
int socket_add_fds(fd_set *rdfs, bool connected)
{
if (!option.socket)
{
return 0;
}
int numclients = 0, maxfd = 0;
for (int i = 0; i != MAX_SOCKET_CLIENTS; ++i)
{
if (clientfds[i] != -1)
{
/* let clients block if they try to send while we're disconnected */
if (connected)
{
FD_SET(clientfds[i], rdfs);
maxfd = MAX(maxfd, clientfds[i]);
}
numclients++;
}
}
/* don't bother to accept clients if we're already full */
if (numclients != MAX_SOCKET_CLIENTS)
{
FD_SET(sockfd, rdfs);
maxfd = MAX(maxfd, sockfd);
}
return maxfd;
}
bool socket_handle_input(fd_set *rdfs, char *output_char)
{
if (!option.socket)
{
return false;
}
if (FD_ISSET(sockfd, rdfs))
{
int clientfd = accept(sockfd, NULL, NULL);
/* this loop should always succeed because we don't select on sockfd when full */
for (int i = 0; i != MAX_SOCKET_CLIENTS; ++i)
{
if (clientfds[i] == -1)
{
clientfds[i] = clientfd;
break;
}
}
}
for (int i = 0; i != MAX_SOCKET_CLIENTS; ++i)
{
if (clientfds[i] != -1 && FD_ISSET(clientfds[i], rdfs))
{
int status = read(clientfds[i], output_char, 1);
if (status == 0)
{
close(clientfds[i]);
clientfds[i] = -1;
continue;
}
if (status < 0)
{
tio_error_printf_silent("Failed to read from socket (%s)", strerror(errno));
close(clientfds[i]);
clientfds[i] = -1;
continue;
}
/* match the behavior of a terminal in raw mode */
if (*output_char == '\n')
{
*output_char = '\r';
}
return true;
}
}
return false;
}

31
src/socket.h Normal file
View file

@ -0,0 +1,31 @@
/*
* tio - a simple serial terminal I/O tool
*
* Copyright (c) 2014-2022 Martin Lund
* Copyright (c) 2022 Google LLC
*
* 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
#include <stdbool.h>
#include <sys/select.h>
void socket_configure(void);
void socket_write(char input_char);
int socket_add_fds(fd_set *fds, bool connected);
bool socket_handle_input(fd_set *fds, char *output_char);

152
src/timestamp.c Normal file
View file

@ -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;
}

36
src/timestamp.h Normal file
View file

@ -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);

1541
src/tty.c Normal file

File diff suppressed because it is too large Load diff

35
src/tty.h Normal file
View file

@ -0,0 +1,35 @@
/*
* 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
#include <stdbool.h>
extern bool interactive_mode;
void stdout_configure(void);
void stdin_configure(void);
void tty_configure(void);
int tty_connect(void);
void tty_wait_for_device(void);
void list_serial_devices(void);
void tty_input_thread_create(void);
void tty_input_thread_wait_ready(void);

4
subprojects/libinih.wrap Normal file
View file

@ -0,0 +1,4 @@
[wrap-git]
directory=libinih
url=https://github.com/benhoyt/inih.git
revision=r56