Compare commits

..

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

39 changed files with 699 additions and 1690 deletions

View file

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

View file

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

@ -21,8 +21,7 @@ jobs:
- name: Install dependencies
run: |
sudo apt update
sudo apt install -y bash-completion git meson liblua5.2-dev libglib2.0-dev
sudo apt-get install -y bash-completion git meson liblua5.2-dev libglib2.0-dev
- name: Build
run: |

View file

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

11
AUTHORS
View file

@ -55,16 +55,5 @@ 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

215
NEWS
View file

@ -1,174 +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
=== tio v3.4 ===
@ -255,7 +86,7 @@ Changes since tio v3.1:
* Fix line ending in --list output
* Print location of configuration file in --list output
* Print location of configuratin file in --list output
* Fix alignment of profile listing
@ -294,7 +125,7 @@ Changes since tio v3.0:
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
All configuraiton 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.
@ -348,9 +179,9 @@ Rui Chen:
* fix: add build patch for `FNM_EXTMATCH`
* feat: add macOS workflow
* feat: add macos workflow
* fix: add macOS build patch for `fs_get_creation_time`
* fix: add macos build patch for `fs_get_creation_time`
@ -575,11 +406,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 +419,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 +470,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 +567,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 +901,7 @@ Changes since tio v1.46:
Victor Oliveira
* add MacPorts install instructions
* add macports install instructions
@ -1570,7 +1401,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
@ -1626,10 +1457,10 @@ Changes since tio v1.34:
* Add support for configurable timestamp format
Also changes default timestamp format from ISO 8601 to classic 24-hour
Also changes default timestamp format from ISO8601 to classic 24-hour
format as this is assumed to be the format that most users would prefer.
And reintroduces strict but optional ISO 8601 format.
And reintroduces strict but optional ISO8601 format.
This feature allows to easily add more timestamp formats in the future.
@ -1750,10 +1581,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 +1663,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 +1676,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 +2170,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

133
README.md
View file

