Compare commits

..

No commits in common. "master" and "v3.0" have entirely different histories.
master ... v3.0

51 changed files with 1755 additions and 4027 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 liblua5.2-dev libglib2.0-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

View file

@ -1,5 +0,0 @@
BasedOnStyle: llvm
IndentWidth: 4
AllowShortFunctionsOnASingleLine: None
KeepEmptyLinesAtTheStartOfBlocks: false
BreakBeforeBraces: Allman

View file

@ -12,8 +12,8 @@
name: "CodeQL"
on:
push:
branches: [ "main", "master" ]
# push:
# branches: [ "main", "master" ]
schedule:
- cron: '0 0 * * *'
pull_request:
@ -27,7 +27,7 @@ jobs:
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners
# Consider using larger runners for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-22.04' }}
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-20.04' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
permissions:
actions: read
@ -51,7 +51,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@ -66,7 +66,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift).
# If this step fails, then you should remove it and run the build manually (see below)
#- name: Autobuild
# uses: github/codeql-action/autobuild@v3
# uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@ -78,7 +78,7 @@ jobs:
./.github/workflows/codeql-buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{matrix.language}}"
upload: false
@ -107,14 +107,14 @@ jobs:
output: ${{ steps.step1.outputs.sarif-output }}/cpp.sarif
- name: Upload CodeQL results to code scanning
uses: github/codeql-action/upload-sarif@v3
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: ${{ steps.step1.outputs.sarif-output }}
category: "/language:${{matrix.language}}"
- name: Upload CodeQL results as an artifact
if: success() || failure()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v3
with:
name: codeql-results
path: ${{ steps.step1.outputs.sarif-output }}

View file

@ -1,30 +0,0 @@
name: MacOS build
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
build:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install dependencies
run: |
brew install meson ninja lua
- name: Build
run: |
meson setup build
meson compile -C build --verbose
meson install -C build

View file

@ -1,31 +0,0 @@
name: Ubuntu build
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install dependencies
run: |
sudo apt update
sudo apt install -y bash-completion git meson liblua5.2-dev libglib2.0-dev
- name: Build
run: |
meson setup build --prefix $HOME/opt/tio
meson compile -C build --verbose
meson install -C build

View file

@ -1,2 +0,0 @@
[default]
extend-ignore-words-re = ["tio"]

13
AUTHORS
View file

@ -53,18 +53,5 @@ Sebastian <sebastian.krahmer@gmail.com>
Mingjie Shen <shen497@purdue.edu>
Brian <bayuan@purdue.edu>
Davis C <davisclaib@gmail.com>
KhazAkar <damianzrb@zohomail.eu>
Eliot Alan Foss <eliotfoss@gmail.com>
Robert Lipe <robertlipe@gpsbabel.org>
Heinrich Schuchardt <heinrich.schuchardt@canonical.com>
Tomka Gergely <tomkatudor@gmail.com>
Steve Marple <stevemarple@googlemail.com>
konosubakonoakua <ailike_meow@qq.com>
Keith Hill <k_hill@unitronlp.com>
Lubov66 <radolevanja@gmail.com>
V <v@anomalous.eu>
Samuel Holland <samuel@sholland.org>
David Ordnung <david.ordnung@googlemail.com>
Thanks to everyone who has contributed to this project.

View file

@ -1,4 +1,4 @@
Copyright (c) 2014-2025 Martin Lund <martin.lund@keep-it-simple.com>
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

385
NEWS
View file

