From a22b27074937cfb21ccf6747f5fa63a1299f5f9e Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 31 Aug 2024 09:23:19 +0200 Subject: [PATCH 01/59] Bump version --- meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/meson.build b/meson.build index b35e649..810f9dd 100644 --- a/meson.build +++ b/meson.build @@ -1,5 +1,5 @@ project('tio', 'c', - version : '3.7', + version : '3.8', license : [ 'GPL-2'], meson_version : '>= 0.53.2', default_options : [ 'warning_level=2', 'buildtype=release', 'c_std=gnu99' ] From 6c4b92270e72299d7260eb26d6fa3c8fdbe68f3d Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 7 Sep 2024 09:31:31 +0200 Subject: [PATCH 02/59] Add clang-format spec --- .clang-format | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..682ae09 --- /dev/null +++ b/.clang-format @@ -0,0 +1,5 @@ +BasedOnStyle: llvm +IndentWidth: 4 +AllowShortFunctionsOnASingleLine: None +KeepEmptyLinesAtTheStartOfBlocks: false +BreakBeforeBraces: Allman From 9fec68911769736ab2595fda911a835e5c21633b Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 15 Sep 2024 05:57:31 +0200 Subject: [PATCH 03/59] Fix name declaration conflict with socket send() --- src/script.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/script.c b/src/script.c index 46e6c4e..d9efb09 100644 --- a/src/script.c +++ b/src/script.c @@ -181,7 +181,7 @@ static int modem_send(lua_State *L) } // lua: send(string) -static int send(lua_State *L) +static int send_(lua_State *L) { const char *string = lua_tostring(L, 1); int ret; @@ -455,7 +455,7 @@ static const struct luaL_Reg tio_lib[] = { "msleep", msleep}, { "line_set", line_set}, { "modem_send", modem_send}, - { "send", send}, + { "send", send_}, { "read", read_string}, { "expect", expect}, { "exit", exit_}, From 4034d0ad51fce93d8e35231267303799c5ab389c Mon Sep 17 00:00:00 2001 From: konosubakonoakua Date: Wed, 25 Sep 2024 20:14:27 +0800 Subject: [PATCH 04/59] Update readme.md Update readme.md issue part Update readme.md issue part --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5c79b6f..0ab480d 100644 --- a/README.md +++ b/README.md @@ -500,9 +500,13 @@ 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. For example, to add your user to the 'dialout' group do: +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 ``` -$ sudo usermod -a -G dialout +Switch to the "dialout" group, temporary but immediately for this session. +```bash +newgrp dialout ``` From d494b9d3ac4b4ac1ccf7a99f1d227b8ed7583bfb Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Wed, 25 Sep 2024 20:51:40 +0200 Subject: [PATCH 05/59] Update README --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0ab480d..fd93d9e 100644 --- a/README.md +++ b/README.md @@ -232,19 +232,24 @@ Connect automatically to latest registered serial device: $ tio --auto-connect latest ``` -It is also possible to use exclude options to affect which serial devices are +It is 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" ``` -Exclude drivers by pattern: +And to 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 From 4fb034858ab22b6aba1bebd969fbf578f92e5465 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Tue, 15 Oct 2024 17:22:34 +0200 Subject: [PATCH 06/59] Update AUTHORS --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 8837ec0..4c95c20 100644 --- a/AUTHORS +++ b/AUTHORS @@ -59,5 +59,6 @@ Robert Lipe Heinrich Schuchardt Tomka Gergely Steve Marple +konosubakonoakua Thanks to everyone who has contributed to this project. From 7e314b2cc342966153dca21bfb9367e44586cff0 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Thu, 17 Oct 2024 18:53:36 +0200 Subject: [PATCH 07/59] Update TODO --- TODO | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO b/TODO index 962ad71..7dce847 100644 --- a/TODO +++ b/TODO @@ -1,3 +1,5 @@ + * Add mapping feature for printing non-printable characters + * Porting layer to support native win32 builds. Some of the work that needs to be done: From 330e99381e700b6172a921513354f806b78ff13c Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Fri, 25 Oct 2024 18:26:59 +0200 Subject: [PATCH 08/59] Fix memory leak in base62_encode() --- src/misc.c | 3 +-- src/misc.h | 2 +- src/tty.c | 3 ++- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/misc.c b/src/misc.c index 50fb339..bd0a429 100644 --- a/src/misc.c +++ b/src/misc.c @@ -121,10 +121,9 @@ unsigned long djb2_hash(const unsigned char *str) } // Function to encode a number to base62 -char *base62_encode(unsigned long num) +void *base62_encode(unsigned long num, char *output) { const char base62_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - char *output = (char *) malloc(5); // 4 characters + null terminator if (output == NULL) { tio_error_print("Memory allocation failed"); diff --git a/src/misc.h b/src/misc.h index 8ba8285..08ae5eb 100644 --- a/src/misc.h +++ b/src/misc.h @@ -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); -char *base62_encode(unsigned long num); +void *base62_encode(unsigned long num, char *output); 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); diff --git a/src/tty.c b/src/tty.c index 7dbd286..c4785b9 100644 --- a/src/tty.c +++ b/src/tty.c @@ -1735,7 +1735,8 @@ 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 = base62_encode(hash); + char tid[5]; + base62_encode(hash, tid); free(devices_path); // Construct the path to the device's driver symlink From ab678e6c882e19cdd0a7d5973348e74ba4099ccb Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Fri, 25 Oct 2024 19:35:13 +0200 Subject: [PATCH 09/59] Use version from git --- src/git-version.h.in | 3 +++ src/main.c | 3 ++- src/meson.build | 10 ++++++++-- src/options.c | 3 ++- src/tty.c | 3 ++- 5 files changed, 17 insertions(+), 5 deletions(-) create mode 100644 src/git-version.h.in diff --git a/src/git-version.h.in b/src/git-version.h.in new file mode 100644 index 0000000..a0d2080 --- /dev/null +++ b/src/git-version.h.in @@ -0,0 +1,3 @@ +#pragma once + +#define GIT_VERSION "@GIT_VERSION@" diff --git a/src/main.c b/src/main.c index 9e6c043..a07ba67 100644 --- a/src/main.c +++ b/src/main.c @@ -22,6 +22,7 @@ #include #include #include +#include "git-version.h" #include "config.h" #include "options.h" #include "configfile.h" @@ -101,7 +102,7 @@ int main(int argc, char *argv[]) error_enter_session_mode(); /* Print launch hints */ - tio_printf("tio v%s", VERSION); + tio_printf("tio %s", GIT_VERSION); if (interactive_mode) { tio_printf("Press ctrl-%c q to quit", option.prefix_key); diff --git a/src/meson.build b/src/meson.build index 2d506de..17cc691 100644 --- a/src/meson.build +++ b/src/meson.build @@ -1,5 +1,10 @@ +# Generate git version header +git_version_h = vcs_tag(command : ['git', 'describe', '--tags', '--always', '--dirty'], + input : 'git-version.h.in', + output :'git-version.h', + replace_string:'@GIT_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) @@ -21,7 +26,8 @@ tio_sources = [ 'xymodem.c', 'script.c', 'fs.c', - 'readline.c' + 'readline.c', + git_version_h ] diff --git a/src/options.c b/src/options.c index 19f8c8a..398279f 100644 --- a/src/options.c +++ b/src/options.c @@ -23,6 +23,7 @@ #include #include #include +#include "git-version.h" #include "config.h" #include "misc.h" #include "print.h" @@ -1085,7 +1086,7 @@ void options_parse(int argc, char *argv[]) break; case 'v': - printf("tio v%s\n", VERSION); + printf("tio %s\n", GIT_VERSION); exit(EXIT_SUCCESS); break; diff --git a/src/tty.c b/src/tty.c index c4785b9..74f6ab3 100644 --- a/src/tty.c +++ b/src/tty.c @@ -22,6 +22,7 @@ #if defined(__linux__) #include #endif +#include "git-version.h" #include "config.h" #include #include @@ -1090,7 +1091,7 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward) break; case KEY_V: - tio_printf("tio v%s", VERSION); + tio_printf("tio %s", GIT_VERSION); break; case KEY_X: From db3f109c7d413dd2f3aa1da713288e3aa28fcc23 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Thu, 7 Nov 2024 18:05:32 +0100 Subject: [PATCH 10/59] Zero initialize buffer in read_string() --- src/script.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/script.c b/src/script.c index d9efb09..484c79f 100644 --- a/src/script.c +++ b/src/script.c @@ -255,7 +255,7 @@ static int read_string(lua_State *L) int timeout = lua_tointeger(L, 2); int ret = 0; - char *buffer = malloc(size); + char *buffer = calloc(1, size); if (buffer == NULL) { ret = -1; // Error From afd82f7ac435170e425f0c7e6b3f6856e3135172 Mon Sep 17 00:00:00 2001 From: Keith Hill Date: Fri, 25 Oct 2024 11:22:56 -0500 Subject: [PATCH 11/59] + 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 --- examples/lua/read.lua | 14 ++++ examples/lua/read_line.lua | 17 +++++ man/tio.1.in | 13 +++- man/tio.1.txt | 9 ++- src/configfile.c | 2 +- src/error.c | 3 +- src/log.c | 3 +- src/options.c | 2 + src/script.c | 127 ++++++++++++++++++++++++++++++++----- src/timestamp.c | 2 - src/timestamp.h | 2 + src/tty.c | 1 + 12 files changed, 171 insertions(+), 24 deletions(-) create mode 100644 examples/lua/read.lua create mode 100644 examples/lua/read_line.lua diff --git a/examples/lua/read.lua b/examples/lua/read.lua new file mode 100644 index 0000000..2ee99db --- /dev/null +++ b/examples/lua/read.lua @@ -0,0 +1,14 @@ +read(1000, 6000) -- initial config +send("\n") +msleep(100) +read(650, 60) -- main menu +send("S") -- S menu +msleep(30) +read(650, 60) +send("t") -- Parallel Value Table +read(650, 60) +while true do + msleep(1000) + send("t") + read(650, 50) -- repeat PVT forever +end diff --git a/examples/lua/read_line.lua b/examples/lua/read_line.lua new file mode 100644 index 0000000..97f157d --- /dev/null +++ b/examples/lua/read_line.lua @@ -0,0 +1,17 @@ +read(1000, 8000) -- read initial config +send("\n") +read(650, 100) -- main menu +send("S") -- S menu +n = 1 +while n > 0 do -- while not empty, read more + n, str = read_line(25) +end +while true do + send("t") -- query PV table + msleep(880) + n = 1 + while n > 0 do -- while not empty, read more + n, str = read_line(60) + msleep(60) + end +end diff --git a/man/tio.1.in b/man/tio.1.in index 631b938..4ad15ed 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -467,7 +467,18 @@ 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. +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. + +.IP "\fBread_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. .IP "\fBset{line=state, ...}" Set state of one or multiple tty modem lines. diff --git a/man/tio.1.txt b/man/tio.1.txt index 7c872f5..6debf36 100644 --- a/man/tio.1.txt +++ b/man/tio.1.txt @@ -373,7 +373,14 @@ SCRIPT API Returns number of bytes read on success, 0 on timeout, or -1 on error. - On success, returns read string as second return value. + 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. set{line=state, ...} Set state of one or multiple tty modem lines. diff --git a/src/configfile.c b/src/configfile.c index 97fc59f..07da79a 100644 --- a/src/configfile.c +++ b/src/configfile.c @@ -209,7 +209,7 @@ static void config_parse_keys(GKeyFile *key_file, char *group) { option.timestamp = TIMESTAMP_24HOUR; } - config_get_string(key_file, group, "timestamp-format", &string, "24hour", "24hour-start", "24hour-delta", "iso8601", NULL); + config_get_string(key_file, group, "timestamp-format", &string, "24hour", "24hour-start", "24hour-delta", "iso8601", "epoch", NULL); if (string != NULL) { option_parse_timestamp(string, &option.timestamp); diff --git a/src/error.c b/src/error.c index f318378..9f6bac2 100644 --- a/src/error.c +++ b/src/error.c @@ -19,8 +19,7 @@ * 02110-1301, USA. */ -#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf - +#define _GNU_SOURCE // To access vasprintf #include #include "print.h" diff --git a/src/log.c b/src/log.c index 8966457..4131617 100644 --- a/src/log.c +++ b/src/log.c @@ -19,8 +19,7 @@ * 02110-1301, USA. */ -#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf - +#define _GNU_SOURCE // To access vasprintf #include #include #include diff --git a/src/options.c b/src/options.c index 398279f..04d5be6 100644 --- a/src/options.c +++ b/src/options.c @@ -19,6 +19,8 @@ * 02110-1301, USA. */ +#define _GNU_SOURCE // To access vasprintf + #include #include #include diff --git a/src/script.c b/src/script.c index 484c79f..b565741 100644 --- a/src/script.c +++ b/src/script.c @@ -29,6 +29,7 @@ #include #include #include +#include #include "misc.h" #include "print.h" #include "options.h" @@ -37,8 +38,11 @@ #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]; @@ -192,6 +196,8 @@ static int send_(lua_State *L) } ret = write(device_fd, string, strlen(string)); + fsync(device_fd); // flush these characters now + tcdrain(device_fd); //ensure we flushed characters to our device lua_pushnumber(L, ret); @@ -248,10 +254,39 @@ static bool match_regex(regex_t *regex) return false; } -// lua: ret,string = read_string(size, timeout) +// Function to echo a buffer to stdout and to the log +// per the option.timestamp and option.log settings +static void echo_buffer(char buffer[], ssize_t len) +{ + if (option.timestamp) + { + char *pTimeStampNow; + pTimeStampNow = timestamp_current_time(); + if (pTimeStampNow) + { + tio_printf("%s", buffer); //does timestamps for us + if (option.log) + { + log_printf("\n[%s] %s", pTimeStampNow, buffer); + } + } + } else { + for (ssize_t i=0; i 0 ? buffer : ""); free(buffer); } + else + { + lua_pushstring(L, ""); // give empty string to caller + } + return 2; +} + +// lua: ret,string = read_line(timeout) +static int read_line(lua_State *L) +{ + static char linebuf[READ_LINE_SIZE]; + int timeout = lua_tointeger(L, 1); //ms + int ret = 0; + int read_result = 1; //enable reading input from device + char ch; + int bytes_read = 0; + + linebuf[0] = '\0'; + if (timeout == 0) + { + timeout = -1; // Wait forever + } + + // loop reading input until a newline seen or timeout + while (true) + { + read_result = read_poll(device_fd, &ch, 1, timeout); + if (read_result < 0) + { + ret = -1; // Error + linebuf[bytes_read] = '\0'; + goto error_rl; + } + else if (!read_result) + { + // Timeout returns a non-empty linebuf as a 'line' + ret = bytes_read; + linebuf[bytes_read] = '\0'; + break; + } + else // we got a character, so handle it + { + if (ch == '\n') + { + linebuf[bytes_read] = '\0'; + break; + } + else if (bytes_read <= (READ_LINE_SIZE-2)) + { + if (isprint(ch)) // store all printable chars + { + linebuf[bytes_read++] = ch; + } + } + } + } + + if (bytes_read) + { + echo_buffer(linebuf, bytes_read); + } + ret = bytes_read; + +error_rl: + lua_pushnumber(L, ret); + lua_pushstring(L, linebuf); return 2; } @@ -457,6 +553,7 @@ static const struct luaL_Reg tio_lib[] = { "modem_send", modem_send}, { "send", send_}, { "read", read_string}, + { "read_line", read_line}, { "expect", expect}, { "exit", exit_}, { "tty_search", tty_search_}, diff --git a/src/timestamp.c b/src/timestamp.c index e81cda2..b5ec306 100644 --- a/src/timestamp.c +++ b/src/timestamp.c @@ -29,8 +29,6 @@ #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]; diff --git a/src/timestamp.h b/src/timestamp.h index 48e0a76..6a10d98 100644 --- a/src/timestamp.h +++ b/src/timestamp.h @@ -32,5 +32,7 @@ typedef enum TIMESTAMP_END, } timestamp_t; +#define TIME_STRING_SIZE_MAX 24 + char *timestamp_current_time(void); diff --git a/src/tty.c b/src/tty.c index 74f6ab3..0021396 100644 --- a/src/tty.c +++ b/src/tty.c @@ -1615,6 +1615,7 @@ const char* get_serial_port_type(const char* port_name) const char* get_serial_port_type(const char* port_name) { + (void)port_name; return ""; } From 4511d74a9e5455c6a764cd491d4a0b7f15c11b2c Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Thu, 7 Nov 2024 22:17:26 +0100 Subject: [PATCH 12/59] Update AUTHORS --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 4c95c20..e67ab85 100644 --- a/AUTHORS +++ b/AUTHORS @@ -60,5 +60,6 @@ Heinrich Schuchardt Tomka Gergely Steve Marple konosubakonoakua +Keith Hill Thanks to everyone who has contributed to this project. From c49faa7337bf30f28f51cf27f95e5415d2b477be Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 30 Nov 2024 11:03:40 +0100 Subject: [PATCH 13/59] Clean up lua API Rename modem_send() to send() Rename send to write() --- README.md | 32 ++++++++++++------- examples/lua/automatic-linux-login.lua | 4 +-- examples/lua/read.lua | 8 ++--- examples/lua/read_line.lua | 6 ++-- man/tio.1.in | 43 +++++++++++++------------- src/script.c | 6 ++-- 6 files changed, 55 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index fd93d9e..0f1a0aa 100644 --- a/README.md +++ b/README.md @@ -401,12 +401,30 @@ expect(string, timeout) On successful match it also returns the match string as second return value. -send(string) - Send 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. + + Returns number of bytes read on success, 0 on timeout, or -1 on error. + + On success, returns read string as second return value. + +read_line(timeout) + Read line from serial device. If timeout is 0 or not provided it will + wait forever until data is ready to read. + + Returns number of bytes read on success, 0 on timeout, or -1 on error. + + On success, returns the string that was read as second return value. + Also emits a single timestamp to stdout and log file per options.timestamp + and options.log. + +write(string) + Write string to serial device. Returns number of bytes written on success or -1 on error. -modem_send(file, protocol) +send(file, protocol) Send file using x/y-modem protocol. Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM. @@ -421,14 +439,6 @@ tty_search() 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. diff --git a/examples/lua/automatic-linux-login.lua b/examples/lua/automatic-linux-login.lua index a287b40..428caa1 100644 --- a/examples/lua/automatic-linux-login.lua +++ b/examples/lua/automatic-linux-login.lua @@ -18,9 +18,9 @@ if (1 == found) then local hostname = string.match(match_str, "^%w+") local login = logins[hostname] if (nil ~= login) then - send(login.username .. "\n") + write(login.username .. "\n") expect("Password:") - send(login.password .. "\n") + write(login.password .. "\n") else io.write("\r\nDon't know login info for " .. hostname .. "\r\n") end diff --git a/examples/lua/read.lua b/examples/lua/read.lua index 2ee99db..6baa032 100644 --- a/examples/lua/read.lua +++ b/examples/lua/read.lua @@ -1,14 +1,14 @@ read(1000, 6000) -- initial config -send("\n") +write("\n") msleep(100) read(650, 60) -- main menu -send("S") -- S menu +write("S") -- S menu msleep(30) read(650, 60) -send("t") -- Parallel Value Table +write("t") -- Parallel Value Table read(650, 60) while true do msleep(1000) - send("t") + write("t") read(650, 50) -- repeat PVT forever end diff --git a/examples/lua/read_line.lua b/examples/lua/read_line.lua index 97f157d..ef6ec20 100644 --- a/examples/lua/read_line.lua +++ b/examples/lua/read_line.lua @@ -1,13 +1,13 @@ read(1000, 8000) -- read initial config -send("\n") +write("\n") read(650, 100) -- main menu -send("S") -- S menu +write("S") -- S menu n = 1 while n > 0 do -- while not empty, read more n, str = read_line(25) end while true do - send("t") -- query PV table + write("t") -- query PV table msleep(880) n = 1 while n > 0 do -- while not empty, read more diff --git a/man/tio.1.in b/man/tio.1.in index 4ad15ed..9d75c45 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -428,7 +428,8 @@ Send ctrl-t character .PP Tio suppots Lua scripting to easily automate interaction with the tty device. -In addition to the Lua API tio makes the following functions available: +In addition to the standard Lua API tio makes the following functions +available: .TP 6n @@ -441,26 +442,6 @@ 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. -.IP "\fBsend(string)" -Send string. - -Returns number of bytes written on success or -1 on error. - -.IP "\fBmodem_send(file, protocol)" -Send file using x/y-modem protocol. - -Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM. - -.IP "\fBtty_search()" -Search for serial devices. - -Returns a table of number indexed tables, one for each serial device found. -Each of these tables contains the serial device information accessible via the -following string indexed elements "path", "tid", "uptime", "driver", -"description". - -Returns nil if no serial devices are found. - .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. @@ -480,6 +461,26 @@ 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. +.IP "\fBwrite(string)" +Write string to serial device. + +Returns number of bytes written on success or -1 on error. + +.IP "\fBsend(file, protocol)" +Send file using x/y-modem protocol. + +Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM. + +.IP "\fBtty_search()" +Search for serial devices. + +Returns a table of number indexed tables, one for each serial device found. +Each of these tables contains the serial device information accessible via the +following string indexed elements "path", "tid", "uptime", "driver", +"description". + +Returns nil if no serial devices are found. + .IP "\fBset{line=state, ...}" Set state of one or multiple tty modem lines. diff --git a/src/script.c b/src/script.c index b565741..f6023eb 100644 --- a/src/script.c +++ b/src/script.c @@ -185,7 +185,7 @@ static int modem_send(lua_State *L) } // lua: send(string) -static int send_(lua_State *L) +static int write_(lua_State *L) { const char *string = lua_tostring(L, 1); int ret; @@ -550,8 +550,8 @@ static const struct luaL_Reg tio_lib[] = { "sleep", sleep_}, { "msleep", msleep}, { "line_set", line_set}, - { "modem_send", modem_send}, - { "send", send_}, + { "send", modem_send}, + { "write", write_}, { "read", read_string}, { "read_line", read_line}, { "expect", expect}, From b8135ea6395ef6f7f437ac00f3ad205dcca86740 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 30 Nov 2024 11:37:12 +0100 Subject: [PATCH 14/59] Rename git version to simply version --- src/git-version.h.in | 3 --- src/main.c | 4 ++-- src/meson.build | 12 ++++++------ src/options.c | 4 ++-- src/tty.c | 4 ++-- src/version.h.in | 3 +++ 6 files changed, 15 insertions(+), 15 deletions(-) delete mode 100644 src/git-version.h.in create mode 100644 src/version.h.in diff --git a/src/git-version.h.in b/src/git-version.h.in deleted file mode 100644 index a0d2080..0000000 --- a/src/git-version.h.in +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -#define GIT_VERSION "@GIT_VERSION@" diff --git a/src/main.c b/src/main.c index a07ba67..1aba51b 100644 --- a/src/main.c +++ b/src/main.c @@ -22,7 +22,7 @@ #include #include #include -#include "git-version.h" +#include "version.h" #include "config.h" #include "options.h" #include "configfile.h" @@ -102,7 +102,7 @@ int main(int argc, char *argv[]) error_enter_session_mode(); /* Print launch hints */ - tio_printf("tio %s", GIT_VERSION); + tio_printf("tio %s", VERSION); if (interactive_mode) { tio_printf("Press ctrl-%c q to quit", option.prefix_key); diff --git a/src/meson.build b/src/meson.build index 17cc691..958d4e9 100644 --- a/src/meson.build +++ b/src/meson.build @@ -1,8 +1,8 @@ -# Generate git version header -git_version_h = vcs_tag(command : ['git', 'describe', '--tags', '--always', '--dirty'], - input : 'git-version.h.in', - output :'git-version.h', - replace_string:'@GIT_VERSION@') +# 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('BAUDRATE_CASES', baudrate_cases) @@ -27,7 +27,7 @@ tio_sources = [ 'script.c', 'fs.c', 'readline.c', - git_version_h + version_h ] diff --git a/src/options.c b/src/options.c index 04d5be6..e685690 100644 --- a/src/options.c +++ b/src/options.c @@ -25,7 +25,7 @@ #include #include #include -#include "git-version.h" +#include "version.h" #include "config.h" #include "misc.h" #include "print.h" @@ -1088,7 +1088,7 @@ void options_parse(int argc, char *argv[]) break; case 'v': - printf("tio %s\n", GIT_VERSION); + printf("tio %s\n", VERSION); exit(EXIT_SUCCESS); break; diff --git a/src/tty.c b/src/tty.c index 0021396..ef2f154 100644 --- a/src/tty.c +++ b/src/tty.c @@ -22,7 +22,7 @@ #if defined(__linux__) #include #endif -#include "git-version.h" +#include "version.h" #include "config.h" #include #include @@ -1091,7 +1091,7 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward) break; case KEY_V: - tio_printf("tio %s", GIT_VERSION); + tio_printf("tio %s", VERSION); break; case KEY_X: diff --git a/src/version.h.in b/src/version.h.in new file mode 100644 index 0000000..459952d --- /dev/null +++ b/src/version.h.in @@ -0,0 +1,3 @@ +#pragma once + +#define VERSION "@VERSION@" From 1b2a0ea1305baa9c266c7da057a9539f0c22b88c Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 30 Nov 2024 12:12:09 +0100 Subject: [PATCH 15/59] Update version date --- meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/meson.build b/meson.build index 810f9dd..f0f2e4d 100644 --- a/meson.build +++ b/meson.build @@ -6,7 +6,7 @@ project('tio', 'c', ) # The tag date of the project_version(), update when the version bumps. -version_date = '2024-08-31' +version_date = '2024-11-30' # Test for dynamic baudrate configuration interface compiler = meson.get_compiler('c') From 01e637cdf4d2d781a87a2fa68e49e7f8fccd0552 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 30 Nov 2024 12:17:47 +0100 Subject: [PATCH 16/59] Update NEWS --- NEWS | 33 ++++++++++++++++++++++++++++++++- README.md | 2 +- man/tio.1.in | 2 +- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/NEWS b/NEWS index 8b2eae4..0a467da 100644 --- a/NEWS +++ b/NEWS @@ -1,5 +1,36 @@ -=== tio v3.7 (2024-08-31) === +=== tio v3.8 (2024-11-30) === + + +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 diff --git a/README.md b/README.md index 0f1a0aa..9d639fe 100644 --- a/README.md +++ b/README.md @@ -359,7 +359,7 @@ color = 11 [svf2] device = /dev/ttyUSB0 baudrate = 9600 -script = expect("login: "); send("root\n"); expect("Password: "); send("root\n") +script = expect("login: "); write("root\n"); expect("Password: "); write("root\n") color = 12 [esp32] diff --git a/man/tio.1.in b/man/tio.1.in index 9d75c45..b27f299 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -722,7 +722,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 'expect("login: "); send("root\\n"); expect("Password: "); send("root\\n")' /dev/ttyUSB0 +$ tio --script 'expect("login: "); write("root\\n"); expect("Password: "); write("root\\n")' /dev/ttyUSB0 .TP Redirect device I/O to network file socket for remote TTY sharing: From 27f8f2c4e6b554a64ba732421c25f7845b2ea902 Mon Sep 17 00:00:00 2001 From: Jakob Haufe Date: Sun, 1 Dec 2024 14:20:45 +0100 Subject: [PATCH 17/59] Manpage: Fix backslash encoding Literal backslash needs to be written as \e. --- man/tio.1.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/man/tio.1.in b/man/tio.1.in index b27f299..6cdfb7c 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -435,7 +435,7 @@ available: .IP "\fBexpect(string, timeout)" Expect string - waits for string to match or timeout before continuing. -Supports regular expressions. Special characters must be escaped with '\\\\'. +Supports regular expressions. Special characters must be escaped with '\e\e'. Timeout is in milliseconds, defaults to 0 meaning it will wait forever. Returns 1 on successful match, 0 on timeout, or -1 on error. From 37994b3cc51ae6e7ad3f0617c7d0149c3293572d Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 25 Jan 2025 15:09:07 +0100 Subject: [PATCH 18/59] Add character mapping examples --- README.md | 5 +++++ examples/config/config | 5 +++++ man/tio.1.in | 5 +++++ 3 files changed, 15 insertions(+) diff --git a/README.md b/README.md index 9d639fe..129e616 100644 --- a/README.md +++ b/README.md @@ -275,6 +275,11 @@ 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 diff --git a/examples/config/config b/examples/config/config index 8cc9017..01e84dd 100644 --- a/examples/config/config +++ b/examples/config/config @@ -71,3 +71,8 @@ device = /dev/ttyUSB0 color = 14 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 diff --git a/man/tio.1.in b/man/tio.1.in index 6cdfb7c..19c36da 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -751,6 +751,11 @@ 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: From f389f116693afe126c9e604f2860c55072c4a610 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 26 Jan 2025 16:41:24 +0100 Subject: [PATCH 19/59] Update plaintext man page --- man/tio.1.txt | 52 ++++++++++++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/man/tio.1.txt b/man/tio.1.txt index 6debf36..d8a277d 100644 --- a/man/tio.1.txt +++ b/man/tio.1.txt @@ -1,4 +1,4 @@ -tio(1) User Commands tio(1) +tio(1) User Commands tio(1) NAME tio - a serial device I/O tool @@ -218,7 +218,8 @@ 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 multiplexed 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 multi‐ + plexed to the terminal and all connected clients. Sockets remain open while the serial port is disconnected, and writes will block. @@ -342,7 +343,7 @@ KEY COMMANDS SCRIPT API Tio suppots Lua scripting to easily automate interaction with the tty device. - In addition to the Lua API tio makes the following functions available: + In addition to the standard 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. @@ -351,29 +352,12 @@ SCRIPT API On successful match it also returns the match string as second return value. - send(string) - Send string. - - Returns number of bytes written on success or -1 on error. - - modem_send(file, protocol) - Send file using x/y-modem protocol. - - Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM. - - tty_search() - Search for serial devices. - - Returns a table of number indexed tables, one for each serial device found. Each of these tables contains the serial device information accessible via the following string indexed elements "path", "tid", "uptime", "driver", "description". - - Returns nil if no serial devices are found. - read(size, timeout) Read from serial device. If timeout is 0 or not provided it will wait forever until data is ready to read. Returns number of bytes read on success, 0 on timeout, or -1 on error. - 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. + 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. @@ -382,6 +366,24 @@ SCRIPT API On success, returns the string that was read as second return value. Also emits a single timestamp to stdout and log file per options.timestamp and options.log. + write(string) + Write string to serial device. + + Returns number of bytes written on success or -1 on error. + + send(file, protocol) + Send file using x/y-modem protocol. + + Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM. + + tty_search() + Search for serial devices. + + Returns a table of number indexed tables, one for each serial device found. Each of these tables contains the serial device information accessible via the following string indexed elements "path", "tid", "uptime", "dri‐ + ver", "description". + + Returns nil if no serial devices are found. + set{line=state, ...} Set state of one or multiple tty modem lines. @@ -572,7 +574,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: "); send("root\n"); expect("Password: "); send("root\n")' /dev/ttyUSB0 + $ tio --script 'expect("login: "); write("root\n"); expect("Password: "); write("root\n")' /dev/ttyUSB0 Redirect device I/O to network file socket for remote TTY sharing: @@ -594,6 +596,10 @@ 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 @@ -608,4 +614,4 @@ WEBSITE AUTHOR Maintained by Martin Lund . -tio 3.7 2024-08-31 tio(1) +tio 3.8 2024-11-30 tio(1) From 8f7bf2fd2cb2cedf5016b4d4df003c50ef7da9d1 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 8 Feb 2025 02:57:48 +0100 Subject: [PATCH 20/59] codeql: Upgrade to upload-artifact@v4 --- .github/workflows/codeql.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 3ef873f..b96d489 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -114,7 +114,7 @@ jobs: - name: Upload CodeQL results as an artifact if: success() || failure() - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: codeql-results path: ${{ steps.step1.outputs.sarif-output }} From 6831ad0eae31fc60f53e3ca9cf7bcf2b3ad8354f Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 15 Feb 2025 19:50:52 +0100 Subject: [PATCH 21/59] Fix parsing of timestamp options --- src/configfile.c | 21 ++++++++++----------- src/options.c | 5 ++++- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/configfile.c b/src/configfile.c index 07da79a..7b21bc7 100644 --- a/src/configfile.c +++ b/src/configfile.c @@ -31,6 +31,7 @@ #include #include #include "configfile.h" +#include "timestamp.h" #include "print.h" #include "rs485.h" #include "misc.h" @@ -148,7 +149,6 @@ 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,17 +204,16 @@ static void config_parse_keys(GKeyFile *key_file, char *group) g_free((void *)string); string = NULL; } - config_get_bool(key_file, group, "timestamp", &boolean); - if (boolean == true) + config_get_bool(key_file, group, "timestamp", (bool*) &option.timestamp); + if (option.timestamp != TIMESTAMP_NONE) { - option.timestamp = TIMESTAMP_24HOUR; - } - config_get_string(key_file, group, "timestamp-format", &string, "24hour", "24hour-start", "24hour-delta", "iso8601", "epoch", NULL); - if (string != NULL) - { - option_parse_timestamp(string, &option.timestamp); - g_free((void *)string); - string = NULL; + config_get_string(key_file, group, "timestamp-format", &string, "24hour", "24hour-start", "24hour-delta", "iso8601", "epoch", 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); diff --git a/src/options.c b/src/options.c index e685690..40bcc23 100644 --- a/src/options.c +++ b/src/options.c @@ -998,7 +998,10 @@ void options_parse(int argc, char *argv[]) break; case 't': - option.timestamp = TIMESTAMP_24HOUR; + if (option.timestamp == TIMESTAMP_NONE) + { + option.timestamp = TIMESTAMP_24HOUR; + } break; case OPT_TIMESTAMP_FORMAT: From 8e155c9276dc155a85b56d7d3bba5d0482d59bc0 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 23 Feb 2025 16:26:28 +0100 Subject: [PATCH 22/59] Update TODO --- TODO | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/TODO b/TODO index 7dce847..dfec023 100644 --- a/TODO +++ b/TODO @@ -1,3 +1,13 @@ + * 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. From 795ef28f79f5a9456848af3ce3e5567bb7563e0f Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Tue, 25 Feb 2025 16:16:24 +0100 Subject: [PATCH 23/59] Update TODO --- TODO | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO b/TODO index dfec023..234be9b 100644 --- a/TODO +++ b/TODO @@ -1,3 +1,5 @@ + * Support input and input mapping from lua scripts + * Add option to send file raw (no modem protocol) * Add loopback option From 1b60dd1ae768251660e5abad56ea5f71c457db94 Mon Sep 17 00:00:00 2001 From: Lubov66 Date: Mon, 10 Mar 2025 09:47:34 +0200 Subject: [PATCH 24/59] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 129e616..f12b9d7 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # tio - a serial device I/O tool -[![](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/ubuntu.yml?label=Ubuntu)](https://github.com/tio/tio/actions/workflows/ubuntu.yml) [![](https://img.shields.io/github/actions/workflow/status/tio/tio/macos.yml?label=MacOS)](https://github.com/tio/tio/actions/workflows/macos.yml) [![](https://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) From d163afc6b164f173e3ee93090d3fe6448bdb1adc Mon Sep 17 00:00:00 2001 From: Lubov66 Date: Mon, 10 Mar 2025 12:15:53 +0200 Subject: [PATCH 25/59] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f12b9d7..f2c2806 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ [![](https://img.shields.io/github/actions/workflow/status/tio/tio/ubuntu.yml?label=Ubuntu)](https://github.com/tio/tio/actions/workflows/ubuntu.yml) [![](https://img.shields.io/github/actions/workflow/status/tio/tio/macos.yml?label=MacOS)](https://github.com/tio/tio/actions/workflows/macos.yml) +[![](https://github.com/tio/tio/actions/workflows/codeql.yml/badge.svg)](https://github.com/tio/tio/actions/workflows/codeql.yml) [![](https://img.shields.io/codefactor/grade/github/tio/tio)](https://www.codefactor.io/repository/github/tio/tio) [![](https://img.shields.io/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) From f5740dbf3150bf292d77a450b9945d7870489192 Mon Sep 17 00:00:00 2001 From: Lubov66 Date: Mon, 10 Mar 2025 16:32:21 +0200 Subject: [PATCH 26/59] docs: edited the license date --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index a793eef..d5fa60d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014-2022 Martin Lund +Copyright (c) 2014-2025 Martin Lund This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License From 6aca9ffee50d5195d9a4c85da9747f99cd990221 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Mon, 10 Mar 2025 16:17:50 +0100 Subject: [PATCH 27/59] Update AUTHORS --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index e67ab85..4d35e4c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -61,5 +61,6 @@ Tomka Gergely Steve Marple konosubakonoakua Keith Hill +Lubov66 Thanks to everyone who has contributed to this project. From 7567e08227ace6992d5c98d1936fd2c119f4b49b Mon Sep 17 00:00:00 2001 From: V Date: Tue, 11 Mar 2025 13:59:45 +0000 Subject: [PATCH 28/59] Disable stdout buffering globally This makes it possible to pipe output to other programs cleanly. --- src/main.c | 4 ++++ src/tty.c | 4 ---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main.c b/src/main.c index 1aba51b..6676bb3 100644 --- a/src/main.c +++ b/src/main.c @@ -61,6 +61,10 @@ 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))) { diff --git a/src/tty.c b/src/tty.c index ef2f154..c72fd67 100644 --- a/src/tty.c +++ b/src/tty.c @@ -1184,10 +1184,6 @@ 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) { From f716d2ccdd461115973c7ca8ab579067152bb41f Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Thu, 13 Mar 2025 15:44:12 +0100 Subject: [PATCH 29/59] Update TODO --- TODO | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO b/TODO index 234be9b..6036c7b 100644 --- a/TODO +++ b/TODO @@ -1,3 +1,5 @@ + * 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) From da4074c9a5d252dabf653a377429cb85d9137775 Mon Sep 17 00:00:00 2001 From: Samuel Holland Date: Sat, 22 Mar 2025 21:35:47 -0500 Subject: [PATCH 30/59] Don't add null characters to the expect buffer They prevent regexec() from seeing the remainder of the buffer. --- src/script.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/script.c b/src/script.c index f6023eb..b471932 100644 --- a/src/script.c +++ b/src/script.c @@ -207,6 +207,11 @@ static int write_(lua_State *L) // Function to add a character to the circular expect buffer static void expect_buffer_add(char c) { + if (!c) + { + return; + } + if (buffer_size < MAX_BUFFER_SIZE) { circular_buffer[buffer_size++] = c; From d33e275ca3ba5c40435fcbf6c6fb9562c073e498 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 23 Mar 2025 07:04:47 +0100 Subject: [PATCH 31/59] Update AUTHORS --- AUTHORS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AUTHORS b/AUTHORS index 4d35e4c..21f2bad 100644 --- a/AUTHORS +++ b/AUTHORS @@ -62,5 +62,7 @@ Steve Marple konosubakonoakua Keith Hill Lubov66 +V +Samuel Holland Thanks to everyone who has contributed to this project. From 16b7aee42f82ead0ae99f36fde905bc7ed200680 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 12 Apr 2025 08:54:50 +0200 Subject: [PATCH 32/59] Update NEWS --- NEWS | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index 0a467da..cc83cde 100644 --- a/NEWS +++ b/NEWS @@ -1,5 +1,39 @@ +=== tio v3.9 (2025-04-12) === + + + +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 + +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. -=== tio v3.8 (2024-11-30) === Changes since tio v3.7 (2024-08-31): From ebce2d4ee9733b76173c4e1692c5caa5e9440d3e Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 12 Apr 2025 08:55:11 +0200 Subject: [PATCH 33/59] Bump version --- meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/meson.build b/meson.build index f0f2e4d..859eec8 100644 --- a/meson.build +++ b/meson.build @@ -1,5 +1,5 @@ project('tio', 'c', - version : '3.8', + version : '3.9', license : [ 'GPL-2'], meson_version : '>= 0.53.2', default_options : [ 'warning_level=2', 'buildtype=release', 'c_std=gnu99' ] From 600c3d7563cf8719622bec7eeff968766f387d7f Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 12 Apr 2025 08:55:40 +0200 Subject: [PATCH 34/59] Update version date --- meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/meson.build b/meson.build index 859eec8..a61dee9 100644 --- a/meson.build +++ b/meson.build @@ -6,7 +6,7 @@ project('tio', 'c', ) # The tag date of the project_version(), update when the version bumps. -version_date = '2024-11-30' +version_date = '2025-04-12' # Test for dynamic baudrate configuration interface compiler = meson.get_compiler('c') From b33045189fc3ee7b1940ba32d623d4fcb13624af Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 12 Apr 2025 08:57:25 +0200 Subject: [PATCH 35/59] Update plain text man page --- man/tio.1.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/man/tio.1.txt b/man/tio.1.txt index d8a277d..7d78859 100644 --- a/man/tio.1.txt +++ b/man/tio.1.txt @@ -614,4 +614,4 @@ WEBSITE AUTHOR Maintained by Martin Lund . -tio 3.8 2024-11-30 tio(1) +tio 3.9 2025-04-12 tio(1) From 013aebcc055f09f9cde4e6a05bc6c877b7642607 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 12 Apr 2025 09:02:22 +0200 Subject: [PATCH 36/59] Update NEWS --- NEWS | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NEWS b/NEWS index cc83cde..52e93cc 100644 --- a/NEWS +++ b/NEWS @@ -30,9 +30,9 @@ Lubov66: Jakob Haufe: - Manpage: Fix backslash encoding + * Manpage: Fix backslash encoding - Literal backslash needs to be written as \e. + Literal backslash needs to be written as \e. From 2e8671897387f25a83e56cdb87a6e97cf7cb80e1 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 13 Apr 2025 08:28:01 +0200 Subject: [PATCH 37/59] Add typos.toml --- .typos.toml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .typos.toml diff --git a/.typos.toml b/.typos.toml new file mode 100644 index 0000000..11f019f --- /dev/null +++ b/.typos.toml @@ -0,0 +1,2 @@ +[default] +extend-ignore-words-re = ["tio"] From f87f470415ad4e257f8ed8d8e2673baf5b9dbecb Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 13 Apr 2025 13:25:25 +0200 Subject: [PATCH 38/59] Fix pattern matching memory corruption --- src/configfile.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/configfile.c b/src/configfile.c index 7b21bc7..6330151 100644 --- a/src/configfile.c +++ b/src/configfile.c @@ -428,12 +428,13 @@ static char *match_and_replace(const char *str, const char *pattern, char *devic assert(pattern != NULL); assert(device != NULL); - char *string = strndup(device, PATH_MAX); + char *string = calloc(PATH_MAX, 1); 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 From 5c2ced1093c0ec7f058f182e94af47661ea34983 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 13 Apr 2025 13:27:50 +0200 Subject: [PATCH 39/59] Update NEWS --- NEWS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NEWS b/NEWS index 52e93cc..5b52e0d 100644 --- a/NEWS +++ b/NEWS @@ -12,6 +12,8 @@ Changes since tio v3.8 (2024-11-30): * Add character mapping examples + * Fix pattern matching memory corruption + Samuel Holland: * Don't add null characters to the expect buffer From bdfe87e1cbf6e3bfd48324a25ea026fcd3cc47e9 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 13 Apr 2025 13:31:06 +0200 Subject: [PATCH 40/59] Update date --- NEWS | 2 +- man/tio.1.txt | 2 +- meson.build | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/NEWS b/NEWS index 5b52e0d..4289610 100644 --- a/NEWS +++ b/NEWS @@ -1,4 +1,4 @@ -=== tio v3.9 (2025-04-12) === +=== tio v3.9 (2025-04-13) === diff --git a/man/tio.1.txt b/man/tio.1.txt index 7d78859..bf44f9d 100644 --- a/man/tio.1.txt +++ b/man/tio.1.txt @@ -614,4 +614,4 @@ WEBSITE AUTHOR Maintained by Martin Lund . -tio 3.9 2025-04-12 tio(1) +tio 3.9 2025-04-13 tio(1) diff --git a/meson.build b/meson.build index a61dee9..05f77ce 100644 --- a/meson.build +++ b/meson.build @@ -6,7 +6,7 @@ project('tio', 'c', ) # The tag date of the project_version(), update when the version bumps. -version_date = '2025-04-12' +version_date = '2025-04-13' # Test for dynamic baudrate configuration interface compiler = meson.get_compiler('c') From d682e98a66161a58b19d40092e90ec5871c3ad91 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Wed, 16 Apr 2025 10:47:39 +0200 Subject: [PATCH 41/59] codeql: Build using ubuntu-22.04 --- .github/workflows/codeql.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index b96d489..1667c7e 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -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-20.04' }} + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-22.04' }} timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }} permissions: actions: read From c736b1e35302c7242e01c16dd77572eecadbe6d1 Mon Sep 17 00:00:00 2001 From: David Ordnung Date: Wed, 23 Apr 2025 01:05:12 +0200 Subject: [PATCH 42/59] Input ICRCRNL mapping to avoid using INLCRNL with ICRNL --- man/tio.1.in | 2 ++ man/tio.1.txt | 2 ++ src/bash-completion/tio.in | 2 +- src/options.c | 5 ++++ src/options.h | 1 + src/tty.c | 53 +++++++++++++++++++++++++------------- 6 files changed, 46 insertions(+), 19 deletions(-) diff --git a/man/tio.1.in b/man/tio.1.in index 19c36da..50f6ae8 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -218,6 +218,8 @@ 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" diff --git a/man/tio.1.txt b/man/tio.1.txt index bf44f9d..c37a38c 100644 --- a/man/tio.1.txt +++ b/man/tio.1.txt @@ -168,6 +168,8 @@ 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 diff --git a/src/bash-completion/tio.in b/src/bash-completion/tio.in index d71aceb..daac432 100644 --- a/src/bash-completion/tio.in +++ b/src/bash-completion/tio.in @@ -85,7 +85,7 @@ _tio() return 0 ;; -m | --map) - COMPREPLY=( $(compgen -W "ICRNL IGNCR INLCR IFFESCC INLCRNL IMSB2LSB OCRNL ODELBS ONLCRNL OLTU ONULBRK OIGNCR" -- ${cur}) ) + COMPREPLY=( $(compgen -W "ICRNL IGNCR INLCR IFFESCC INLCRNL ICRCRNL IMSB2LSB OCRNL ODELBS ONLCRNL OLTU ONULBRK OIGNCR" -- ${cur}) ) return 0 ;; --timestamp-format) diff --git a/src/options.c b/src/options.c index 40bcc23..3bdbfef 100644 --- a/src/options.c +++ b/src/options.c @@ -116,6 +116,7 @@ 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, @@ -770,6 +771,10 @@ 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; diff --git a/src/options.h b/src/options.h index dadf133..c552217 100644 --- a/src/options.h +++ b/src/options.h @@ -98,6 +98,7 @@ 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; diff --git a/src/tty.c b/src/tty.c index c72fd67..a2c917b 100644 --- a/src/tty.c +++ b/src/tty.c @@ -623,16 +623,18 @@ 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_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_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) { - tio_printf(" Mappings:%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%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" : "", @@ -783,30 +785,34 @@ 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_6: + 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_7: + case KEY_8: 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_8: + case KEY_9: 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_9: + case KEY_A: option.map_o_ltu = !option.map_o_ltu; tio_printf("OLTU is %s", option.map_o_ltu ? "set" : "unset"); break; - case KEY_A: + case KEY_B: option.map_o_nulbrk = !option.map_o_nulbrk; tio_printf("ONULBRK is %s", option.map_o_nulbrk ? "set" : "unset"); break; - case KEY_B: + 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"); break; @@ -1007,20 +1013,22 @@ 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_cr ? "Unset" : "Set"); - tio_printf(" (5) IMSB2LSB: %s mapping MSB bit order to LSB 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(" (6) OCRNL: %s mapping CR to NL on output", + tio_printf(" (7) OCRNL: %s mapping CR to NL on output", option.map_o_cr_nl ? "Unset" : "Set"); - tio_printf(" (7) ODELBS: %s mapping DEL to BS on output", + tio_printf(" (8) ODELBS: %s mapping DEL to BS on output", option.map_o_del_bs ? "Unset" : "Set"); - tio_printf(" (8) ONLCRNL: %s mapping NL to CR-NL on output", + tio_printf(" (9) ONLCRNL: %s mapping NL to CR-NL on output", option.map_o_nl_crnl ? "Unset" : "Set"); - tio_printf(" (9) OLTU: %s mapping lowercase to uppercase on output", + tio_printf(" (a) OLTU: %s mapping lowercase to uppercase on output", option.map_o_ltu ? "Unset" : "Set"); - tio_printf(" (a) ONULBRK: %s mapping NUL to send break signal on output", + tio_printf(" (b) ONULBRK: %s mapping NUL to send break signal on output", option.map_o_nulbrk ? "Unset" : "Set"); - tio_printf(" (b) OIGNCR: %s ignoring CR on output", + tio_printf(" (c) OIGNCR: %s ignoring CR on output", option.map_o_ign_cr ? "Unset" : "Set"); // Process next input character as sub command @@ -2584,6 +2592,15 @@ 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)) { printchar('\e'); From 437881f0ed220e5a44153c75ef1993a04c0c9205 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Wed, 23 Apr 2025 08:15:37 +0200 Subject: [PATCH 43/59] Update AUTHORS --- AUTHORS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AUTHORS b/AUTHORS index 21f2bad..3754640 100644 --- a/AUTHORS +++ b/AUTHORS @@ -64,5 +64,7 @@ Keith Hill Lubov66 V Samuel Holland +David Ordnung + Thanks to everyone who has contributed to this project. From 03ef931fb2394f74ce2598fa112aced09cc9342a Mon Sep 17 00:00:00 2001 From: Robert Lipe Date: Thu, 24 Apr 2025 06:49:08 -0500 Subject: [PATCH 44/59] - Implemented getPropertyString(), getDeviceLocation(), tty_search_for_serial_devices() for MacOS - Added error handling and memory management - Improved code readability and consistency - Updated coding style to match project conventions - Added robust error checking for CoreFoundation property retrieval - Implemented more defensive memory allocation and type checking - Switched to using callout device key for more reliable device discovery - Added single-line block bracing consistent with project style - Improved comments and code formatting - Used `kIOCalloutDeviceKey` instead of `kIODialinDeviceKey` for device path retrieval - Enhanced type checking for CoreFoundation objects - Simplified memory management and error handling - Added additional logging and error reporting - Verified functionality on MacOS 10.11 and 10.15. Tested with ESP32-P4 and ESP32-BOX Resolves potential device discovery and memory management issues in the MacOS serial device detection code. --- src/tty.c | 269 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 265 insertions(+), 4 deletions(-) diff --git a/src/tty.c b/src/tty.c index a2c917b..6de4af7 100644 --- a/src/tty.c +++ b/src/tty.c @@ -22,6 +22,15 @@ #if defined(__linux__) #include #endif + +#if defined(__APPLE__) || defined(__MACH__) +#include +#include +#include +#include +#include +#endif + #include "version.h" #include "config.h" #include @@ -623,9 +632,9 @@ 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_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) { tio_printf(" Mappings:%s%s%s%s%s%s%s%s%s%s%s%s%s", @@ -1841,6 +1850,246 @@ 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) +{ + GList *device_list = NULL; + 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) + { + tio_error_print("No serial devices found"); + return NULL; + } + + /* Sort device list by uptime */ + device_list = g_list_sort(device_list, compare_uptime); + + /* Print header for device listing */ + print_padded("Device", listing_device_name_length_max, ' '); + printf(" TID Uptime [s] Driver Description\n"); + print_padded("", listing_device_name_length_max, '-'); + printf(" ---- -------------- ---------------- --------------------------\n"); + + /* Print sorted device list */ + for (GList *l = device_list; l; l = l->next) + { + device_t *dev = l->data; + printf("%-*s %-4s %14.3f %-16s %s\n", + (int)listing_device_name_length_max, dev->path, + dev->tid ?: "", + dev->uptime, + dev->driver ?: "", + dev->description ?: ""); + } + printf("\n"); + + return device_list; +} + #else GList *tty_search_for_serial_devices(void) @@ -2121,8 +2370,21 @@ 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 } } @@ -2761,4 +3023,3 @@ error_read: error_open: return TIO_ERROR; } - From 7516dff8023c9242ef706ffc40d9f5d45113ed3f Mon Sep 17 00:00:00 2001 From: Robert Lipe Date: Thu, 24 Apr 2025 07:12:57 -0500 Subject: [PATCH 45/59] Add missing build piece. --- src/meson.build | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/meson.build b/src/meson.build index 958d4e9..6919e7e 100644 --- a/src/meson.build +++ b/src/meson.build @@ -47,6 +47,12 @@ 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 = ['-Wno-unused-result'] if enable_setspeed2 From 5d915134a3792d8b9c6e40a1030bc0d9836cca0e Mon Sep 17 00:00:00 2001 From: Robert Lipe Date: Tue, 29 Apr 2025 00:00:42 -0500 Subject: [PATCH 46/59] Fix --auto new and --auto latest on MacOS. (redo) Git is being dumb about https://github.com/tio/tio/commit/67c071633dc6d659fae1e529a85f5990531e1669 This PR is identical to that one and will supercede it. Fix --auto new and --auto latest on MacOS. 'device_list' was both a global (eww!) and a local inside tty_search_for_serial_devices(). The local got set and returned, so it looked sane, but the caller used the global instead of the return value of the function it had just called, meaning (global) device_list was NULL while (ignored, local) device_list held a perfectly lovely linked list. Tested: tio --auto new waits for a new device to appare and connects tio --latest will connect to the most recently attached device which, in most worlds, is the most recently enumerated USB device, conveniently skipping all the bluetooth nonsense. If the lone USB device is disconnected, it then connects to one of those, meaning you really do have to restart tio. --- src/tty.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tty.c b/src/tty.c index 6de4af7..c5e6876 100644 --- a/src/tty.c +++ b/src/tty.c @@ -1938,7 +1938,7 @@ char *getDeviceLocation(io_object_t device) // for __APPLE__ GList *tty_search_for_serial_devices(void) { - GList *device_list = NULL; + search_reset(); io_iterator_t iter = IO_OBJECT_NULL; CFMutableDictionaryRef matchingDict = NULL; listing_device_name_length_max = 0; From f887756a7159967e015e3422e9ab04a82db8945f Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Tue, 29 Apr 2025 17:42:22 +0200 Subject: [PATCH 47/59] meson: Enable compiler warnings on unused result and global shadows --- src/meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/meson.build b/src/meson.build index 6919e7e..b44e9a5 100644 --- a/src/meson.build +++ b/src/meson.build @@ -53,7 +53,7 @@ if host_machine.system() == 'darwin' tio_dep += [iokit_dep, corefoundation_dep] endif -tio_c_args = ['-Wno-unused-result'] +tio_c_args = ['-Wshadow'] if enable_setspeed2 tio_c_args += '-DHAVE_TERMIOS2' From 2fb788f817be131c56d7cd44426f6d64dc42ea7c Mon Sep 17 00:00:00 2001 From: Hideaki Tai Date: Tue, 6 May 2025 15:31:45 +0900 Subject: [PATCH 48/59] fix: lua script stops output if it includes null terminate --- src/script.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/script.c b/src/script.c index b471932..1e46a33 100644 --- a/src/script.c +++ b/src/script.c @@ -187,7 +187,9 @@ static int modem_send(lua_State *L) // lua: send(string) static int write_(lua_State *L) { - const char *string = lua_tostring(L, 1); + size_t len = 0; + const char *string = lua_tolstring(L, 1, &len); + int ret; if (string == NULL) @@ -195,7 +197,7 @@ static int write_(lua_State *L) return 0; } - ret = write(device_fd, string, strlen(string)); + ret = write(device_fd, string, len); fsync(device_fd); // flush these characters now tcdrain(device_fd); //ensure we flushed characters to our device From 7e61a34df342c00f05e323cd4dc0602c19fa64d1 Mon Sep 17 00:00:00 2001 From: Maximilian Seesslen Date: Fri, 23 May 2025 16:14:16 +0200 Subject: [PATCH 49/59] Added timestamp format "epoch-usec" This timestamp format will print the seconds since epoch along with subdivision in microseconds. Example: [1748009585.087083] tio v3.9-8-g2fb788f-dirty [1748009585.087156] Press ctrl-t q to quit [1748009585.087683] Connected to /dev/ttyUSB0 --- man/tio.1.in | 2 ++ man/tio.1.txt | 2 ++ src/bash-completion/tio.in | 2 +- src/configfile.c | 2 +- src/options.c | 8 ++++++++ src/timestamp.c | 13 ++++++++++--- src/timestamp.h | 1 + src/tty.c | 3 +++ 8 files changed, 28 insertions(+), 5 deletions(-) diff --git a/man/tio.1.in b/man/tio.1.in index 50f6ae8..a7cf83f 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -150,6 +150,8 @@ Set timestamp format to any of the following timestamp formats: 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 diff --git a/man/tio.1.txt b/man/tio.1.txt index c37a38c..3021890 100644 --- a/man/tio.1.txt +++ b/man/tio.1.txt @@ -116,6 +116,8 @@ OPTIONS 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 diff --git a/src/bash-completion/tio.in b/src/bash-completion/tio.in index daac432..f510b7e 100644 --- a/src/bash-completion/tio.in +++ b/src/bash-completion/tio.in @@ -89,7 +89,7 @@ _tio() return 0 ;; --timestamp-format) - COMPREPLY=( $(compgen -W "24hour 24hour-start 24hour-delta iso8601" -- ${cur}) ) + COMPREPLY=( $(compgen -W "24hour 24hour-start 24hour-delta iso8601 epoch epoch-usec" -- ${cur}) ) return 0 ;; -c | --color) diff --git a/src/configfile.c b/src/configfile.c index 6330151..ca116bf 100644 --- a/src/configfile.c +++ b/src/configfile.c @@ -207,7 +207,7 @@ static void config_parse_keys(GKeyFile *key_file, char *group) config_get_bool(key_file, group, "timestamp", (bool*) &option.timestamp); if (option.timestamp != TIMESTAMP_NONE) { - config_get_string(key_file, group, "timestamp-format", &string, "24hour", "24hour-start", "24hour-delta", "iso8601", "epoch", NULL); + 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); diff --git a/src/options.c b/src/options.c index 3bdbfef..6aeff88 100644 --- a/src/options.c +++ b/src/options.c @@ -400,6 +400,10 @@ const char* option_timestamp_format_to_string(timestamp_t timestamp) return "epoch"; break; + case TIMESTAMP_EPOCH_USEC: + return "epoch-usec"; + break; + default: return "unknown"; break; @@ -430,6 +434,10 @@ void option_parse_timestamp(const char *arg, timestamp_t *timestamp) { *timestamp = TIMESTAMP_EPOCH; } + else if (strcmp(arg, "epoch-usec") == 0) + { + *timestamp = TIMESTAMP_EPOCH_USEC; + } else { tio_error_print("Invalid timestamp '%s'", arg); diff --git a/src/timestamp.c b/src/timestamp.c index b5ec306..9273758 100644 --- a/src/timestamp.c +++ b/src/timestamp.c @@ -75,6 +75,7 @@ char *timestamp_current_time(void) 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); @@ -84,12 +85,18 @@ char *timestamp_current_time(void) return NULL; } - // Append milliseconds to all timestamps + // Append millis-/microseconds to all timestamps if (len) { - len = snprintf(time_string + len, TIME_STRING_SIZE_MAX - len, ".%03ld", (long)tv.tv_usec / 1000); + if ( option.timestamp == TIMESTAMP_EPOCH_USEC ) + { + len = snprintf(time_string + len, TIME_STRING_SIZE_MAX - len, ".%06ld", (long)tv.tv_usec); + } + else + { + len = snprintf(time_string + len, TIME_STRING_SIZE_MAX - len, ".%03ld", (long)tv.tv_usec / 1000); + } } - // Save previous time value for next run tv_previous = tv_now; diff --git a/src/timestamp.h b/src/timestamp.h index 6a10d98..0544544 100644 --- a/src/timestamp.h +++ b/src/timestamp.h @@ -29,6 +29,7 @@ typedef enum TIMESTAMP_24HOUR_DELTA, TIMESTAMP_ISO8601, TIMESTAMP_EPOCH, + TIMESTAMP_EPOCH_USEC, TIMESTAMP_END, } timestamp_t; diff --git a/src/tty.c b/src/tty.c index c5e6876..c38d5dc 100644 --- a/src/tty.c +++ b/src/tty.c @@ -1100,6 +1100,9 @@ void handle_command_sequence(char input_char, char *output_char, bool *forward) 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"); From 58bf5c500886596d9eda188c7be58ec764eb9a13 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sun, 25 May 2025 19:46:18 +0200 Subject: [PATCH 50/59] Update tio man page --- man/tio.1.in | 4 ++-- man/tio.1.txt | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/man/tio.1.in b/man/tio.1.in index a7cf83f..9d5ebee 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -447,8 +447,8 @@ 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. .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. +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. diff --git a/man/tio.1.txt b/man/tio.1.txt index 3021890..4363879 100644 --- a/man/tio.1.txt +++ b/man/tio.1.txt @@ -357,7 +357,7 @@ SCRIPT API On successful match it also returns the match string as second return value. read(size, timeout) - Read from serial device. If timeout is 0 or not provided it will wait forever until data is ready to read. + 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. From a1217af4c631345fe6d11280b4192ef24b125326 Mon Sep 17 00:00:00 2001 From: ii8 Date: Sun, 25 May 2025 19:24:11 +0100 Subject: [PATCH 51/59] Fix string truncation bug in scripting api --- src/script.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/script.c b/src/script.c index 1e46a33..8204563 100644 --- a/src/script.c +++ b/src/script.c @@ -332,7 +332,11 @@ error_rs: lua_pushnumber(L, ret); if (buffer != NULL) { - lua_pushstring(L, ret > 0 ? buffer : ""); + if (ret > 0) { + lua_pushlstring(L, buffer, ret); + } else { + lua_pushstring(L, ""); + } free(buffer); } else @@ -400,7 +404,7 @@ static int read_line(lua_State *L) error_rl: lua_pushnumber(L, ret); - lua_pushstring(L, linebuf); + lua_pushlstring(L, linebuf, ret); return 2; } From 3e0b2d861dd8e8c2da70e7494e346dc1d6de006d Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Fri, 30 May 2025 17:18:21 +0200 Subject: [PATCH 52/59] Fix Ubuntu workflow --- .github/workflows/ubuntu.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index a72e3d3..90e1a93 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -21,7 +21,8 @@ jobs: - name: Install dependencies run: | - sudo apt-get install -y bash-completion git meson liblua5.2-dev libglib2.0-dev + sudo apt update + sudo apt install -y bash-completion git meson liblua5.2-dev libglib2.0-dev - name: Build run: | From 9d00cd3492915792baf1725baaf79e22521bc563 Mon Sep 17 00:00:00 2001 From: Keith Barratt Date: Thu, 29 May 2025 15:57:11 +0100 Subject: [PATCH 53/59] Fix device description-Linux This commit only effects Linux. The description field of the `device_list`, populated by `tty_search_for_serial_devices()`, was either incorrect or less than ideal for CDC ACM virtual com ports. For instance: (i) Some devices incorrectly have the description field populated by the 'product' property of USB hub they are connected via. (ii) Other devices have description fields populated with the interface, e.g. CDC, when there is a 'product' property available that would give a clearer description. To solve these issues, we first prioritise searching for the 'product' property of the device over the 'interface' property. We also look for the 'product' property in an additional directory. --- src/tty.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/tty.c b/src/tty.c index c38d5dc..22b7eef 100644 --- a/src/tty.c +++ b/src/tty.c @@ -1785,18 +1785,22 @@ 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 of the driver + // Read sysfs files to get best possible description char description[50] = {}; - 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); - } + 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); + } + if (length == -1) + { + length = fs_read_file_stripped(description, sizeof(description), "/sys/class/tty/%s/device/../interface", entry->d_name); + } + if (length == -1) { snprintf(description, sizeof(description), "%s", get_serial_port_type(path)); } From 8f33cff6ead809fbf08ff19c2cd720e4de7304d5 Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 31 May 2025 19:42:08 +0200 Subject: [PATCH 54/59] Disable compiler warning on unused result --- src/meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/meson.build b/src/meson.build index b44e9a5..05168f7 100644 --- a/src/meson.build +++ b/src/meson.build @@ -53,7 +53,7 @@ if host_machine.system() == 'darwin' tio_dep += [iokit_dep, corefoundation_dep] endif -tio_c_args = ['-Wshadow'] +tio_c_args = ['-Wshadow','-Wno-unused-result'] if enable_setspeed2 tio_c_args += '-DHAVE_TERMIOS2' From 381c0b78236b97a265604801d381587bc204fc5b Mon Sep 17 00:00:00 2001 From: Martin Lund Date: Sat, 14 Jun 2025 07:03:17 +0200 Subject: [PATCH 55/59] Update codeql to v3 --- .github/workflows/codeql.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 1667c7e..8a195f4 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -51,7 +51,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 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@v2 + # uses: github/codeql-action/autobuild@v3 # ℹ️ 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@v2 + uses: github/codeql-action/analyze@v3 with: category: "/language:${{matrix.language}}" upload: false @@ -107,7 +107,7 @@ jobs: output: ${{ steps.step1.outputs.sarif-output }}/cpp.sarif - name: Upload CodeQL results to code scanning - uses: github/codeql-action/upload-sarif@v2 + uses: github/codeql-action/upload-sarif@v3 with: sarif_file: ${{ steps.step1.outputs.sarif-output }} category: "/language:${{matrix.language}}" From 86f48a2fb689dad56d0e195b4735ef0d4661e8b2 Mon Sep 17 00:00:00 2001 From: ii8 Date: Fri, 13 Jun 2025 15:49:33 +0100 Subject: [PATCH 56/59] Overhaul Lua API Lua API moved into a tio library table and names adjusted to Lua stdlib style. Regex in expect() replaced with Lua patterns so binary data can be handled. New tio.alwaysecho variable allows enabling and disabling echo to console. Read and write functions now manage complex retry and timeout logic internally, giving the user a simple "nil if fail" API like the rest of Lua. exit() was removed, os.exit() already exists in the Lua standard library. --- README.md | 104 ++--- examples/config/config | 2 +- examples/lua/automatic-linux-login.lua | 11 +- examples/lua/control-lines-test.lua | 10 +- examples/lua/read.lua | 24 +- examples/lua/read_line.lua | 28 +- examples/lua/serial-device-search.lua | 2 +- man/tio.1.in | 58 ++- src/script.c | 544 +++++++++---------------- 9 files changed, 318 insertions(+), 465 deletions(-) diff --git a/README.md b/README.md index f2c2806..e3ab066 100644 --- a/README.md +++ b/README.md @@ -288,12 +288,12 @@ $ cat data.bin | tio /dev/ttyUSB0 Manipulate modem lines on connect: ``` -$ tio --script "set{DTR=high,RTS=low}; msleep(100); set{DTR=toggle,RTS=toggle}" /dev/ttyUSB0 +$ tio --script "tio.set{DTR=high,RTS=low}; tio.msleep(100); tio.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 "expect('\r\n', 1000)" --mute +$ echo "*IDN?" | tio /dev/ttyACM0 --script "tio.expect('\r\n', 1000)" --mute KORAD KD3305P V4.2 SN:32475045 ``` @@ -365,12 +365,12 @@ color = 11 [svf2] device = /dev/ttyUSB0 baudrate = 9600 -script = expect("login: "); write("root\n"); expect("Password: "); write("root\n") +script = tio.expect("login: "); tio.write("root\n"); tio.expect("Password: "); tio.write("root\n") color = 12 [esp32] device = /dev/serial/by-id/usb-0403_6014-if00-port0 -script = set{DTR=high,RTS=low}; msleep(100); set{DTR=low,RTS=high}; msleep(100); set{RTS=low} +script = tio.set{DTR=high,RTS=low}; tio.msleep(100); tio.set{DTR=low,RTS=high}; tio.msleep(100); tio.set{RTS=low} script-run = once color = 13 @@ -395,72 +395,80 @@ 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 Lua API tio makes the following functions available: +In addition to the standard Lua API tio makes the following functions +and variables available: -``` -expect(string, timeout) - Expect string - waits for string to match or timeout before continueing. - Supports regular expressions. Special characters must be escaped with '\\'. - Timeout is in milliseconds, defaults to 0 meaning it will wait forever. - Returns 1 on successful match, 0 on timeout, or -1 on error. +#### `tio.expect(pattern, timeout)` - On successful match it also returns the match string as second return value. +Waits for the Lua pattern to match or timeout before continuing. +Timeout is in milliseconds, defaults to 0 meaning it will wait forever. -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 the captures from the pattern or `nil` on timeout. - Returns number of bytes read on success, 0 on timeout, or -1 on error. +#### `tio.read(size, timeout)` - On success, returns read string as second return value. +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. -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 a string up to `size` bytes long on success and `nil` on timeout. - Returns number of bytes read on success, 0 on timeout, or -1 on error. +#### `tio.readline(timeout)` - 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. +Read line from serial device. If timeout is 0 or not provided it will wait +forever until data is ready to read. -write(string) - Write string to serial device. +Returns a string on success and `nil` on timeout. On timeout a partially read +line may be returned as a second return value. - Returns number of bytes written on success or -1 on error. +#### `tio.write(string)` -send(file, protocol) - Send file using x/y-modem protocol. +Write string to serial device. - Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM. +Returns the `tio` table. -tty_search() - Search for serial devices. +#### `tio.send(file, protocol)` - 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". +Send file using x/y-modem protocol. - Returns nil if no serial devices are found. +Protocol can be any of `XMODEM_1K`, `XMODEM_CRC`, `YMODEM`. -set{line=state, ...} - Set state of one or multiple tty modem lines. +#### `tio.ttysearch()` - Line can be any of DTR, RTS, CTS, DSR, CD, RI +Search for serial devices. - State is high, low, or toggle. +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". -sleep(seconds) - Sleep for seconds. +Returns `nil` if no serial devices are found. -msleep(ms) - Sleep for miliseconds. +#### `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`. -exit(code) - Exit with exit code. -``` ## 4. Installation diff --git a/examples/config/config b/examples/config/config index 01e84dd..7bd141e 100644 --- a/examples/config/config +++ b/examples/config/config @@ -69,7 +69,7 @@ color = 13 [esp32] device = /dev/ttyUSB0 color = 14 -script = set{DTR=high,RTS=low}; msleep(100); set{DTR=low,RTS=high}; msleep(100); set{RTS=low} +script = tio.set{DTR=high,RTS=low}; tio.msleep(100); tio.set{DTR=low,RTS=high}; tio.msleep(100); tio.set{RTS=low} script-run = always [buspirate] diff --git a/examples/lua/automatic-linux-login.lua b/examples/lua/automatic-linux-login.lua index 428caa1..aa7a990 100644 --- a/examples/lua/automatic-linux-login.lua +++ b/examples/lua/automatic-linux-login.lua @@ -13,14 +13,13 @@ local logins = { }, } -local found, match_str = expect("\\w+- login:", 10) -if (1 == found) then - local hostname = string.match(match_str, "^%w+") +local hostname = tio.expect("^(%g+) login:", 10) +if hostname then local login = logins[hostname] if (nil ~= login) then - write(login.username .. "\n") - expect("Password:") - write(login.password .. "\n") + tio.write(login.username .. "\n") + tio.expect("Password:") + tio.write(login.password .. "\n") else io.write("\r\nDon't know login info for " .. hostname .. "\r\n") end diff --git a/examples/lua/control-lines-test.lua b/examples/lua/control-lines-test.lua index 5b54ab4..55d98b5 100644 --- a/examples/lua/control-lines-test.lua +++ b/examples/lua/control-lines-test.lua @@ -1,5 +1,5 @@ -set{DTR=high, RTS=low} -msleep(100) -set{DTR=low, RTS=high} -msleep(100) -set{RTS=toggle} +tio.set{DTR=high, RTS=low} +tio.msleep(100) +tio.set{DTR=low, RTS=high} +tio.msleep(100) +tio.set{RTS=toggle} diff --git a/examples/lua/read.lua b/examples/lua/read.lua index 6baa032..6452816 100644 --- a/examples/lua/read.lua +++ b/examples/lua/read.lua @@ -1,14 +1,14 @@ -read(1000, 6000) -- initial config -write("\n") -msleep(100) -read(650, 60) -- main menu -write("S") -- S menu -msleep(30) -read(650, 60) -write("t") -- Parallel Value Table -read(650, 60) +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 - msleep(1000) - write("t") - read(650, 50) -- repeat PVT forever + tio.msleep(1000) + tio.write("t") + tio.read(650, 50) -- repeat PVT forever end diff --git a/examples/lua/read_line.lua b/examples/lua/read_line.lua index ef6ec20..a844b48 100644 --- a/examples/lua/read_line.lua +++ b/examples/lua/read_line.lua @@ -1,17 +1,15 @@ -read(1000, 8000) -- read initial config -write("\n") -read(650, 100) -- main menu -write("S") -- S menu -n = 1 -while n > 0 do -- while not empty, read more - n, str = read_line(25) -end +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 - write("t") -- query PV table - msleep(880) - n = 1 - while n > 0 do -- while not empty, read more - n, str = read_line(60) - msleep(60) - end + tio.write("t") -- query PV table + tio.msleep(880) + repeat + str = tio.readline(60) + tio.msleep(60) + until str == nil end diff --git a/examples/lua/serial-device-search.lua b/examples/lua/serial-device-search.lua index 120d650..77d9dbc 100644 --- a/examples/lua/serial-device-search.lua +++ b/examples/lua/serial-device-search.lua @@ -1,6 +1,6 @@ io.write("Searching... ") -local device = tty_search() +local device = tio.ttysearch() io.write("done\r\n") diff --git a/man/tio.1.in b/man/tio.1.in index 9d5ebee..eb03ec2 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -433,49 +433,40 @@ Send ctrl-t character 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: +and variables available: .TP 6n -.IP "\fBexpect(string, timeout)" -Expect string - waits for string to match or timeout before continuing. -Supports regular expressions. Special characters must be escaped with '\e\e'. +.IP "\fBtio.expect(pattern, timeout)" +Waits for the Lua pattern to match or timeout before continuing. Timeout is in milliseconds, defaults to 0 meaning it will wait forever. -Returns 1 on successful match, 0 on timeout, or -1 on error. +Returns the captures from the pattern or nil on timeout. -On successful match it also returns the match string as second return value. - -.IP "\fBread(size, timeout)" +.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. -Returns number of bytes read on success, 0 on timeout, or -1 on error. +Returns a string up to size bytes long on success and nil on timeout. -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. - -.IP "\fBread_line(timeout)" +.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 read on success, 0 on timeout, 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. -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. - -.IP "\fBwrite(string)" +.IP "\fBtio.write(string)" Write string to serial device. -Returns number of bytes written on success or -1 on error. +Returns the tio table. -.IP "\fBsend(file, protocol)" +.IP "\fBtio.send(file, protocol)" Send file using x/y-modem protocol. Protocol can be any of XMODEM_1K, XMODEM_CRC, YMODEM. -.IP "\fBtty_search()" +.IP "\fBtio.ttysearch()" Search for serial devices. Returns a table of number indexed tables, one for each serial device found. @@ -485,19 +476,26 @@ following string indexed elements "path", "tid", "uptime", "driver", Returns nil if no serial devices are found. -.IP "\fBset{line=state, ...}" +.IP "\fBtio.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. -.IP "\fBsleep(seconds)" +.IP "\fBtio.sleep(seconds)" Sleep for seconds. -.IP "\fBmsleep(ms)" +.IP "\fBtio.msleep(ms)" Sleep for milliseconds. -.IP "\fBexit(code)" -Exit with exit code. + +.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. .SH "CONFIGURATION FILE" .PP @@ -726,7 +724,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 'expect("login: "); write("root\\n"); expect("Password: "); write("root\\n")' /dev/ttyUSB0 +$ tio --script 'tio.expect("login: "); tio.write("root\\n"); tio.expect("Password: "); tio.write("root\\n")' /dev/ttyUSB0 .TP Redirect device I/O to network file socket for remote TTY sharing: @@ -747,7 +745,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 "expect('\\r\\n', 1000)" --mute +$ echo "*IDN?" | tio /dev/ttyACM0 --script "tio.expect('\\r\\n', 1000)" --mute .TP .TP @@ -768,7 +766,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 "set{DTR=high,RTS=low}; msleep(100); set{RTS=toggle}" --script-run once /dev/ttyUSB0 +$ tio --script "tio.set{DTR=high,RTS=low}; tio.msleep(100); tio.set{RTS=toggle}" --script-run once /dev/ttyUSB0 .SH "WEBSITE" .PP diff --git a/src/script.c b/src/script.c index 8204563..b69d55b 100644 --- a/src/script.c +++ b/src/script.c @@ -20,7 +20,6 @@ */ #include -#include #include #include #include @@ -45,23 +44,87 @@ #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[] = -"function set(arg)\n" +"tio.set = function(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" -" line_set(dtr, rts, cts, dsr, cd, ri)\n" -"end\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"; -// lua: sleep(seconds) -static int sleep_(lua_State *L) +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 0 && --attempts); + + if (len > 0) + return luaL_error(L, "partial write"); - ret = write(device_fd, string, len); fsync(device_fd); // flush these characters now tcdrain(device_fd); //ensure we flushed characters to our device - lua_pushnumber(L, ret); + lua_getglobal(L, "tio"); return 1; } -// Function to add a character to the circular expect buffer -static void expect_buffer_add(char c) +// lua: tio.read(size, timeout) +static int api_read(lua_State *L) { - if (!c) - { - return; - } - - if (buffer_size < MAX_BUFFER_SIZE) - { - circular_buffer[buffer_size++] = c; - } - else - { - // 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; - } -} - -// 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; -} - -// Function to echo a buffer to stdout and to the log -// per the option.timestamp and option.log settings -static void echo_buffer(char buffer[], ssize_t len) -{ - if (option.timestamp) - { - char *pTimeStampNow; - pTimeStampNow = timestamp_current_time(); - if (pTimeStampNow) - { - tio_printf("%s", buffer); //does timestamps for us - if (option.log) - { - log_printf("\n[%s] %s", pTimeStampNow, buffer); - } - } - } else { - for (ssize_t i=0; i= 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) { - ret = -1; // Error - goto error_rs; - } - else if (bytes_read == 0) - { - ret = 0; // Timeout - goto error_rs; + // On timeout return nil instead of an empty string + lua_pop(L, 1); + lua_pushnil(L); } else { - buffer[bytes_read] = (char)0; + maybe_echo(L); } - echo_buffer(&buffer[0], bytes_read); - ret = bytes_read; - -error_rs: - lua_pushnumber(L, ret); - if (buffer != NULL) - { - if (ret > 0) { - lua_pushlstring(L, buffer, ret); - } else { - lua_pushstring(L, ""); - } - free(buffer); - } - else - { - lua_pushstring(L, ""); // give empty string to caller - } - return 2; + return 1; } -// lua: ret,string = read_line(timeout) -static int read_line(lua_State *L) -{ - static char linebuf[READ_LINE_SIZE]; +// lua: string = tio.readline(timeout) +static int api_readline(lua_State *L) { int timeout = lua_tointeger(L, 1); //ms - int ret = 0; - int read_result = 1; //enable reading input from device + luaL_Buffer b; char ch; - int bytes_read = 0; - linebuf[0] = '\0'; if (timeout == 0) { timeout = -1; // Wait forever } - // loop reading input until a newline seen or timeout - while (true) - { - read_result = read_poll(device_fd, &ch, 1, timeout); - if (read_result < 0) - { - ret = -1; // Error - linebuf[bytes_read] = '\0'; - goto error_rl; - } - else if (!read_result) - { - // Timeout returns a non-empty linebuf as a 'line' - ret = bytes_read; - linebuf[bytes_read] = '\0'; - break; - } - else // we got a character, so handle it - { - if (ch == '\n') - { - linebuf[bytes_read] = '\0'; - break; - } - else if (bytes_read <= (READ_LINE_SIZE-2)) - { - if (isprint(ch)) // store all printable chars - { - linebuf[bytes_read++] = ch; - } - } - } - } + luaL_buffinit(L, &b); + luaL_prepbuffer(&b); + while (true) { + int ret = read_poll(device_fd, &ch, 1, timeout); - if (bytes_read) - { - echo_buffer(linebuf, bytes_read); - } - ret = bytes_read; + if (ret < 0) + return luaL_error(L, "%s", strerror(errno)); -error_rl: - lua_pushnumber(L, ret); - lua_pushlstring(L, linebuf, ret); - return 2; + 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); + } } -// 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(®ex, 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(®ex)) - { - ret = 1; - break; - } - } - else - { - // Timeout or error - break; - } - } - - // Cleanup - regfree(®ex); - -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) +// lua: table = tio.ttysearch() +static int api_ttysearch(lua_State *L) { UNUSED(L); GList *iter; @@ -556,66 +424,7 @@ static void script_buffer_run(lua_State *L, const char *script_buffer) } } -static const struct luaL_Reg tio_lib[] = -{ - { "sleep", sleep_}, - { "msleep", msleep}, - { "line_set", line_set}, - { "send", modem_send}, - { "write", write_}, - { "read", read_string}, - { "read_line", read_line}, - { "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) +static void script_file_run(lua_State *L, const char *filename) { if (strlen(filename) == 0) { @@ -631,13 +440,39 @@ void script_file_run(lua_State *L, const char *filename) } } -void script_set_global(lua_State *L, const char *name, long value) +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) { lua_pushnumber(L, value); lua_setglobal(L, name); } -void script_set_globals(lua_State *L) +static void script_set_globals(lua_State *L) { script_set_global(L, "toggle", 2); script_set_global(L, "high", 1); @@ -647,6 +482,14 @@ 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; @@ -656,8 +499,15 @@ void script_run(int fd, const char *script_filename) L = luaL_newstate(); luaL_openlibs(L); - // Bind tio functions - lua_register_tio(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); // Initialize globals script_set_globals(L); From cce94b9d9280415d34575103b0f7f1d783ad1b0c Mon Sep 17 00:00:00 2001 From: John Barbero Unenge Date: Mon, 16 Jun 2025 14:59:24 +0200 Subject: [PATCH 57/59] Add --complete-profiles to help printout and man pages --- man/tio.1.in | 4 ++++ man/tio.1.txt | 4 ++++ src/bash-completion/tio.in | 1 + src/options.c | 1 + 4 files changed, 10 insertions(+) diff --git a/man/tio.1.in b/man/tio.1.in index eb03ec2..eb0338d 100644 --- a/man/tio.1.in +++ b/man/tio.1.in @@ -371,6 +371,10 @@ 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 diff --git a/man/tio.1.txt b/man/tio.1.txt index 4363879..eeac82c 100644 --- a/man/tio.1.txt +++ b/man/tio.1.txt @@ -289,6 +289,10 @@ OPTIONS Execute shell command with I/O redirected to device + --complete-profiles + + Prints profiles (for shell completion) + -v, --version Display program version. diff --git a/src/bash-completion/tio.in b/src/bash-completion/tio.in index f510b7e..b3b61cb 100644 --- a/src/bash-completion/tio.in +++ b/src/bash-completion/tio.in @@ -46,6 +46,7 @@ _tio() --script-file \ --script-run \ --exec \ + --complete-profiles \ -v --version \ -h --help" diff --git a/src/options.c b/src/options.c index 6aeff88..acff7ce 100644 --- a/src/options.c +++ b/src/options.c @@ -171,6 +171,7 @@ void option_print_help(char *argv[]) printf(" --script-file Run script from file\n"); printf(" --script-run once|always|never Run script on connect (default: always)\n"); printf(" --exec 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"); From 3af4c5591e0183ea9871654ea4d62254ac23226d Mon Sep 17 00:00:00 2001 From: aiotter Date: Thu, 7 Aug 2025 23:40:39 +0900 Subject: [PATCH 58/59] Fix redundant output on macOS --- src/tty.c | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/src/tty.c b/src/tty.c index 22b7eef..efda859 100644 --- a/src/tty.c +++ b/src/tty.c @@ -2068,32 +2068,12 @@ GList *tty_search_for_serial_devices(void) /* Check if device list is empty */ if (!device_list) { - tio_error_print("No serial devices found"); return NULL; } /* Sort device list by uptime */ device_list = g_list_sort(device_list, compare_uptime); - /* Print header for device listing */ - print_padded("Device", listing_device_name_length_max, ' '); - printf(" TID Uptime [s] Driver Description\n"); - print_padded("", listing_device_name_length_max, '-'); - printf(" ---- -------------- ---------------- --------------------------\n"); - - /* Print sorted device list */ - for (GList *l = device_list; l; l = l->next) - { - device_t *dev = l->data; - printf("%-*s %-4s %14.3f %-16s %s\n", - (int)listing_device_name_length_max, dev->path, - dev->tid ?: "", - dev->uptime, - dev->driver ?: "", - dev->description ?: ""); - } - printf("\n"); - return device_list; } From 6fb3a64ba234cc255f9637ba938cf0c01e132e4a Mon Sep 17 00:00:00 2001 From: Jakob Haufe Date: Thu, 22 Jan 2026 08:33:20 +0100 Subject: [PATCH 59/59] Fix license in meson.build - Make license here match LICENSE - According to meson docs, it should not be an array --- meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/meson.build b/meson.build index 05f77ce..b95b5c0 100644 --- a/meson.build +++ b/meson.build @@ -1,6 +1,6 @@ project('tio', 'c', version : '3.9', - license : [ 'GPL-2'], + license : 'GPL-2.0-or-later', meson_version : '>= 0.53.2', default_options : [ 'warning_level=2', 'buildtype=release', 'c_std=gnu99' ] )