@ -3,9 +3,8 @@
# 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/ubuntu.yml?label=GNU%2FLinux)](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/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)
@ -75,7 +74,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
@ -102,7 +100,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 +126,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 +142,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.
```
@ -233,24 +228,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 +266,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 +273,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
```
@ -365,12 +350,12 @@ 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
@ -395,80 +380,62 @@ Another more elaborate configuration file example is available [here](examples/c
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:
```
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.
#### `tio.expect(pattern, timeout)`
Returns 1 on successful match, 0 on timeout, or -1 on error.
Waits for the Lua pattern to match or timeout before continuing.
Timeout is in milliseconds, defaults to 0 meaning it will wait forever.
On successful match it also returns the match string as second return value.
Returns the captures from the pattern or `nil` on timeout.
send(string)
Send string.
#### `tio.read(size, timeout)`
Returns number of bytes written on success or -1 on error.
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.
modem_send(file, protocol)
Send file using x/y-modem protocol.
Returns a string up to `size` bytes long on success and `nil` on timeout.
Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM.
#### `tio.readline(timeout)`
tty_search()
Search for serial devices.
Read line from serial device. If timeout is 0 or not provided it will wait
forever until data is ready to read.
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 a string on success and `nil` on timeout. On timeout a partially read
line may be returned as a second return value.
Returns nil if no serial devices are found.
#### `tio.write(string)`
read(size, timeout)
Read from serial device. If timeout is 0 or not provided it will wait
forever until data is ready to read.
Write string to serial device.
Returns number of bytes read on success, 0 on timeout, or -1 on error.
Returns the `tio` table.
On success, returns read string as second return value.
#### `tio.send(file, protocol)`
set{line=state, ...}
Set state of one or multiple tty modem lines.
Send file using x/y-modem protocol.
Line can be any of DTR, RTS, CTS, DSR, CD, RI
Protocol can be any of `XMODEM_1K`, `XMODEM_CRC`, `YMODEM`.
State is high, low, or toggle.
#### `tio.ttysearch()`
sleep(seconds)
Sleep for seconds.
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`.
msleep(ms)
Sleep for miliseconds.
exit(code)
Exit with exit code.
```
## 4. Installation
@ -529,13 +496,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>
```

22
TODO
View file

@ -1,19 +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:
@ -50,6 +34,12 @@
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.
* Allow tio to connect to socket
After some more consideration I think it makes sense to support connecting to a

View file

@ -69,10 +69,5 @@ 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 = set{DTR=high,RTS=low}; msleep(100); set{DTR=low,RTS=high}; msleep(100); set{RTS=low}
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
@ -205,8 +201,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 +216,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 +226,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
@ -371,10 +363,6 @@ Default value is "always".
Execute shell command with I/O redirected to device
.TP
.BR "\-\-complete-profiles
Prints profiles (for shell completion)
.TP
.BR \-v ", " \-\-version
@ -383,10 +371,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"
@ -436,41 +424,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 +457,27 @@ 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.
On success, returns read string as second return value.
.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
@ -601,9 +579,6 @@ 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"
@ -728,7 +703,7 @@ expect -i $uart "prompt> "
.TP
It is also possible to use tio's own simpler 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 +724,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 +732,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 +740,7 @@ $ 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
.SH "WEBSITE"
.PP

View file

@ -1,4 +1,4 @@
tio(1) User Commands tio(1)
tio(1) User Commands tio(1)
NAME
tio - a serial device I/O tool
@ -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>
@ -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.
@ -222,8 +214,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.
@ -289,10 +280,6 @@ OPTIONS
Execute shell command with I/O redirected to device
--complete-profiles
Prints profiles (for shell completion)
-v, --version
Display program version.
@ -301,8 +288,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 +311,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 +321,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 +338,21 @@ 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.
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.
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.
send(string)
Send string.
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,11 +360,17 @@ 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.
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.
On success, returns read string as second return value.
set{line=state, ...}
Set state of one or multiple tty modem lines.
@ -403,7 +382,7 @@ SCRIPT API
Sleep for seconds.
msleep(ms)
Sleep for milliseconds.
Sleep for miliseconds.
exit(code)
Exit with exit code.
@ -495,8 +474,6 @@ CONFIGURATION FILE
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:
@ -582,7 +559,7 @@ EXAMPLES
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
$ tio --script 'expect("login: "); send("root\n"); expect("Password: "); send("root\n")' /dev/ttyUSB0
Redirect device I/O to network file socket for remote TTY sharing:
@ -604,10 +581,6 @@ 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
@ -622,4 +595,4 @@ WEBSITE
AUTHOR
Maintained by Martin Lund <martin.lund@keep-it-simple.com>.
tio 3.9 2025-04-13 tio(1)
tio 3.3 2024-05-15 tio(1)

View file

@ -1,12 +1,12 @@
project('tio', 'c',
version : '3.9',
license : 'GPL-2.0-or-later',
version : '3.4',
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-06-15'
# Test for dynamic baudrate configuration interface
compiler = meson.get_compiler('c')

View file

@ -46,7 +46,6 @@ _tio()
--script-file \
--script-run \
--exec \
--complete-profiles \
-v --version \
-h --help"
@ -86,11 +85,11 @@ _tio()
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
;;
--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
;;
-c | --color)

View file

@ -26,25 +26,18 @@
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <libgen.h>
#include <errno.h>
#include <regex.h>
#include <glib.h>
#include "configfile.h"
#include "timestamp.h"
#include "print.h"
#include "rs485.h"
#include "misc.h"
#define CONFIG_GROUP_NAME_DEFAULT "default"
#define CONFIG_GROUP_INCLUDE_PREFIX "include "
#define MAX_LINE_LENGTH 1024
struct config_t config = {};
static void config_file_load(const char *filename, GString *buffer, bool test);
static void config_file_process(const char *filename, GString *buffer, GList **included_files, bool test);
static void config_get_string(GKeyFile *key_file, gchar *group, gchar *key, char **dest, char *allowed_string, ...)
{
(void)dest;
@ -149,6 +142,7 @@ static void config_get_bool(GKeyFile *key_file, gchar *group, gchar *key, bool *
static void config_parse_keys(GKeyFile *key_file, char *group)
{
char *string = NULL;
bool boolean = false;
config_get_string(key_file, group, "device", &config.device, NULL);
config_get_integer(key_file, group, "baudrate", &option.baudrate, 0, INT_MAX);
@ -204,21 +198,21 @@ static void config_parse_keys(GKeyFile *key_file, char *group)
g_free((void *)string);
string = NULL;
}
config_get_bool(key_file, group, "timestamp", (bool*) &option.timestamp);
if (option.timestamp != TIMESTAMP_NONE)
config_get_bool(key_file, group, "timestamp", &boolean);
if (boolean == true)
{
config_get_string(key_file, group, "timestamp-format", &string, "24hour", "24hour-start", "24hour-delta", "iso8601", "epoch", "epoch-usec", NULL);
if (string != NULL)
{
option_parse_timestamp(string, &option.timestamp);
g_free((void *)string);
string = NULL;
}
option.timestamp = TIMESTAMP_24HOUR;
}
config_get_string(key_file, group, "timestamp-format", &string, "24hour", "24hour-start", "24hour-delta", "iso8601", NULL);
if (string != NULL)
{
option_parse_timestamp(string, &option.timestamp);
g_free((void *)string);
string = NULL;
}
config_get_integer(key_file, group, "timestamp-timeout", &option.timestamp_timeout, 0, INT_MAX);
config_get_bool(key_file, group, "log", &option.log);
config_get_string(key_file, group, "log-file", &option.log_filename, NULL);
config_get_string(key_file, group, "log-directory", &option.log_directory, NULL);
config_get_bool(key_file, group, "log-append", &option.log_append);
config_get_bool(key_file, group, "log-strip", &option.log_strip);
config_get_string(key_file, group, "map", &string, NULL);
@ -353,11 +347,9 @@ static int config_file_resolve(void)
void config_file_show_profiles(void)
{
GString *config_buffer;
GError *error = NULL;
GKeyFile *keyfile;
GError *error = NULL;
// Reset configuration
memset(&config, 0, sizeof(struct config_t));
// Find config file
@ -367,16 +359,13 @@ void config_file_show_profiles(void)
return;
}
// Load content of configuration file into buffer
config_buffer = g_string_new(NULL);
config_file_load(config.path, config_buffer, false);
// Load configuration
keyfile = g_key_file_new();
if (g_key_file_load_from_data(keyfile, config_buffer->str, config_buffer->len, G_KEY_FILE_NONE, &error) == false)
if (!g_key_file_load_from_file(keyfile, config.path, G_KEY_FILE_NONE, &error))
{
tio_error_print("Failure loading file: %s", error->message);
g_error_free(error);
goto error_load;
return;
}
// Get all group names
@ -390,20 +379,11 @@ void config_file_show_profiles(void)
{
continue;
}
// Skip group with include directive
if (strncmp(group[i], CONFIG_GROUP_INCLUDE_PREFIX, strlen(CONFIG_GROUP_INCLUDE_PREFIX)) == 0)
{
continue;
}
printf("%s ", group[i]);
}
g_strfreev(group);
error_load:
g_key_file_free(keyfile);
g_string_free(config_buffer, TRUE);
}
static void replace_substring(char *str, const char *substr, const char *replacement)
@ -428,13 +408,12 @@ static char *match_and_replace(const char *str, const char *pattern, char *devic
assert(pattern != NULL);
assert(device != NULL);
char *string = calloc(PATH_MAX, 1);
char *string = strndup(device, PATH_MAX);
if (string == NULL)
{
tio_debug_printf("Failure allocating string memory\n");
return NULL;
}
strncpy(string, device, PATH_MAX - 1);
/* Find matches of pattern in str. For each match, replace any '%mN' in the
* copy of the device string with the corresponding match subexpression and
@ -504,95 +483,6 @@ error:
return NULL;
}
static void config_file_process_line(const char *line, GString *buffer, GList **included_files, bool test)
{
if (strncmp(line, "[include ", 9) == 0 && line[strlen(line) - 2] == ']')
{
char include_filename[MAX_LINE_LENGTH];
// Construct the format string safely
char format_string[50];
snprintf(format_string, sizeof(format_string), "[include %%%ds]", MAX_LINE_LENGTH - 1);
int ret = sscanf(line, format_string, include_filename);
if (ret != 1)
{
return;
}
// Remove the trailing ']' character
include_filename[strlen(include_filename) - 1] = '\0';
if (g_list_find_custom(*included_files, include_filename, (GCompareFunc)strcmp) != NULL)
{
// Already included, avoid recursion
return;
}
// Add to included files list
*included_files = g_list_append(*included_files, g_strdup(include_filename));
// Process the included file
config_file_process(include_filename, buffer, included_files, test);
}
else
{
// Normal line, add to buffer
g_string_append(buffer, line);
}
}
static void config_file_process(const char *filename, GString *buffer, GList **included_files, bool test)
{
if (test)
{
// Test that configuration file can be parsed
GError *error = NULL;
GKeyFile *keyfile = g_key_file_new();
if (g_key_file_load_from_file(keyfile, filename, G_KEY_FILE_NONE, &error) == false)
{
tio_error_print("Failure loading file %s: %s", filename, error->message);
g_key_file_free(keyfile);
g_error_free(error);
exit(EXIT_FAILURE);
}
}
FILE *file = fopen(filename, "r");
if (file)
{
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), file))
{
config_file_process_line(line, buffer, included_files, test);
}
fclose(file);
}
}
static void config_file_load(const char *filename, GString *buffer, bool test)
{
char current_dir[PATH_MAX] = ".";
char *config_file_dir = dirname(strdup(config.path));
GList *included_files = NULL;
getcwd(current_dir, PATH_MAX);
// Change to the directory of the configuration file
chdir(config_file_dir);
config_file_process(filename, buffer, &included_files, test);
// Restore current directory
chdir(current_dir);
// Free memory
g_list_free_full(included_files, g_free);
free(config_file_dir);
}
void config_file_parse(void)
{
// Find config file
@ -607,18 +497,12 @@ void config_file_parse(void)
return;
}
GString *config_buffer = g_string_new(NULL);
GKeyFile *keyfile = g_key_file_new();
GList *included_files = NULL;
GError *error = NULL;
config_file_load(config.path, config_buffer, true);
if (g_key_file_load_from_data(keyfile, config_buffer->str, config_buffer->len, G_KEY_FILE_NONE, &error) == false)
if (g_key_file_load_from_file(keyfile, config.path, G_KEY_FILE_NONE, &error) == false)
{
tio_error_print("Failure loading file %s: %s", config.path, error->message);
g_string_free(config_buffer, TRUE);
g_key_file_free(keyfile);
g_error_free(error);
exit(EXIT_FAILURE);
}
@ -690,10 +574,7 @@ void config_file_parse(void)
g_strfreev(group);
}
// Cleanup
g_key_file_free(keyfile);
g_string_free(config_buffer, TRUE);
g_list_free_full(included_files, g_free);
atexit(&config_exit);
}
@ -733,14 +614,10 @@ void config_list_targets(void)
keyfile = g_key_file_new();
GString *config_buffer = g_string_new(NULL);
config_file_load(config.path, config_buffer, false);
if (g_key_file_load_from_data(keyfile, config_buffer->str, config_buffer->len, G_KEY_FILE_NONE, &error) == false)
if (!g_key_file_load_from_file(keyfile, config.path, G_KEY_FILE_NONE, &error))
{
g_error_free(error);
goto cleanup;
return;
}
// Get all group names
@ -749,7 +626,7 @@ void config_list_targets(void)
if (num_groups == 0)
{
goto cleanup;
return;
}
printf("\nConfiguration profiles (%s)\n", config.path);
@ -763,13 +640,6 @@ void config_list_targets(void)
{
continue;
}
// Skip group with include directive
if (strncmp(group[i], CONFIG_GROUP_INCLUDE_PREFIX, strlen(CONFIG_GROUP_INCLUDE_PREFIX)) == 0)
{
continue;
}
printf("%-19s ", group[i]);
if (j++ % 4 == 0)
{
@ -782,7 +652,5 @@ void config_list_targets(void)
}
g_strfreev(group);
cleanup:
g_key_file_free(keyfile);
g_string_free(config_buffer, TRUE);
}

View file

@ -19,7 +19,8 @@
* 02110-1301, USA.
*/
#define _GNU_SOURCE // To access vasprintf
#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf
#include <stdio.h>
#include "print.h"

View file

@ -199,6 +199,7 @@ double fs_get_creation_time(const char *path)
double fs_get_creation_time(const char *path)
{
// Use stat on macOS to access creation time
struct stat st;
if (stat(path, &st) != 0)
@ -206,7 +207,7 @@ double fs_get_creation_time(const char *path)
return -1;
}
return st.st_mtimespec.tv_sec + st.st_mtimespec.tv_nsec / 1e9;
return st.st_birthtimespec.tv_sec + st.st_birthtimespec.tv_nsec / 1e9;
}
#else

View file

@ -19,7 +19,8 @@
* 02110-1301, USA.
*/
#define _GNU_SOURCE // To access vasprintf
#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf
#include <sys/time.h>
#include <libgen.h>
#include <errno.h>

View file

@ -22,7 +22,6 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "version.h"
#include "config.h"
#include "options.h"
#include "configfile.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)))
{
@ -106,7 +101,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'
]
@ -47,13 +40,7 @@ tio_dep = [
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

@ -121,9 +121,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");

View file

@ -30,7 +30,7 @@ void delay(long ms);
int ctrl_key_code(unsigned char key);
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);

View file

@ -19,13 +19,10 @@
* 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 "misc.h"
#include "print.h"
@ -116,14 +113,12 @@ struct option_t option =
.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,
.map_o_msblsb = false,
};
void option_print_help(char *argv[])
@ -171,14 +166,11 @@ void option_print_help(char *argv[])
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");
}
@ -397,14 +389,6 @@ const char* option_timestamp_format_to_string(timestamp_t timestamp)
return "iso8601";
break;
case TIMESTAMP_EPOCH:
return "epoch";
break;
case TIMESTAMP_EPOCH_USEC:
return "epoch-usec";
break;
default:
return "unknown";
break;
@ -431,14 +415,6 @@ void option_parse_timestamp(const char *arg, timestamp_t *timestamp)
{
*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);
@ -780,10 +756,6 @@ void option_parse_mappings(const char *map)
{
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;
@ -796,13 +768,9 @@ void option_parse_mappings(const char *map)
{
option.map_o_nulbrk = true;
}
else if (strcmp(token, "OIGNCR") == 0)
else if (strcmp(token, "MSB2LSB") == 0)
{
option.map_o_ign_cr = true;
}
else if (strcmp(token, "IMSB2LSB") == 0)
{
option.map_i_msb2lsb = true;
option.map_o_msblsb = true;
}
else
{
@ -1012,10 +980,7 @@ void options_parse(int argc, char *argv[])
break;
case 't':
if (option.timestamp == TIMESTAMP_NONE)
{
option.timestamp = TIMESTAMP_24HOUR;
}
option.timestamp = TIMESTAMP_24HOUR;
break;
case OPT_TIMESTAMP_FORMAT:
@ -1105,7 +1070,7 @@ void options_parse(int argc, char *argv[])
break;
case 'v':
printf("tio %s\n", VERSION);
printf("tio v%s\n", VERSION);
exit(EXIT_SUCCESS);
break;

View file

@ -98,14 +98,12 @@ struct option_t
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;
bool map_o_msblsb;
};
extern struct option_t option;

View file

@ -85,28 +85,5 @@ void print(const char *format, ...)
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);
}
print_tainted = false;
}