@ -1,356 +1,5 @@
=== tio v3.9 (2025-04-13) ===
Changes since tio v3.8 (2024-11-30):
* Fix parsing of timestamp options
* codeql: Upgrade to upload-artifact@v4
* Update plaintext man page
* Add character mapping examples
* Fix pattern matching memory corruption
Samuel Holland:
* Don't add null characters to the expect buffer
They prevent regexec() from seeing the remainder of the buffer.
V:
* Disable stdout buffering globally
This makes it possible to pipe output to other programs cleanly.
Lubov66:
* docs: edited the license date
Jakob Haufe:
* Manpage: Fix backslash encoding
Literal backslash needs to be written as \e.
Changes since tio v3.7 (2024-08-31):
* Rename git version to simply version
* Clean up lua API
Rename modem_send() to send()
Rename send to write()
* Zero initialize buffer in read_string()
* Use version from git
* Fix memory leak in base62_encode()
* Fix name declaration conflict with socket send()
* Add clang-format spec
Keith Hill:
+ Add system timestamps to lua read() and new lua read_line() per global options
+ Add missing timestamp-format epoch
+ Update send_ to use fsync and tcdrain like normal tty_sync does
+ Rework read_line to save partial line at timeout
+ Simplified read_line to reduce cyclomatic complexity
+ renamed example files read.lua and read_line.lua
+ moved #define READ_LINE_SIZE to top of file
+ renamed g_linebuf to linebuf, and moved it into read_line as a static variable
Changes since tio v3.6 (2024-07-19):
* Remove unnecessary sync in line input mode
This caused a problem for some highly timing sensitive modem read-eval-print
loops because the input line and line termination characters (cr/nl) would be
shifted out on the UART with too big delay inbetween because of two
syncs.
* Fix socket send call on platforms without MSG_NOSIGNAL
To fix build issue encountered on MacOS Catalina but may apply to other
platforms.
Steve Marple:
* Add "epoch" timestamp option
Add an option that prints the timestamp as the number of seconds since
the Unix epoch.
Tomka Gergely:
* The log-directory options is not read from the configuration file.
Changes since tio v3.5 (2024-06-29):
* Add configuration file include directive
To include the contents of another configuration file simply do e.g.:
[include raspberrypi.conf]
Also, included file can include other files which can include other
files etc.
This feature is useful for managing many configuration files and sharing
configuration files with others.
* Mention how to list key commands in help output
* Fix hex output mode when using normal input mode
In this combination of modes the input character was not forwarded to
the tty device. This fix makes sure it is forwarded.
* Fix uptime on MacOS
On MacOS the birth time is apparently not available so we use
modification time instead.
* Improve warning upon failing connect
Add device path to warning when connect fails.
* Fix crashy search_reset() on macOS
* Clean up shadow variable
* Clean up readline code
* Improve listing of long device names
* Fix listing of serial devices on macOS
Heinrich Schuchardt:
* Print correct 'Done' timestamp for X- and Y-modem transfers
Call tio_printf() after completing xymodem_send().
Robert Lipe:
* Recompute listing_device_name_length_max for MacOS case, too.
Changes since tio v3.4:
* Clarify input and output direction of map flags
* Rename mapping flag MSB2LSB to IMSB2LSB
This is the correct naming since we are changing the input bit order on
input from the serial device.
* Add OIGNCR mapping flag
Ignores CR on output to serial device.
* Fix line input mode ignoring characters ABCD
* Fix tainted print
Jakob Haufe:
* Fix typos
Changes since tio v3.3:
* Update configuration output
* Clean up script run interaction text
* Fix unbounded writes
* Add history and editing feature to line input mode
Use up and down arrow keys to navigate history.
Use left and right arrow keys to move cursor back and forth.
We try mimic the behaviour of GNU readline which we can not use because
we also need to react to key commands.
* Reuse socket address
To avoid having to wait for socket timeout when restarting server.
* Fix line input mode
Fix so that ABCD are no longer ignored.
* Make sure ICRNL, IGNCR, INLCR take effect
* Include correct header for poll()
* Add group write permission to xymodem received file
* Fix missing open() flags in xymodem_receive()
Vyacheslav Patkov:
* Show current mappings in the configuration printout
* Use "ctrl-t m" to change mappings interactively
* Prompt for Lua script or shell command in interactive session
Eliot Alan Foss:
* Added support to receive XMODEM-CRC files from the connected serial port.
Changes since tio v3.2:
* Force destructive backspace when using local echo
Only takes effect in normal output mode.
* Fix local-echo in configuration file
* Clean up includes
* Force socket write operation to ignore any signals
* Man page cleanup
Changes since tio v3.1:
* Do not print error when using --list with broken config file
* Clean up completion script
* Add option '--exec <command>' for running shell command
Runs shell command with I/O redirected to device.
* Make sure all error output is directed to stderr
* Fix shadow variables
* Update man page
* Fix build on older GNU/Linux systems without statx
* Fix line ending in --list output
* Print location of configuration file in --list output
* Fix alignment of profile listing
Changes since tio v3.0:
* Improve --list feature on non-linux platform
* List available profiles in --list output
* Always message when saving log file
* Add support for using TID as device in config file
* Fix use of invalid flag with regexec()
* Fix potential buffer overflow in match_and_replace()
* Fix profile autocompletion
* Remove inih dependency from CI builds
* Replace use of stat() with fstat()
For better security.
* Fix hexN output mode
* Update pattern matching example
* Fix submenu response when invalid key hit
* Replace inih with glib key file parser
After including the use of glib we might as well replace inih
with the glib key file parser.
All configuration file parsing has been reworked and also the options
parsing has been cleaned up, resulting in better and stricter
configuration file and option value checks.
Compared to old, configuration files now requires any default
configurations to be put in a group/section named [default].
Configuration file keywords such as "enable", "disable", "on",
"off", "yes", "no", "0", "1" have been retired. Now only "true" and
"false" apply to boolean configuration options. This is done to simplify
things and avoid any confusion.
The pattern option feature has been reworked so now the user can now
access the full match string and any matching subexpression using the
%mN syntax.
For example:
[usb devices]
pattern = usb([0-9]*)
device = /dev/ttyUSB%m1
Then when using tio:
$ tio usb12
%m0 = 'usb12' // Full match string
%m1 = 12 // First match subexpression
Which results in device = /dev/ttyUSB12
* Remove CircleCI
Replaced with github workflow CI.
* Add github workflow for Ubuntu build
* Enable extended pattern matching
So that the exclude options can also work as include using special
pattern syntax.
For example, to only include /dev/ttyUSB* devices simply do:
$ tio --exclude-devices=!(/dev/ttyUSB*) --list
See the man page of fnmatch() for all available extended pattern
options.
* Update lua read() description
Rui Chen:
* fix: add build patch for `FNM_EXTMATCH`
* feat: add macOS workflow
* fix: add macOS build patch for `fs_get_creation_time`
=== tio v3.0 ===
@ -575,11 +224,11 @@ Changes since tio v2.7:
* Add lua modem_send(file,protocol)
* Fix xymodem error messages
* Fix xymodem error print outs
* Rework x/y-modem transfer command
Remove ctrl-t X option and instead introduce submenu to ctrl-t x option
Remove ctrl-t X optin and instead introduce submenu to ctrl-t x option
for picking which xmodem protocol to use.
* Update README
@ -588,22 +237,22 @@ Changes since tio v2.7:
* Add independent input and output mode
Replaces -x, --hexadecimal option with --input-mode and --output-mode
Replaces -x, --hexadecimal option with --intput-mode and --output-mode
so it is possible to select hex or normal mode for both input and output
independently.
To obtain same behavior as -x, --hexadecimal use the following
To obtain same behaviour as -x, --hexadecimal use the following
configuration:
input-mode = hex
output-mode = hex
* Fix file descriptor handling on macOS
* Fix file descriptor handling on MacOS
* Add tty line configuration script API
On some platforms calling high()/low() to switch line states result in
costly system calls which makes it impossible to switch two or more tty
costly system calls whick makes it impossible to swith two or more tty
lines simultaneously.
To help solve this timing issue we introduce a tty line state
@ -639,7 +288,7 @@ Changes since tio v2.7:
lines. Script is activated automatically on connect or manually via in
session key command.
The Lua scripting feature opens up for many possibilities in the future
The Lua scripting feature opens up for many posibilities in the future
such as adding expect like functionality to easily and programatically
interact with the connected device.
@ -736,7 +385,7 @@ Changes since tio v2.5:
Add --log-append option which makes tio append to any existing log file.
This also changes the default behavior of tio from appending to
This also changes the default behaviour of tio from appending to
overwriting any existing log file. Now you have to use this new option
to make tio append.
@ -1070,7 +719,7 @@ Changes since tio v1.46:
Victor Oliveira
* add MacPorts install instructions
* add macports install instructions
@ -1570,7 +1219,7 @@ Changes since tio v1.35:
* Handle SIGHUP
Handle SIGHUP so that the registered exit handlers are called to restore
the terminal back to its original state.
the terminal back to its orignal state.
* Add color configuration support
@ -1750,10 +1399,10 @@ Sylvain LAFRASSE:
attila-v:
* Refine timestamps with milliseconds and ISO 8601 format (#129).
* Refine timestamps with milliseconds and ISO-8601 format (#129).
* Show milliseconds too in the timestamp (#114) and log file (#124)
* Change timestamp format to ISO 8601.
* Change timestamp format to ISO-8601.
Yin Fengwei:
@ -1832,7 +1481,7 @@ Lars Kellogg-Stedman:
George Stark:
* don't show line state if ioctl failed
* dont show line state if ioctl failed
* add serial lines manual control
@ -1845,9 +1494,9 @@ arichi:
Mariusz Midor:
* Newline: handle both NL and CR
* Newline: handle booth NL and CR
Flag ONLCRNL expects code \n after press Enter, but on some systems \r is sent instead.
Flag ONLCRNL expects code \n after press Enter, but on some systems \r is send instead.
@ -2339,7 +1988,7 @@ Changes since tio v1.11:
To display the total number of bytes transmitted/received simply perform the
'ctrl-t s' command sequence.
This feature can be useful when e.g. trying to detect non-printable
This feature can be useful when eg. trying to detect non-printable
characters.
* Further simplification of key handling

230
README.md
View file

@ -3,12 +3,10 @@
# tio - a serial device I/O tool
[![](https://img.shields.io/github/actions/workflow/status/tio/tio/ubuntu.yml?label=Ubuntu)](https://github.com/tio/tio/actions/workflows/ubuntu.yml)
[![](https://img.shields.io/github/actions/workflow/status/tio/tio/macos.yml?label=MacOS)](https://github.com/tio/tio/actions/workflows/macos.yml)
[![](https://github.com/tio/tio/actions/workflows/codeql.yml/badge.svg)](https://github.com/tio/tio/actions/workflows/codeql.yml)
[![](https://img.shields.io/codefactor/grade/github/tio/tio)](https://www.codefactor.io/repository/github/tio/tio)
[![](https://img.shields.io/circleci/build/github/tio/tio)](https://circleci.com/github/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
@ -34,15 +32,14 @@ when used in combination with [tmux](https://tmux.github.io).
* Easily connect to serial TTY devices
* Sensible defaults (115200 8n1)
* Support for non-standard baud rates
* Support for mark and space parity
* Automatic connection management
* Automatic detection of serial ports
* Automatic reconnect
* Automatically connect to first new appearing serial device
* Automatically connect to latest registered serial device
* Connect to same port/device combination via unique topology ID (TID)
* Useful for reconnecting when serial device has no serial device by ID
* Support for non-standard baud rates
* Support for mark and space parity
* X-modem (1K/CRC) and Y-modem file upload
* Support for RS-485 mode
* List available serial devices
@ -75,8 +72,6 @@ when used in combination with [tmux](https://tmux.github.io).
* Configuration file support
* Support for configuration profiles
* Activate configuration profiles by name or pattern
* Support for including other configuration files
* Redirect I/O of shell command to serial device
* Redirect I/O to UNIX socket or IPv4/v6 network socket
* Useful for scripting or TTY sharing
* Pipe input and/or output
@ -92,7 +87,7 @@ when used in combination with [tmux](https://tmux.github.io).
* Send files via x/y-modem protocol
* Search for serial devices
* Man page documentation
* Plays nicely with [tmux](https://tmux.github.io) and similar terminal multiplexers
* Plays nicely with [tmux](https://tmux.github.io)
## 3. Usage
@ -102,7 +97,7 @@ For more usage details please see the man page documentation
### 3.1 Command-line
The command-line interface is straightforward as reflected in the output from
```tio --help```:
'tio --help':
```
Usage: tio [<options>] <tty-device|profile|tid>
@ -128,7 +123,7 @@ Options:
-t, --timestamp Enable line timestamp
--timestamp-format <format> Set timestamp format (default: 24hour)
--timestamp-timeout <ms> Set timestamp timeout (default: 200)
-l, --list List available serial devices, TIDs, and profiles
-l, --list List available serial devices
-L, --log Enable log to file
--log-file <filename> Set log filename
--log-directory <path> Set log directory path for automatic named logs
@ -144,14 +139,11 @@ Options:
--script <string> Run script from string
--script-file <filename> Run script from file
--script-run once|always|never Run script on connect (default: always)
--exec <command> Execute shell command with I/O redirected to device
-v, --version Display version
-h, --help Display help
Options and profiles may be set via configuration file.
In session you can press ctrl-t ? to list available key commands.
See the man page for more details.
```
@ -199,11 +191,6 @@ By-path
/dev/serial/by-path/pci-0000:00:14.0-usb-0:6.4:1.0-port0
/dev/serial/by-path/pci-0000:00:14.0-usbv2-0:6.3:1.2
/dev/serial/by-path/pci-0000:00:14.0-usb-0:6.3:1.2
Configuration profiles (/home/lundmar/.config/tio/config)
--------------------------------------------------------------------------------
rpi3 stm32 esp32 am64-evm
imx8mp-evk nucleo-h743zi2 usb-devices
```
It is recommended to connect serial TTY devices by ID:
@ -219,9 +206,8 @@ topology ID (TID):
$ tio bCC2
```
Note: The TID is unique and will stay the same as long as your USB serial port
device plugs into the same USB topology (same ports, same hubs, same
connections, etc.). This way it is possible for tio to successfully reconnect
to the same device.
device plugs into the same USB topology (same ports, same hubs, etc.). This way
it is possible for tio to successfully reconnect to the same device.
Connect automatically to first new appearing serial device:
```
@ -233,24 +219,19 @@ Connect automatically to latest registered serial device:
$ tio --auto-connect latest
```
It is possible to use exclude options to affect which serial devices are
It is also possible to use exclude options to affect which serial devices are
involved in the automatic connection strategy:
```
$ tio --auto-connect new --exclude-devices "/dev/ttyACM?,/dev/ttyUSB2"
```
And to exclude drivers by pattern:
Exclude drivers by pattern:
```
$ tio --auto-connect new --exclude-drivers "cdc_acm,ftdi_sio"
```
Note: Pattern matching supports '*' and '?'. Use comma separation to define
multiple patterns.
To include drivers by specific pattern simply negate the exclude option:
```
$ tio --auto-connect new --exclude-drivers !("cp2102")
```
Log to file with autogenerated filename:
```
$ tio --log /dev/ttyUSB0
@ -276,11 +257,6 @@ Redirect I/O to IPv4 network socket on port 4242:
$ tio --socket inet:4242 /dev/ttyUSB0
```
Map NL to CR-NL on input from device and DEL to BS on output to device:
```
$ tio --map INLCRNL,ODELBS /dev/ttyUSB0
```
Pipe data to the serial device:
```
$ cat data.bin | tio /dev/ttyUSB0
@ -288,12 +264,12 @@ $ cat data.bin | tio /dev/ttyUSB0
Manipulate modem lines on connect:
```
$ tio --script "tio.set{DTR=high,RTS=low}; tio.msleep(100); tio.set{DTR=toggle,RTS=toggle}" /dev/ttyUSB0
$ tio --script "set{DTR=high,RTS=low}; msleep(100); set{DTR=toggle,RTS=toggle}" /dev/ttyUSB0
```
Pipe command to serial device and wait for line response within 1 second:
```
$ echo "*IDN?" | tio /dev/ttyACM0 --script "tio.expect('\r\n', 1000)" --mute
$ echo "*IDN?" | tio /dev/ttyACM0 --script "expect('\r\n', 1000)" --mute
KORAD KD3305P V4.2 SN:32475045
```
@ -314,14 +290,14 @@ ctrl-t ? to list the available key commands.
[15:02:53.269] ctrl-t i Toggle input mode
[15:02:53.269] ctrl-t l Clear screen
[15:02:53.269] ctrl-t L Show line states
[15:02:53.269] ctrl-t m Change mapping of characters on input or output
[15:02:53.269] ctrl-t m Toggle MSB to LSB bit order
[15:02:53.269] ctrl-t o Toggle output mode
[15:02:53.269] ctrl-t p Pulse serial port line
[15:02:53.269] ctrl-t q Quit
[15:02:53.269] ctrl-t r Run script
[15:02:53.269] ctrl-t R Execute shell command with I/O redirected to device
[15:02:53.269] ctrl-t s Show statistics
[15:02:53.269] ctrl-t t Toggle line timestamp mode
[15:02:53.269] ctrl-t U Toggle conversion to uppercase on output
[15:02:53.269] ctrl-t v Show version
[15:02:53.269] ctrl-t x Send file via Xmodem
[15:02:53.269] ctrl-t y Send file via Ymodem
@ -330,7 +306,66 @@ ctrl-t ? to list the available key commands.
If needed, the prefix key (ctrl-t) can be remapped via configuration file.
### 3.3 Configuration file
### 3.3 Lua script API
Tio suppots Lua scripting to easily automate interaction with the tty device.
In addition to the Lua API tio makes the following functions available:
```
expect(string, timeout)
Expect string - waits for string to match or timeout before continueing.
Supports regular expressions. Special characters must be escaped with '\\'.
Timeout is in milliseconds, defaults to 0 meaning it will wait forever.
Returns 1 on successful match, 0 on timeout, or -1 on error.
On successful match it also returns the match string as second return value.
send(string)
Send string.
Returns number of bytes written on success or -1 on error.
modem_send(file, protocol)
Send file using x/y-modem protocol.
Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM.
tty_search()
Search for serial devices.
Returns a table of number indexed tables, one for each serial device
found. Each of these tables contains the serial device information accessible
via the following string indexed elements "path", "tid", "uptime", "driver",
"description".
Returns nil if no serial devices are found.
read(size, timeout)
Read from serial device. If timeout is 0 or not provided it will wait
forever until data is ready to read.
Returns number of bytes read on success, 0 on timeout, or -1 on error.
set{line=state, ...}
Set state of one or multiple tty modem lines.
Line can be any of DTR, RTS, CTS, DSR, CD, RI
State is high, low, or toggle.
sleep(seconds)
Sleep for seconds.
msleep(ms)
Sleep for miliseconds.
exit(code)
Exit with exit code.
```
### 3.4 Configuration file
Options can be set via the configuration file first found in any of the
following locations in the order listed:
@ -342,13 +377,13 @@ The configuration file supports profiles using named sections which can be
activated via the command-line by name or pattern. A profile specifies which
TTY device to connect to and other options.
### 3.3.1 Example
### 3.4.1 Examples
Example configuration file:
```
[default]
baudrate = 115200
# Defaults
baudrate = 9600
databits = 8
parity = none
stopbits = 1
@ -356,27 +391,27 @@ color = 10
[rpi3]
device = /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
no-reconnect = true
log = true
baudrate = 115200
no-reconnect = enable
log = enable
log-file = rpi3.log
line-pulse-duration = DTR=200,RTS=150
color = 11
[svf2]
device = /dev/ttyUSB0
baudrate = 9600
script = tio.expect("login: "); tio.write("root\n"); tio.expect("Password: "); tio.write("root\n")
script = expect("login: "); send("root\n"); expect("Password: "); send("root\n")
color = 12
[esp32]
device = /dev/serial/by-id/usb-0403_6014-if00-port0
script = tio.set{DTR=high,RTS=low}; tio.msleep(100); tio.set{DTR=low,RTS=high}; tio.msleep(100); tio.set{RTS=low}
script = set{DTR=high,RTS=low}; msleep(100); set{DTR=low,RTS=high}; msleep(100); set{RTS=low}
script-run = once
color = 13
[usb-devices]
pattern = ^usb([0-9]*)
device = /dev/ttyUSB%m1
[usb devices]
pattern = usb([0-9]*)
device = /dev/ttyUSB%s
color = 14
```
@ -391,85 +426,6 @@ $ tio usb12
Another more elaborate configuration file example is available [here](examples/config/config).
### 3.4 Lua script API
Tio suppots Lua scripting to easily automate interaction with the tty device.
In addition to the standard Lua API tio makes the following functions
and variables available:
#### `tio.expect(pattern, timeout)`
Waits for the Lua pattern to match or timeout before continuing.
Timeout is in milliseconds, defaults to 0 meaning it will wait forever.
Returns the captures from the pattern or `nil` on timeout.
#### `tio.read(size, timeout)`
Read up to `size` bytes from serial device. If timeout is 0 or not provided it
will wait forever until data is ready to read.
Returns a string up to `size` bytes long on success and `nil` on timeout.
#### `tio.readline(timeout)`
Read line from serial device. If timeout is 0 or not provided it will wait
forever until data is ready to read.
Returns a string on success and `nil` on timeout. On timeout a partially read
line may be returned as a second return value.
#### `tio.write(string)`
Write string to serial device.
Returns the `tio` table.
#### `tio.send(file, protocol)`
Send file using x/y-modem protocol.
Protocol can be any of `XMODEM_1K`, `XMODEM_CRC`, `YMODEM`.
#### `tio.ttysearch()`
Search for serial devices.
Returns a table of number indexed tables, one for each serial device found.
Each of these tables contains the serial device information accessible via the
following string indexed elements "path", "tid", "uptime", "driver",
"description".
Returns `nil` if no serial devices are found.
#### `tio.set{line=state, ...}`
Set state of one or multiple tty modem lines.
Line can be any of `DTR`, `RTS`, `CTS`, `DSR`, `CD`, `RI`
State is `high`, `low`, or `toggle`.
#### `tio.sleep(seconds)`
Sleep for seconds.
#### `tio.msleep(ms)`
Sleep for milliseconds.
#### `tio.alwaysecho`
A boolean value, defaults to `true`.
If `tio.alwaysecho` is `false`, the result of `tio.read`, `tio.readline` or
`tio.expect` will only be returned from the function and not logged or printed.
If `tio.alwaysecho` is set to `true`, reading functions also emit a single
timestamp to stdout and log file per `options.timestamp` and `options.log`.
## 4. Installation
### 4.1 Installation using package manager (Linux)
@ -508,12 +464,6 @@ $ pacman -S tio
The latest source releases can be found [here](https://github.com/tio/tio/releases).
Before running the install steps make sure you have glib and lua libraries installed. For example:
```
$ sudo apt install libglib2.0-dev liblua5.2-dev
```
Install steps:
```
$ meson setup build
@ -529,13 +479,9 @@ Note: The meson install steps may differ depending on your specific system.
Getting permission access errors trying to open your serial device?
Add your user to the group which allows serial device access permanently. For example, to add your user to the 'dialout' group do:
```bash
sudo usermod -a -G dialout <username>
Add your user to the group which allows serial device access. For example, to add your user to the 'dialout' group do:
```
Switch to the "dialout" group, temporary but immediately for this session.
```bash
newgrp dialout
$ sudo usermod -a -G dialout <username>
```

53
TODO
View file

@ -1,40 +1,3 @@
* Add release support for arm and x86 binary tarballs
* Support input and input mapping from lua scripts
* Add option to send file raw (no modem protocol)
* Add loopback option
Send received serial input back to output (for testing etc.)
* Add loopback support between two serial ports
Useful for traffic monitoring
* Add mapping feature for printing non-printable characters
* Porting layer to support native win32 builds.
Some of the work that needs to be done:
All posix functions need to be platform independent, go though file by file:
termios.h
unistd.h has very limited functions
ENV different in config_file_resolve
errno
sys/ioctl.h
sys/poll.h
socket, may need a new thread
Serial, RS485, character mapping
Communication pipe
Port enumerate, all devices of the same type have the same name (eg. USB
Serial Device for ttyACM) -> which makes regex not meaningful (kind of a
good thing since libtre in Mingw has too much dependencies makes binary too
big)
* Support traditional hex output format such as:
00000000 74 65 73 74 20 74 65 73 74 20 74 65 73 74 20 74 |test test test t|
@ -50,6 +13,22 @@
Already supported in hex output mode.
* Advanced line mode
Current line mode only support backspace editing. Would be nice with arrow
key navigation left/right and insert/overwrite support. Also history browsing
pressing up/down.
* Support for running external command
Add key command e.g. 'ctrl-t r' which prompts user to run external command.
The command will be run in a process which stdin/stdout is redirected to the
serial port.
This is the first step towards maybe also adding automatic support for
x/y/zmodem data transfer protocols by calling external programs such as
rb/sb, rx/sx, rz/sz, etc.
* Allow tio to connect to socket
After some more consideration I think it makes sense to support connecting to a

View file

@ -9,28 +9,28 @@
# $HOME/.config/tio/config
# $HOME/.tioconfig
[default]
# Defaults
baudrate = 115200
databits = 8
flow = none
stopbits = 1
parity = none
prefix-ctrl-key = t
output-delay = 0
output-line-delay = 0
auto-connect = direct
no-reconnect = false
local-echo = false
no-reconnect = disable
input-mode = normal
output-mode = normal
timestamp = false
log = false
log-append = false
log-strip = false
timestamp = disable
log = disable
log-append = disable
log-strip = disable
local-echo = disable
color = bold
rs-485 = false
rs-485 = disable
alert = none
script-run = always
prefix-ctrl-key = t
# Configuration profiles
@ -50,29 +50,25 @@ color = 10
[tincan]
baudrate = 9600
device = /dev/serial/by-id/usb-TinCanTools_Flyswatter2_FS20000-if00-port0
log = true
log = enable
log-file = tincan.log
log-strip = true
log-strip = enable
color = 11
[usb-devices]
pattern = ^usb([0-9]*)
device = /dev/ttyUSB%m1
[usb]
pattern = usb([0-9]*)
device = /dev/ttyUSB%s
color = 12
[rs-485-device]
device = /dev/ttyUSB0
rs-485 = true
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
[esp32]
device = /dev/ttyUSB0
color = 14
script = tio.set{DTR=high,RTS=low}; tio.msleep(100); tio.set{DTR=low,RTS=high}; tio.msleep(100); tio.set{RTS=low}
script = high(DTR); low(RTS); msleep(100); low(DTR); high(RTS); msleep(100); low(RTS)
script-run = always
[buspirate]
device = /dev/ttyACM0
map = INLCRNL,ODELBS
color = 15

View file

@ -13,13 +13,14 @@ local logins = {
},
}
local hostname = tio.expect("^(%g+) login:", 10)
if hostname then
local found, match_str = expect("\\w+- login:", 10)
if (1 == found) then
local hostname = string.match(match_str, "^%w+")
local login = logins[hostname]
if (nil ~= login) then
tio.write(login.username .. "\n")
tio.expect("Password:")
tio.write(login.password .. "\n")
send(login.username .. "\n")
expect("Password:")
send(login.password .. "\n")
else
io.write("\r\nDon't know login info for " .. hostname .. "\r\n")
end

View file

@ -1,5 +1,5 @@
tio.set{DTR=high, RTS=low}
tio.msleep(100)
tio.set{DTR=low, RTS=high}
tio.msleep(100)
tio.set{RTS=toggle}
set{DTR=high, RTS=low}
msleep(100)
set{DTR=low, RTS=high}
msleep(100)
set{RTS=toggle}

View file

@ -1,14 +0,0 @@
tio.read(1000, 6000) -- initial config
tio.write("\n")
tio.msleep(100)
tio.read(650, 60) -- main menu
tio.write("S") -- S menu
tio.msleep(30)
tio.read(650, 60)
tio.write("t") -- Parallel Value Table
tio.read(650, 60)
while true do
tio.msleep(1000)
tio.write("t")
tio.read(650, 50) -- repeat PVT forever
end

View file

@ -1,15 +0,0 @@
tio.read(1000, 8000) -- read initial config
tio.write("\n")
tio.read(650, 100) -- main menu
tio.write("S") -- S menu
repeat
str = tio.readline(25)
until str == nil
while true do
tio.write("t") -- query PV table
tio.msleep(880)
repeat
str = tio.readline(60)
tio.msleep(60)
until str == nil
end

View file

@ -1,6 +1,6 @@
io.write("Searching... ")
local device = tio.ttysearch()
local device = tty_search()
io.write("done\r\n")

View file

@ -148,10 +148,6 @@ Set timestamp format to any of the following timestamp formats:
24-hour format relative to previous timestamp
.IP "\fBiso8601"
ISO8601 format ("YYYY-MM-DDThh:mm:ss.sss")
.IP "\fBepoch"
Seconds since Unix epoch (1970-01-01)
.IP "\fBepoch-usec"
Seconds since Unix epoch (1970-01-01) with subdivision in microseconds
.PP
Default format is \fB24hour\fR
.RE
@ -169,7 +165,7 @@ Default value is 200.
.TP
.BR \-l ", " \-\-list
List available targets (serial devices, TIDs, configuration profiles).
List available serial devices.
.TP
.BR \-L ", " \-\-log
@ -177,8 +173,7 @@ List available targets (serial devices, TIDs, configuration profiles).
Enable log to file.
The log file will be automatically named using the following format
tio_TARGET_YYYY-MM-DDTHH:MM:SS.log. Target being the command line target such
as tty-device, tid, or configuration profile.
tio_DEVICE_YYYY-MM-DDTHH:MM:SS.log.
The filename can be manually set using the \-\-log-file option.
@ -205,8 +200,8 @@ Strip control characters and escape sequences from log.
.TP
.BR \-m ", " "\-\-map " \fI<flags>
Map (replace, translate) characters on input to the serial device or output
from the serial device. The following mapping flags are supported:
Map (replace, translate) characters on input or output. The following mapping
flags are supported:
.RS
.TP 12n
@ -220,10 +215,6 @@ Map FF to ESC-c on input
Map NL to CR on input
.IP "\fBINLCRNL"
Map NL to CR-NL on input
.IP "\fBICRCRNL"
Map CR to CR-NL on input
.IP "\fBIMSB2LSB"
Map MSB bit order to LSB on input
.IP "\fBOCRNL"
Map CR to NL on output
.IP "\fBODELBS"
@ -234,8 +225,8 @@ Map NL to CR-NL on output
Map lowercase characters to uppercase on output
.IP "\fBONULBRK"
Map nul (zero) to send break signal on output
.IP "\fBOIGNCR"
Ignore CR 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
@ -366,15 +357,6 @@ Run script on connect once, always, or never.
Default value is "always".
.TP
.BR "\-\-exec \fI<command>
Execute shell command with I/O redirected to device
.TP
.BR "\-\-complete-profiles
Prints profiles (for shell completion)
.TP
.BR \-v ", " \-\-version
@ -383,10 +365,10 @@ Display program version.
.BR \-h ", " \-\-help
Display help.
.SH "KEY COMMANDS"
.SH "KEYS"
.PP
.TP 16n
In session, all key strokes are forwarded to the serial device except the following key sequence: a prefix key (default: ctrl-t) followed by a command key. These sequences are intercepted as key commands:
In session, all key strokes are forwarded to the serial device except the following key sequence: a prefix key (default: ctrl-t) followed by a command key. These sequences are intercepted as tio commands:
.IP "\fBctrl-t ?"
List available key commands
.IP "\fBctrl-t b"
@ -408,7 +390,7 @@ Clear screen
.IP "\fBctrl-t L"
Show line states (DTR, RTS, CTS, DSR, DCD, RI)
.IP "\fBctrl-t m"
Change mapping of characters on input or output
Toggle MSB to LSB bit order
.IP "\fBctrl-t o"
Toggle output mode
.IP "\fBctrl-t p"
@ -417,12 +399,12 @@ Pulse serial port line
Quit
.IP "\fBctrl-t r"
Run script
.IP "\fBctrl-t R"
Execute shell command with I/O redirected to device
.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 x"
@ -436,41 +418,30 @@ Send ctrl-t character
.PP
Tio suppots Lua scripting to easily automate interaction with the tty device.
In addition to the standard Lua API tio makes the following functions
and variables available:
In addition to the Lua API tio makes the following functions available:
.TP 6n
.IP "\fBtio.expect(pattern, timeout)"
Waits for the Lua pattern to match or timeout before continuing.
.IP "\fBexpect(string, timeout)"
Expect string - waits for string to match or timeout before continueing.
Supports regular expressions. Special characters must be escaped with '\\\\'.
Timeout is in milliseconds, defaults to 0 meaning it will wait forever.
Returns the captures from the pattern or nil on timeout.
Returns 1 on successful match, 0 on timeout, or -1 on error.
.IP "\fBtio.read(size, timeout)"
Read up to size bytes from serial device. If timeout is 0 or not provided it
will wait forever until data is ready to read.
On successful match it also returns the match string as second return value.
Returns a string up to size bytes long on success and nil on timeout.
.IP "\fBsend(string)"
Send string.
.IP "\fBtio.readline(timeout)"
Read line from serial device. If timeout is 0 or not provided it will wait
forever until data is ready to read.
Returns number of bytes written on success or -1 on error.
Returns a string on success and nil on timeout. On timeout a partially read
line may be returned as a second return value.
.IP "\fBtio.write(string)"
Write string to serial device.
Returns the tio table.
.IP "\fBtio.send(file, protocol)"
.IP "\fBmodem_send(file, protocol)"
Send file using x/y-modem protocol.
Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM.
.IP "\fBtio.ttysearch()"
.IP "\fBtty_search()"
Search for serial devices.
Returns a table of number indexed tables, one for each serial device found.
@ -480,26 +451,25 @@ following string indexed elements "path", "tid", "uptime", "driver",
Returns nil if no serial devices are found.
.IP "\fBtio.set{line=state, ...}"
.IP "\fBread(size, timeout)"
Read from serial device. If timeout is 0 or not provided it will wait forever
until data is ready to read.
Returns number of bytes read on success, 0 on timeout, or -1 on error.
.IP "\fBset{line=state, ...}"
Set state of one or multiple tty modem lines.
Line can be any of DTR, RTS, CTS, DSR, CD, RI
State is high, low, or toggle.
.IP "\fBtio.sleep(seconds)"
.IP "\fBsleep(seconds)"
Sleep for seconds.
.IP "\fBtio.msleep(ms)"
Sleep for milliseconds.
.IP "\fBtio.alwaysecho"
A boolean value, defaults to true.
If tio.alwaysecho is false, the result of tio.read, tio.readline or tio.expect
will only be returned from the function and not logged or printed.
If tio.alwaysecho is set to true, reading functions also emit a single
timestamp to stdout and log file per options.timestamp and options.log.
.IP "\fBmsleep(ms)"
Sleep for miliseconds.
.IP "\fBexit(code)"
Exit with exit code.
.SH "CONFIGURATION FILE"
.PP
@ -598,12 +568,6 @@ Run script from string
Run script from file
.IP "\fBscript-run"
Run script on connect
.IP "\fBexec"
Execute shell command with I/O redirected to device
.PP
It is possible to include the content of other configuration files using the
include directive like so: "[include <file>]".
.SH "CONFIGURATION FILE EXAMPLES"
@ -613,7 +577,7 @@ To change the default configuration simply set options like so:
.RS
.nf
.eo
[default]
# Defaults
baudrate = 9600
databits = 8
parity = none
@ -649,14 +613,15 @@ Which is equivalent to:
$ tio -b 115200 -c 11 /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
.TP
A configuration profile can also be activated by its pattern which supports regular expressions:
A configuration profile can also be activated by its pattern which supports
regular expressions:
.RS
.nf
.eo
[usb-devices]
pattern = ^usb([0-9]*)
device = /dev/ttyUSB%m1
[usb device]
pattern = usb([0-9]*)
device = /dev/ttyUSB%s
baudrate = 115200
.ec
.fi
@ -668,12 +633,13 @@ Activate the configuration profile by pattern match:
$ tio usb12
.TP
Which becomes equivalent to:
Which is equivalent to:
$ tio -b 115200 /dev/ttyUSB12
.TP
It is also possible to combine use of configuration profile and command-line options. For example:
It is also possible to combine use of configuration profile and command-line
options. For example:
$ tio -l -t usb12
@ -726,9 +692,9 @@ expect -i $uart "prompt> "
.RE
.TP
It is also possible to use tio's own simpler expect/send script functionality to e.g. automate logins:
It is also possible to use the expect/send script functionality to e.g. automate logins:
$ tio --script 'tio.expect("login: "); tio.write("root\\n"); tio.expect("Password: "); tio.write("root\\n")' /dev/ttyUSB0
$ tio --script 'expect("login: "); send("root\\n"); expect("Password: "); send("root\\n")' /dev/ttyUSB0
.TP
Redirect device I/O to network file socket for remote TTY sharing:
@ -749,7 +715,7 @@ $ echo "ls -la" | tio /dev/serial/by\-id/usb\-FTDI_TTL232R-3V3_FTGQVXBL\-if00\-p
.TP
Pipe command to serial device and wait for line response within 1 second:
$ echo "*IDN?" | tio /dev/ttyACM0 --script "tio.expect('\\r\\n', 1000)" --mute
$ echo "*IDN?" | tio /dev/ttyACM0 --script "expect('\\r\\n', 1000)" --mute
.TP
.TP
@ -757,11 +723,6 @@ 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
Map NL to CR-NL on input from device and DEL to BS on output to device:
$ tio --map INLCRNL,ODELBS /dev/ttyUSB0
.TP
Enable RS-485 mode:
@ -770,7 +731,12 @@ $ tio --rs-485 --rs-485-config=RTS_ON_SEND=1,RX_DURING_TX /dev/ttyUSB0
.TP
Manipulate DTR and RTS lines upon first connect to reset connected microcontroller:
$ tio --script "tio.set{DTR=high,RTS=low}; tio.msleep(100); tio.set{RTS=toggle}" --script-run once /dev/ttyUSB0
$ tio --script "set{DTR=high,RTS=low}; msleep(100); set{RTS=toggle}" --script-run once /dev/ttyUSB0
.TP
Automatically log in to connected OS:
$ tio --script "expect('password:'); send('my_password\\n')" /dev/ttyUSB0
.SH "WEBSITE"
.PP

View file

@ -4,7 +4,7 @@ NAME
tio - a serial device I/O tool
SYNOPSIS
tio [<options>] <tty-device|profile|tid>
tio [<options>] <tty-device|sub-config>
DESCRIPTION
tio is a 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.
@ -114,10 +114,6 @@ OPTIONS
iso8601 ISO8601 format ("YYYY-MM-DDThh:mm:ss.sss")
epoch Seconds since Unix epoch (1970-01-01)
epoch-usec Seconds since Unix epoch (1970-01-01) with subdivision microseconds
Default format is 24hour
--timestamp-timeout <ms>
@ -130,13 +126,13 @@ OPTIONS
-l, --list
List available targets (serial devices, TIDs, configuration profiles).
List available serial devices.
-L, --log
Enable log to file.
The log file will be automatically named using the following format tio_TARGET_YYYY-MM-DDTHH:MM:SS.log. Target being the command line target such as tty-device, tid, or configuration profile.
The log file will be automatically named using the following format tio_DEVICE_YYYY-MM-DDTHH:MM:SS.log.
The filename can be manually set using the --log-file option.
@ -158,7 +154,7 @@ OPTIONS
-m, --map <flags>
Map (replace, translate) characters on input to the serial device or output from the serial device. The following mapping flags are supported:
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)
@ -170,10 +166,6 @@ OPTIONS
INLCRNL Map NL to CR-NL on input
ICRCRNL Map CR to CR-NL on input
IMSB2LSB Map MSB bit order to LSB on input
OCRNL Map CR to NL on output
ODELBS Map DEL to BS on output
@ -184,7 +176,7 @@ OPTIONS
ONULBRK Map nul (zero) to send break signal on output
OIGNCR Ignore CR on output
MSB2LSB Map MSB bit order to LSB on output
If defining more than one flag, the flags must be comma separated.
@ -200,13 +192,9 @@ OPTIONS
Default value is "normal".
--output-mode normal|hex|hexN
--output-mode normal|hex
Set output mode.
In hex mode each incoming byte is printed out as a 1 byte hex value.
In hexN mode, N is a number less than or equal to 4096 which defines how many hex values will be printed before a line break.
Set output mode. In hex mode each incoming byte is printed out as a 1 byte hex value.
Default value is "normal".
@ -222,8 +210,7 @@ OPTIONS
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 multi
plexed to the terminal and all connected clients.
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.
@ -285,14 +272,6 @@ OPTIONS
Default value is "always".
--exec <command>
Execute shell command with I/O redirected to device
--complete-profiles
Prints profiles (for shell completion)
-v, --version
Display program version.
@ -301,8 +280,8 @@ OPTIONS
Display help.
KEY COMMANDS
In session, all key strokes are forwarded to the serial device except the following key sequence: a prefix key (default: ctrl-t) followed by a command key. These sequences are intercepted as key commands:
KEYS
In session, all key strokes are forwarded to the serial device except the following key sequence: a prefix key (default: ctrl-t) followed by a command key. These sequences are intercepted as tio commands:
ctrl-t ? List available key commands
@ -324,7 +303,7 @@ KEY COMMANDS
ctrl-t L Show line states (DTR, RTS, CTS, DSR, DCD, RI)
ctrl-t m Change mapping of characters on input or output
ctrl-t m Toggle MSB to LSB bit order
ctrl-t o Toggle output mode
@ -334,12 +313,12 @@ KEY COMMANDS
ctrl-t r Run script
ctrl-t R Execute shell command with I/O redirected to device
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 x Send file using the XMODEM-1K or XMODEM-CRC protocol (prompts for file name and protocol)
@ -351,35 +330,19 @@ KEY COMMANDS
SCRIPT API
Tio suppots Lua scripting to easily automate interaction with the tty device.
In addition to the standard Lua API tio makes the following functions available:
In addition to the Lua API tio makes the following functions available:
expect(string, timeout)
Expect string - waits for string to match or timeout before continuing. Supports regular expressions. Special characters must be escaped with '\\'. Timeout is in milliseconds, defaults to 0 meaning it will wait forever.
Expect string - waits for string to match or timeout before continueing. Supports regular expressions. Special characters must be escaped with '\\'. Timeout is in milliseconds, defaults to 0 meaning it will wait forever.
Returns 1 on successful match, 0 on timeout, or -1 on error.
Returns 1 on successful match, 0 on timeout, or -1 on invalid regular expression.
On successful match it also returns the match string as second return value.
read(size, timeout)
Read up to size bytes from serial device. If timeout is 0 or not provided it will wait forever until data is ready to read.
send(string)
Send string.
Returns number of bytes read on success, 0 on timeout, or -1 on error.
On success, returns read string as second return value. Also emits a single timestamp to stdout and log file per options.timestamp and options.log.
read_line(timeout)
Read line from serial device. If timeout is 0 or not provided it will wait forever until data is ready to read.
Returns number of bytes read on success, 0 on timeout, or -1 on error.
On success, returns the string that was read as second return value. Also emits a single timestamp to stdout and log file per options.timestamp and options.log.
write(string)
Write string to serial device.
Returns number of bytes written on success or -1 on error.
send(file, protocol)
modem_send(file, protocol)
Send file using x/y-modem protocol.
Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM.
@ -387,26 +350,38 @@ SCRIPT API
tty_search()
Search for serial devices.
Returns a table of number indexed tables, one for each serial device found. Each of these tables contains the serial device information accessible via the following string indexed elements "path", "tid", "uptime", "dri
ver", "description".
Returns a table of number indexed tables, one for each serial device found. Each of these tables contains the serial device information accessible via the following string indexed elements "path", "tid", "uptime", "driver", "description".
Returns nil if no serial devices are found.
set{line=state, ...}
Set state of one or multiple tty modem lines.
exit(code)
Exit with exit code.
Line can be any of DTR, RTS, CTS, DSR, CD, RI
high(line)
Set tty line high.
State is high, low, or toggle.
low(line)
Set tty line low.
toggle(line)
Toggle the tty line.
sleep(seconds)
Sleep for seconds.
msleep(ms)
Sleep for milliseconds.
Sleep for miliseconds.
exit(code)
Exit with exit code.
config_high(line)
Set tty line state configuration to high.
config_low(line)
Set tty line state configuration to low.
apply_config()
Apply tty line state configuration. Using the line state configuration API instead of high()/low() will help to make the lines physically switch as simultaneously as possible. This may solve timing issues on some platforms.
Note: Line can be any of DTR, RTS, CTS, DSR, CD, RI
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:
@ -417,9 +392,9 @@ CONFIGURATION FILE
$HOME/.tioconfig
Labels can be used to group settings into named configuration profiles which can be activated from the command-line when starting tio.
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 configuration profile by name or by pattern to get the TTY device and other options.
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.
@ -493,14 +468,10 @@ CONFIGURATION FILE
script-run Run script on connect
exec Execute shell command with I/O redirected to device
It is possible to include the content of other configuration files using the include directive like so: "[include <file>]".
CONFIGURATION FILE EXAMPLES
To change the default configuration simply set options like so:
[default]
# Defaults
baudrate = 9600
databits = 8
parity = none
@ -508,14 +479,14 @@ CONFIGURATION FILE EXAMPLES
color = 10
line-pulse-duration = DTR=200,RTS=400
Named configuration profiles can be added via labels:
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 configuration profile by name:
Activate the sub-configuration by name:
$ tio rpi3
@ -523,22 +494,22 @@ CONFIGURATION FILE EXAMPLES
$ tio -b 115200 -c 11 /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
A configuration profile can also be activated by its pattern which supports regular expressions:
A sub-configuration can also be activated by its pattern which supports regular expressions:
[usb-devices]
pattern = ^usb([0-9]*)
device = /dev/ttyUSB%m1
[usb device]
pattern = usb([0-9]*)
device = /dev/ttyUSB%s
baudrate = 115200
Activate the configuration profile by pattern match:
Activate the sub-configuration by pattern match:
$ tio usb12
Which becomes equivalent to:
Which is equivalent to:
$ tio -b 115200 /dev/ttyUSB12
It is also possible to combine use of configuration profile and command-line options. For example:
It is also possible to combine use of sub-configuration and command-line options. For example:
$ tio -l -t usb12
@ -580,10 +551,6 @@ EXAMPLES
send -i $uart "ls -la\n"
expect -i $uart "prompt> "
It is also possible to use tio's own simpler expect/send script functionality to e.g. automate logins:
$ tio --script 'expect("login: "); write("root\n"); expect("Password: "); write("root\n")' /dev/ttyUSB0
Redirect device I/O to network file socket for remote TTY sharing:
$ tio --socket inet:4444 /dev/ttyUSB0
@ -604,17 +571,17 @@ EXAMPLES
$ cat data.bin | tio /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0
Map NL to CR-NL on input from device and DEL to BS on output to device:
$ tio --map INLCRNL,ODELBS /dev/ttyUSB0
Enable RS-485 mode:
$ tio --rs-485 --rs-485-config=RTS_ON_SEND=1,RX_DURING_TX /dev/ttyUSB0
Manipulate DTR and RTS lines upon first connect to reset connected microcontroller:
$ tio --script "set{DTR=high,RTS=low}; msleep(100); set{RTS=toggle}" --script-run once /dev/ttyUSB0
$ tio --script "high(DTR); low(RTS); msleep(100); toggle(DTR)" --script-run once /dev/ttyUSB0
Automatically log in to connected OS:
$ tio --script "expect('password:'); send('my_password\n')" /dev/ttyUSB0
WEBSITE
Visit https://tio.github.io
@ -622,4 +589,4 @@ WEBSITE
AUTHOR
Maintained by Martin Lund <martin.lund@keep-it-simple.com>.
tio 3.9 2025-04-13 tio(1)
tio 2.9 2024-04-14 tio(1)

View file

@ -1,12 +1,12 @@
project('tio', 'c',
version : '3.9',
license : 'GPL-2.0-or-later',
version : '3.0',
license : [ 'GPL-2'],
meson_version : '>= 0.53.2',
default_options : [ 'warning_level=2', 'buildtype=release', 'c_std=gnu99' ]
)
# The tag date of the project_version(), update when the version bumps.
version_date = '2025-04-13'
version_date = '2024-04-14'
# Test for dynamic baudrate configuration interface
compiler = meson.get_compiler('c')

View file

@ -19,10 +19,38 @@
* 02110-1301, USA.
*/
#include <stdio.h>
#include <unistd.h>
#include "options.h"
#include "alert.h"
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "error.h"
#include "print.h"
#include "options.h"
alert_t alert_option_parse(const char *arg)
{
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)
{
@ -81,3 +109,18 @@ void alert_disconnect(void)
break;
}
}
const char *alert_state_to_string(alert_t state)
{
switch (state)
{
case ALERT_NONE:
return "none";
case ALERT_BELL:
return "bell";
case ALERT_BLINK:
return "blink";
default:
return "Unknown";
}
}

View file

@ -29,5 +29,7 @@ typedef enum
ALERT_END,
} alert_t;
alert_t alert_option_parse(const char *arg);
void alert_connect(void);
void alert_disconnect(void);
const char *alert_state_to_string(alert_t state);

View file

@ -45,8 +45,6 @@ _tio()
--script \
--script-file \
--script-run \
--exec \
--complete-profiles \
-v --version \
-h --help"
@ -81,16 +79,60 @@ _tio()
COMPREPLY=( $(compgen -W "1 10 100" -- ${cur}) )
return 0
;;
--line-pulse-duration)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-a | --auto-connect)
COMPREPLY=( $(compgen -W "new latest none" -- ${cur}) )
return 0
;;
-n | --no-reconnect)
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-directory)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
--log-append)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
--log-strip)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-m | --map)
COMPREPLY=( $(compgen -W "ICRNL IGNCR INLCR IFFESCC INLCRNL ICRCRNL IMSB2LSB OCRNL ODELBS ONLCRNL OLTU ONULBRK OIGNCR" -- ${cur}) )
COMPREPLY=( $(compgen -W "ICRNL IGNCR INLCR IFFESCC 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 epoch epoch-usec" -- ${cur}) )
COMPREPLY=( $(compgen -W "24hour 24hour-start 24hour-delta iso8601" -- ${cur}) )
return 0
;;
--timestamp-timeout)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-L | --list)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-c | --color)
@ -109,6 +151,10 @@ _tio()
COMPREPLY=( $(compgen -W "normal hex" -- ${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
@ -117,10 +163,30 @@ _tio()
COMPREPLY=( $(compgen -W "none bell blink" -- ${cur}) )
return 0
;;
--mute)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
--script)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
--script-file)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
--script-run)
COMPREPLY=( $(compgen -W "once always never" -- ${cur}) )
return 0
;;
-v | --version)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
-h | --help)
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
;;
*)
;;
esac