View file

@ -140,4 +140,3 @@ 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

@ -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");
break;
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");
break;
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;
}
// lua: string = tio.readline(timeout)
static int api_readline(lua_State *L) {
int timeout = lua_tointeger(L, 1); //ms
luaL_Buffer b;
char ch;
// 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");
}
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)
{
luaL_pushresult(&b);
maybe_echo(L);
lua_pushnil(L);
lua_insert(L, -2);
return 2;
}
if (ch == '\n')
{
luaL_pushresult(&b);
maybe_echo(L);
return 1;
}
luaL_addchar(&b, ch);
ssize_t bytes_read = read_poll(device_fd, buffer, size, timeout);
if (bytes_read < 0)
{
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;
}
// lua: table = tio.ttysearch()
static int api_ttysearch(lua_State *L)
// lua: expect(string, timeout)
static int expect(lua_State *L)
{
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;
}
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;
}
}
// 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,7 +445,65 @@ static void script_buffer_run(lua_State *L, const char *script_buffer)
}
}
static void script_file_run(lua_State *L, const char *filename)
static const struct luaL_Reg tio_lib[] =
{
{ "sleep", sleep_},
{ "msleep", msleep},
{ "line_set", line_set},
{ "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;
error = luaL_loadbuffer(L, script_init, strlen(script_init), "tio") || lua_pcall(L, 0, 0, 0);
if (error)
{
tio_error_print("%s\n", lua_tostring(L, -1));
lua_pop(L, 1); // Pop error message from the stack
}
}
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)
{
@ -440,39 +519,13 @@ static void script_file_run(lua_State *L, const char *filename)
}
}
static const struct luaL_Reg tio_lib[] =
{
{ "echo", api_echo},
{ "sleep", api_sleep},
{ "msleep", api_msleep},
{ "line_set", line_set},
{ "send", api_send},
{ "write", api_write},
{ "read", api_read},
{ "readline", api_readline},
{ "ttysearch", api_ttysearch},
{NULL, NULL}
};
static void script_load(lua_State *L)
{
int error;
error = luaL_loadbuffer(L, script_init, strlen(script_init), "tio") || lua_pcall(L, 0, 0, 0);
if (error)
{
tio_error_print("%s\n", lua_tostring(L, -1));
lua_pop(L, 1); // Pop error message from the stack
}
}
static void script_set_global(lua_State *L, const char *name, long value)
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,14 +535,6 @@ 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)
{
lua_State *L;
@ -499,15 +544,8 @@ 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);