File diff suppressed because it is too large Load diff

View file

@ -22,17 +22,7 @@
#pragma once
struct config_t
{
char *path;
char *active_group;
char *device;
};
extern struct config_t config;
void config_file_print(void);
void config_file_parse(void);
void config_exit(void);
void config_file_show_profiles(void);
void config_list_targets(void);

View file

@ -19,18 +19,22 @@
* 02110-1301, USA.
*/
#define _GNU_SOURCE // To access vasprintf
#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;
bool error_normal = true;
void switch_error_output_mode(void)
{
error_normal = false;
}
void error_enter_session_mode(void)
{

View file

@ -21,10 +21,6 @@
#pragma once
#include <stdbool.h>
extern bool error_normal;
#define TIO_SUCCESS 0
#define TIO_ERROR 1
@ -32,4 +28,3 @@ 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);
void switch_error_output_mode(void);

View file

@ -32,7 +32,7 @@
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
#include <poll.h>
#include <sys/poll.h>
#include <termios.h>
#include "error.h"
#include "print.h"
@ -150,7 +150,14 @@ char* fs_search_directory(const char *dir_path, const char *dirname)
// If it's a directory, check if it's the one we're looking for
if (strcmp(entry->d_name, dirname) == 0)
{
char *result = strndup(path, PATH_MAX);
char* result = malloc(strlen(path) + 1);
if (result == NULL)
{
// Error allocating memory
closedir(dir);
return NULL;
}
strcpy(result, path);
closedir(dir);
return result;
}
@ -171,20 +178,22 @@ char* fs_search_directory(const char *dir_path, const char *dirname)
return NULL;
}
#if defined(__linux__) && defined(STATX_BTIME)
// Function to return creation time of file
double fs_get_creation_time(const char *path)
{
struct statx stx;
int fd = open(path, O_RDONLY);
if (fd == -1)
{
// Error
return -1;
}
if (statx(fd, "", AT_EMPTY_PATH, STATX_ALL, &stx) != 0)
int ret = statx(fd, "", AT_EMPTY_PATH, STATX_ALL, &stx);
if (ret == -1)
{
// Error
close(fd);
return -1;
}
@ -194,33 +203,3 @@ double fs_get_creation_time(const char *path)
return stx.stx_btime.tv_sec + stx.stx_btime.tv_nsec / 1e9;
}
#elif defined(__APPLE__) || defined(__MACH__)
double fs_get_creation_time(const char *path)
{
struct stat st;
if (stat(path, &st) != 0)
{
return -1;
}
return st.st_mtimespec.tv_sec + st.st_mtimespec.tv_nsec / 1e9;
}
#else
double fs_get_creation_time(const char *path)
{
struct stat st;
if (stat(path, &st) != 0)
{
return -1;
}
return (double) st.st_ctime;
}
#endif