View file

@ -226,11 +226,7 @@ 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);
@ -274,12 +270,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
{
tio_error_printf_silent("Failed to write to socket (%s)", strerror(errno));
close(clientfds[i]);

View file

@ -29,6 +29,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,29 +76,16 @@ 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);
}
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;

View file

@ -28,12 +28,8 @@ 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);

619
src/tty.c
View file

@ -22,16 +22,6 @@
#if defined(__linux__)
#include <linux/serial.h>
#endif
#if defined(__APPLE__) || defined(__MACH__)
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOBSD.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/serial/IOSerialKeys.h>
#include <IOKit/usb/IOUSBLib.h>
#endif
#include "version.h"
#include "config.h"
#include <stdarg.h>
#include <stdio.h>
@ -74,7 +64,6 @@
#include "script.h"
#include "xymodem.h"
#include "fs.h"
#include "readline.h"
/* tty device listing configuration */
@ -98,6 +87,9 @@
#define CMSPAR 010000000000
#endif
#define MAX_LINE_LEN PATH_MAX
#define MAX_HISTORY 1000
#define KEY_0 0x30
#define KEY_1 0x31
#define KEY_2 0x32
@ -181,8 +173,7 @@ static char *tty_buffer_write_ptr = tty_buffer;
static pthread_t thread;
static int pipefd[2];
static pthread_mutex_t mutex_input_ready = PTHREAD_MUTEX_INITIALIZER;
static char line[PATH_MAX];
static size_t listing_device_name_length_max = 0;
static char line[MAX_LINE_LEN];
static void optional_local_echo(char c)
{
@ -590,7 +581,7 @@ static int tio_readln(void)
char *p = line;
/* Read line, accept BS and DEL as rubout characters */
for (p = line ; p < &line[PATH_MAX-1]; )
for (p = line ; p < &line[MAX_LINE_LEN-1]; )
{
if (read(pipefd[0], p, 1) > 0)
{
@ -632,25 +623,22 @@ void tty_output_mode_set(output_mode_t mode)
static void mappings_print(void)
{
if (option.map_i_cr_nl || option.map_ign_cr || option.map_i_ff_escc ||
option.map_i_nl_cr || option.map_i_nl_crnl || option.map_i_cr_crnl ||
option.map_o_cr_nl || option.map_o_del_bs || option.map_o_nl_crnl ||
option.map_o_ltu || option.map_o_nulbrk || option.map_i_msb2lsb ||
option.map_o_ign_cr)
option.map_i_nl_cr || option.map_i_nl_crnl || option.map_o_cr_nl ||
option.map_o_del_bs || option.map_o_nl_crnl || option.map_o_ltu ||
option.map_o_nulbrk || option.map_o_msblsb)
{
tio_printf(" Mappings:%s%s%s%s%s%s%s%s%s%s%s%s%s",
tio_printf(" Mappings:%s%s%s%s%s%s%s%s%s%s%s",
option.map_i_cr_nl ? " ICRNL" : "",
option.map_ign_cr ? " IGNCR" : "",
option.map_i_ff_escc ? " IFFESCC" : "",
option.map_i_nl_cr ? " INLCR" : "",
option.map_i_nl_crnl ? " INLCRNL" : "",
option.map_i_cr_crnl ? " ICRCRNL" : "",
option.map_i_msb2lsb ? " IMSB2LSB" : "",
option.map_o_cr_nl ? " OCRNL" : "",
option.map_o_del_bs ? " ODELBS" : "",
option.map_o_nl_crnl ? " ONLCRNL" : "",
option.map_o_ltu ? " OLTU" : "",
option.map_o_nulbrk ? " ONULBRK" : "",
option.map_o_ign_cr ? " OIGNCR" : "");
option.map_o_msblsb ? " MSB2LSB" : "");
}
else
{
@ -724,12 +712,9 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward)
tio_printf_raw("Enter file name: ");
if (tio_readln())
{
int ret;
tio_printf("Sending file '%s' ", line);
tio_printf("Press any key to abort transfer");
ret = xymodem_send(device_fd, line, XMODEM_1K);
tio_printf("%s", ret < 0 ? "Aborted" : "Done");
tio_printf("%s", xymodem_send(device_fd, line, XMODEM_1K) < 0 ? "Aborted" : "Done");
}
break;
@ -738,12 +723,9 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward)
tio_printf_raw("Enter file name: ");
if (tio_readln())
{
int ret;
tio_printf("Sending file '%s' ", line);
tio_printf("Press any key to abort transfer");
ret = xymodem_send(device_fd, line, XMODEM_CRC);
tio_printf("%s", ret < 0 ? "Aborted" : "Done");
tio_printf("%s", xymodem_send(device_fd, line, XMODEM_CRC) < 0 ? "Aborted" : "Done");
}
break;
@ -752,12 +734,9 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward)
tio_printf_raw("Enter file name: ");
if (tio_readln())
{
int ret;
tio_printf("Ready to receiving file '%s' ", line);
tio_printf("Press any key to abort transfer");
ret = xymodem_send(device_fd, line, XMODEM_CRC);
tio_printf("%s", ret < 0 ? "Aborted" : "Done");
tio_printf("%s", xymodem_receive(device_fd, line, XMODEM_CRC) < 0 ? "Aborted" : "Done");
}
break;
@ -794,36 +773,28 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward)
tio_printf("INLCRNL is %s", option.map_i_nl_crnl ? "set" : "unset");
break;
case KEY_5:
option.map_i_cr_crnl = !option.map_i_cr_crnl;
tio_printf("ICRCRNL is %s", option.map_i_cr_crnl ? "set" : "unset");
break;
case KEY_6:
option.map_i_msb2lsb = !option.map_i_msb2lsb;
tio_printf("IMSB2LSB is %s", option.map_i_msb2lsb ? "set" : "unset");
break;
case KEY_7:
option.map_o_cr_nl = !option.map_o_cr_nl;
tio_printf("OCRNL is %s", option.map_o_cr_nl ? "set" : "unset");
break;
case KEY_8:
case KEY_6:
option.map_o_del_bs = !option.map_o_del_bs;
tio_printf("ODELBS is %s", option.map_o_del_bs ? "set" : "unset");
break;
case KEY_9:
case KEY_7:
option.map_o_nl_crnl = !option.map_o_nl_crnl;
tio_printf("ONLCRNL is %s", option.map_o_nl_crnl ? "set" : "unset");
break;
case KEY_A:
case KEY_8:
option.map_o_ltu = !option.map_o_ltu;
tio_printf("OLTU is %s", option.map_o_ltu ? "set" : "unset");
break;
case KEY_B:
case KEY_9:
option.map_o_nulbrk = !option.map_o_nulbrk;
tio_printf("ONULBRK is %s", option.map_o_nulbrk ? "set" : "unset");
break;
case KEY_C:
option.map_o_ign_cr = !option.map_o_ign_cr;
tio_printf("OIGNCR is %s", option.map_o_ign_cr ? "set" : "unset");
case KEY_A:
option.map_o_msblsb = !option.map_o_msblsb;
tio_printf("MSB2LSB is %s", option.map_o_msblsb ? "set" : "unset");
break;
default:
tio_error_print("Invalid input");
@ -1022,23 +993,19 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward)
tio_printf(" (3) INLCR: %s mapping NL to CR on input",
option.map_i_nl_cr ? "Unset" : "Set");
tio_printf(" (4) INLCRNL: %s mapping NL to CR-NL on input",
option.map_i_nl_crnl ? "Unset" : "Set");
tio_printf(" (5) ICRCRNL: %s mapping CR to CR-NL on input",
option.map_i_cr_crnl ? "Unset" : "Set");
tio_printf(" (6) IMSB2LSB: %s mapping MSB bit order to LSB on input",
option.map_i_msb2lsb ? "Unset" : "Set");
tio_printf(" (7) OCRNL: %s mapping CR to NL on output",
option.map_i_nl_cr ? "Unset" : "Set");
tio_printf(" (5) OCRNL: %s mapping CR to NL on output",
option.map_o_cr_nl ? "Unset" : "Set");
tio_printf(" (8) ODELBS: %s mapping DEL to BS on output",
tio_printf(" (6) ODELBS: %s mapping DEL to BS on output",
option.map_o_del_bs ? "Unset" : "Set");
tio_printf(" (9) ONLCRNL: %s mapping NL to CR-NL on output",
tio_printf(" (7) ONLCRNL: %s mapping NL to CR-NL on output",
option.map_o_nl_crnl ? "Unset" : "Set");
tio_printf(" (a) OLTU: %s mapping lowercase to uppercase on output",
tio_printf(" (8) OLTU: %s mapping lowercase to uppercase on output",
option.map_o_ltu ? "Unset" : "Set");
tio_printf(" (b) ONULBRK: %s mapping NUL to send break signal on output",
tio_printf(" (9) ONULBRK: %s mapping NUL to send break signal on output",
option.map_o_nulbrk ? "Unset" : "Set");
tio_printf(" (c) OIGNCR: %s ignoring CR on output",
option.map_o_ign_cr ? "Unset" : "Set");
tio_printf(" (a) MSB2LSB: %s mapping MSB bit order to LSB on output",
option.map_o_msblsb ? "Unset" : "Set");
// Process next input character as sub command
sub_command = SUBCOMMAND_MAP;
@ -1097,12 +1064,6 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward)
case TIMESTAMP_ISO8601:
tio_printf("Switched timestamp mode to iso8601");
break;
case TIMESTAMP_EPOCH:
tio_printf("Switched timestamp mode to epoch");
break;
case TIMESTAMP_EPOCH_USEC:
tio_printf("Switched timestamp mode to epoch with subdivision in microseconds");
break;
case TIMESTAMP_END:
option.timestamp = TIMESTAMP_NONE;
tio_printf("Switched timestamp mode off");
@ -1111,7 +1072,7 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward)
break;
case KEY_V:
tio_printf("tio %s", VERSION);
tio_printf("tio v%s", VERSION);
break;
case KEY_X:
@ -1127,12 +1088,9 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward)
tio_printf("Send file with YMODEM");
tio_printf_raw("Enter file name: ");
if (tio_readln()) {
int ret;
tio_printf("Sending file '%s' ", line);
tio_printf("Press any key to abort transfer");
ret = xymodem_send(device_fd, line, YMODEM);
tio_printf("%s", ret < 0 ? "Aborted" : "Done");
tio_printf("%s", xymodem_send(device_fd, line, YMODEM) < 0 ? "Aborted" : "Done");
}
break;
@ -1204,6 +1162,10 @@ void stdout_configure(void)
{
int status;
/* Disable line buffering in stdout. This is necessary if we
* want things like local echo to work correctly. */
setvbuf(stdout, NULL, _IONBF, 0);
/* Save current stdout settings */
if (tcgetattr(STDOUT_FILENO, &stdout_old) < 0)
{
@ -1440,14 +1402,6 @@ static bool is_serial_device(const char *format, ...)
return false;
}
#if defined(__APPLE__)
// Make sure device name is on the form /dev/cu.* or /dev/tty.*
if ((strncmp(filename, "/dev/cu.", 8) != 0) && (strncmp(filename, "/dev/tty.", 9) != 0))
{
return false;
}
#endif
fd = open(filename, O_RDONLY | O_NONBLOCK | O_NOCTTY);
if (fd == -1)
{
@ -1631,7 +1585,6 @@ const char* get_serial_port_type(const char* port_name)
const char* get_serial_port_type(const char* port_name)
{
(void)port_name;
return "";
}
@ -1661,9 +1614,6 @@ static void search_reset(void)
// Indicate an empty list
device_list = NULL;
// Reset max device name length
listing_device_name_length_max = 0;
}
#if defined(__linux__)
@ -1753,8 +1703,7 @@ GList *tty_search_for_serial_devices(void)
// Hash remaining string to get unique topology ID
unsigned long hash = djb2_hash((const unsigned char *)devices_path);
char tid[5];
base62_encode(hash, tid);
char *tid = base62_encode(hash);
free(devices_path);
// Construct the path to the device's driver symlink
@ -1785,22 +1734,18 @@ GList *tty_search_for_serial_devices(void)
creation_time = fs_get_creation_time(path);
double uptime = current_time - creation_time;
// Read sysfs files to get best possible description
// Read sysfs files to get best possible description of the driver
char description[50] = {};
length = fs_read_file_stripped(description, sizeof(description), "/sys/class/tty/%s/device/../product", entry->d_name);
if (length == -1)
{
length = fs_read_file_stripped(description, sizeof(description), "/sys/class/tty/%s/device/../../product", entry->d_name);
}
if (length == -1)
{
length = fs_read_file_stripped(description, sizeof(description), "/sys/class/tty/%s/device/interface", entry->d_name);
}
length = fs_read_file_stripped(description, sizeof(description), "/sys/class/tty/%s/device/interface", entry->d_name);
if (length == -1)
{
length = fs_read_file_stripped(description, sizeof(description), "/sys/class/tty/%s/device/../interface", entry->d_name);
}
if (length == -1)
{
length = fs_read_file_stripped(description, sizeof(description), "/sys/class/tty/%s/device/../../product", entry->d_name);
}
if (length == -1)
{
snprintf(description, sizeof(description), "%s", get_serial_port_type(path));
}
@ -1835,12 +1780,6 @@ GList *tty_search_for_serial_devices(void)
// Add device information to device list
device_list = g_list_append(device_list, device);
// Update length of longest device name string
if (strlen(device->path) > listing_device_name_length_max)
{
listing_device_name_length_max = strlen(device->path);
}
}
if (g_list_length(device_list) == 0)
@ -1857,226 +1796,6 @@ GList *tty_search_for_serial_devices(void)
return device_list;
}
#elif defined(__APPLE__) || defined(__MACH__)
char *getPropertyString(io_object_t device, CFStringRef property)
{
/* Validate inputs */
if (device == IO_OBJECT_NULL || property == NULL)
{
return NULL;
}
/* Attempt to get property */
CFTypeRef valueRef = IORegistryEntryCreateCFProperty(
device, property, kCFAllocatorDefault, 0);
if (!valueRef)
{
return NULL;
}
/* Ensure it's a CFString */
if (CFGetTypeID(valueRef) != CFStringGetTypeID())
{
CFRelease(valueRef);
return NULL;
}
/* Convert to C string */
CFIndex length = CFStringGetLength(valueRef);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
char *result = malloc(maxSize);
if (!result)
{
CFRelease(valueRef);
return NULL;
}
bool converted = CFStringGetCString(
(CFStringRef)valueRef,
result,
maxSize,
kCFStringEncodingUTF8
);
CFRelease(valueRef);
if (!converted)
{
free(result);
return NULL;
}
return result;
}
char *getDeviceLocation(io_object_t device)
{
/* Validate device */
if (device == IO_OBJECT_NULL)
{
return strdup("Invalid Device");
}
/* Attempt to get location */
io_string_t location = {0};
kern_return_t result = IORegistryEntryGetLocationInPlane(
device, kIOServicePlane, location);
if (result != KERN_SUCCESS)
{
return strdup("Unknown Location");
}
/* Safely copy location */
size_t len = strnlen(location, sizeof(io_string_t));
char *trimmed_location = calloc(1, len + 1);
if (!trimmed_location)
{
return strdup("Memory Error");
}
memcpy(trimmed_location, location, len);
return trimmed_location;
}
// for __APPLE__
GList *tty_search_for_serial_devices(void)
{
search_reset();
io_iterator_t iter = IO_OBJECT_NULL;
CFMutableDictionaryRef matchingDict = NULL;
listing_device_name_length_max = 0;
/* Create matching dictionary for serial devices */
if (!(matchingDict = IOServiceMatching(kIOSerialBSDServiceValue)))
{
tio_error_print("Failed to create matching dictionary for serial devices");
return NULL;
}
/* Get matching services */
kern_return_t kernResult = IOServiceGetMatchingServices(
kIOMainPortDefault, matchingDict, &iter);
matchingDict = NULL; /* Dictionary ownership transferred */
if (kernResult != KERN_SUCCESS)
{
tio_error_print("IOServiceGetMatchingServices failed: %d", kernResult);
return NULL;
}
/* Defensive check for iterator */
if (iter == IO_OBJECT_NULL)
{
tio_error_print("Invalid device iterator");
return NULL;
}
/* Iterate through serial devices and collect information */
for (io_object_t device; (device = IOIteratorNext(iter));)
{
char *devicePath = NULL, *locationID = NULL;
char *productName = NULL, *vendorName = NULL;
char tid[5] = {0};
double uptime = 0.0;
/* Get device path - key determines if we get tty. or cu. */
//if (!(devicePath = getPropertyString(device, CFSTR(kIODialinDeviceKey))))
if (!(devicePath = getPropertyString(device, CFSTR(kIOCalloutDeviceKey))))
{
IOObjectRelease(device);
continue; /* Skip devices without a path */
}
/* Update length of longest device name string */
listing_device_name_length_max =
strlen(devicePath) > listing_device_name_length_max
? strlen(devicePath)
: listing_device_name_length_max;
/* Calculate uptime */
uptime = get_current_time() - fs_get_creation_time(devicePath);
/* Find USB device (if applicable) */
io_object_t usbDevice = IO_OBJECT_NULL;
kern_return_t usbResult = IORegistryEntryGetParentEntry(
device, kIOServicePlane, &usbDevice);
/* Traverse up the device tree to find a USB device */
while (usbResult == KERN_SUCCESS &&
!IOObjectConformsTo(usbDevice, "IOUSBDevice"))
{
io_object_t oldUsbDevice = usbDevice;
usbResult = IORegistryEntryGetParentEntry(
usbDevice, kIOServicePlane, &usbDevice);
IOObjectRelease(oldUsbDevice);
}
/* If we found a USB device */
if (usbResult == KERN_SUCCESS)
{
locationID = getDeviceLocation(usbDevice);
unsigned long hash2 = djb2_hash((const unsigned char *)(locationID ?: ""));
base62_encode(hash2, tid);
/* Get product and vendor names */
productName = getPropertyString(usbDevice, CFSTR("USB Product Name"));
vendorName = getPropertyString(usbDevice, CFSTR("USB Vendor Name"));
IOObjectRelease(usbDevice);
}
/* Create device structure */
device_t *device_info = g_new0(device_t, 1);
if (!device_info)
{
tio_error_print("Memory allocation failed for device_info");
free(devicePath);
free(locationID);
free(productName);
free(vendorName);
IOObjectRelease(device);
continue;
}
/* Populate device info */
*device_info = (device_t) {
.path = devicePath,
.tid = g_strdup(tid),
.uptime = uptime,
.driver = g_strdup(vendorName),
.description = g_strdup(productName ?: vendorName ?: "")
};
/* Add to device list */
device_list = g_list_append(device_list, device_info);
/* Clean up */
free(locationID);
free(productName);
free(vendorName);
IOObjectRelease(device);
}
/* Clean up iterator */
IOObjectRelease(iter);
/* Check if device list is empty */
if (!device_list)
{
return NULL;
}
/* Sort device list by uptime */
device_list = g_list_sort(device_list, compare_uptime);
return device_list;
}
#else
GList *tty_search_for_serial_devices(void)
@ -2134,19 +1853,13 @@ GList *tty_search_for_serial_devices(void)
// Fill in device information
device->path = g_strdup(path);
device->tid = g_strdup("");
device->tid = "";
device->uptime = uptime;
device->driver = g_strdup("");
device->description = g_strdup("");
device->driver = "";
device->description = "";
// Add device information to device list
device_list = g_list_append(device_list, device);
// Update length of longest device name string
if (strlen(device->path) > listing_device_name_length_max)
{
listing_device_name_length_max = strlen(device->path);
}
}
if (g_list_length(device_list) == 0)
@ -2171,14 +1884,8 @@ void list_serial_devices(void)
if (g_list_length(device_list) > 0)
{
if (listing_device_name_length_max < 17)
{
listing_device_name_length_max = 17;
}
print_padded("Device", listing_device_name_length_max, ' ');
printf(" TID Uptime [s] Driver Description\n");
print_padded("", listing_device_name_length_max, '-');
printf(" ---- ------------- ---------------- --------------------------\n");
printf("Device TID Uptime [s] Driver Description\n");
printf("----------------- ---- ------------- ---------------- --------------------------\n");
// Iterate through the device list
GList *iter;
@ -2187,8 +1894,7 @@ void list_serial_devices(void)
device_t *device = (device_t *) iter->data;
// Print device information
print_padded(device->path, listing_device_name_length_max, ' ');
printf(" %4s %13.3f %-16s %s\n", device->tid, device->uptime, device->driver, device->description);
printf("%-17s %4s %13.3f %-16s %s\n", device->path, device->tid, device->uptime, device->driver, device->description);
}
printf("\n");
}
@ -2357,21 +2063,8 @@ void tty_wait_for_device(void)
}
else if (status == -1)
{
#if defined(__CYGWIN__)
// Happens when port unpluged
if (errno == EACCES)
{
goto error;
}
#elif defined(__APPLE__)
if (errno == EBADF)
{
break; // tty_disconnect() will be naturally triggered by atexit()
}
#else
tio_error_printf("select() failed (%s)", strerror(errno));
exit(EXIT_FAILURE);
#endif
}
}
@ -2384,7 +2077,7 @@ void tty_wait_for_device(void)
}
else if (last_errno != errno)
{
tio_warning_printf("Could not open %s (%s)", device_name, strerror(errno));
tio_warning_printf("Could not open tty device (%s)", strerror(errno));
tio_printf("Waiting for tty device..");
last_errno = errno;
}
@ -2442,10 +2135,6 @@ void forward_to_tty(int fd, char output_char)
{
output_char = '\n';
}
if ((output_char == '\r') && (option.map_o_ign_cr))
{
return;
}
/* Map newline character */
if ((output_char == '\n' || output_char == '\r') && (option.map_o_nl_crnl))
@ -2503,17 +2192,11 @@ void forward_to_tty(int fd, char output_char)
{
handle_hex_prompt(output_char);
}
else if (option.input_mode == INPUT_MODE_NORMAL)
else
{
status = tty_write(device_fd, &output_char, 1);
if (status < 0)
{
tio_warning_printf("Could not write to tty device");
}
else
if (option.input_mode == INPUT_MODE_NORMAL)
{
optional_local_echo(output_char);
tx_total++;
}
}
break;
@ -2524,6 +2207,17 @@ void forward_to_tty(int fd, char output_char)
}
}
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
}
}
int tty_connect(void)
{
fd_set rdfs; /* Read file descriptor set */
@ -2678,7 +2372,18 @@ int tty_connect(void)
}
// Initialize readline like history
readline_init();
char *history[MAX_HISTORY];
int history_count = 0;
int history_index = 0;
for (int i = 0; i < MAX_HISTORY; ++i)
{
history[i] = NULL;
}
int line_length = 0;
int cursor_pos = 0;
int escape = 0;
/* Input loop */
while (true)
@ -2815,13 +2520,13 @@ int tty_connect(void)
break;
default:
tio_error_printf("Unknown output mode");
tio_error_printf("Unknown outut mode");
exit(EXIT_FAILURE);
break;
}
/* Convert MSB to LSB bit order */
if (option.map_i_msb2lsb)
if (option.map_o_msblsb)
{
char ch = input_char;
input_char = 0;
@ -2832,7 +2537,7 @@ int tty_connect(void)
}
/* Map input character */
if ((input_char == '\n') && (option.map_i_nl_crnl) && (!option.map_i_msb2lsb))
if ((input_char == '\n') && (option.map_i_nl_crnl) && (!option.map_o_msblsb))
{
printchar('\r');
printchar('\n');
@ -2841,16 +2546,7 @@ int tty_connect(void)
do_timestamp = true;
}
}
else if ((input_char == '\r') && (option.map_i_cr_crnl) && (!option.map_i_msb2lsb))
{
printchar('\r');
printchar('\n');
if (option.timestamp)
{
do_timestamp = true;
}
}
else if ((input_char == '\f') && (option.map_i_ff_escc) && (!option.map_i_msb2lsb))
else if ((input_char == '\f') && (option.map_i_ff_escc) && (!option.map_o_msblsb))
{
printchar('\e');
printchar('c');
@ -2929,21 +2625,157 @@ int tty_connect(void)
break;
case INPUT_MODE_LINE:
if (input_char == '\r')
switch (input_char)
{
// Carriage return
readline_input(input_char);
case '\r': // Carriage return
if (line_length > 0)
{
// Save to history
if (history_count < MAX_HISTORY)
{
history[history_count] = strndup(line, line_length);
history_count++;
}
else
{
free(history[0]);
memmove(&history[0], &history[1], (MAX_HISTORY - 1) * sizeof(char*));
history[MAX_HISTORY - 1] = strndup(line, line_length);
}
}
// Write current line to tty device
char *rl_line = readline_get();
tty_write(device_fd, rl_line, strlen(rl_line));
line[line_length] = '\0';
if (option.local_echo == false)
{
clear_line();
}
else
{
print("\r\n");
}
// Write line to tty device
tty_write(device_fd, line, line_length);
tty_sync(device_fd);
line_length = 0;
cursor_pos = 0;
history_index = history_count;
escape = 0;
break;
case 127: // Backspace
if (cursor_pos > 0)
{
memmove(&line[cursor_pos - 1], &line[cursor_pos], line_length - cursor_pos);
line_length--;
cursor_pos--;
line[line_length] = '\0';
print_line(line, cursor_pos);
}
forward = false;
escape = 0;
break;
case 27: // Escape
escape = 1;
forward = false;
break;
case '[':
if (escape == 1)
{
escape = 2;
}
else
{
escape = 0;
}
break;
case 'A':
if (escape == 2)
{
// Up arrow
if (history_index > 0)
{
history_index--;
strncpy(line, history[history_index], MAX_LINE_LEN-1);
line_length = strlen(line);
cursor_pos = line_length;
print_line(line, cursor_pos);
}
}
forward = false;
escape = 0;
break;
case 'B':
if (escape == 2)
{
// Down arrow
if (history_index < history_count - 1)
{
history_index++;
strncpy(line, history[history_index], MAX_LINE_LEN-1);
line_length = strlen(line);
cursor_pos = line_length;
print_line(line, cursor_pos);
}
else if (history_index == history_count - 1)
{
history_index++;
line_length = 0;
cursor_pos = 0;
line[line_length] = '\0';
print_line(line, cursor_pos);
}
}
forward = false;
escape = 0;
break;
case 'C':
if (escape == 2)
{
// Right arrow
if (cursor_pos < line_length)
{
cursor_pos++;
print("\x1b[C");
}
}
forward = false;
escape = 0;
break;
case 'D':
if (escape == 2)
{
// Left arrow
if (cursor_pos > 0)
{
cursor_pos--;
print("\b");
}
}
forward = false;
escape = 0;
break;
default:
if (line_length < MAX_LINE_LEN - 1)
{
memmove(&line[cursor_pos + 1], &line[cursor_pos], line_length - cursor_pos);
line[cursor_pos] = input_char;
line_length++;
cursor_pos++;
line[line_length] = '\0';
print_line(line, cursor_pos);
}
escape = 0;
break;
}
else
{
readline_input(input_char);
forward = false;
}
break;
default:
break;
@ -3010,3 +2842,4 @@ error_read:
error_open:
return TIO_ERROR;
}

View file

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