View file

@ -19,11 +19,20 @@
* 02110-1301, USA.
*/
#define _GNU_SOURCE // To access vasprintf
#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 <errno.h>
#include "options.h"
#include "print.h"
#include "error.h"
#include "fs.h"
#define IS_ESC_CSI_INTERMEDIATE_CHAR(c) ((c >= 0x20) && (c <= 0x3F))
@ -66,7 +75,7 @@ int log_open(const char *filename)
// If using 'new' or 'latest' autoconnect strategy we simply use strategy
// name to name autogenerated log name as device names may vary
asprintf(&automatic_filename, "tio_%s_%s.log",
option_auto_connect_state_to_string(option.auto_connect),
auto_connect_state_to_string(option.auto_connect),
date_time());
}
@ -222,7 +231,6 @@ void log_close(void)
if (fp != NULL)
{
fclose(fp);
tio_printf("Saved log to file %s", log_filename);
fp = NULL;
log_filename = NULL;
}
@ -232,6 +240,7 @@ void log_exit(void)
{
if ((option.log) && (log_filename != NULL))
{
tio_printf("Saved log to file %s", log_filename);
log_close();
}
}

View file

@ -19,11 +19,10 @@
* 02110-1301, USA.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "version.h"
#include "config.h"
#include "options.h"
#include "configfile.h"
#include "tty.h"
@ -61,10 +60,6 @@ int main(int argc, char *argv[])
/* Configure tty device */
tty_configure();
/* Disable line buffering in stdout. This is necessary if we
* want things like local echo to work correctly. */
setvbuf(stdout, NULL, _IONBF, 0);
/* Configure input terminal */
if (isatty(fileno(stdin)))
{
@ -76,9 +71,6 @@ int main(int argc, char *argv[])
interactive_mode = false;
}
/* Switch error output format */
switch_error_output_mode();
/* Configure output terminal */
if (isatty(fileno(stdout)))
{
@ -106,7 +98,7 @@ int main(int argc, char *argv[])
error_enter_session_mode();
/* Print launch hints */
tio_printf("tio %s", VERSION);
tio_printf("tio v%s", VERSION);
if (interactive_mode)
{
tio_printf("Press ctrl-%c q to quit", option.prefix_key);

View file

@ -1,10 +1,5 @@
# Generate version header
version_h = vcs_tag(command : ['git', 'describe', '--tags', '--always', '--dirty'],
input : 'version.h.in',
output :'version.h',
replace_string:'@VERSION@')
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)
@ -25,9 +20,7 @@ tio_sources = [
'alert.c',
'xymodem.c',
'script.c',
'fs.c',
'readline.c',
version_h
'fs.c'
]
@ -44,16 +37,13 @@ endif
tio_dep = [
dependency('threads', required: true),
dependency('glib-2.0', required: true),
dependency('inih', required: true,
fallback : ['libinih', 'inih_dep'],
default_options: ['default_library=static', 'distro_install=false']),
lua_dep
]
if host_machine.system() == 'darwin'
iokit_dep = dependency('appleframeworks', modules: ['IOKit'], required: true)
corefoundation_dep = dependency('appleframeworks', modules: ['CoreFoundation'], required: true)
tio_dep += [iokit_dep, corefoundation_dep]
endif
tio_c_args = ['-Wshadow','-Wno-unused-result']
tio_c_args = ['-Wno-unused-result']
if enable_setspeed2
tio_c_args += '-DHAVE_TERMIOS2'

View file

@ -19,15 +19,24 @@
* 02110-1301, USA.
*/
#define _GNU_SOURCE // For FNM_EXTMATCH
#include "config.h"
#include <ctype.h>
#include <dirent.h>
#include <regex.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <poll.h>
#include <sys/wait.h>
#include <fnmatch.h>
#include <regex.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
#include <sys/poll.h>
#include <termios.h>
#include <fnmatch.h>
#include "error.h"
#include "print.h"
#include "options.h"
void delay(long ms)
{
@ -44,6 +53,22 @@ void delay(long ms)
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'))
@ -121,9 +146,10 @@ unsigned long djb2_hash(const unsigned char *str)
}
// Function to encode a number to base62
void *base62_encode(unsigned long num, char *output)
char *base62_encode(unsigned long num)
{
const char base62_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
char *output = (char *) malloc(5); // 4 characters + null terminator
if (output == NULL)
{
tio_error_print("Memory allocation failed");
@ -171,11 +197,7 @@ bool match_patterns(const char *string, const char *patterns)
while (pattern != NULL)
{
// Check if the string matches the current pattern
#ifdef FNM_EXTMATCH
if (fnmatch(pattern, string, FNM_EXTMATCH) == 0)
#else
if (fnmatch(pattern, string, 0) == 0)
#endif
{
free(patterns_copy);
return true;
@ -188,66 +210,3 @@ bool match_patterns(const char *string, const char *patterns)
free(patterns_copy);
return false;
}
// Function that forks subprocess, redirects its stdin and stdout to the
// specified filedescriptor, and runs command.
int execute_shell_command(int fd, const char *command)
{
pid_t pid;
int status;
// Fork a child process
pid = fork();
if (pid == -1)
{
// Error occurred
tio_error_print("fork() failed (%s)", strerror(errno));
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
// Child process
tio_printf("Executing shell command '%s'", command);
// Redirect stdout and stderr to the file descriptor
if (dup2(fd, STDOUT_FILENO) == -1 || dup2(fd, STDERR_FILENO) == -1)
{
tio_error_print("dup2() failed (%s)", strerror(errno));
exit(EXIT_FAILURE);
}
// Execute the shell command
execl("/bin/sh", "sh", "-c", command, (char *)NULL);
// If execlp() returns, it means an error occurred
perror("execlp");
tio_error_print("execlp() failed (%s)", strerror(errno));
exit(EXIT_FAILURE);
}
else
{
// Parent process
// Wait for the child process to finish
waitpid(pid, &status, 0);
if (WIFEXITED(status))
{
tio_printf("Command exited with status %d", WEXITSTATUS(status));
return WEXITSTATUS(status);
}
else
{
tio_error_printf("Child process exited abnormally\n");
return -1;
}
}
return 0;
}
void clear_line()
{
print("\r\033[K");
}

View file

@ -27,12 +27,13 @@
#define UNUSED(expr) do { (void)(expr); } while (0)
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);
bool regex_match(const char *string, const char *pattern);
unsigned long djb2_hash(const unsigned char *str);
void *base62_encode(unsigned long num, char *output);
char *base62_encode(unsigned long num);
int read_poll(int fd, void *data, size_t len, int timeout);
double get_current_time(void);
bool match_patterns(const char *string, const char *patterns);
int execute_shell_command(int fd, const char *command);
void clear_line();

View file

@ -19,19 +19,28 @@
* 02110-1301, USA.
*/
#define _GNU_SOURCE // To access vasprintf
#include <assert.h>
#include <regex.h>
#include <getopt.h>
#include <errno.h>
#include "version.h"
#include "config.h"
#include <regex.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"
#include "configfile.h"
#include "script.h"
#define HEX_N_VALUE_MAX 4096
@ -58,7 +67,6 @@ enum opt_t
OPT_EXCLUDE_DEVICES,
OPT_EXCLUDE_DRIVERS,
OPT_EXCLUDE_TIDS,
OPT_EXEC,
};
/* Default options */
@ -67,9 +75,9 @@ struct option_t option =
.target = "",
.baudrate = 115200,
.databits = 8,
.flow = FLOW_NONE,
.flow = "none",
.stopbits = 1,
.parity = PARITY_NONE,
.parity = "none",
.output_delay = 0,
.output_line_delay = 0,
.dtr_pulse_duration = 100,
@ -88,6 +96,7 @@ struct option_t option =
.local_echo = false,
.timestamp = TIMESTAMP_NONE,
.socket = NULL,
.map = "",
.color = 256, // Bold
.input_mode = INPUT_MODE_NORMAL,
.output_mode = OUTPUT_MODE_NORMAL,
@ -110,23 +119,9 @@ struct option_t option =
.exclude_tids = NULL,
.hex_n_value = 0,
.vt100 = false,
.exec = NULL,
.map_i_nl_cr = false,
.map_i_cr_nl = false,
.map_ign_cr = false,
.map_i_ff_escc = false,
.map_i_nl_crnl = false,
.map_i_cr_crnl = false,
.map_o_cr_nl = false,
.map_o_nl_crnl = false,
.map_o_del_bs = false,
.map_o_ltu = false,
.map_o_nulbrk = false,
.map_i_msb2lsb = false,
.map_o_ign_cr = false,
};
void option_print_help(char *argv[])
void print_help(char *argv[])
{
UNUSED(argv);
@ -154,7 +149,7 @@ void option_print_help(char *argv[])
printf(" -t, --timestamp Enable line timestamp\n");
printf(" --timestamp-format <format> Set timestamp format (default: 24hour)\n");
printf(" --timestamp-timeout <ms> Set timestamp timeout (default: 200)\n");
printf(" -l, --list List available serial devices, TIDs, and profiles\n");
printf(" -l, --list List available serial devices\n");
printf(" -L, --log Enable log to file\n");
printf(" --log-file <filename> Set log filename\n");
printf(" --log-directory <path> Set log directory path for automatic named logs\n");
@ -170,298 +165,15 @@ void option_print_help(char *argv[])
printf(" --script <string> Run script from string\n");
printf(" --script-file <filename> Run script from file\n");
printf(" --script-run once|always|never Run script on connect (default: always)\n");
printf(" --exec <command> Execute shell command with I/O redirected to device\n");
printf(" --complete-profiles Prints profiles (for shell completion)\n");
printf(" -v, --version Display version\n");
printf(" -h, --help Display help\n");
printf("\n");
printf("Options and profiles may be set via configuration file.\n");
printf("\n");
printf("In session you can press ctrl-%c ? to list available key commands.\n", option.prefix_key);
printf("\n");
printf("See the man page for more details.\n");
}
int option_string_to_integer(const char *string, int *value, const char *desc, int min, int max)
{
int val;
char *end_token;
errno = 0;
val = strtol(string, &end_token, 10);
if ((errno != 0) || (*end_token != 0))
{
if (desc != NULL)
{
tio_error_print("Invalid %s '%s'", desc, string);
exit(EXIT_FAILURE);
}
else
{
tio_error_print("Invalid digit '%s'", string);
exit(EXIT_FAILURE);
}
return -1;
}
else
{
if ((val < min) || (val > max))
{
if (desc != NULL)
{
tio_error_print("Invalid %s '%s'", desc, string);
exit(EXIT_FAILURE);
}
else
{
tio_error_print("Invalid digit '%s'", string);
exit(EXIT_FAILURE);
}
return -1;
}
else
{
*value = val;
}
}
return 0;
}
void option_parse_flow(const char *arg, flow_t *flow)
{
assert(arg != NULL);
/* Parse flow control */
if (strcmp("hard", arg) == 0)
{
*flow = FLOW_HARD;
}
else if (strcmp("soft", arg) == 0)
{
*flow = FLOW_SOFT;
}
else if (strcmp("none", arg) == 0)
{
*flow = FLOW_NONE;
}
else
{
tio_error_print("Invalid flow control '%s'", arg);
exit(EXIT_FAILURE);
}
}
const char *option_flow_to_string(flow_t flow)
{
switch (flow)
{
case FLOW_NONE:
return "none";
case FLOW_HARD:
return "hard";
case FLOW_SOFT:
return "soft";
default:
return "unknown";
}
}
void option_parse_parity(const char *arg, parity_t *parity)
{
assert(arg != NULL);
if (strcmp("none", arg) == 0)
{
*parity = PARITY_NONE;
}
else if (strcmp("odd", arg) == 0)
{
*parity = PARITY_ODD;
}
else if (strcmp("even", arg) == 0)
{
*parity = PARITY_EVEN;
}
else if (strcmp("mark", arg) == 0)
{
*parity = PARITY_MARK;
}
else if (strcmp("space", arg) == 0)
{
*parity = PARITY_SPACE;
}
else
{
tio_error_print("Invalid parity '%s'", arg);
exit(EXIT_FAILURE);
}
}
const char *option_parity_to_string(parity_t parity)
{
switch (parity)
{
case PARITY_NONE:
return "none";
case PARITY_ODD:
return "odd";
case PARITY_EVEN:
return "even";
case PARITY_MARK:
return "mark";
case PARITY_SPACE:
return "space";
default:
return "unknown";
}
}
void option_parse_color(const char *arg, int *color)
{
int value;
assert(arg != NULL);
if (strcmp(optarg, "list") == 0)
{
// 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(arg, "none") == 0)
{
*color = -1; // No color
}
else if (strcmp(arg, "bold") == 0)
{
*color = 256; // Bold
}
else
{
if (option_string_to_integer(arg, &value, "color code", 0, 255) == 0)
{
*color = value;
}
}
}
void option_parse_alert(const char *arg, alert_t *alert)
{
assert(arg != NULL);
if (strcmp(arg, "none") == 0)
{
*alert = ALERT_NONE;
}
else if (strcmp(arg, "bell") == 0)
{
*alert = ALERT_BELL;
}
else if (strcmp(arg, "blink") == 0)
{
*alert = ALERT_BLINK;
}
else
{
tio_error_print("Invalid alert '%s'", arg);
exit(EXIT_FAILURE);
}
}
const char* option_timestamp_format_to_string(timestamp_t timestamp)
{
switch (timestamp)
{
case TIMESTAMP_NONE:
return "none";
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;
case TIMESTAMP_EPOCH:
return "epoch";
break;
case TIMESTAMP_EPOCH_USEC:
return "epoch-usec";
break;
default:
return "unknown";
break;
}
}
void option_parse_timestamp(const char *arg, timestamp_t *timestamp)
{
assert(arg != NULL);
if (strcmp(arg, "24hour") == 0)
{
*timestamp = TIMESTAMP_24HOUR;
}
else if (strcmp(arg, "24hour-start") == 0)
{
*timestamp = TIMESTAMP_24HOUR_START;
}
else if (strcmp(arg, "24hour-delta") == 0)
{
*timestamp = TIMESTAMP_24HOUR_DELTA;
}
else if (strcmp(arg, "iso8601") == 0)
{
*timestamp = TIMESTAMP_ISO8601;
}
else if (strcmp(arg, "epoch") == 0)
{
*timestamp = TIMESTAMP_EPOCH;
}
else if (strcmp(arg, "epoch-usec") == 0)
{
*timestamp = TIMESTAMP_EPOCH_USEC;
}
else
{
tio_error_print("Invalid timestamp '%s'", arg);
exit(EXIT_FAILURE);
}
}
const char *option_alert_state_to_string(alert_t state)
{
switch (state)
{
case ALERT_NONE:
return "none";
case ALERT_BELL:
return "bell";
case ALERT_BLINK:
return "blink";
default:
return "unknown";
}
}
const char *option_auto_connect_state_to_string(auto_connect_t strategy)
const char *auto_connect_state_to_string(auto_connect_t strategy)
{
switch (strategy)
{
@ -472,44 +184,39 @@ const char *option_auto_connect_state_to_string(auto_connect_t strategy)
case AUTO_CONNECT_LATEST:
return "latest";
default:
return "unknown";
return "Unknown";
}
}
void option_parse_auto_connect(const char *arg, auto_connect_t *auto_connect)
auto_connect_t auto_connect_option_parse(const char *arg)
{
assert(arg != NULL);
auto_connect_t auto_connect = option.auto_connect; // Default
if (arg != NULL)
{
if (strcmp(arg, "direct") == 0)
{
*auto_connect = AUTO_CONNECT_DIRECT;
return AUTO_CONNECT_DIRECT;
}
else if (strcmp(arg, "new") == 0)
{
*auto_connect = AUTO_CONNECT_NEW;
return AUTO_CONNECT_NEW;
}
else if (strcmp(arg, "latest") == 0)
{
*auto_connect = AUTO_CONNECT_LATEST;
}
else
{
tio_error_print("Invalid auto-connect strategy '%s'", arg);
exit(EXIT_FAILURE);
}
return AUTO_CONNECT_LATEST;
}
}
void option_parse_line_pulse_duration(const char *arg)
return auto_connect;
}
void line_pulse_duration_option_parse(const char *arg)
{
bool token_found = true;
char *token = NULL;
char *buffer = strdup(arg);
assert(arg != NULL);
while (token_found == true)
{
if (token == NULL)
@ -552,11 +259,6 @@ void option_parse_line_pulse_duration(const char *arg)
{
option.ri_pulse_duration = value;
}
else
{
tio_error_print("Invalid line '%s'", keyname);
exit(EXIT_FAILURE);
}
}
else
{
@ -572,7 +274,7 @@ void option_parse_line_pulse_duration(const char *arg)
}
// Function to parse the input string
int option_parse_hexN_string(const char *input_string)
int parse_hexN_string(const char *input_string)
{
regmatch_t match[2]; // One for entire match, one for the optional N
int n_value = 0;
@ -583,7 +285,7 @@ int option_parse_hexN_string(const char *input_string)
ret = regcomp(&regex, "^hex([0-9]+)?$", REG_EXTENDED);
if (ret)
{
tio_error_print("Could not compile regex");
tio_error_printf("Could not compile regex\n");
exit(EXIT_FAILURE);
}
@ -617,7 +319,7 @@ int option_parse_hexN_string(const char *input_string)
{
char msgbuf[100];
regerror(ret, &regex, msgbuf, sizeof(msgbuf));
tio_error_print("Regex match failed: %s", msgbuf);
tio_error_printf("Regex match failed: %s\n", msgbuf);
exit(EXIT_FAILURE);
}
@ -626,52 +328,48 @@ int option_parse_hexN_string(const char *input_string)
return n_value;
}
void option_parse_input_mode(const char *arg, input_mode_t *mode)
input_mode_t input_mode_option_parse(const char *arg)
{
assert(arg != NULL);
if (strcmp("normal", arg) == 0)
{
*mode = INPUT_MODE_NORMAL;
return INPUT_MODE_NORMAL;
}
else if (strcmp("hex", arg) == 0)
{
*mode = INPUT_MODE_HEX;
return INPUT_MODE_HEX;
}
else if (strcmp("line", arg) == 0)
{
*mode = INPUT_MODE_LINE;
return INPUT_MODE_LINE;
}
else
{
tio_error_print("Invalid input mode '%s'", arg);
tio_error_printf("Invalid input mode option");
exit(EXIT_FAILURE);
}
}
void option_parse_output_mode(const char *arg, output_mode_t *mode)
output_mode_t output_mode_option_parse(const char *arg)
{
int n = 0;
assert(arg != NULL);
if (strcmp("normal", arg) == 0)
{
*mode = OUTPUT_MODE_NORMAL;
return OUTPUT_MODE_NORMAL;
}
else if ((n = option_parse_hexN_string(arg)) != -1)
else if ((n = parse_hexN_string(arg)) != -1)
{
option.hex_n_value = n;
*mode = OUTPUT_MODE_HEX;
return OUTPUT_MODE_HEX;
}
else
{
tio_error_print("Invalid output mode '%s'", arg);
tio_error_printf("Invalid output mode option");
exit(EXIT_FAILURE);
}
}
const char *option_input_mode_to_string(input_mode_t mode)
const char *input_mode_by_string(input_mode_t mode)
{
switch (mode)
{
@ -688,7 +386,7 @@ const char *option_input_mode_to_string(input_mode_t mode)
return NULL;
}
const char *option_output_mode_to_string(output_mode_t mode)
const char *output_mode_by_string(output_mode_t mode)
{
switch (mode)
{
@ -703,145 +401,55 @@ const char *option_output_mode_to_string(output_mode_t mode)
return NULL;
}
void option_parse_script_run(const char *arg, script_run_t *script_run)
script_run_t script_run_option_parse(const char *arg)
{
assert(arg != NULL);
if (strcmp("once", arg) == 0)
{
*script_run = SCRIPT_RUN_ONCE;
return SCRIPT_RUN_ONCE;
}
else if (strcmp("always", arg) == 0)
{
*script_run = SCRIPT_RUN_ALWAYS;
return SCRIPT_RUN_ALWAYS;
}
else if (strcmp("never", arg) == 0)
{
*script_run = SCRIPT_RUN_NEVER;
return SCRIPT_RUN_NEVER;
}
else
{
tio_error_print("Invalid script run option '%s'", arg);
tio_error_printf("Invalid script run option");
exit(EXIT_FAILURE);
}
}
void option_parse_mappings(const char *map)
{
bool token_found = true;
char *token = NULL;
char *buffer;
if (map == NULL)
{
return;
}
/* Parse any specified input or output mappings */
buffer = strdup(map);
while (token_found == true)
{
if (token == NULL)
{
token = strtok(buffer,",");
}
else
{
token = strtok(NULL, ",");
}
if (token != NULL)
{
if (strcmp(token,"INLCR") == 0)
{
option.map_i_nl_cr = true;
}
else if (strcmp(token,"IGNCR") == 0)
{
option.map_ign_cr = true;
}
else if (strcmp(token,"ICRNL") == 0)
{
option.map_i_cr_nl = true;
}
else if (strcmp(token,"OCRNL") == 0)
{
option.map_o_cr_nl = true;
}
else if (strcmp(token,"ODELBS") == 0)
{
option.map_o_del_bs = true;
}
else if (strcmp(token,"IFFESCC") == 0)
{
option.map_i_ff_escc = true;
}
else if (strcmp(token,"INLCRNL") == 0)
{
option.map_i_nl_crnl = true;
}
else if (strcmp(token,"ICRCRNL") == 0)
{
option.map_i_cr_crnl = true;
}
else if (strcmp(token, "ONLCRNL") == 0)
{
option.map_o_nl_crnl = true;
}
else if (strcmp(token, "OLTU") == 0)
{
option.map_o_ltu = true;
}
else if (strcmp(token, "ONULBRK") == 0)
{
option.map_o_nulbrk = true;
}
else if (strcmp(token, "OIGNCR") == 0)
{
option.map_o_ign_cr = true;
}
else if (strcmp(token, "IMSB2LSB") == 0)
{
option.map_i_msb2lsb = true;
}
else
{
printf("Error: Unknown mapping flag %s\n", token);
exit(EXIT_FAILURE);
}
}
else
{
token_found = false;
}
}
free(buffer);
}
void options_print()
{
tio_printf(" Device: %s", device_name);
tio_printf(" Baudrate: %u", option.baudrate);
tio_printf(" Databits: %d", option.databits);
tio_printf(" Flow: %s", option_flow_to_string(option.flow));
tio_printf(" Flow: %s", option.flow);
tio_printf(" Stopbits: %d", option.stopbits);
tio_printf(" Parity: %s", option_parity_to_string(option.parity));
tio_printf(" Local echo: %s", option.local_echo ? "true" : "false");
tio_printf(" Timestamp: %s", option_timestamp_format_to_string(option.timestamp));
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(" Timestamp timeout: %u", option.timestamp_timeout);
tio_printf(" Output delay: %d", option.output_delay);
tio_printf(" Output line delay: %d", option.output_line_delay);
tio_printf(" Automatic connect strategy: %s", option_auto_connect_state_to_string(option.auto_connect));
tio_printf(" Automatic reconnect: %s", option.no_reconnect ? "true" : "false");
tio_printf(" Automatic connect strategy: %s", auto_connect_state_to_string(option.auto_connect));
tio_printf(" Automatic reconnect: %s", option.no_reconnect ? "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(" Input mode: %s", option_input_mode_to_string(option.input_mode));
tio_printf(" Output mode: %s", option_output_mode_to_string(option.output_mode));
tio_printf(" Alert: %s", option_alert_state_to_string(option.alert));
tio_printf(" Input mode: %s", input_mode_by_string(option.input_mode));
tio_printf(" Output mode: %s", output_mode_by_string(option.output_mode));
tio_printf(" Alert: %s", alert_state_to_string(option.alert));
if (option.map[0] != 0)
{
tio_printf(" Map flags: %s", option.map);
}
if (option.log)
{
tio_printf(" Log file: %s", log_get_filename());
@ -849,8 +457,8 @@ void options_print()
{
tio_printf(" Log file directory: %s", option.log_directory);
}
tio_printf(" Log append: %s", option.log_append ? "true" : "false");
tio_printf(" Log strip: %s", option.log_strip ? "true" : "false");
tio_printf(" Log append: %s", option.log_append ? "enabled" : "disabled");
tio_printf(" Log strip: %s", option.log_strip ? "enabled" : "disabled");
}
if (option.socket)
{
@ -869,7 +477,7 @@ void options_parse(int argc, char *argv[])
if (argc == 1)
{
option_print_help(argv);
print_help(argv);
exit(EXIT_SUCCESS);
}
@ -926,7 +534,6 @@ void options_parse(int argc, char *argv[])
{"script", required_argument, 0, OPT_SCRIPT },
{"script-file", required_argument, 0, OPT_SCRIPT_FILE },
{"script-run", required_argument, 0, OPT_SCRIPT_RUN },
{"exec", required_argument, 0, OPT_EXEC },
{"version", no_argument, 0, 'v' },
{"help", no_argument, 0, 'h' },
{"complete-profiles", no_argument, 0, OPT_COMPLETE_PROFILES },
@ -956,39 +563,39 @@ void options_parse(int argc, char *argv[])
break;
case 'b':
option_string_to_integer(optarg, &option.baudrate, "baudrate", 0, INT_MAX);
option.baudrate = string_to_long(optarg);
break;
case 'd':
option_string_to_integer(optarg, &option.databits, "databits", 5, 8);
option.databits = string_to_long(optarg);
break;
case 'f':
option_parse_flow(optarg, &option.flow);
option.flow = optarg;
break;
case 's':
option_string_to_integer(optarg, &option.stopbits, "stopbits", 1, 2);
option.stopbits = string_to_long(optarg);
break;
case 'p':
option_parse_parity(optarg, &option.parity);
option.parity = optarg;
break;
case 'o':
option_string_to_integer(optarg, &option.output_delay, "output delay", 0, INT_MAX);
option.output_delay = string_to_long(optarg);
break;
case 'O':
option_string_to_integer(optarg, &option.output_line_delay, "output line delay", 0, INT_MAX);
option.output_line_delay = string_to_long(optarg);
break;
case OPT_LINE_PULSE_DURATION:
option_parse_line_pulse_duration(optarg);
line_pulse_duration_option_parse(optarg);
break;
case 'a':
option_parse_auto_connect(optarg, &option.auto_connect);
option.auto_connect = auto_connect_option_parse(optarg);
break;
case OPT_EXCLUDE_DEVICES:
@ -1012,18 +619,15 @@ void options_parse(int argc, char *argv[])
break;
case 't':
if (option.timestamp == TIMESTAMP_NONE)
{
option.timestamp = TIMESTAMP_24HOUR;
}
break;
case OPT_TIMESTAMP_FORMAT:
option_parse_timestamp(optarg, &option.timestamp);
option.timestamp = timestamp_option_parse(optarg);
break;
case OPT_TIMESTAMP_TIMEOUT:
option_string_to_integer(optarg, &option.timestamp_timeout, "timestamp timeout", 0, INT_MAX);
option.timestamp_timeout = string_to_long(optarg);
break;
case 'L':
@ -1032,7 +636,6 @@ void options_parse(int argc, char *argv[])
case 'l':
list_serial_devices();
config_list_targets();
exit(EXIT_SUCCESS);
break;
@ -1057,19 +660,45 @@ void options_parse(int argc, char *argv[])
break;
case 'm':
option_parse_mappings(optarg);
option.map = optarg;
break;
case 'c':
option_parse_color(optarg, &option.color);
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 OPT_INPUT_MODE:
option_parse_input_mode(optarg, &option.input_mode);
option.input_mode = input_mode_option_parse(optarg);
break;
case OPT_OUTPUT_MODE:
option_parse_output_mode(optarg, &option.output_mode);
option.output_mode = output_mode_option_parse(optarg);
break;
case OPT_RS485:
@ -1081,7 +710,7 @@ void options_parse(int argc, char *argv[])
break;
case OPT_ALERT:
option_parse_alert(optarg, &option.alert);
option.alert = alert_option_parse(optarg);
break;
case OPT_MUTE:
@ -1097,20 +726,16 @@ void options_parse(int argc, char *argv[])
break;
case OPT_SCRIPT_RUN:
option_parse_script_run(optarg, &option.script_run);
break;
case OPT_EXEC:
option.exec = optarg;
option.script_run = script_run_option_parse(optarg);
break;
case 'v':
printf("tio %s\n", VERSION);
printf("tio v%s\n", VERSION);
exit(EXIT_SUCCESS);
break;
case 'h':
option_print_help(argv);
print_help(argv);
exit(EXIT_SUCCESS);
break;
@ -1150,7 +775,7 @@ void options_parse(int argc, char *argv[])
if (strlen(option.target) == 0)
{
tio_error_print("Missing tty device, profile or topology ID");
tio_error_printf("Missing tty device, profile or topology ID");
exit(EXIT_FAILURE);
}
@ -1169,6 +794,9 @@ void options_parse(int argc, char *argv[])
void options_parse_final(int argc, char *argv[])
{
/* Preserve target which may have been set by configuration file */
const char *target = option.target;
/* Do 2nd pass to override settings set by configuration file */
optind = 1; // Reset option index to restart scanning of argv
options_parse(argc, argv);
@ -1176,13 +804,16 @@ void options_parse_final(int argc, char *argv[])
#ifdef __CYGWIN__
unsigned char portnum;
char *tty_win;
if ( ((strncmp("COM", option.target, 3) == 0)
|| (strncmp("com", option.target, 3) == 0) )
&& (sscanf(option.target + 3, "%hhu", &portnum) == 1)
if ( ((strncmp("COM", target, 3) == 0)
|| (strncmp("com", target, 3) == 0) )
&& (sscanf(target + 3, "%hhu", &portnum) == 1)
&& (portnum > 0) )
{
asprintf(&tty_win, "/dev/ttyS%hhu", portnum - 1);
option.target = tty_win;
target = tty_win;
}
#endif
/* Restore target */
option.target = target;
}

View file

@ -23,6 +23,9 @@
#include <stdint.h>
#include <stdbool.h>
#include <limits.h>
#include <termios.h>
#include <sys/param.h>
#include "script.h"
#include "timestamp.h"
#include "alert.h"
@ -46,20 +49,20 @@ typedef enum
/* Options */
struct option_t
{
char *target;
int baudrate;
const char *target;
unsigned int baudrate;
int databits;
flow_t flow;
char *flow;
int stopbits;
parity_t parity;
char *parity;
int output_delay;
int output_line_delay;
int dtr_pulse_duration;
int rts_pulse_duration;
int cts_pulse_duration;
int dsr_pulse_duration;
int dcd_pulse_duration;
int ri_pulse_duration;
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_reconnect;
auto_connect_t auto_connect;
bool log;
@ -67,14 +70,15 @@ struct option_t
bool log_strip;
bool local_echo;
timestamp_t timestamp;
char *log_filename;
char *log_directory;
char *socket;
const char *log_filename;
const char *log_directory;
const char *map;
const char *socket;
int color;
input_mode_t input_mode;
output_mode_t output_mode;
char prefix_code;
char prefix_key;
unsigned char prefix_code;
unsigned char prefix_key;
bool prefix_enabled;
bool mute;
bool rs485;
@ -83,29 +87,15 @@ struct option_t
int32_t rs485_delay_rts_after_send;
alert_t alert;
bool complete_profiles;
char *script;
char *script_filename;
const char *script;
const char *script_filename;
script_run_t script_run;
int timestamp_timeout;
char *exclude_devices;
char *exclude_drivers;
char *exclude_tids;
unsigned int timestamp_timeout;
const char *exclude_devices;
const char *exclude_drivers;
const char *exclude_tids;
int hex_n_value;
bool vt100;
char *exec;
bool map_i_nl_cr;
bool map_i_cr_nl;
bool map_ign_cr;
bool map_i_ff_escc;
bool map_i_nl_crnl;
bool map_i_cr_crnl;
bool map_o_cr_nl;
bool map_o_nl_crnl;
bool map_o_del_bs;
bool map_o_ltu;
bool map_o_nulbrk;
bool map_i_msb2lsb;
bool map_o_ign_cr;
};
extern struct option_t option;
@ -114,22 +104,10 @@ void options_print();
void options_parse(int argc, char *argv[]);
void options_parse_final(int argc, char *argv[]);
int option_string_to_integer(const char *string, int *value, const char *desc, int min, int max);
void line_pulse_duration_option_parse(const char *arg);
script_run_t script_run_option_parse(const char *arg);
void option_parse_flow(const char *arg, flow_t *flow);
void option_parse_parity(const char *arg, parity_t *parity);
void option_parse_output_mode(const char *arg, output_mode_t *mode);
void option_parse_input_mode(const char *arg, input_mode_t *mode);
void option_parse_line_pulse_duration(const char *arg);
void option_parse_script_run(const char *arg, script_run_t *script_run);
void option_parse_alert(const char *arg, alert_t *alert);
void option_parse_auto_connect(const char *arg, auto_connect_t *auto_connect);
const char *option_auto_connect_state_to_string(auto_connect_t strategy);
void option_parse_timestamp(const char *arg, timestamp_t *timestamp);
const char* option_timestamp_format_to_string(timestamp_t timestamp);
void option_parse_mappings(const char *map);
input_mode_t input_mode_option_parse(const char *arg);
output_mode_t output_mode_option_parse(const char *arg);
auto_connect_t auto_connect_option_parse(const char *arg);
const char *auto_connect_state_to_string(auto_connect_t strategy);

View file

@ -19,6 +19,11 @@
* 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;
@ -75,38 +80,3 @@ void print_tainted_set()
{
print_tainted = true;
}
void print(const char *format, ...)
{
va_list args;
va_start(args, format);
vprintf(format, args);
fflush(stdout);
va_end(args);
print_tainted = true;
}
void print_padded(char *string, size_t length, char pad_char)
{
size_t padding = 0;
size_t string_length = 0;
size_t i;
string_length = strlen(string);
if (string_length < length)
{
padding += length - string_length;
printf("%s", string);
for (i=0; i<padding; i++)
{
putchar(pad_char);
}
}
else
{
printf("%s", string);
}
}

View file

@ -23,6 +23,7 @@
#include <stdio.h>
#include <stdbool.h>
#include "misc.h"
#include "error.h"
#include "options.h"
#include "timestamp.h"
@ -86,18 +87,10 @@ extern char ansi_format[];
{ \
if (print_tainted) \
putchar('\n'); \
if (option.color < 0) { \
if (error_normal) \
fprintf (stderr, "Error: " format "\n", ## args); \
if (option.color < 0) \
fprintf (stdout, "\r[%s] Error: " format "\r\n", timestamp_current_time(), ## args); \
else \
fprintf (stderr, "\r[%s] Error: " format "\r\n", timestamp_current_time(), ## args); \
} \
else { \
if (error_normal) \
{ ansi_error_printf("Error: " format, ## args); }\
else \
{ ansi_error_printf("[%s] Error: " format, timestamp_current_time(), ## args); }\
} \
ansi_printf("[%s] Error: " format, timestamp_current_time(), ## args); \
print_tainted = false; \
} \
}
@ -134,10 +127,8 @@ extern char ansi_format[];
#define tio_debug_printf_raw(format, args...)
#endif
void print(const char *format, ...);
void print_hex(char c);
void print_normal(char c);
void print_init_ansi_formatting(void);
void tio_printf_array(const char *array);
void print_tainted_set(void);
void print_padded(char *string, size_t length, char pad_char);

View file

@ -1,276 +0,0 @@
/*
* tio - a serial device I/O tool
*
* Copyright (c) 2014-2024 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 "print.h"
#include "misc.h"
#define RL_LINE_LENGTH_MAX PATH_MAX
#define RL_HISTORY_MAX 1000
static char rl_line[RL_LINE_LENGTH_MAX] = {};
static char *rl_history[RL_HISTORY_MAX];
static int rl_history_count = 0;
static int rl_history_index = 0;
static int rl_line_length = 0;
static int rl_cursor_pos = 0;
static int rl_escape = 0;
static void print_line(const char *string, int cursor_pos)
{
clear_line();
print("%s", string);
print("\r"); // Move the cursor back to the beginning
for (int i = 0; i < cursor_pos; ++i)
{
print("\x1b[C"); // Move the cursor right
}
}
void readline_init(void)
{
rl_history_count = 0;
rl_history_index = 0;
for (int i = 0; i < RL_HISTORY_MAX; ++i)
{
rl_history[i] = NULL;
}
rl_line[0] = 0;
rl_line_length = 0;
rl_cursor_pos = 0;
rl_escape = 0;
}
char * readline_get(void)
{
return rl_line;
}
static void readline_input_char(char input_char)
{
if (rl_line_length < RL_LINE_LENGTH_MAX - 1)
{
memmove(&rl_line[rl_cursor_pos + 1], &rl_line[rl_cursor_pos], rl_line_length - rl_cursor_pos);
rl_line[rl_cursor_pos] = input_char;
rl_line_length++;
rl_cursor_pos++;
rl_line[rl_line_length] = '\0';
print_line(rl_line, rl_cursor_pos);
}
rl_escape = 0;
}
static void readline_input_cr(void)
{
if (rl_line_length > 0)
{
// Save to history
if (rl_history_count < RL_HISTORY_MAX)
{
rl_history[rl_history_count] = strndup(rl_line, rl_line_length);
rl_history_count++;
}
else
{
free(rl_history[0]);
memmove(&rl_history[0], &rl_history[1], (RL_HISTORY_MAX - 1) * sizeof(char*));
rl_history[RL_HISTORY_MAX - 1] = strndup(rl_line, rl_line_length);
}
}
rl_line[rl_line_length] = '\0';
if (option.local_echo == false)
{
clear_line();
}
else
{
print("\r\n");
}
rl_line_length = 0;
rl_cursor_pos = 0;
rl_history_index = rl_history_count;
rl_escape = 0;
}
static void readline_input_bs(void)
{
if (rl_cursor_pos > 0)
{
memmove(&rl_line[rl_cursor_pos - 1], &rl_line[rl_cursor_pos], rl_line_length - rl_cursor_pos);
rl_line_length--;
rl_cursor_pos--;
rl_line[rl_line_length] = '\0';
print_line(rl_line, rl_cursor_pos);
}
rl_escape = 0;
}
static void readline_input_escape(void)
{
rl_escape = 1;
}
static void readline_input_left_bracket(void)
{
if (rl_escape == 1)
{
rl_escape = 2;
}
else
{
rl_escape = 0;
}
}
static void readline_input_A(void)
{
if (rl_escape == 2)
{
// Up arrow
if (rl_history_index > 0)
{
rl_history_index--;
strncpy(rl_line, rl_history[rl_history_index], RL_LINE_LENGTH_MAX-1);
rl_line_length = strlen(rl_line);
rl_cursor_pos = rl_line_length;
print_line(rl_line, rl_cursor_pos);
}
}
else
{
readline_input_char('A');
}
rl_escape = 0;
}
static void readline_input_B(void)
{
if (rl_escape == 2)
{
// Down arrow
if (rl_history_index < rl_history_count - 1)
{
rl_history_index++;
strncpy(rl_line, rl_history[rl_history_index], RL_LINE_LENGTH_MAX-1);
rl_line_length = strlen(rl_line);
rl_cursor_pos = rl_line_length;
print_line(rl_line, rl_cursor_pos);
}
else if (rl_history_index == rl_history_count - 1)
{
rl_history_index++;
rl_line_length = 0;
rl_cursor_pos = 0;
rl_line[rl_line_length] = '\0';
print_line(rl_line, rl_cursor_pos);
}
}
else
{
readline_input_char('B');
}
rl_escape = 0;
}
static void readline_input_C(void)
{
if (rl_escape == 2)
{
// Right arrow
if (rl_cursor_pos < rl_line_length)
{
rl_cursor_pos++;
print("\x1b[C");
}
}
else
{
readline_input_char('C');
}
rl_escape = 0;
}
static void readline_input_D(void)
{
if (rl_escape == 2)
{
// Left arrow
if (rl_cursor_pos > 0)
{
rl_cursor_pos--;
print("\b");
}
}
else
{
readline_input_char('D');
}
rl_escape = 0;
}
void readline_input(char input_char)
{
switch (input_char)
{
case '\r': // Carriage return
readline_input_cr();
break;
case 127: // Backspace
readline_input_bs();
break;
case 27: // Escape
readline_input_escape();
break;
case '[':
readline_input_left_bracket();
break;
case 'A':
readline_input_A();
break;
case 'B':
readline_input_B();
break;
case 'C':
readline_input_C();
break;
case 'D':
readline_input_D();
break;
default:
readline_input_char(input_char);
break;
}
}

View file

@ -1,26 +0,0 @@
/*
* tio - a serial device I/O tool
*
* Copyright (c) 2014-2024 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 readline_init(void);
void readline_input(char input_char);
char * readline_get(void);

View file

@ -19,13 +19,14 @@
* 02110-1301, USA.
*/
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <stdbool.h>
#include "options.h"
#include "print.h"
#include "misc.h"
#include "error.h"
#ifdef HAVE_RS485
@ -127,7 +128,7 @@ void rs485_print_config(void)
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) ? "true" : "false");
tio_printf(" RX_DURING_TX: %s", (rs485_config.flags & SER_RS485_RX_DURING_TX) ? "enabled" : "disabled");
}
int rs485_mode_enable(int fd)

View file

@ -20,6 +20,7 @@
*/
#include <errno.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
@ -28,7 +29,6 @@
#include <lauxlib.h>
#include <lualib.h>
#include <sys/ioctl.h>
#include <ctype.h>
#include "misc.h"
#include "print.h"
#include "options.h"
@ -37,94 +37,27 @@
#include "log.h"
#include "script.h"
#include "fs.h"
#include "timestamp.h"
#include "termios.h"
#define MAX_BUFFER_SIZE 2000 // Maximum size of circular buffer
#define READ_LINE_SIZE 4096 // read_line buffer length
static int device_fd;
static char circular_buffer[MAX_BUFFER_SIZE];
static char match_string[MAX_BUFFER_SIZE];
static int buffer_size = 0;
static char script_init[] =
"tio.set = function(arg)\n"
"function set(arg)\n"
" local dtr = arg.DTR or -1\n"
" local rts = arg.RTS or -1\n"
" local cts = arg.CTS or -1\n"
" local dsr = arg.DSR or -1\n"
" local cd = arg.CD or -1\n"
" local ri = arg.RI or -1\n"
" tio.line_set(dtr, rts, cts, dsr, cd, ri)\n"
"end\n"
"tio.expect = function(pattern, timeout)\n"
" local str = ''\n"
" while true do\n"
" local c = tio.read(1, timeout)\n"
" if c then\n"
" str = str .. c\n"
" if string.match(str, pattern) then\n"
" return string.match(str, pattern)\n"
" end\n"
" else\n"
" return nil, str\n"
" end\n"
" end\n"
"end\n"
"tio.alwaysecho = true\n"
"setmetatable(tio, tio)\n";
" line_set(dtr, rts, cts, dsr, cd, ri)\n"
"end\n";
static bool alwaysecho(lua_State *L)
{
bool b;
lua_getglobal(L, "tio");
lua_getfield(L, -1, "alwaysecho");
b = lua_toboolean(L, -1);
lua_pop(L, 2);
return b;
}
static int api_echo(lua_State *L)
{
size_t len = 0;
const char *str = luaL_checklstring(L, 1, &len);
if (option.timestamp)
{
char *pTimeStampNow = timestamp_current_time();
if (pTimeStampNow)
{
tio_printf("%s", str);
if (option.log)
{
log_printf("\n[%s] %s", pTimeStampNow, str);
}
}
} else {
for (size_t i=0; i<len; i++)
{
putchar(str[i]);
if (option.log)
log_putc(str[i]);
}
}
return 0;
}
static void maybe_echo(lua_State *L)
{
if (alwaysecho(L))
{
lua_pushcfunction(L, api_echo);
lua_pushvalue(L, -2);
lua_call(L, 1, 0);
}
}
// lua: tio.sleep(seconds)
static int api_sleep(lua_State *L)
// lua: sleep(seconds)
static int sleep_(lua_State *L)
{
long seconds = lua_tointeger(L, 1);
@ -140,8 +73,8 @@ static int api_sleep(lua_State *L)
return 0;
}
// lua: tio.msleep(miliseconds)
static int api_msleep(lua_State *L)
// lua: msleep(miliseconds)
static int msleep(lua_State *L)
{
long mseconds = lua_tointeger(L, 1);
long useconds = mseconds * 1000;
@ -157,7 +90,7 @@ static int api_msleep(lua_State *L)
return 0;
}
// lua: tio.line_set(dtr,rts,cts,dsr,cd,ri)
// lua: line_set(dtr,rts,cts,dsr,cd,ri)
static int line_set(lua_State *L)
{
tty_line_config_t line_config[6] = { };
@ -211,12 +144,11 @@ static int line_set(lua_State *L)
return 0;
}
// lua: tio.send(file, protocol)
static int api_send(lua_State *L)
// lua: modem_send(file, protocol)
static int modem_send(lua_State *L)
{
const char *file = luaL_checkstring(L, 1);
int protocol = luaL_checkinteger(L, 2);
int ret;
const char *file = lua_tostring(L, 1);
int protocol = lua_tointeger(L, 2);
if (file == NULL)
{
@ -227,138 +159,227 @@ static int api_send(lua_State *L)
{
case XMODEM_1K:
tio_printf("Sending file '%s' using XMODEM-1K", file);
ret = xymodem_send(device_fd, file, XMODEM_1K);
tio_printf("%s", ret < 0 ? "Aborted" : "Done");
tio_printf("%s", xymodem_send(device_fd, file, XMODEM_1K) < 0 ? "Aborted" : "Done");
break;
case XMODEM_CRC:
tio_printf("Sending file '%s' using XMODEM-CRC", file);
ret = xymodem_send(device_fd, file, XMODEM_CRC);
tio_printf("%s", ret < 0 ? "Aborted" : "Done");
tio_printf("%s", xymodem_send(device_fd, file, XMODEM_CRC) < 0 ? "Aborted" : "Done");
break;
case YMODEM:
tio_printf("Sending file '%s' using YMODEM", file);
ret = xymodem_send(device_fd, file, YMODEM);
tio_printf("%s", ret < 0 ? "Aborted" : "Done");
tio_printf("%s", xymodem_send(device_fd, file, YMODEM) < 0 ? "Aborted" : "Done");
break;
}
return 0;
}
// lua: tio.write(string)
static int api_write(lua_State *L)
// lua: send(string)
static int send(lua_State *L)
{
size_t len = 0;
const char *string = luaL_checklstring(L, 1, &len);
ssize_t ret;
int attempts = 100;
const char *string = lua_tostring(L, 1);
int ret;
do {
ret = write(device_fd, string, len);
if (ret < 0)
return luaL_error(L, "%s", strerror(errno));
if (string == NULL)
{
return 0;
}
len -= ret;
string += ret;
} while (len > 0 && --attempts);
ret = write(device_fd, string, strlen(string));
if (len > 0)
return luaL_error(L, "partial write");
fsync(device_fd); // flush these characters now
tcdrain(device_fd); //ensure we flushed characters to our device
lua_getglobal(L, "tio");
lua_pushnumber(L, ret);
return 1;
}
// lua: tio.read(size, timeout)
static int api_read(lua_State *L)
// Function to add a character to the circular expect buffer
static void expect_buffer_add(char c)
{
int size = luaL_checkinteger(L, 1);
int timeout = lua_tointeger(L, 2);
if (timeout == 0)
if (buffer_size < MAX_BUFFER_SIZE)
{
timeout = -1; // Wait forever
}
luaL_Buffer buffer;
luaL_buffinit(L, &buffer);
#if LUA_VERSION_NUM >= 502
char *p = luaL_prepbuffsize(&buffer, size);
#else
if (size > LUAL_BUFFERSIZE)
return luaL_error(L, "buffer overflow, max size is: %d", LUAL_BUFFERSIZE);
char *p = luaL_prepbuffer(&buffer);
#endif
ssize_t ret = read_poll(device_fd, p, size, timeout);
if (ret < 0)
return luaL_error(L, "%s", strerror(errno));
luaL_addsize(&buffer, ret);
luaL_pushresult(&buffer);
if (ret == 0)
{
// On timeout return nil instead of an empty string
lua_pop(L, 1);
lua_pushnil(L);
circular_buffer[buffer_size++] = c;
}
else
{
maybe_echo(L);
// Shift the buffer to accommodate the new character
memmove(circular_buffer, circular_buffer + 1, MAX_BUFFER_SIZE - 1);
circular_buffer[MAX_BUFFER_SIZE - 1] = c;
}
}
return 1;
// Function to match against the circular expect buffer using regex
static bool match_regex(regex_t *regex)
{
char buffer[MAX_BUFFER_SIZE + 1]; // Temporary buffer for regex matching
const char *s = circular_buffer;
regmatch_t pmatch[1];
regoff_t len;
memcpy(buffer, circular_buffer, buffer_size);
buffer[buffer_size] = '\0'; // Null-terminate the buffer
// Match against the regex
int ret = regexec(regex, buffer, 1, pmatch, 0);
if (!ret)
{
// Match found
len = pmatch[0].rm_eo - pmatch[0].rm_so;
memcpy(match_string, s + pmatch[0].rm_so, len);
match_string[len] = '\0';
return true;
}
else if (ret == REG_NOMATCH)
{
// No match found, do nothing
}
else
{
// Error occurred during matching
tio_error_print("Regex match failed");
}
// lua: string = tio.readline(timeout)
static int api_readline(lua_State *L) {
int timeout = lua_tointeger(L, 1); //ms
luaL_Buffer b;
char ch;
return false;
}
// lua: ret,string = read_string(size, timeout)
static int read_string(lua_State *L)
{
int size = lua_tointeger(L, 1);
int timeout = lua_tointeger(L, 2);
int ret = 0;
char *buffer = malloc(size);
if (buffer == NULL)
{
ret = -1; // Error
goto error;
}
if (timeout == 0)
{
timeout = -1; // Wait forever
}
luaL_buffinit(L, &b);
luaL_prepbuffer(&b);
while (true) {
int ret = read_poll(device_fd, &ch, 1, timeout);
if (ret < 0)
return luaL_error(L, "%s", strerror(errno));
if (ret == 0)
ssize_t bytes_read = read_poll(device_fd, buffer, size, timeout);
if (bytes_read < 0)
{
luaL_pushresult(&b);
maybe_echo(L);
lua_pushnil(L);
lua_insert(L, -2);
ret = -1; // Error
goto error;
}
else if (bytes_read == 0)
{
ret = 0; // Timeout
goto error;
}
for (ssize_t i=0; i<bytes_read; i++)
{
putchar(buffer[i]);
if (option.log)
{
log_putc(buffer[i]);
}
}
ret = bytes_read;
error:
lua_pushnumber(L, ret);
if (buffer != NULL)
{
lua_pushstring(L, buffer);
free(buffer);
}
return 2;
}
if (ch == '\n')
// lua: expect(string, timeout)
static int expect(lua_State *L)
{
luaL_pushresult(&b);
maybe_echo(L);
return 1;
const char *string = lua_tostring(L, 1);
long timeout = lua_tointeger(L, 2);
regex_t regex;
int ret = 0;
char c;
// Resets buffer to ignore previous `expect` calls
buffer_size = 0;
match_string[0] = '\0';
if ((string == NULL) || (timeout < 0))
{
ret = -1;
goto error;
}
luaL_addchar(&b, ch);
if (timeout == 0)
{
// Let poll() wait forever
timeout = -1;
}
// Compile the regular expression
ret = regcomp(&regex, string, REG_EXTENDED);
if (ret)
{
tio_error_print("Could not compile regex");
ret = -1;
goto error;
}
// Main loop to read and match
while (true)
{
ssize_t bytes_read = read_poll(device_fd, &c, 1, timeout);
if (bytes_read > 0)
{
putchar(c);
expect_buffer_add(c);
if (option.log)
{
log_putc(c);
}
// Match against the entire buffer
if (match_regex(&regex))
{
ret = 1;
break;
}
}
else
{
// Timeout or error
break;
}
}
// lua: table = tio.ttysearch()
static int api_ttysearch(lua_State *L)
// Cleanup
regfree(&regex);
error:
lua_pushnumber(L, ret);
lua_pushstring(L, match_string);
return 2;
}
// lua: exit(code)
static int exit_(lua_State *L)
{
long code = lua_tointeger(L, 1);
exit(code);
return 0;
}
// lua: list = tty_search()
static int tty_search_(lua_State *L)
{
UNUSED(L);
GList *iter;
@ -424,36 +445,39 @@ static void script_buffer_run(lua_State *L, const char *script_buffer)
}
}
static void script_file_run(lua_State *L, const char *filename)
{
if (strlen(filename) == 0)
{
tio_warning_printf("Missing script filename\n");
return;
}
if (luaL_dofile(L, filename))
{
tio_warning_printf("lua: %s", lua_tostring(L, -1));
lua_pop(L, 1); /* pop error message from the stack */
return;
}
}
static const struct luaL_Reg tio_lib[] =
{
{ "echo", api_echo},
{ "sleep", api_sleep},
{ "msleep", api_msleep},
{ "sleep", sleep_},
{ "msleep", msleep},
{ "line_set", line_set},
{ "send", api_send},
{ "write", api_write},
{ "read", api_read},
{ "readline", api_readline},
{ "ttysearch", api_ttysearch},
{ "modem_send", modem_send},
{ "send", send},
{ "read", read_string},
{ "expect", expect},
{ "exit", exit_},
{ "tty_search", tty_search_},
{NULL, NULL}
};
#if !defined LUA_VERSION_NUM || LUA_VERSION_NUM==501
/*
** Adapted from Lua 5.2.0 (for backwards compatibility)
*/
static void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup)
{
luaL_checkstack(L, nup+1, "too many upvalues");
for (; l->name != NULL; l++) { /* fill the table with given functions */
int i;
lua_pushstring(L, l->name);
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -(nup+1));
lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
lua_settable(L, -(nup + 3));
}
lua_pop(L, nup); /* remove upvalues */
}
#endif
static void script_load(lua_State *L)
{
int error;
@ -466,13 +490,42 @@ static void script_load(lua_State *L)
}
}
static void script_set_global(lua_State *L, const char *name, long value)
int lua_register_tio(lua_State *L)
{
// Register lxi functions
lua_getglobal(L, "_G");
luaL_setfuncs(L, tio_lib, 0);
lua_pop(L, 1);
// Load lua init script
script_load(L);
return 0;
}
void script_file_run(lua_State *L, const char *filename)
{
if (strlen(filename) == 0)
{
tio_warning_printf("Missing script filename\n");
return;
}
if (luaL_dofile(L, filename))
{
tio_warning_printf("lua: %s\n", lua_tostring(L, -1));
lua_pop(L, 1); /* pop error message from the stack */
return;
}
}
void script_set_global(lua_State *L, const char *name, long value)
{
lua_pushnumber(L, value);
lua_setglobal(L, name);
}
static void script_set_globals(lua_State *L)
void script_set_globals(lua_State *L)
{
script_set_global(L, "toggle", 2);
script_set_global(L, "high", 1);
@ -482,15 +535,7 @@ static void script_set_globals(lua_State *L)
script_set_global(L, "YMODEM", YMODEM);
}
#if LUA_VERSION_NUM >= 502
static int luaopen_tio(lua_State *L)
{
luaL_newlib(L, tio_lib);
return 1;
}
#endif
void script_run(int fd, const char *script_filename)
void script_run(int fd)
{
lua_State *L;
@ -499,25 +544,13 @@ void script_run(int fd, const char *script_filename)
L = luaL_newstate();
luaL_openlibs(L);
#if LUA_VERSION_NUM >= 502
luaL_requiref(L, "tio", luaopen_tio, 1);
#else
luaL_register(L, "tio", tio_lib);
#endif
lua_pop(L, 1);
// Load lua init script
script_load(L);
// Bind tio functions
lua_register_tio(L);
// Initialize globals
script_set_globals(L);
if (script_filename != NULL)
{
tio_printf("Running script %s", script_filename);
script_file_run(L, script_filename);
}
else if (option.script_filename != NULL)
if (option.script_filename != NULL)
{
tio_printf("Running script %s", option.script_filename);
script_file_run(L, option.script_filename);

View file

@ -29,5 +29,5 @@ typedef enum
SCRIPT_RUN_END,
} script_run_t;
void script_run(int fd, const char *script_filename);
void script_run(int fd);
const char *script_run_state_to_string(script_run_t state);

View file

@ -124,7 +124,6 @@ void socket_configure(void)
struct sockaddr_in6 sockaddr_inet6 = {};
struct sockaddr *sockaddr_p;
socklen_t socklen;
int optval;
/* Parse socket string */
@ -226,16 +225,6 @@ void socket_configure(void)
exit(EXIT_FAILURE);
}
#if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_NOSIGPIPE, &optval, sizeof(optval)))
#else
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)))
#endif
{
tio_error_printf("Failed to set socket options (%s)", strerror(errno));
exit(EXIT_FAILURE);
}
/* Bind */
if (bind(sockfd, sockaddr_p, socklen) < 0)
{
@ -274,12 +263,7 @@ void socket_write(char input_char)
{
if (clientfds[i] != -1)
{
#if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
if (send(clientfds[i], &input_char, 1, 0) <= 0)
#else
if (send(clientfds[i], &input_char, 1, MSG_NOSIGNAL) <= 0)
#endif
if (write(clientfds[i], &input_char, 1) <= 0)
{
tio_error_printf_silent("Failed to write to socket (%s)", strerror(errno));
close(clientfds[i]);
@ -359,20 +343,20 @@ bool socket_handle_input(fd_set *rdfs, char *output_char)
}
/* If INLCR is set, a received NL character shall be translated into a CR character */
if (*output_char == '\n' && option.map_i_nl_cr)
if (*output_char == '\n' && map_i_nl_cr)
{
*output_char = '\r';
}
else if (*output_char == '\r')
{
/* If IGNCR is set, a received CR character shall be ignored (not read). */
if (option.map_ign_cr)
if (map_ign_cr)
{
return false;
}
/* If IGNCR is not set and ICRNL is set, a received CR character shall be translated into an NL character. */
if (option.map_i_cr_nl)
if (map_i_cr_nl)
{
*output_char = '\n';
}

View file

@ -22,6 +22,8 @@
#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"
@ -29,6 +31,8 @@
#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];
@ -74,31 +78,75 @@ char *timestamp_current_time(void)
tm = localtime(&tv.tv_sec);
len = strftime(time_string, sizeof(time_string), "%Y-%m-%dT%H:%M:%S", tm);
break;
case TIMESTAMP_EPOCH:
case TIMESTAMP_EPOCH_USEC:
// "N.sss" (seconds since Unix epoch, 1970-01-01 00:00:00Z)
tv = tv_now;
tm = localtime(&tv.tv_sec);
len = strftime(time_string, sizeof(time_string), "%s", tm);
break;
default:
return NULL;
}
// Append millis-/microseconds to all timestamps
// Append milliseconds to all timestamps
if (len)
{
if ( option.timestamp == TIMESTAMP_EPOCH_USEC )
{
len = snprintf(time_string + len, TIME_STRING_SIZE_MAX - len, ".%06ld", (long)tv.tv_usec);
}
else
{
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(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;
}
}
timestamp_t timestamp_option_parse(const char *arg)
{
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;
}

View file

@ -28,12 +28,9 @@ typedef enum
TIMESTAMP_24HOUR_START,
TIMESTAMP_24HOUR_DELTA,
TIMESTAMP_ISO8601,
TIMESTAMP_EPOCH,
TIMESTAMP_EPOCH_USEC,
TIMESTAMP_END,
} timestamp_t;
#define TIME_STRING_SIZE_MAX 24
char *timestamp_current_time(void);
const char* timestamp_state_to_string(timestamp_t timestamp);
timestamp_t timestamp_option_parse(const char *arg);

1030
src/tty.c

File diff suppressed because it is too large Load diff

View file

@ -29,22 +29,6 @@
#define TOPOLOGY_ID_SIZE 4
typedef enum
{
FLOW_NONE,
FLOW_HARD,
FLOW_SOFT,
} flow_t;
typedef enum
{
PARITY_NONE,
PARITY_ODD,
PARITY_EVEN,
PARITY_MARK,
PARITY_SPACE,
} parity_t;
typedef enum
{
AUTO_CONNECT_DIRECT,
@ -71,11 +55,13 @@ typedef struct
extern const char *device_name;
extern bool interactive_mode;
extern bool map_i_nl_cr;
extern bool map_i_cr_nl;
extern bool map_ign_cr;
void stdout_configure(void);
void stdin_configure(void);
void tty_configure(void);
void tty_reconfigure(void);
int tty_connect(void);
void tty_wait_for_device(void);
void list_serial_devices(void);

View file

@ -1,3 +0,0 @@
#pragma once
#define VERSION "@VERSION@"

View file

@ -7,36 +7,30 @@
*
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <poll.h>
#include <sys/poll.h>
#include <termios.h>
#include "xymodem.h"
#include "print.h"
#include "misc.h"
#define SOH 0x01
#define STX 0x02
#define ACK 0x06
#define NAK 0x15
#define CAN 0x18
#define EOT 0x04
#define SOH_STR "\001"
#define ACK_STR "\006"
#define NAK_STR "\025"
#define CAN_STR "\030"
#define EOT_STR "\004"
#define EOT "\004"
#define OK 0
#define ERR (-1)
#define ERR_FATAL (-2)
#define USER_CAN (-5)
#define RX_IGNORE 5
#define min(a, b) ((a) < (b) ? (a) : (b))
@ -172,7 +166,7 @@ static int xmodem_1k(int sio, const void *data, size_t len, int seq)
while (seq) {
if (key_hit)
return ERR;
if (write(sio, EOT_STR, 1) < 0) {
if (write(sio, EOT, 1) < 0) {
tio_error_print("Write EOT to serial failed");
return ERR;
}
@ -291,7 +285,7 @@ static int xmodem(int sio, const void *data, size_t len)
while (1) {
if (key_hit)
return ERR;
if (write(sio, EOT_STR, 1) < 0) {
if (write(sio, EOT, 1) < 0) {
tio_error_print("Write EOT to serial failed");
return ERR;
}
@ -312,345 +306,6 @@ static int xmodem(int sio, const void *data, size_t len)
return 0; /* not reached */
}
int start_receive(int sio)
{
int rc;
struct pollfd fds;
fds.events = POLLIN;
fds.fd = sio;
for (int n = 0; n < 20; n++)
{
/* Send the 'C' byte until the sender of the file responds with
something. The start character will be sent once a second for a number of
seconds. If nothing is received in that time then return false to indicate
that the transfer did not start. */
rc = write(sio, "C", 1);
if (rc < 0) {
if (errno == EWOULDBLOCK) {
usleep(1000);
continue;
}
tio_error_print("Write packet to serial failed");
return ERR;
}
/* Wait until data is available */
rc = poll(&fds, 1, 3000);
if (rc < 0)
{
tio_error_print("%s", strerror(errno));
return rc;
}
else if (rc > 0)
{
if (fds.revents & POLLIN)
{
return rc;
}
}
if (key_hit)
return USER_CAN;
}
return rc;
}
uint16_t update_CRC(uint16_t crc, char data_char)
{
uint8_t data = data_char;
crc = crc ^ ((uint16_t)data << 8);
for (int ix = 0; (ix < 8); ix++)
{
if (crc & 0x8000)
{
crc = (crc << 1) ^ 0x1021;
}
else
{
crc <<= 1;
}
}
return crc;
}
int receive_packet(int sio, struct xpacket packet, int fd)
{
char rxSeq1, rxSeq2 = 0;
char resp = 0;
uint16_t calcCrc = 0;
uint16_t rxCrc = 0;
int rc;
struct pollfd fds;
fds.events = POLLIN;
fds.fd = sio;
/* Read seq bytes*/
rc = read_poll(sio, &rxSeq1, 1, 3000);
if (rc == 0) {
tio_error_print("Timeout waiting for first seq byte");
return ERR;
} else if (rc < 0) {
tio_error_print("Error reading first seq byte")
return ERR_FATAL;
}
rc = read_poll(sio, &rxSeq2, 1, 3000);
if (rc == 0) {
tio_error_print("Timeout waiting for second seq byte");
return ERR;
} else if (rc < 0) {
tio_error_print("Error reading second seq byte")
return ERR_FATAL;
}
if (key_hit)
return USER_CAN;
/* Read packet Data */
for (unsigned ix = 0; (ix < sizeof(packet.data)); ix++)
{
rc = read_poll(sio, &resp, 1, 3000);
/* If the read times out or fails then fail this packet. */
if (rc == 0)
{
tio_error_print("Timeout waiting for next packet char");
rc = write(sio, CAN_STR, 1);
if (rc < 0) {
tio_error_print("Write cancel packet to serial failed");
return ERR_FATAL;
}
return ERR;
} else if (rc < 0) {
tio_error_print("Error reading next packet char")
rc = write(sio, CAN_STR, 1);
if (rc < 0) {
tio_error_print("Write cancel packet to serial failed");
}
return ERR_FATAL;
}
packet.data[ix] = (uint8_t) resp;
calcCrc = update_CRC(calcCrc, resp);
if (key_hit)
return USER_CAN;
}
/* Read CRC */
rc = read_poll(sio, &resp, 1, 3000);
if (rc == 0) {
tio_error_print("Timeout waiting for first CRC byte");
return ERR;
} else if (rc < 0) {
tio_error_print("Error reading first CRC byte")
return ERR_FATAL;
}
uint8_t uresp = resp;
uint16_t uresp16 = uresp;
rxCrc = uresp16 << 8;
rc = read_poll(sio, &resp, 1, 3000);
if (rc == 0) {
tio_error_print("Timeout waiting for second CRC byte");
return ERR;
} else if (rc < 0) {
tio_error_print("Error reading second CRC byte")
return ERR_FATAL;
}
uresp = resp;
uresp16 = uresp;
rxCrc |= uresp16;
if (key_hit)
return USER_CAN;
/* At this point in the code, there should not be anything in the receive buffer
because the sender has just sent a complete packet and is waiting on a response. */
rc = poll(&fds, 1, 10);
if (rc < 0)
{
tio_error_print("%s", strerror(errno));
tio_error_print("Poll check error after packet finish");
rc = write(sio, CAN_STR, 1);
if (rc < 0) {
tio_error_print("Write cancel packet to serial failed");
}
return ERR_FATAL;
}
else if (rc > 0)
{
if (fds.revents & POLLIN)
{
tio_error_print("RX sync error");
char dummy = 0;
/* Drain buffer */
while (read_poll(sio, &dummy, 1, 100) > 0) {}
return ERR;
}
}
uint8_t tester = 0xff;
uint8_t seq1 = rxSeq1;
uint8_t seq2 = rxSeq2;
if ((calcCrc == rxCrc) && (seq1 == packet.seq - 1) && ((seq1 ^ seq2) == tester))
{
/* Resend of previously processed packet. */
rc = write(sio, ACK_STR, 1);
if (rc < 0) {
tio_error_print("Write acknowlegdement packet to serial failed");
return ERR_FATAL;
}
return RX_IGNORE;
}
else if ((calcCrc != rxCrc) || (seq1 != packet.seq) || ((seq1 ^ seq2) != tester))
{
/* Fail if the CRC or sequence number is not correct or if the two received
sequence numbers are not the complement of one another. */
tio_error_print("Bad CRC or sequence number");
tio_debug_printf("CRC read: %u", rxCrc);
tio_debug_printf("CRC calculated: %u", calcCrc);
tio_debug_printf("Seq read: %hhu", rxSeq1);
tio_debug_printf("Seq should be: %hhu", packet.seq);
tio_debug_printf("inv seq: %hhu", rxSeq2);
return ERR;
}
else
{
/* The data is good. Process the packet then ACK it to the sender. */
rc = write(fd, packet.data, sizeof(packet.data));
if (rc < 0)
{
tio_error_print("Problem writing to file");
rc = write(sio, CAN_STR, 1);
if (rc < 0) {
tio_error_print("Write cancel packet to serial failed");
}
return ERR_FATAL;
}
rc = write(sio, ACK_STR, 1);
if (rc < 0)
{
tio_error_print("Write acknowlegdement packet to serial failed");
return ERR_FATAL;
}
}
return OK;
}
int xmodem_receive(int sio, int fd)
{
struct xpacket packet;
char resp = 0;
int rc;
bool complete = false;
char status;
/* Drain pending characters from serial line.*/
while(1) {
if (key_hit)
return -1;
rc = read_poll(sio, &resp, 1, 50);
if (rc == 0) {
if (resp == CAN) return ERR;
break;
}
else if (rc < 0) {
if (rc != USER_CAN) {
tio_error_print("Read sync from serial failed");
}
return ERR;
}
}
/* Always work with 128b packets */
packet.seq = 1;
packet.type = SOH;
/* Start Receive*/
rc = start_receive(sio);
if (rc == 0)
{
tio_error_print("Timeout waiting for transfer to start");
return ERR;
} else if (rc < 0) {
tio_error_print("Error starting XMODEM receive");
return ERR;
}
while (!complete) {
/* Poll for 1 new byte for 3 seconds */
rc = read_poll(sio, &resp, 1, 3000);
if (rc == 0) {
tio_error_print("Timeout waiting for start of next packet");
return ERR;
} else if (rc < 0) {
tio_error_print("Error reading start of next packet")
return ERR;
}
if (key_hit)
return USER_CAN;
switch(resp)
{
case SOH:
/* Start of a packet */
rc = receive_packet(sio, packet, fd);
if (rc == OK) {
packet.seq++;
status = '.';
} else if (rc == ERR) {
rc = write(sio, NAK_STR, 1);
if (rc < 0) {
tio_error_print("Writing not acknowledge packet to serial failed");
return ERR;
}
status = 'N';
} else if (rc == ERR_FATAL) {
tio_error_print("Receive cancelled due to fatal error");
return ERR;
} else if (rc == USER_CAN) {
rc = write(sio, CAN_STR, 1);
if (rc < 0) {
tio_error_print("Writing cancel to serial failed");
return ERR;
}
return USER_CAN;
} else if (rc == RX_IGNORE) {
status = ':';
}
break;
case EOT:
/* End of Transfer */
rc = write(sio, ACK_STR, 1);
if (rc < 0)
{
tio_error_print("Write acknowlegdement packet to serial failed");
return ERR;
}
complete = true;
status = '\0';
write(STDOUT_FILENO, "|\r\n", 3);
break;
case CAN:
/* Cancel from sender */
tio_error_print("Transmission cancelled from sender");
return ERR;
break;
default:
tio_error_print("Unexpected character received waiting for next packet");
return ERR;
break;
}
/* Update "progress bar" */
write(STDOUT_FILENO, &status, 1);
}
return OK;
}
int xymodem_send(int sio, const char *filename, modem_mode_t mode)
{
size_t len;
@ -688,7 +343,7 @@ int xymodem_send(int sio, const char *filename, modem_mode_t mode)
rc = -1;
if (strlen(filename) > 977) break; /* hdr block overrun */
p = stpncpy(hdr, filename, 1024) + 1;
p = stpcpy(hdr, filename) + 1;
p += sprintf(p, "%ld %lo %o", len, stat.st_mtime, stat.st_mode);
if (xmodem_1k(sio, hdr, p - hdr, 0) < 0) break; /* hdr with metadata */
@ -705,35 +360,3 @@ int xymodem_send(int sio, const char *filename, modem_mode_t mode)
close(fd);
return rc;
}
int xymodem_receive(int sio, const char *filename, modem_mode_t mode)
{
int rc, fd;
/* Create new file */
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fd < 0) {
tio_error_print("Could not open file");
return ERR;
}
/* Do transfer */
key_hit = 0;
if (mode == XMODEM_1K) {
tio_error_print("Not supported");
rc = -1;
}
else if (mode == XMODEM_CRC) {
rc = xmodem_receive(sio, fd);
}
else {
tio_error_print("Not supported");
rc = -1;
}
key_hit = 0xff;
/* Flush serial and release resources */
tcflush(sio, TCIOFLUSH);
close(fd);
return rc;
}

View file

@ -30,5 +30,3 @@ typedef enum {
extern char key_hit;
int xymodem_send(int sio, const char *filename, modem_mode_t mode);
int xymodem_receive(int sio, const char *filename, modem_mode_t mode);

4
subprojects/libinih.wrap Normal file
View file

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