commit a31bce5175c82505055e0762dab6f32197a846c0 Author: Peter van Dijk Date: Mon Mar 20 19:13:09 2023 +0000 import diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..418ee82 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,27 @@ +# Use the latest 2.1 version of CircleCI pipeline process engine. +# See: https://circleci.com/docs/2.0/configuration-reference +version: 2.1 + +# Define a job to be invoked later in a workflow. +# See: https://circleci.com/docs/2.0/configuration-reference/#jobs +jobs: + build-tio: + # Specify the execution environment. You can specify an image from Dockerhub or use one of our Convenience Images from CircleCI's Developer Hub. + # See: https://circleci.com/docs/2.0/configuration-reference/#docker-machine-macos-windows-executor + docker: + - image: cimg/base:edge + # Add steps to the job + # See: https://circleci.com/docs/2.0/configuration-reference/#steps + steps: + - checkout + - run: sudo apt-get -qq update + - run: sudo apt-get install -y bash-completion git meson libinih-dev + - run: git clone https://github.com/tio/tio.git + - run: cd tio && meson build --prefix $HOME/test/tio && ninja -C build install + +# Invoke jobs via workflows +# See: https://circleci.com/docs/2.0/configuration-reference/#workflows +workflows: + build-tio-workflow: + jobs: + - build-tio diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..2cfa94a --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +custom: ["https://www.paypal.me/lundmar"] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40120d6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/build +/subprojects/libinih +*.swp +.cache diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..2941ec9 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,46 @@ +Maintainer: +Martin Lund + +Co-maintainer: +Sylvain LAFRASSE + +Contributors: +Jesper Larsen +Jeppe Ledet-Pedersen +Jakob Haufe +Jakub Wilk +Martin Hundeboll +Nick Østergaard +Adam Borowski +Robert Scheck +Dmitri Goutnik +Daniel Engberg +Petr Vaněk +qianfan Zhao +Henner Zeller +Robey Pointer +Lars Kellogg-Stedman +arichi +George Stark +Erik Moqvist +Fabrice Fontaine +Alban Bedel +Björn Stenberg +Henner Zeller +Henrik Brix Andersen +Mariusz Midor +attila-v +Yin Fengwei +Liam Beguin +Peter Collingbourne +g0mb4 +ZeroMemoryEx on GitHub +George Joseph +Robert Snell +Rui Chen +Ralph Siemsen +Victor Oliveira +Attila Veghelyi +Vyacheslav Patkov + +Thanks to everyone who has contributed to this project. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a793eef --- /dev/null +++ b/LICENSE @@ -0,0 +1,15 @@ +Copyright (c) 2014-2022 Martin Lund + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License version 2 +along with tio, in a file named COPYING. If not, see +. diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..cb608e0 --- /dev/null +++ b/NEWS @@ -0,0 +1,1730 @@ + +=== tio v2.5 === + + + +Changes since tio v2.4: + + * Update configuration file documentation + + Rename .tiorc to .tioconfig, tiorc to config, etc. + + * Add support for $HOME/.tioconfig + + Replaces what used to be $HOME/.tiorc + + * Fix double prefix key regression + +Vyacheslav Patkov: + + * Better error checking in config file, rename the file + + Accept "true", "enable", "on", "yes", "1" as true values, their + counterparts as false ones. Check integer values for errors and range. + Warn about ignored (e.g. misspelled) options. + + Check getenv() return value for NULL. + + Rename "tiorc" to "config", as it's a static INI file, not an executable + "run commands". + + + +Changes since tio v2.3: + + * Add threaded input handling + + To make tio more responsive to quit and I/O flush key command when main I/O + thread is blocked on output. + + * Fix so that is it possible to quit tio in tio etc. + + Fix regression so that it is possible to send the prefix key code to the + remote tio session without local tio session reacting to same key code + (quitting etc.). + + * Add key command to toggle log on/off + + Add key command 'ctrl-t f' which will toggle log on/off. + + If no log filename has been specified via the 'log-filename' option then + tio will automatically generate a new log filename every time the log + feature is toggled on. Meaning, when toggled multiple times, multiple + log files will be generated. + + However, if a log filename has been specified, tio will only write and + append to that same file. + + + +Changes since tio v2.2: + + * Add mute feature + + This will make tio go fully silent and not print anything. + + * Rename config variable 'tty' to 'device' + + * Deprecate tty config keyword but keep it around for now + + * Update show config + + * Update example tiorc + + + +Changes since tio v2.1: + + * Add shell completion of sub-configuration names + + Does not work with sub configuration names that contains one or more + white spaces. + + * Beautify help + + * Fix error message + + * Simplify configfile implementation + + + +Changes since tio v2.0: + + * Fix output line delay + + Apply output line delay on lines ending with \n. + + On most systems lines ends with \n or \r\n. + + * Do not print timestamps in hex mode + + * Improve input mechanism in hex mode + + Print the 2 character hex code that you input in hex mode but then + delete it before sending. This way it is easier to keep track of what + you are inputting. It basically mimics the ctrl-shift-u input mechanism + that is used to input unicode. + + * Add support for sending prefix character to serial device + + Do so by inputting prefix key twice, e.g. input ctrl-t ctrl-t to send + ctrl-t character to serial device. + + * Clean up indentation + + * Update example tiorc + +Attila Veghelyi: + + * Add bit reverse order feature + + + +Changes since tio v1.47: + + * Handle stale unix socket file + + Delete existing unix socket file if it is tested to be stale, meaning no + one is listening on it. + + * Add visual or audible alert support on connect/disconnect + + The feature is detailed via the following option: + + --alert none|bell|blink + + Set alert action on connect/disconnect. + + It will sound the bell once or blink once on successful connect. + Likewise it will sound the bell twice or blink twice on disconnect. + + Default value is "none" for no alert. + + * Add experimental RS-485 support + + Many modern RS-485 serial devices such as the ones from FTDI already + operate in RS-485 mode by default and will work with tio out of the box. + However, there are some RS-232/485 devices which need to be switched + from e.g. RS-232 to RS-485 mode to operate accordingly on the physical + level. + + This commit implements the switching mechanism and interface required to + enable RS-485 mode. It only works on Linux and with serial devices which + use device drivers that support the Linux RS-485 control interface. + + The RS-485 feature is detailed via the following options: + + --rs-485 Enable RS-485 mode + --rs-485-config Set RS-485 configuration + + Set the RS-485 configuration using the following key or key value pair + format in the configuration field: + + RTS_ON_SEND=value Set logical level (0 or 1) for RTS pin when sending + RTS_AFTER_SEND=value Set logical level (0 or 1) for RTS pin after sending + RTS_DELAY_BEFORE_SEND=value Set RTS delay (ms) before sending + RTS_DELAY_AFTER_SEND=value Set RTS delay (ms) after sending + RX_DURING_TX Receive data even while sending data + + If defining more than one key or key value pair, they must be comma + separated. + + Example use: + + $ tio /dev/ttyUSB0 --rs-485 --rs-r485-config=RTS_DELAY_AFTER_SEND=50,RX_DURING_TX + + * Add line response feature + + Add a simple line response feature to make it possible to send e.g. a + command string to your serial device and easily receive and parse a line + response. + + This is a convenience feature for simple request/response interaction + based on lines. For more advanced interaction the socket feature should + be used instead. + + The line response feature is detailed via the following options: + + -r, --response-wait + + Wait for line response then quit. A line is considered any string ending + with either CR or NL character. If no line is received tio will quit + after response timeout. + + Any tio text is automatically muted when piping a string to tio while in + response mode to make it easy to parse the response. + + --response-timeout + + Set timeout [ms] of line response (default: 100). + + Example: + + Sending a string (SCPI command) to a test instrument (Korad PSU) and + print line response: + + $ echo "*IDN?" | tio /dev/ttyACM0 --response-wait + KORAD KD3305P V4.2 SN:32477045 + + * Fix potential sscanf() overflow + + * Only print version on '--version' + + * Remove duplicate show config entry of DTR pulse duration + + * Remove MacPorts instructions + + Remove instructions for MacPorts because the port has no maintainer and + the port build definition is broken (missing dependency on libinih etc.). + + It is recommended to use brew instead. + +Peter Collingbourne: + + * Ignore SIGPIPE signals + + If the remote end of a socket is closed between when an input character + is received from the serial port and when it is written to the socket, + tio will receive a SIGPIPE signal when writing the character to the + socket, which will terminate the program. To prevent this, ignore the + signal, which will cause write(2) to return -EPIPE, causing tio to close + the socket. + + + +Changes since tio v1.46: + + * Enable log feature when using --log-filename + + No reason to not assume that the user wants to enable log when the + --log-filename is used. This way uses can skip the use of --log to + enable log. + + * Enable line buffering of log + + Replace flushing/writing of log at every log write operation with line + buffering, meaning log will be written line by line to make it more I/O + friendly but still update frequently. + + * Avoid invalid hex character messages when switching hex mode + + * Force flushing of log writes + + * Renamed tty_flush() to tty_sync() + + * Fix sync output to serial port + + Using fsync() on filedescriptors for serial ports can not be relied on. + Add use of tcdrain() to make sure data has been written by the serial + port before proceeding. + + This fixes a problem with tio sometimes not writing piped input data to + the serial port before exiting which results in the pending writes being + cancelled / flushed. + + * Clean up tty_flush() + + * Force frequent sync on tty_flush() + + * Update README + + * Update example tiorc + + * Quit from non-interactive mode using ctrl-c + + When piping to tio it will automatically enter "non-interactive" mode + which means it will not react to any input key sequences but simple read + the input stream and write it to the tty device. + + This also means that ctrl-t q can not be used to quit and so tio would + hang forever when used in non-interactive mode. + + This change allows to send the standard termination signal by pressing + ctrl-c on tio in non-interactive mode to make it quit. + + * Make sure we flush output buffer to tty when piping to tio + + * Do not return false read error when piping to tio + + * Show error message when reading port settings fail + +Victor Oliveira + + * add macports install instructions + + + +Changes since tio v1.45: + + * Rework toggle and pulse feature to support all lines + + Replace existing toggle and pulse key commands with the following + generalized key commands which allows to toggle or pulse all serial port + lines: + + ctrl-t g Toggle serial port line + ctrl-t p Pulse serial port line + + When used, user will be asked which serial line to toggle or pulse. + + Also introduce --line-pulse-duration option for setting specific pulse + duration in milliseconds for each serial line using a key value pair + format. Each key represents a serial line. The following keys are + available: DTR, RTS, CTS, DSR, DCD, RI. + + Example: + + $ tio /dev/ttyUSB0 --line-pulse-duration DTR=200,RTS=300,RI=50 + + Likewise, the pulse duration can also be set via configuration file + using the line-pulse-duration variable: + + line-pulse-duration = DTR=200,RTS=300,RI=50 + + * Upgrade inih wrap to r56 + + * Optimization + + * Add example configuration file + + +Ralph Siemsen: + + * Fix relative timestamps + + Fix the display of relative timestamps. The hack of subtracting 3600 + only works if you happen to be in a time zone that is one hour away from + UTC. When subtracting two time values, the result is an absolute + quantity (interval). These should be displayed as-is; without local time + zone nor daylight saving correction. Hence gmtime() instead of + localtime(). + + + +Changes since tio v1.44: + + * Introduce bold color option + + Introduce "bold" color option which only apply bold color formatting to + existing system color. + + Also make "bold" the default color option. + + Fixes all white issue with black on white tio text. + + * Update README + + * Change 'ctrl-t T' to 'ctrl-t t' for timestamp toggle + + * Add support for remapping prefix key + + Make it possible to remap the prefix key (default: ctrl-t) by setting + the prefix-ctrl-key variable in the configuration file. + + Allowed values are in the range a..z. + + Example, to set the prefix key to ctrl-a simply do: + + prefix-ctrl-key = a + + * Add plaintext man page + +Rui Chen: + + * docs: add homebrew installation note + + * fix macOS build + + * fix compilation error + + + +Changes since tio v1.43: + + * Simplify arbitrary baudrate code + + * Cleanup error printing routines + + Clean up so that only the following error related printing functions are + used: tio_error_printf(), tio_error_printf_silent(), + tio_warning_printf(). + + A session mode switch is introduced for error printing so that it will + print error messages with better formatting depending on in or out of + session. + + * Update README + + * Clean up man page + + * Add support for space parity + + * Rename EOL delay to Output line delay + + * Replace -U,--upcase with mapping flag OLTU + + * Simplify tty_write() + +Robert Snell: + + * Additional commands: EOL delay, lower to upper translation, added mark parity + + Added command line options: + -O, --eol-delay to have a separate delay for end of line + -U, --upper to enable translation of lower case alpha to upper case + + Added ability to set mark parity. + Added ctrl-t U key sequence to allow enable/disable lower case alpha to + upper case during a session. + Updated Man page with command line options, ctrl-t sequences and + configuration file options. + Updated README.md, with above information. + + + +Changes since tio v1.42: + + * Add '24hour-delta' timestamp option + + When enabled this option will timestamp new lines with the time elapsed + since the line before. + + This is a very useful feature to identify which events takes the most + time. + + * Improve description of socket option + + * Rename ChangeLog to NEWS + + * Update README + + * Update man page + +George Joseph: + + * Add Pulse DTR command + + MCUs like the ESP32 can be reset if the serial port DTR line is + pulsed for a short time. You could just type CTRL-t d CTRL-t d + but that's a little awkward since you have to lift your finger + off the CTRL key to type the Ds. Now you can just type CTRL-T D. + + * Added new command "D" to pulse the DTR line. I.E. Toggle its + state twice with a configurable duration between toggles. + + * Added new config/command line option "--dtr-pulse-duration" + to set the duration between the DTR state toggles. The default + is 100ms. + + + +Changes since tio v1.41: + + * Update man page + +ZeroMemoryEx: + + * Handle malloc failure + +Sylvain LAFRASSE: + + * Add missing 'string.h' include. + + + +Changes since tio v1.40: + + * Rename --hex-mode to --hexadecimal + + * Enable buffered writing + + Read block of bytes from input and process same block for output. This + will speed things up by reducing I/O overhead. + + * Enable buffered reading + + Read block of bytes from input and process byte by byte for output. This + will speed things up by reducing I/O overhead. + + * Refactoring + + * Cleanup stdout flushing + + Flushing is not needed since we disabled buffering of stdout. + + * Simplify stdout_configure() code + + * Simplify stdin_configure() code + + * Update man page + + * Update README + + + +Changes since tio v1.39: + + * Add config support for log-strip + + * Add config support for hex-mode + + * Rename --hex to --hex-mode + + * Fix completion for -e, --local-echo + + * Ignore newlines in hex output + + * Fix newline in warning_printf() + + * Fix ansi_printf_raw() in no color mode + + * Enter non-interactive mode when piping to tio + + Add support for a non interactive mode which allows other application to + pipe data to tio which then forwards the data to the connected serial + device. + + Non ineractive means that tio does not react to interactive key commands + in the incoming stream. This allows users to pipe binary data directly + to the connected serial device. + + Example use: + + $ cat commands.txt | tio /dev/ttyUSB0 + + * Also strip backspace from log + + To make log strip feature consistent so that we remove all unprintable + control characters and escape sequences. + + * Socket code cleanup + + * Cleanup man page + + * Rename --log-filename to --log-file + +Yin Fengwei: + + * Allow strip escape sequence characters from log file + + The log without escape key stripped is like: + + ^M[12:47:17] ACRN:\> + ^M[12:47:17] ACRN:\>lasdfjklsdjf + ^M + ^M[12:47:18] Error: Invalid command. + ^M[12:47:19] ACRN:\> + ^M[12:47:26] ACRN:\> + ^M[12:47:26] ACRN:\>sdafkljsdkaljfklsadjflksdjafjsda^H ^H^H... + ^M + ^M[12:47:31] Error: Invalid command. + + After strip escape key, the log is like: + + [12:49:18] ACRN:\> + [12:49:19] ACRN:\> + [12:49:19] ACRN:\>ls + + [12:49:19] Error: Invalid command. + [12:49:19] ACRN:\> + [12:49:19] ACRN:\>dfaslhj + + [12:49:24] Error: Invalid command. + + Beside escape key, it also handle backspace key as well. + + + +Changes since tio v1.38: + + * Improve key command response for local echo and timestamp + + * Fix invalid hex character error message + + * Make sure only matched config section is parsed + + * Add support for "disable" keyword in config file + + * Unify error message formating + + * Cleanup list devices code + + * Fix command-line tty-device|config parsing + + Allow user to add options on both sides of the provided config argument. + + For example: + + $ tio -b 9600 am64-evm -e + + Before, tio only allowed adding arguments after the config argument. + + Implemented as simple as possible by introducing two stage option parsing. + + * Update bash completion + + * Add support for IPv4 and IPv6 network sockets + + Add support for IPv4 and IPv6 network sockets via socket syntax + "inet:" and "inet6:" respectively. + + For example, to listen and redirect serial device I/O to a host bound + IPv4 socket simply do: + + $ tio /dev/ttyUSB0 --socket inet:4444 + + To connect do e.g.: + + $ nc 127.0.0.1 4444 + + Likewise, for IPv6 do: + + $ tio /dev/ttyUSB0 --socket inet6:4444 + + To connect do e.g.: + + $ nc ::1 4444 + + If port is 0 or no port is provided default port 3333 is used. + + * Fix tio deleting unix socket file + + If tio has a unix file socket open, a second tio instance of tio may + delete the socket file. This change fixes so that it will not be deleted + and tio will instead error and complain about conflicting socket file. + + * Rework color option + + Rework the color option to support setting ANSI color code values + ranging from 0..255 or "none" for no color or "list" to print a list of + available ANSI colors codes. + + Also, disables color when piping. + + * Remove print of hex mode status at startup + + * Remove newline option in hex mode + + * Fix configfile memory leaks + + * Remove command-line option inconsistencies + + Optional arguments, as parsed by the getopt_long mechanism, are + inherently inconsistent with how you define required arguments. + + To avoid confusion we decide to avoid this inconsistency by replacing + optional options with additional options with required argmuments. + + * Replace '1' with 'enable' in config files + + * Convert errors to warnings + +g0mb4: + + * Extended hexadecimal mode. + + While in hex mode (ctrl-t h) you can output hexadecimal values. + E.g.: to send 0x0A you have to type 0A (always 2 characters). + + Added option -x, --hex to start in hexadecimal mode. + + Added option --newline-in-hex to interpret newline characters in hex mode. + This is disabled by default, because, in my opinion, hex stream is + fundamentally different from text, so a "new line" is meaningless in this + context. + + + +Changes since tio v1.37: + + * Redirect error messages to stderr + + * Improve help and man page + + * Mention config file in --help + + * Fix running without config file + + * Fix config file error messages + + * Redirect error messages to stderr + + * Add repology packaging status + + * Fix parsing of default settings + + Default configuration file settings were not parsed in case a section + was matched. Now we make sure that the default (unnamed) settings are + always parsed. + + * Append to existing log file (no truncation) + + * Add socket info to show configuration + + * Print socket info at startup + + * Fix socket option parsing + +Peter Collingbourne: + + * Match user input against config section names if pattern matching was unsuccessful. + + This allows for better config file ergonomics if the user has a diverse + set of serial devices as the name does not need to be specified in + the config file twice. + + * Add support for external control via a Unix domain socket. + + This feature allows an external program to inject output into and + listen to input from a serial port via a Unix domain socket (path + specified via the -S/--socket command line flag, or the socket + config file option) while tio is running. This is useful for ad-hoc + scripting of serial port interactions while still permitting manual + control. Since many serial devices (at least on Linux) get confused + when opened by multiple processes, and most commands do not know + how to correctly open a serial device, this allows a more convenient + usage model than directly writing to the device node from an external + program. + + Any input from clients connected to the socket is sent on the serial + port as if entered at the terminal where tio is running (except that + ctrl-t sequences are not recognized), and any input from the serial + port is multiplexed to the terminal and all connected clients. + + Sockets remain open while the serial port is disconnected, and writes + will block. + + Example usage 1 (issue a command): + + echo command | nc -UN /path/to/socket > /dev/null + + Example usage 2 (use the expect command to script an interaction): + + #!/usr/bin/expect -f + + set timeout -1 + log_user 0 + + spawn nc -UN /path/to/socket + set uart $spawn_id + + send -i $uart "command1\n" + expect -i $uart "prompt> " + send -i $uart "command2\n" + expect -i $uart "prompt> " + +lexaone: + + * fix for using option 'log' without 'log-filename' in config file + + + +Changes since tio v1.36: + + * Make libinih a fallback dependency + + This means that in case meson does not find libinih it will + automatically clone libinih and include it in the build. + + The libinih library is reconfigured to be statically built so that no + shared object will be installed. + +Sylvain LAFRASSE: + + * Fix timestamp parsing in INI conf + + * Factorize timestamp parsing to be coherent with command line format in configuration file. + + + +Changes since tio v1.35: + + * Add support for defaults in config file + + If no section name is specified the configuration will be considered the + default one. + + This allows to set e.g. a default color code for sections which do not + configure a color code. + + * Handle SIGHUP + + Handle SIGHUP so that the registered exit handlers are called to restore + the terminal back to its orignal state. + + * Add color configuration support + + * Bypass unused result warnings + + * Force dependency on libinih + + Configuration file support is considered a mandatory feature. + + * Update headers + + * Update AUTHORS + + * Update man page + + * Move string_to_long() to misc.c + + * Update CircleCI config + + * Update tio gif + + * Update README + + * Update LICENSE date + + * Remove redundant COPYING file + +Liam Beguin: + + * Document configuration file options + + * Add support for a configuration file + + * misc: add _unused macro + + Some parameters are expected to be unused. + Add a basic macro to mute these compiler warnings. + + * options: expose string_to_long() + + Expose string_to_long() so that other source files can use it. + + + +Changes since tio v1.34: + + * Add support for automatically generated log filename + + Automatically generate log filename if none is provided. + + The auto generated file name is on the form: + "tio_DEVICE_YYYY-MM-DDTHH:MM:SS.log" + + * Add support for configurable timestamp format + + Also changes default timestamp format from ISO8601 to classic 24-hour + format as this is assumed to be the format that most users would prefer. + + And reintroduces strict but optional ISO8601 format. + + This feature allows to easily add more timestamp formats in the future. + + * Reintroduce asm-generic/ioctls.h + + It is needed for ppc builds. + + * Add macro hack to workaround older buggy glibc + +Robey Pointer: + + * Add support for high bps on OS X + + + +Changes since tio v1.33: + + * Fix setspeed2 compilation + + * Only apply color formatting when using color option + + To help the color blind who may use custom terminal foreground / + background colors. + + * Update README + + * Add '-c, --color' option + + Allow user to select which ANSI color code to use to colorize the tio + text. To successfully set the color the color code must be in the range + 0..255. + + If color code is negative tio will print all available ANSI colors. + + The default color is changed to bold white to make tio defaults usable + for most users, including color blind users. + + * Fix setspeed2 check + + * Fix meson header check string + + * Reintroduce long timestamp format + + But make the timestamp format RFC3339 compliant instead. The RFC states: + + NOTE: ISO 8601 defines date and time separated by "T". + Applications using this syntax may choose, for the sake of + readability, to specify a full-date and full-time separated by + (say) a space character. + + This way we keep the information specified by ISO 8601 but make it more + human readable which is better for the console output. + + * Update version year + +Sylvain LAFRASSE: + + * Fix TTY device listing on Darwin. (#136) + + * Fix TCGETS2 search on Darwin. + + + +Changes since tio v1.32: + + * Show auto connect status in show configuration + + * Use '#pragma once' in all headers + + * Improve printed output + + Get rid of inconsistencies in the printed output (error printing, + colors, etc.). + + Prepare for user configurable color. + + * Rename option -i to -L + + * Shorten timestamp + + * Shorten timestamp description + + We do not need the date part of the timestamp. It simply takes up too + much precious line space. In case of logging to file, one can easily + conclude the date from the file date information. + + * Replace Travis with circleCI + + * Replace autotools with meson + + To introduce much simpler build configuration which is also easier to + maintain. + + * Add list serial devices feature + + For convenience, add a --list-devices option which lists the available + serial devices. + + * Cleanup: Use dot notation for default options struct + + * Update AUTHORS + + * Add command to show version + + The key sequence ctrl-t v will now show the version of tio. + + * Align format of timestamps + + * Add Sylvain as official co-maintainer + +Sylvain LAFRASSE: + + * Add '-t' option description for time stamping. + + * Add description for time stamping. + + * Resolved tio/tio#84: Added timestamps in log file if enabled. + +attila-v: + + * Refine timestamps with milliseconds and ISO-8601 format (#129). + + * Show milliseconds too in the timestamp (#114) and log file (#124) + * Change timestamp format to ISO-8601. + +Yin Fengwei: + + * Output newline on stdout with hex print mode + + This is to fix the issue #104. The timestamp will always be + printed at the beginning of line: + + [10:25:56] Switched to hexadecimal mode + 0d 0a 0d [10:25:57] 41 43 52 4e 3a 5c 3e 0d 0a 0d [10:25:58] 41 + + is changed to: + + [12:34:56] 45 72 72 6f 72 3a 20 49 6e 76 61 6c 69 64 20 + [12:34:56] 41 43 52 4e 3a 5c 3e + [12:34:56] 41 43 52 4e 3a 5c 3e + [12:34:57] 41 43 52 4e 3a 5c 3e 6c 73 + +Jakob Haufe: + + * Make comparison POSIX compliant + + String comparison with == is not POSIX compliant and can fail with e.g. + dash. + +Henrik Brix Andersen: + + * Add bash completion of tty devices. + + * Add -t/--timestamp to bash completion script. + +Henner Zeller: + + * Local echo: show character by character even if stdout buffered. + +Björn Stenberg: + + * Show error when failing to open a tty + +Alban Bedel: + + * Fix out of tree builds + + Out of tree builds are currently broken because $(top_srcdir)src/include + is not in the search path. In tree builds are working because autconf add + $(top_builddir)/src/include to the search path for the generated config.h. + As $(top_builddir) and $(top_srcdir) are identical during in tree builds + the search path still end up beeing somehow correct. + + To fix this add -I$(srcdir)/include to the CPPFLAGS in Makefile.am. + +Fabrice Fontaine: + + * src/setspeed2.c: fix redefinition of termio + + Include ioctls.h and termbits.h from asm-generic instead of asm to avoid + build failures. + +Erik Moqvist + + * Exit if output speed cannot be set. + +Lars Kellogg-Stedman: + + * fflush() after putchar() for print_hex and print_normal + + In order for local echo to work properly, we have to either call + fflush(stdout) after every character or just disable line buffering. + This change calls fflush() after putchar(). + + * Disable line buffering in stdout + + In order for local echo to work properly, we have to either call + fflush(stdout) after every character or just disable line buffering. + This change uses setbuf(stdout, NULL) to do the latter. + +George Stark: + + * dont show line state if ioctl failed + + * add serial lines manual control + +arichi: + + * Flush every local echo char + + Flush stdout at every char in case it + happens to be buffered. + +Mariusz Midor: + + * Newline: handle booth NL and CR + + Flag ONLCRNL expects code \n after press Enter, but on some systems \r is send instead. + + + +Changes since tio v1.31: + + * Update AUTHORS + + * Minor code style cleanups + + * Cleanup print macros + + * Flush output + + Make sure output is transmitted immediately by flushing the output. + +Robey Pointer: + + * add optional timestamps + + with "-t" or "C-t T", toggle a timestamp prefix to each line. + +Jakub Wilk: + + * Fix typos + +Sylvain Lafrasse: + + * Added macOS compatibility + + * Made O_NONBLOCK flag to open() call specific to macOS only. + + * Added macOS-related details. + + * Added O_NONBLOCK flag to open() call for macOS (10.13.6) compatibility. + + + +Changes since tio v1.30: + + * Update date + + * Update AUTHORS + +Henner Zeller: + + * Clarify the input/output variable names (No-op change) + + * Organize options the same sequence they are mentioned in cmdline help. + + * Update README. + + * Map CR->NL locally on output instead of using tio.c_oflag |= OCRNL. + + This mostly is intended to have local echo output exactly what is sent + to the remote endpoint. + A nice side-effect is, that it also fixes tty-implementations, that can't + deal with the OCRNL flag on tio.c_oflag. + + * Provide local-echo option. + + Can be switched on with -e on the command line. + Can be toggled with Ctrl t e while program is running. + + * Write to logfile as soon as we have the data, don't buffer. + + Logfiles are important to see what happened, in particular if something + unexpected happened; so we want to make sure that the logfile is flushed + to disk. + + Before this change, the logfile was typically written at the end in + a large chunk as the default (large) buffering applied. Now, characters are + written out ASAP, so it is possible to get a live-view with a + tail -f + + + +Changes since tio v1.29: + + * Update README + + * Update man page and bash completion + + * Update AUTHORS + +qianfan Zhao: + + * ONLCRNL: change the method to map NL to CR-NL + + + +Changes since tio v1.28: + + * Add mapping flags INLCRNL and ODELBS + + The following new mapping flags are added: + + INLCRNL: Map NL to CR-NL on input. + ODELBS: Map DEL to BS on output. + + Flags requested and tested by Jan Ciger (janoc). + + + +Changes since tio v1.27: + + * Update README + + * Update AUTHORS + + * Add snap status to README.md + + * Add README.md to prettify GitHub page + + * Add missing header + +Petr Vaněk: + + * Add missing header file under musl-libc + + Musl's inclusion tree slightly differs from glibc, therefore TCGETS2 is + not reachable through sys/ioctl.h, so asm/ioctls.h needs to be included + too. + +Jakub Wilk: + + * Fix grammar and typos + + + +Changes since tio v1.26: + + * Update man page + + * Add support for setting non-standard baudrates + + Support for non-standard baudrate settings will be automatically enabled + if the termios2 interface is detected available. However, to play it + safe, the old and widely supported termios interface will still be used + when setting standard baudrates. + + * Cleanup + + * Update AUTHORS + + + +Changes since tio v1.25: + + * Reconfigure stdin + + Make stdin behave more raw'ish. In particular, don't + translate CR -> NL on input. + + * Add special character map feature + + Add a --map option which allows mapping special characters, in particular CR and + NL characters which are used in various combinations on various platforms. + + * Cleanup + + * Update AUTHORS + + * Update README + + * Mention website + + * Update man page + + + +Changes since tio v1.24: + + * Fix error applying new stdout settings + + On Fedora 26 tio will quit with the following error message: + + "Error: Could not apply new stdout settings (Invalid argument)" + + In case of Fedora, it turns out that the new stdout settings used are a + bit too aggressive because an empty termios structure is used. To remedy + this we reuse the existing stdout settings and only reconfigure the + specific options we need to make a "raw" stdout configuration. + + * Remove unused pkgconfig in configure + + * Code cleanup + + Remove unused variable. + + + +Changes since tio v1.23: + + * Optimize clear screen command + + Replaced system call with inline ANSI/VT100 clear screen code sequence + + * Fix bash completion installation + + Fixed the configure script to avoid that the bash completion script gets + installed outside of the prefix location. The default install location + is now $prefix/share/bash-completion/completions. + + Use the configure option '--with-bash-completion-dir=PATH' if you need + to install the bash completion script elsewhere. + +Jakub Wilk: + + * Add missing commas in conditional sentences + + + +Changes since tio v1.22: + + * Update copyright headers + +Jakub Wilk: + + * Fix typos + + + +Changes since tio v1.21: + + * Update man page date + + * Update copyright year + + * Code cleanup + + * Update README and man page + + + +Changes since tio v1.20: + + * Add support for hexadecimal mode + + A new key command 'ctrl-t h' is introduced which toggles between + hexadecimal mode and normal mode. When in hexadecimal mode data received + will be printed in hexadecimal. + + * Do not distribute src/bash_completion/tio + + Since the bash completion tio script is now autogenerated from tio.in it + should not be distributed in the tarball. + + * Add missing forward flag + + * Update AUTHORS file + +Adam Borowski: + + * 'ctrl-t b' to send serial break. + +Jakub Wilk: + + * Removed git commit references from ChangeLog + + ChangeLog is primary useful for users who don't have the git repository + at hand. + + Replace git commit references with version numbers; or if the change + only cleans up another change with no release in between, remove the + changelog item completely. + + + +Changes since tio v1.19: + + * Added more error handling of terminal calls + + Also removed duplicate terminal flushing calls. + + * Revert "Added support for non-standard baud rates" + + This reverts a change made in v1.18. + + Reverting because supporting non-standard or arbitrary baud rates is + troublesome because the c library provides no means of doing so and even + if bare metal linux kernel interface is used it will not work on all + Linux kernels version. + + + +Changes since tio v1.18: + + * Rearranged key commands + + Rearranged the key commands: + + ctrl-t c (clear screen) is now + ctrl-t l which is similar to the well known shell ctrl-l + + ctrl-t i (show settings information) is now + ctrl-t c (show configuration) + + Updated man page accordingly. + + * Added "ctrl-t c" key command to clear screen + + + +Changes since tio v1.17: + + * Updated man page + + * Added support for non-standard baud rates + + Only enabled when possible, that is, when the BOTHER definition is + available. + + It is untested but it should work as described here: + https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=683826 + + Some Cypress USB<->serial devices supposedly supports arbitrary speeds. + + * Generate baudrate switch cases based on detection + + Support a single source of baud rate configuration as discussed in + https://github.com/tio/tio/issues/45 . + + To do so, autogeneration of the switch cases which do the baud rate + option value check and configuration/conversion in tty_configure() is + introduced via a single macro. + + Just to be safe, this change also enables configure detection of all + baud rates, including the ones previously assumed supported by most/all + systems (POSIX). + + * Minor cleanup + + * Exit when not a tty device in autoconnect mode + +Jakub Wilk: + + * Added non-standard baud rates that are defined on FreeBSD + + * Capitalized "GitHub" in README + + + +Changes since tio v1.16: + + * Compacted tty_configure() a bit + + * Fixed automatic baud rate enablement + + * Minor cleanups + + * Added autodetection of available baud rates + + Various platforms support different baud rates. + + To avoid adding platform specific handling generic baud rate detection + tests are introduced in the configure script. Successfully detected baud + rates are automatically enabled. This applies to both the C code and the + bash completion script. + + Note: + Baud rates below 57600 are defined by POSIX-1 and supported by most + platforms so only baud rate 57600 and above are tested. + + * Updated bash-completion + + * Fixed printf() format type + + * Added Travis build configuration + +Jakub Wilk: + + * Generated bash completion at configure time + + * Reduce code duplication in baud rate detection + + * Add support for baud rates 200 and 1800 + + * Fixed baudrate type + + + +Changes since tio v1.15: + + * Updated man page + + * Updated README + + * Removed obsolete packaging files + + * Removed use of deprecated bzero() + + + +Changes since tio v1.14: + + * Removed + to remove potential confusion + + * Added input digit checks + + * Fixed license string + + * Introduced tty_configure() + + Moved tty configuration actions to tty_configure() in tty.c. This way + options.c is strictly about parsing options nothing else. + + * Function names cleanup + + * Updated AUTHORS file + + Added Nick who created the new tio package for Arch Linux. + + * Fixed tx/rx counters type + +Jakob Haufe: + + * Include config.h before standard headers + + Large file support was meant to be enabled in v1.11. + This change enables it for real. + + + +Changes since tio v1.13: + + * Fixed tio_printf macro + + * Fixed launch hints + + Fixed launch hints not being printed in no autoconnect mode. + + * Added 'ctrl-t ?' to list available commands + + * Fixed log mechanism + + To avoid echoing only log what is received from tty device. + + * Improved tio output + + Added titles and indentation to commands output for clearer separation + when firing commands repeatedly. + + Also added print of tio version and quit command hint at launch. + + * Cleaned up tio print mechanism + +Jakub Wilk: + + * Fixed grammar + + "allow" is a transitive verb, which requires an object, + so "allow to " is ungrammatical. + + * Fixed typo + + + +Changes since tio v1.12: + + * Fixed some error prints + + * Fixed error printing for no autoconnect mode + + Always print errors but only print silent errors when in no autoconnect + mode. + + * Added key command for showing session settings + + A new key command "ctrl-t i" is added to allow the user to display the + various session settings information (baudrate, databits, log file, etc.). + + This is useful in case you have a running session but have forgotten + what the settings are. + + + +Changes since tio v1.11: + + * Consolidated command key handling + + * Moved delay mechanism into separate function + + * Retired obsolete usleep() + + Replaced with nanosleep() + + * Added simple tx/rx statistics command (ctrl-t s) + + To display the total number of bytes transmitted/received simply perform the + 'ctrl-t s' command sequence. + + This feature can be useful when eg. trying to detect non-printable + characters. + + * Further simplification of key handling + + Changed so that the "ctrl-t ctrl-t" sequence is now simply "ctrl-t t" to + send the ctrl-t key code. This is inspired by screen which does similar + to send its command key code (ctrl-a a). + + This change also eases adding new key commands if needed. + + Updated man page accordingly. + + * Cleaned up and simplified key handling + +Jakub Wilk: + + * Insert output delay only if something was output + + + +Changes since tio v1.10: + + * Enabled large file support (LFS) + + Added autotools AC_SYS_LARGEFILE to support 64 bit file size handling. + + * Updated tio title + + + +Changes since tio v1.9: + + * Introduced lock on device file + + Tio will now test for and obtain an advisory lock on the tty device file + to prevent starting multiple sessions on the same tty device. + + * Updated AUTHORS + +Jakub Wilk: + + * Treat EOF on stdin as error + + + +Changes since tio v1.8: + + * Cleanup of error handling + + Introduced consistent way of handling errors and printing error messages. + + Also upgraded some warnings to errors. + + * Updated localtime() error message + + * Cleanup + +Jakub Wilk: + + * Fix error handling for select() + + Previously the error handling code for select() was unreachable. + + * Removed unneeded quotes from AM_CFLAGS + + * Expanded tabs + + * Fixed setting "tainted" + + Set "tainted" if and only if any character was read from the device. + + Ctrl-t is no longer sent to the device on exit, so the trick to avoid + its echo is not necessary. + + Characters read from stdin don't directly affect output, so they + shouldn't enable "tainted". + + * Used \r in color_printf() + + \033[300D is an unusual way to move the cursor back to column 1. + Use straightforward \r instead. + + * Added missing \r\n to warning messages + + \n alone is not enough, because the terminal is in raw mode. + + + +Changes since tio v1.7: + + * Fixed enablement of compiler warnings + + * Fixed log_open() prototype + + * Fixed index error wrt ctrl-t detection + + * Fixed handling of ctrl-t + + Before, when exercising the quit key sequence (ctrl-t + q) the ctrl-t code + (0x14) would be sent. + + This is now fixed so that it is not sent. + + However, in case it is needed to send ctrl-t to the device it is possible by + simply repeating the ctrl-t. + + Meaning, ctrl-t + ctrl-t = ctrl-t sent to device. + + * Improved error handling + + Fixes a memory leak and avoids aggressive busy looping when problems + accessing tty device. + + * Removed redundant log_close() call + + * Enabled compiler warnings + +Jakub Wilk: + + * Stopped copying arguments to fixed-size buffers + + Don't needlessly copy command-line arguments into fixed-size buffers. + + Previously the program crashed if an overlong pathname was provided on + the command line. Also, some systems (such as GNU Hurd) don't define + MAXPATHLEN at all. + + * Added const to log_open() prototype + + * Completed the ^g to ^t transition + + In v1.7 the escape key was changed from ^g to ^t, but some + code and comments still referred to the old key. + + * Used HTTPS for tio.github.io + + * Man page beautification + + * Bumped date in man page + + * Improve man page formatting + + Use regular font for metacharacters such as "[]", "," or "|"; + use italic font for metavariables. + + * Fixed hyphen vs minus vs em-dash confusion in man page + + - prints as hyphen; + \- prints as minus sign; + \em prints as em-dash. + + + +Changes since tio v1.6: + + * Changed escape key from ^g to ^t + + After renaming to "tio" it makes sense to change the escape key + accordingly. Hence, the new escape key is ^t. + + Meaning, in session, its now ctrl-t + q to quit. + +Jakub Wilk: + + * Fixed silly "tio or tio" in man page + + * Fixed typo + diff --git a/README.md b/README.md new file mode 100644 index 0000000..7625e85 --- /dev/null +++ b/README.md @@ -0,0 +1,326 @@ +# tio - a simple serial device I/O tool + +[![](https://img.shields.io/circleci/build/gh/tio/tio?token=da7e7fd0d0ee99b9f986f8877dcdbe28f73d9e06)](https://circleci.com/gh/tio/tio/tree/master) +[![](https://img.shields.io/github/v/release/tio/tio?sort=semver)](https://github.com/tio/tio/releases) +[![](https://img.shields.io/repology/repositories/tio)](https://repology.org/project/tio/versions) +[![](https://img.shields.io/tokei/lines/github/tio/tio)](https://github.com/tio/tio) + +## 1. Introduction + +tio is a simple serial device tool which features a straightforward +command-line and configuration file interface to easily connect to serial TTY +devices for basic I/O operations. + +

+ +

+ +### 1.1 Motivation + +To make a simpler serial device tool for talking with serial TTY devices with +less focus on classic terminal/modem features and more focus on the needs of +embedded developers and hackers. + +tio was originally created to replace +[screen](https://www.gnu.org/software/screen) for connecting to serial devices +when used in combination with [tmux](https://tmux.github.io). + +## 2. Features + + * Easily connect to serial TTY devices + * Automatic connect and reconnect + * Sensible defaults + * Support for non-standard baud rates + * Support for RS-485 mode + * Support for mark and space parity + * List available serial devices by ID + * Show RX/TX statistics + * Toggle serial lines + * Pulse serial lines with configurable pulse duration + * Local echo support + * Remapping of characters (nl, cr-nl, bs, lowercase to uppercase, etc.) + * Line timestamps + * Support for delayed output per character + * Support for delayed output per line + * Hexadecimal mode + * Log to file + * Autogeneration of log filename + * Configuration file support + * Activate sub-configurations by name or pattern + * Redirect I/O to UNIX socket or IPv4/v6 network socket for scripting or TTY sharing + * Pipe input and/or output + * Support for simple line request/response handling + * Bash completion on options, serial device names, and sub-configuration names + * Configurable text color + * Visual or audible alert on connect/disconnect + * Remapping of prefix key + * Man page documentation + * Plays nicely with [tmux](https://tmux.github.io) + +## 3. Usage + +For more usage details please see the man page documentation +[here](https://raw.githubusercontent.com/tio/tio/master/man/tio.1.txt). + +### 3.1 Command-line + +The command-line interface is straightforward as reflected in the output from +'tio --help': +``` + Usage: tio [] + + Connect to TTY device directly or via sub-configuration. + + Options: + -b, --baudrate Baud rate (default: 115200) + -d, --databits 5|6|7|8 Data bits (default: 8) + -f, --flow hard|soft|none Flow control (default: none) + -s, --stopbits 1|2 Stop bits (default: 1) + -p, --parity odd|even|none|mark|space Parity (default: none) + -o, --output-delay Output character delay (default: 0) + -O, --output-line-delay Output line delay (default: 0) + --line-pulse-duration Set line pulse duration + -n, --no-autoconnect Disable automatic connect + -e, --local-echo Enable local echo + -t, --timestamp Enable line timestamp + --timestamp-format Set timestamp format (default: 24hour) + -L, --list-devices List available serial devices + -l, --log Enable log to file + --log-file Set log filename + --log-strip Strip control characters and escape sequences + -m, --map Map characters + -c, --color 0..255|bold|none|list Colorize tio text (default: bold) + -S, --socket Redirect I/O to socket + -x, --hexadecimal Enable hexadecimal mode + -r, --response-wait Wait for line response then quit + --response-timeout Response timeout (default: 100) + --rs-485 Enable RS-485 mode + --rs-485-config Set RS-485 configuration + --alert bell|blink|none Alert on connect/disconnect (default: none) + -v, --version Display version + -h, --help Display help + + Options and sub-configurations may be set via configuration file. + + See the man page for more details. + +``` + +By default tio automatically connects to the provided TTY device if present. +If the device is not present, it will wait for it to appear and then connect. +If the connection is lost (eg. device is unplugged), it will wait for the +device to reappear and then reconnect. However, if the `--no-autoconnect` +option is provided, tio will exit if the device is not present or an +established connection is lost. + +tio features full bash autocompletion. + +#### 3.1.1 Examples + +Typical use is without options: +``` +$ tio /dev/ttyUSB0 +``` + +Which corresponds to the commonly used default options: +``` +$ tio -b 115200 -d 8 -f none -s 1 -p none /dev/ttyUSB0 +``` + +It is recommended to connect serial TTY devices by ID: +``` +$ tio /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 +``` +Using serial devices by ID ensures that tio automatically reconnects to the +correct serial device if it is disconnected and then reconnected. + +List available serial devices by ID: +``` +$ tio --list-devices +``` +Note: One can also use tio shell completion on /dev which will automatically +list all available serial TTY devices. + +Log to file with autogenerated filename: +``` +$ tio --log /dev/ttyUSB0 +``` + +Enable ISO8601 timestamps per line: +``` +$ tio --timestamp --timestamp-format iso8601 /dev/ttyUSB0 +``` + +Redirect I/O to IPv4 network socket on port 4242: +``` +$ tio --socket inet:4242 /dev/ttyUSB0 +``` + +Inject data to the serial device: +``` +$ cat data.bin | tio /dev/ttyUSB0 +``` + +Send command to serial device and wait for line response: +``` +$ echo "*IDN?" | tio /dev/ttyACM0 --response-wait +KORAD KD3305P V4.2 SN:32475045 +``` + +### 3.2 Key commands + +Various in session key commands are supported. When tio is started, press +ctrl-t ? to list the available key commands. + +``` +[20:19:12.040] Key commands: +[20:19:12.040] ctrl-t ? List available key commands +[20:19:12.040] ctrl-t b Send break +[20:19:12.040] ctrl-t c Show configuration +[20:19:12.040] ctrl-t e Toggle local echo mode +[20:19:12.040] ctrl-t f Toggle log to file +[20:19:12.040] ctrl-t g Toggle serial port line +[20:19:12.040] ctrl-t h Toggle hexadecimal mode +[20:19:12.040] ctrl-t l Clear screen +[20:19:12.040] ctrl-t L Show line states +[20:19:12.040] ctrl-t p Pulse serial port line +[20:19:12.040] ctrl-t q Quit +[20:19:12.041] ctrl-t s Show statistics +[20:19:12.041] ctrl-t t Toggle line timestamp mode +[20:19:12.041] ctrl-t U Toggle conversion to uppercase +[20:19:12.041] ctrl-t v Show version +[20:19:12.041] ctrl-t ctrl-t Send ctrl-t character +``` + +If needed, the prefix key (ctrl-t) can be remapped via configuration file. + +### 3.3 Configuration file + +Options can be set via the configuration file first found in any of the +following locations in the order listed: + - $XDG_CONFIG_HOME/tio/config + - $HOME/.config/tio/config + - $HOME/.tioconfig + +The configuration file supports sub-configurations using named sections which can +be activated via the command-line by name or pattern. A sub-configuration +specifies which TTY device to connect to and other options. + +Example configuration file: + +``` +# Defaults +baudrate = 9600 +databits = 8 +parity = none +stopbits = 1 +color = 10 + +[rpi3] +device = /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 +baudrate = 115200 +no-autoconnect = enable +log = enable +log-file = rpi3.log +line-pulse-duration = DTR=200,RTS=150 +color = 12 + +[usb devices] +pattern = usb([0-9]*) +device = /dev/ttyUSB%s +color = 13 +``` + +To use a specific sub-configuration by name simply start tio like so: +``` +$ tio rpi3 +``` +Or by pattern match: +``` +$ tio usb12 +``` + +Another more elaborate configuration file example is available [here](example/config). + +## 4. Installation + +### 4.1 Installation using package manager (Linux) + +Packages for various GNU/Linux distributions are available. Please consult your +package manager tool to find and install tio. + +If you would like to see tio included in your favorite distribution, please +reach out to its package maintainers team. + +### 4.2 Installation using snap (Linux) + +Install latest stable version: +``` +$ snap install tio +``` + +### 4.3 Installation using brew (MacOS, Linux) + +If you have [brew](http://brew.sh) installed: +``` +$ brew install tio +``` + +### 4.4 Installation using MSYS2 (Windows) + +If you have [MSYS2](https://www.msys2.org) installed: +``` +$ pacman -S tio +``` + +### 4.5 Installation from source + +The latest source releases can be found [here](https://github.com/tio/tio/releases). + +Install steps: +``` +$ meson build +$ meson compile -C build +$ meson install -C build +``` + +See meson\_options.txt for tio specific build options. + +Note: The meson install steps may differ depending on your specific system. + + +## 5. Contributing + +tio is open source. If you want to help out with the project please feel free +to join in. + +All contributions (bug reports, code, doc, ideas, etc.) are welcome. + +Please use the github issue tracker and pull request features. + +Also, if you find this free open source software useful please feel free to +consider making a donation of your choice: + +[![Donate](images/paypal.png)](https://www.paypal.me/lundmar) + + +## 6. Support + +Submit bug reports via GitHub: https://github.com/tio/tio/issues + + +## 7. Website + +Visit [tio.github.io](https://tio.github.io) + + +## 8. License + +tio is GPLv2+. See LICENSE file for more details. + + +## 9. Authors + +Created by Martin Lund \ + +See the AUTHORS file for full list of contributors. diff --git a/TODO b/TODO new file mode 100644 index 0000000..ce25173 --- /dev/null +++ b/TODO @@ -0,0 +1,60 @@ + + * Allow tio to connect to socket + + After some more consideration I think it makes sense to support connecting to a + socket as that will make tio be able to both serve a serial port via a socket + and connect to it - it will be an end to end solution. In short we will be able + to do the following: + + Host serial port on socket (existing feature): + $ tio --socket unix:/tmp/tio-socket-0 /dev/ttyUSB0 + + Connect to same socket (new feature): + $ tio unix:/tmp/tio-socket-0 + + Besides a bit of refactoring the following required changes spring to mind: + + * Socket mode and type of socket should be activated via device name prefix. For example: + * UNIX socket: tio unix: + * TCPv4 socket: tio inet:: + * TCPv6 socket: tio inet6:: + * If no port number defined default to 3333 + * Mapping flags INLCR, IGNCR, ICRNL needs implementation for socket mode + * Error messages should just say "device" instead of "tty device" etc. + * Remove other tty'isms (tty_write() should be device_write() etc.) + * In session key commands that do not work in socket mode should either not be listed or print an error messages if used. + * All non-tty features should continue work (auto-connect etc.) + * Shell completion script update + * Man page update + + + * Split I/O feature + + Allow to split input and output so that it is possible to manage these + independently. + + The general idea is to redirect the output stream on the socket port number + specified but then redirect the input stream on the same port number + 1. + + Example: + + $ tio /dev/ttyUSB0 --socket inet:4444,split-io + + Will result in output stream being hosted on port 4444 and input stream + hosted on port 4445. + + For file sockets something similar can be arranged: + + $ tio /dev/ttyUSB0 --socket unix:/tmp/tio-socket-0,split-io + + Will result in output stream being hosted via /tmp/tio-socket-0 and input + stream hosted via /tmp/tio-socket-0_input + + * Websocket support + + Extend the socket feature to redirect serial I/O to websocket on e.g. port + 1234 like so: + + $ tio --socket ws:1234 + + Use libwesockets to implement feature. diff --git a/example/config b/example/config new file mode 100644 index 0000000..05f96c9 --- /dev/null +++ b/example/config @@ -0,0 +1,64 @@ +############################### +# tio - https://tio.github.io # +############################### + +# Example tio configuration file +# +# Place file in any of the following locations: +# $XDG_CONFIG_HOME/tio/config +# $HOME/.config/tio/config +# $HOME/.tioconfig + +# Defaults +baudrate = 115200 +databits = 8 +flow = none +stopbits = 1 +parity = none +prefix-ctrl-key = t +output-delay = 0 +output-line-delay = 0 +no-autoconnect = disable +hexadecimal = disable +timestamp = disable +log = disable +log-strip = disable +local-echo = disable +color = bold +rs-485 = disable +response-wait = disable +alert = none + +# Sub-configuraions + +[rpi3] +baudrate = 115200 +device = /dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A6009HU3-if00-port0 +socket = unix:/tmp/tio-socket-0 +color = 9 + +[am64-evm] +baudrate = 115200 +device = /dev/serial/by-id/usb-Silicon_Labs_CP2105_Dual_USB_to_UART_Bridge_Controller_01093176-if01-port0 +line-pulse-duration = DTR=200,RTS=300,RI=50 +alert = bell +color = 10 + +[tincan] +baudrate = 9600 +device = /dev/serial/by-id/usb-TinCanTools_Flyswatter2_FS20000-if00-port0 +log = enable +log-file = tincan.log +log-strip = enable +color = 11 + +[usb] +pattern = usb([0-9]*) +device = /dev/ttyUSB%s +color = 12 + +[rs-485-device] +device = /dev/ttyUSB0 +rs-485 = enable +rs-485-config = RTS_ON_SEND=1,RTS_AFTER_SEND=1,RTS_DELAY_BEFORE_SEND=60,RTS_DELAY_AFTER_SEND=80,RX_DURING_TX +color = 13 diff --git a/images/paypal.png b/images/paypal.png new file mode 100644 index 0000000..00bc3e2 Binary files /dev/null and b/images/paypal.png differ diff --git a/images/tio-demo.gif b/images/tio-demo.gif new file mode 100644 index 0000000..7e12336 Binary files /dev/null and b/images/tio-demo.gif differ diff --git a/man/meson.build b/man/meson.build new file mode 100644 index 0000000..bf49040 --- /dev/null +++ b/man/meson.build @@ -0,0 +1,15 @@ +mandir = join_paths(get_option('prefix'), get_option('mandir')) +man1dir = join_paths(mandir, 'man1') + +conf = configuration_data() +conf.set('version', meson.project_version()) +conf.set('version_date', version_date) + +manpage = configure_file( + input: files('tio.1.in'), + output: 'tio.1', + configuration: conf) + +install_man( + manpage, + install_dir: man1dir) diff --git a/man/tio.1.in b/man/tio.1.in new file mode 100644 index 0000000..52523ee --- /dev/null +++ b/man/tio.1.in @@ -0,0 +1,573 @@ +.TH "tio" "1" "@version_date@" "tio @version@" "User Commands" + +.SH "NAME" +tio \- a simple serial device I/O tool + +.SH "SYNOPSIS" +.PP +.B tio +.RI "[" "] " "" + +.SH "DESCRIPTION" +.PP +\fBtio\fR is a simple serial device tool which features a straightforward +command-line and configuration file interface to easily connect to serial TTY +devices for basic I/O operations. + +.SH "OPTIONS" + +.TP +.BR \-b ", " "\-\-baudrate " \fI + +Set baud rate [bps] (default: 115200). +.TP +.BR \-d ", " "\-\-databits 5" | 6 | 7 | 8 + +Set data bits (default: 8). +.TP +.BR \-f ", " "\-\-flow hard" | soft | none + +Set flow control (default: none). +.TP +.BR \-s ", " "\-\-stopbits 1" | 2 + +Set stop bits (default: 1). +.TP +.BR \-p ", " "\-\-parity odd" | even | none | mark | space + +Set parity (default: none). + +Note: With \fBmark\fR parity the parity bit is always 0. With \fBspace\fR +parity the parity bit is always 1. Not all platforms support \fBmark\fR and +\fBspace\fR parity. + +.TP +.BR \-o ", " "\-\-output\-delay " \fI + +Set output delay [ms] inserted between each sent character (default: 0). + +.TP +.BR \-O ", " "\-\-output\-line\-delay " \fI + +Set output delay [ms] inserted between each sent line (default: 0). + +.TP +.BR " \-\-line\-pulse\-duration " \fI + +Set the pulse duration [ms] of each serial port line using the following key +value pair format in the duration field: = + +Each key represents a serial line. The following keys are available: + +.RS +.TP 8n +.IP \fBDTR +Data Terminal Ready +.IP \fBRTS +Request To Send +.IP \fBCTS +Clear To Send +.IP \fBDSR +Data Set Ready +.IP \fBDCD +Data Carrier Detect +.IP \fBRI +Ring Indicator +.P +If defining more than one key value pair, the pairs must be comma separated. + +The default pulse duration for each line is 100 ms. +.RE + +.TP +.BR \-n ", " \-\-no\-autoconnect + +Disable automatic connect. + +By default tio automatically connects to the provided device if present. If the +device is not present, it will wait for it to appear and then connect. If the +connection is lost (eg. device disconnects), it will wait for the device to +reappear and then reconnect. + +However, if the \fB\-\-no\-autoconnect\fR option is provided, tio will exit if +the device is not present or an established connection is lost. + +.TP +.BR \-e ", " "\-\-local\-echo + +Enable local echo. + +.TP +.BR \-t ", " \-\-timestamp + +Enable line timestamp. + +.TP +.BR " \-\-timestamp-format \fI + +Set timestamp format to any of the following timestamp formats: +.RS +.TP 16n + +.IP "\fB24hour" +24-hour format ("hh:mm:ss.sss") +.IP "\fB24hour-start" +24-hour format relative to start time +.IP "\fB24hour-delta" +24-hour format relative to previous timestamp +.IP "\fBiso8601" +ISO8601 format ("YYYY-MM-DDThh:mm:ss.sss") +.PP +Default format is \fB24hour\fR +.RE + +.TP +.BR \-L ", " \-\-list\-devices + +List available serial devices by ID. + +.TP +.BR \-l ", " \-\-log + +Enable log to file. + +If no filename is provided the filename will be automatically generated. + +.TP +.BR " \-\-log-file \fI + +Set log filename. + +.TP +.BR " \-\-log-strip + +Strip control characters and escape sequences from log. + +.TP +.BR \-m ", " "\-\-map " \fI + +Map (replace, translate) characters on input or output. The following mapping +flags are supported: + +.RS +.TP 12n +.IP "\fBICRNL" +Map CR to NL on input (unless IGNCR is set) +.IP "\fBIGNCR" +Ignore CR on input +.IP "\fBINLCR" +Map NL to CR on input +.IP "\fBINLCRNL" +Map NL to CR-NL on input +.IP "\fBOCRNL" +Map CR to NL on output +.IP "\fBODELBS" +Map DEL to BS on output +.IP "\fBONLCRNL" +Map NL to CR-NL on output +.IP "\fBOLTU" +Map lowercase characters to uppercase on output +.IP "\fBMSB2LSB" +Map MSB bit order to LSB on output +.P +If defining more than one flag, the flags must be comma separated. +.RE + +.TP +.BR \-x ", " \-\-hexadecimal + +Enable hexadecimal mode. + +.TP +.BR \-c ", " "\-\-color " \fI0..255|bold|none|list + +Colorize tio text using ANSI color code value ranging from 0 to 255 or use +"none" for no color or use "bold" to apply bold formatting to existing system +color. + +Use "list" to print a list of available ANSI color codes. + +Default value is "bold". + +.TP +.BR \-S ", " "\-\-socket \fI\fR\fB + +Redirect I/O to socket. + +Any input from clients connected to the socket is sent on the serial port as if +entered at the terminal where tio is running (except that \fBctrl-t\fR sequences +are not recognized), and any input from the serial port is multiplexed to the +terminal and all connected clients. + +Sockets remain open while the serial port is disconnected, and writes will block. + +Various socket types are supported using the following prefixes in the socket field: + +.RS +.TP 20n +.IP "\fBunix:" +Unix Domain Socket (file) +.IP "\fBinet:" +Internet Socket (network) +.IP "\fBinet6:" +Internet IPv6 Socket (network) +.P +If port is 0 or no port is provided default port 3333 is used. +.P +At present there is a hardcoded limit of 16 clients connected at one time. +.RE + +.TP +.BR \-r ", " \-\-response-wait + +Wait for line response then quit. A line is considered any string ending with +either CR or NL character. If no line is received tio will quit after response +timeout. + +Any tio text is automatically muted when piping a string to tio while in +response mode to make it easy to parse the response. + +.TP +.BR " \-\-response\-timeout " \fI + +Set timeout [ms] of line response (default: 100). + +.TP +.BR " \-\-rs\-485" + +Enable RS-485 mode. + +.TP +.BR " \-\-rs\-485\-config " \fI + +Set the RS-485 configuration using the following key or key value pair format in +the configuration field: + +.RS +.TP 30n +.IP \fBRTS_ON_SEND=value +Set logical level (0 or 1) for RTS pin when sending +.IP \fBRTS_AFTER_SEND=value +Set logical level (0 or 1) for RTS pin after sending +.IP \fBRTS_DELAY_BEFORE_SEND=value +Set RTS delay (ms) before sending +.IP \fBRTS_DELAY_AFTER_SEND=value +Set RTS delay (ms) after sending +.IP \fBRX_DURING_TX +Receive data even while sending data +.P +If defining more than one key or key value pair, they must be comma separated. +.RE + +.TP +.BR "\-\-alert none|bell|blink" + +Set alert action on connect/disconnect. + +It will sound the bell once or blink once on successful connect. Likewise it +will sound the bell twice or blink twice on disconnect. + +Default value is "none". + +.TP +.BR \-v ", " \-\-version + +Display program version. +.TP +.BR \-h ", " \-\-help + +Display help. +.SH "KEYS" +.PP +.TP 16n +In session, the following key sequences, a prefix key (default: ctrl-t) followed by a command key, are intercepted as tio commands: +.IP "\fBctrl-t ?" +List available key commands +.IP "\fBctrl-t b" +Send serial break (triggers SysRq on Linux, etc.) +.IP "\fBctrl-t c" +Show configuration (baudrate, databits, etc.) +.IP "\fBctrl-t e" +Toggle local echo mode +.IP "\fBctrl-t f" +Toggle log to file +.IP "\fBctrl-t F" +Flush data I/O buffers (discard data written but not transmitted and data received but not read) +.IP "\fBctrl-t g" +Toggle serial port line +.IP "\fBctrl-t h" +Toggle hexadecimal mode +.IP "\fBctrl-t l" +Clear screen +.IP "\fBctrl-t L" +Show line states (DTR, RTS, CTS, DSR, DCD, RI) +.IP "\fBctrl-t p" +Pulse serial port line +.IP "\fBctrl-t q" +Quit +.IP "\fBctrl-t s" +Show TX/RX statistics +.IP "\fBctrl-t t" +Toggle line timestamp mode +.IP "\fBctrl-t U" +Toggle conversion to uppercase on output +.IP "\fBctrl-t v" +Show version +.IP "\fBctrl-t ctrl-t" +Send ctrl-t character + +.SH "HEXADECIMAL MODE" +.PP +In hexadecimal mode each incoming byte is printed out as a hexadecimal value. + +.PP +Bytes can be sent in this mode by typing the \fBtwo-character hexadecimal\fR +representation of the value, e.g.: to send \fI0xA\fR you must type \fI0a\fR or +\fI0A\fR. + +.SH "CONFIGURATION FILE" +.PP +Options can be set via configuration file using the INI format. \fBtio\fR uses +the configuration file first found in the following locations in the order +listed: + +.PP +.I $XDG_CONFIG_HOME/tio/config +.PP +.I $HOME/.config/tio/config +.PP +.I $HOME/.tioconfig + +.PP +Labels can be used to group settings into named sub-configurations which can be +activated from the command-line when starting tio. + +.PP +\fBtio\fR will try to match the user input to a sub-configuration by name or by +pattern to get the TTY device and other options. + +.PP +Options without any label change the default options. + +.PP +Any options set via command-line will override options set in the configuration file. + +.PP +The following configuration file options are available: + +.TP 25n +.IP "\fBpattern" +Pattern matching user input. This pattern can be an extended regular expression with a single group. +.IP "\fBdevice" +TTY device to open. If it contains a "%s" it is substituted with the first group match. +.IP "\fBbaudrate" +Set baud rate +.IP "\fBdatabits" +Set data bits +.IP "\fBflow" +Set flow control +.IP "\fBstopbits" +Set stop bits +.IP "\fBparity" +Set parity +.IP "\fBoutput-delay" +Set output character delay +.IP "\fBoutput-line-delay" +Set output line delay +.IP "\fBline-pulse-duration" +Set line pulse duration +.IP "\fBno-autoconnect" +Disable automatic connect +.IP "\fBlog" +Enable log to file +.IP "\fBlog-file" +Set log filename +.IP "\fBlog-strip" +Enable strip of control and escape sequences from log +.IP "\fBlocal-echo" +Enable local echo +.IP "\fBtimestamp" +Enable line timestamp +.IP "\fBtimestamp-format" +Set timestamp format +.IP "\fBmap" +Map characters on input or output +.IP "\fBcolor" +Colorize tio text using ANSI color code ranging from 0 to 255 +.IP "\fBhexadecimal" +Enable hexadecimal mode +.IP "\fBsocket" +Set socket to redirect I/O to +.IP "\fBprefix-ctrl-key" +Set prefix ctrl key (a..z, default: t) +.IP "\fBresponse-wait" +Enable wait for line response +.IP "\fBresponse-timeout" +Set line response timeout +.IP "\fBrs-485" +Enable RS-485 mode +.IP "\fBrs-485-config" +Set RS-485 configuration +.IP "\fBalert" +Set alert action on connect/disconnect + +.SH "CONFIGURATION FILE EXAMPLES" + +.TP +To change the default configuration simply set options like so: + +.RS +.nf +.eo +# Defaults +baudrate = 9600 +databits = 8 +parity = none +stopbits = 1 +color = 10 +line-pulse-duration = DTR=200,RTS=400 +.ec +.fi +.RE + +.TP +Named sub-configurations can be added via labels: + +.RS +.nf +.eo +[rpi3] +device = /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 +baudrate = 115200 +color = 11 +.ec +.fi +.RE + +.TP +Activate the sub-configuration by name: + +$ tio rpi3 + +.TP +Which is equivalent to: + +$ tio -b 115200 -c 11 /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 + +.TP +A sub-configuration can also be activated by its pattern which supports regular expressions: + +.RS +.nf +.eo +[usb device] +pattern = usb([0-9]*) +device = /dev/ttyUSB%s +baudrate = 115200 +.ec +.fi +.RE + +.TP +Activate the sub-configuration by pattern match: + +$ tio usb12 + +.TP +Which is equivalent to: + +$ tio -b 115200 /dev/ttyUSB12 + +.TP +It is also possible to combine use of sub-configuration and command-line options. For example: + +$ tio -l -t usb12 + +.SH "EXAMPLES" +.TP +Typical use is without options: + +$ tio /dev/ttyUSB0 +.TP +Which corresponds to the commonly used default options: + +$ tio \-b 115200 \-d 8 \-f none \-s 1 \-p none /dev/ttyUSB0 +.TP +It is recommended to connect serial TTY devices by ID: + +$ tio /dev/serial/by\-id/usb\-FTDI_TTL232R-3V3_FTGQVXBL\-if00\-port0 +.PP +Using serial devices by ID ensures that tio automatically reconnects to the +correct serial device if it is disconnected and then reconnected. +.TP +Redirect serial device I/O to Unix file socket for scripting: + +$ tio -S unix:/tmp/tmux-socket0 /dev/ttyUSB0 + +.TP +Then, to issue a command via the file socket simply do: + +$ echo "ls -la" | nc -UN /tmp/tmux-socket0 > /dev/null + +.TP +Or use the expect command to script an interaction: + +.RS +.nf +.eo +#!/usr/bin/expect -f + +set timeout -1 +log_user 0 + +spawn nc -UN /tmp/tio-socket0 +set uart $spawn_id + +send -i $uart "date\n" +expect -i $uart "prompt> " +send -i $uart "ls -la\n" +expect -i $uart "prompt> " +.ec +.fi +.RE + +.TP +Redirect device I/O to network file socket for remote TTY sharing: + +$ tio --socket inet:4444 /dev/ttyUSB0 + +.TP + +Then, use netcat to connect to the shared TTY session over network (assuming tio is hosted on IP 10.0.0.42): + +$ nc -N 10.0.0.42 4444 + +.TP +Pipe command to the serial device: + +$ echo "ls -la" | tio /dev/serial/by\-id/usb\-FTDI_TTL232R-3V3_FTGQVXBL\-if00\-port0 + +.TP +Pipe command to the serial device and wait for line response (string ending with CR or NL): + +$ echo "*IDN?" | tio /dev/ttyACM0 --response-wait +.TP +In this mode, only the response will be printed. + +.TP +Likewise, to pipe data from file to the serial device: + +$ cat data.bin | tio /dev/serial/by\-id/usb\-FTDI_TTL232R-3V3_FTGQVXBL\-if00\-port0 + +.TP +Enable RS-485 mode: + +$ tio --rs-485 --rs-485-config=RTS_ON_SEND=1,RX_DURING_TX /dev/ttyUSB0 + +.SH "WEBSITE" +.PP +Visit https://tio.github.io + +.SH "AUTHOR" +.PP +Created by Martin Lund . diff --git a/man/tio.1.txt b/man/tio.1.txt new file mode 100644 index 0000000..c66269f --- /dev/null +++ b/man/tio.1.txt @@ -0,0 +1,447 @@ +tio(1) User Commands tio(1) + +NAME + tio - a simple serial device I/O tool + +SYNOPSIS + tio [] + +DESCRIPTION + tio is a simple serial device tool which features a straightforward command-line and configuration file interface to easily connect to serial TTY devices for basic I/O operations. + +OPTIONS + -b, --baudrate + + Set baud rate [bps] (default: 115200). + + -d, --databits 5|6|7|8 + + Set data bits (default: 8). + + -f, --flow hard|soft|none + + Set flow control (default: none). + + -s, --stopbits 1|2 + + Set stop bits (default: 1). + + -p, --parity odd|even|none|mark|space + + Set parity (default: none). + + Note: With mark parity the parity bit is always 0. With space parity the parity bit is always 1. Not all platforms support mark and space parity. + + -o, --output-delay + + Set output delay [ms] inserted between each sent character (default: 0). + + -O, --output-line-delay + + Set output delay [ms] inserted between each sent line (default: 0). + + --line-pulse-duration + + Set the pulse duration [ms] of each serial port line using the following key value pair format in the duration field: = + + Each key represents a serial line. The following keys are available: + + DTR Data Terminal Ready + + RTS Request To Send + + CTS Clear To Send + + DSR Data Set Ready + + DCD Data Carrier Detect + + RI Ring Indicator + + If defining more than one key value pair, the pairs must be comma separated. + + The default pulse duration for each line is 100 ms. + + -n, --no-autoconnect + + Disable automatic connect. + + By default tio automatically connects to the provided device if present. If the device is not present, it will wait for it to appear and then connect. If the connection is lost (eg. device disconnects), it will wait for the device to + reappear and then reconnect. + + However, if the --no-autoconnect option is provided, tio will exit if the device is not present or an established connection is lost. + + -e, --local-echo + + Enable local echo. + + -t, --timestamp + + Enable line timestamp. + + --timestamp-format + + Set timestamp format to any of the following timestamp formats: + + 24hour 24-hour format ("hh:mm:ss.sss") + + 24hour-start 24-hour format relative to start time + + 24hour-delta 24-hour format relative to previous timestamp + + iso8601 ISO8601 format ("YYYY-MM-DDThh:mm:ss.sss") + + Default format is 24hour + + -L, --list-devices + + List available serial devices by ID. + + -l, --log + + Enable log to file. + + If no filename is provided the filename will be automatically generated. + + --log-file + + Set log filename. + + --log-strip + + Strip control characters and escape sequences from log. + + -m, --map + + Map (replace, translate) characters on input or output. The following mapping flags are supported: + + ICRNL Map CR to NL on input (unless IGNCR is set) + + IGNCR Ignore CR on input + + INLCR Map NL to CR on input + + INLCRNL Map NL to CR-NL on input + + OCRNL Map CR to NL on output + + ODELBS Map DEL to BS on output + + ONLCRNL Map NL to CR-NL on output + + OLTU Map lowercase characters to uppercase on output + + MSB2LSB Map MSB bit order to LSB on output + + If defining more than one flag, the flags must be comma separated. + + -x, --hexadecimal + + Enable hexadecimal mode. + + -c, --color 0..255|bold|none|list + + Colorize tio text using ANSI color code value ranging from 0 to 255 or use "none" for no color or use "bold" to apply bold formatting to existing system color. + + Use "list" to print a list of available ANSI color codes. + + Default value is "bold". + + -S, --socket + + Redirect I/O to socket. + + Any input from clients connected to the socket is sent on the serial port as if entered at the terminal where tio is running (except that ctrl-t sequences are not recognized), and any input from the serial port is multiplexed to the + terminal and all connected clients. + + Sockets remain open while the serial port is disconnected, and writes will block. + + Various socket types are supported using the following prefixes in the socket field: + + unix: Unix Domain Socket (file) + + inet: Internet Socket (network) + + inet6: Internet IPv6 Socket (network) + + If port is 0 or no port is provided default port 3333 is used. + + At present there is a hardcoded limit of 16 clients connected at one time. + + -r, --response-wait + + Wait for line response then quit. A line is considered any string ending with either CR or NL character. If no line is received tio will quit after response timeout. + + Any tio text is automatically muted when piping a string to tio while in response mode to make it easy to parse the response. + + --response-timeout + + Set timeout [ms] of line response (default: 100). + + --rs-485 + + Enable RS-485 mode. + + --rs-485-config + + Set the RS-485 configuration using the following key or key value pair format in the configuration field: + + RTS_ON_SEND=value Set logical level (0 or 1) for RTS pin when sending + + RTS_AFTER_SEND=value Set logical level (0 or 1) for RTS pin after sending + + RTS_DELAY_BEFORE_SEND=value Set RTS delay (ms) before sending + + RTS_DELAY_AFTER_SEND=value Set RTS delay (ms) after sending + + RX_DURING_TX Receive data even while sending data + + If defining more than one key or key value pair, they must be comma separated. + + --alert none|bell|blink + + Set alert action on connect/disconnect. + + It will sound the bell once or blink once on successful connect. Likewise it will sound the bell twice or blink twice on disconnect. + + Default value is "none". + + -v, --version + + Display program version. + + -h, --help + + Display help. + +KEYS + In session, the following key sequences, a prefix key (default: ctrl-t) followed by a command key, are intercepted as tio commands: + + ctrl-t ? List available key commands + + ctrl-t b Send serial break (triggers SysRq on Linux, etc.) + + ctrl-t c Show configuration (baudrate, databits, etc.) + + ctrl-t e Toggle local echo mode + + ctrl-t f Toggle log to file + + ctrl-t F Flush data I/O buffers (discard data written but not transmitted and data received but not read) + + ctrl-t g Toggle serial port line + + ctrl-t h Toggle hexadecimal mode + + ctrl-t l Clear screen + + ctrl-t L Show line states (DTR, RTS, CTS, DSR, DCD, RI) + + ctrl-t p Pulse serial port line + + ctrl-t q Quit + + ctrl-t s Show TX/RX statistics + + ctrl-t t Toggle line timestamp mode + + ctrl-t U Toggle conversion to uppercase on output + + ctrl-t v Show version + + ctrl-t ctrl-t Send ctrl-t character + +HEXADECIMAL MODE + In hexadecimal mode each incoming byte is printed out as a hexadecimal value. + + Bytes can be sent in this mode by typing the two-character hexadecimal representation of the value, e.g.: to send 0xA you must type 0a or 0A. + +CONFIGURATION FILE + Options can be set via configuration file using the INI format. tio uses the configuration file first found in the following locations in the order listed: + + $XDG_CONFIG_HOME/tio/config + + $HOME/.config/tio/config + + $HOME/.tioconfig + + Labels can be used to group settings into named sub-configurations which can be activated from the command-line when starting tio. + + tio will try to match the user input to a sub-configuration by name or by pattern to get the TTY device and other options. + + Options without any label change the default options. + + Any options set via command-line will override options set in the configuration file. + + The following configuration file options are available: + + pattern Pattern matching user input. This pattern can be an extended regular expression with a single group. + + device TTY device to open. If it contains a "%s" it is substituted with the first group match. + + baudrate Set baud rate + + databits Set data bits + + flow Set flow control + + stopbits Set stop bits + + parity Set parity + + output-delay Set output character delay + + output-line-delay Set output line delay + + line-pulse-duration Set line pulse duration + + no-autoconnect Disable automatic connect + + log Enable log to file + + log-file Set log filename + + log-strip Enable strip of control and escape sequences from log + + local-echo Enable local echo + + timestamp Enable line timestamp + + timestamp-format Set timestamp format + + map Map characters on input or output + + color Colorize tio text using ANSI color code ranging from 0 to 255 + + hexadecimal Enable hexadecimal mode + + socket Set socket to redirect I/O to + + prefix-ctrl-key Set prefix ctrl key (a..z, default: t) + + response-wait Enable wait for line response + + response-timeout Set line response timeout + + rs-485 Enable RS-485 mode + + rs-485-config Set RS-485 configuration + + alert Set alert action on connect/disconnect + +CONFIGURATION FILE EXAMPLES + To change the default configuration simply set options like so: + + # Defaults + baudrate = 9600 + databits = 8 + parity = none + stopbits = 1 + color = 10 + line-pulse-duration = DTR=200,RTS=400 + + Named sub-configurations can be added via labels: + + [rpi3] + device = /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 + baudrate = 115200 + color = 11 + + Activate the sub-configuration by name: + + $ tio rpi3 + + Which is equivalent to: + + $ tio -b 115200 -c 11 /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 + + A sub-configuration can also be activated by its pattern which supports regular expressions: + + [usb device] + pattern = usb([0-9]*) + device = /dev/ttyUSB%s + baudrate = 115200 + + Activate the sub-configuration by pattern match: + + $ tio usb12 + + Which is equivalent to: + + $ tio -b 115200 /dev/ttyUSB12 + + It is also possible to combine use of sub-configuration and command-line options. For example: + + $ tio -l -t usb12 + +EXAMPLES + Typical use is without options: + + $ tio /dev/ttyUSB0 + + Which corresponds to the commonly used default options: + + $ tio -b 115200 -d 8 -f none -s 1 -p none /dev/ttyUSB0 + + It is recommended to connect serial TTY devices by ID: + + $ tio /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 + + Using serial devices by ID ensures that tio automatically reconnects to the correct serial device if it is disconnected and then reconnected. + + Redirect serial device I/O to Unix file socket for scripting: + + $ tio -S unix:/tmp/tmux-socket0 /dev/ttyUSB0 + + Then, to issue a command via the file socket simply do: + + $ echo "ls -la" | nc -UN /tmp/tmux-socket0 > /dev/null + + Or use the expect command to script an interaction: + + #!/usr/bin/expect -f + + set timeout -1 + log_user 0 + + spawn nc -UN /tmp/tio-socket0 + set uart $spawn_id + + send -i $uart "date\n" + expect -i $uart "prompt> " + send -i $uart "ls -la\n" + expect -i $uart "prompt> " + + Redirect device I/O to network file socket for remote TTY sharing: + + $ tio --socket inet:4444 /dev/ttyUSB0 + + Then, use netcat to connect to the shared TTY session over network (assuming tio is hosted on IP 10.0.0.42): + + $ nc -N 10.0.0.42 4444 + + Pipe command to the serial device: + + $ echo "ls -la" | tio /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 + + Pipe command to the serial device and wait for line response (string ending with CR or NL): + + $ echo "*IDN?" | tio /dev/ttyACM0 --response-wait + + In this mode, only the response will be printed. + + Likewise, to pipe data from file to the serial device: + + $ cat data.bin | tio /dev/serial/by-id/usb-FTDI_TTL232R-3V3_FTGQVXBL-if00-port0 + + Enable RS-485 mode: + + $ tio --rs-485 --rs-485-config=RTS_ON_SEND=1,RX_DURING_TX /dev/ttyUSB0 + +WEBSITE + Visit https://tio.github.io + +AUTHOR + Created by Martin Lund . + +tio 2.5 2022-11-02 tio(1) diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..3fb3a22 --- /dev/null +++ b/meson.build @@ -0,0 +1,83 @@ +project('tio', 'c', + version : '2.5', + license : [ 'GPL-2'], + meson_version : '>= 0.53.2', + default_options : [ 'warning_level=2', 'buildtype=release', 'c_std=gnu99' ] +) + +# The tag date of the project_version(), update when the version bumps. +version_date = '2022-12-17' + +# Test for dynamic baudrate configuration interface +compiler = meson.get_compiler('c') +enable_setspeed2 = false +enable_iossiospeed = false +if host_machine.system() != 'darwin' + if compiler.check_header('asm-generic/ioctls.h') + enable_setspeed2 = compiler.has_header_symbol('asm-generic/ioctls.h', 'TCGETS2') + endif +else + if compiler.check_header('IOKit/serial/ioss.h') + enable_iossiospeed = compiler.has_header_symbol('IOKit/serial/ioss.h', 'IOSSIOSPEED') + endif +endif + +# Test for supported baudrates +test_baudrates = [ + 0, + 50, + 75, + 110, + 134, + 150, + 200, + 300, + 600, + 1200, + 1800, + 2400, + 4800, + 7200, + 9600, + 14400, + 19200, + 28800, + 38400, + 57600, + 76800, + 115200, + 230400, + 460800, + 500000, + 576000, + 921600, + 1000000, + 1152000, + 1500000, + 2000000, + 2500000, + 3000000, + 3500000, + 4000000 ] + +baudrates = '' +baudrate_cases = '' +foreach rate : test_baudrates + baudrate = rate.to_string() + value = compiler.get_define('B' + baudrate, prefix: '#include ') + if value != '' + baudrates = baudrates + baudrate + ' ' + baudrate_cases = baudrate_cases + ' case ' + baudrate + ': baudrate = B' + baudrate + '; break;' + endif +endforeach + +# Test for RS-485 support on Linux +enable_rs485 = false +if host_machine.system() == 'linux' + if compiler.check_header('linux/serial.h') + enable_rs485 = compiler.has_header_symbol('sys/ioctl.h', 'TIOCSRS485') + endif +endif + +subdir('src') +subdir('man') diff --git a/meson_options.txt b/meson_options.txt new file mode 100644 index 0000000..ddb4225 --- /dev/null +++ b/meson_options.txt @@ -0,0 +1,3 @@ +option('bashcompletiondir', + type : 'string', + description : 'Directory for bash completion scripts ["no" disables]') diff --git a/src/alert.c b/src/alert.c new file mode 100644 index 0000000..4cb0132 --- /dev/null +++ b/src/alert.c @@ -0,0 +1,110 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "config.h" +#include +#include +#include +#include +#include "error.h" +#include "print.h" +#include "options.h" + +enum alert_t alert_option_parse(const char *arg) +{ + enum alert_t alert = option.alert; // Default + + if (arg != NULL) + { + if (strcmp(arg, "none") == 0) + { + return ALERT_NONE; + } + else if (strcmp(arg, "bell") == 0) + { + return ALERT_BELL; + } + else if (strcmp(arg, "blink") == 0) + { + return ALERT_BLINK; + } + } + + return alert; +} + +void blink_background(void) +{ + // Turn on reverse video + printf("\e[?5h"); + fflush(stdout); + + usleep(200*1000); + + // Turn on normal video + printf("\e[?5l"); + fflush(stdout); +} + +void sound_bell(void) +{ + // Audio bell + printf("\a"); + fflush(stdout); +} + +void alert_connect(void) +{ + switch (option.alert) + { + case ALERT_NONE: + break; + case ALERT_BELL: + sound_bell(); + break; + case ALERT_BLINK: + blink_background(); + break; + default: + break; + } +} + +void alert_disconnect(void) +{ + switch (option.alert) + { + case ALERT_NONE: + break; + case ALERT_BELL: + sound_bell(); + usleep(200*1000); + sound_bell(); + break; + case ALERT_BLINK: + blink_background(); + usleep(200*1000); + blink_background(); + break; + default: + break; + } +} diff --git a/src/alert.h b/src/alert.h new file mode 100644 index 0000000..cb26eff --- /dev/null +++ b/src/alert.h @@ -0,0 +1,34 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +enum alert_t +{ + ALERT_NONE, + ALERT_BELL, + ALERT_BLINK, + ALERT_END, +}; + +enum alert_t alert_option_parse(const char *arg); +void alert_connect(void); +void alert_disconnect(void); diff --git a/src/bash-completion/meson.build b/src/bash-completion/meson.build new file mode 100644 index 0000000..c393aef --- /dev/null +++ b/src/bash-completion/meson.build @@ -0,0 +1,18 @@ +conf = configuration_data() +conf.set('baudrates', baudrates) + +completion_file = configure_file( input: files('tio.in'), + output: 'tio', + configuration: conf ) + +bashcompletiondir = get_option('bashcompletiondir') +if bashcompletiondir == '' + bash_completion_dep = dependency('bash-completion', required: false) + if bash_completion_dep.found() + bashcompletiondir = join_paths(get_option('datadir'), 'bash-completion', 'completions') + endif +endif + +if (bashcompletiondir != 'no') and (bashcompletiondir != '') + install_data(completion_file, install_dir: bashcompletiondir) +endif diff --git a/src/bash-completion/tio.in b/src/bash-completion/tio.in new file mode 100644 index 0000000..9602c4f --- /dev/null +++ b/src/bash-completion/tio.in @@ -0,0 +1,179 @@ +# +# Bash completion script for tio. +# + +_tio() +{ + local cur prev opts base ttys + COMPREPLY=() + cur="${COMP_WORDS[COMP_CWORD]}" + prev="${COMP_WORDS[COMP_CWORD-1]}" + + # The options we'll complete. + opts="-b --baudrate \ + -d --databits \ + -f --flow \ + -s --stopbits \ + -p --parity \ + -o --output-delay \ + -o --output-line-delay \ + --line-pulse-duration \ + -n --no-autoconnect \ + -e --local-echo \ + -l --log \ + --log-file \ + --log-strip \ + -m --map \ + -t --timestamp \ + --timestamp-format \ + -L --list-devices \ + -c --color \ + -S --socket \ + -x --hexadecimal \ + -r --response-wait \ + --response-timeout \ + --rs-485 \ + --rs-485-config \ + --alert \ + --mute \ + -v --version \ + -h --help" + + # Complete the arguments to the options. + case "${prev}" in + -b | --baudrate) + local baudrates="@baudrates@" + COMPREPLY=( $(compgen -W "$baudrates" -- ${cur}) ) + return 0 + ;; + -d | --databits) + COMPREPLY=( $(compgen -W "5 6 7 8" -- ${cur}) ) + return 0 + ;; + -f | --flow) + COMPREPLY=( $(compgen -W "hard soft none" -- ${cur}) ) + return 0 + ;; + -s | --stopbits) + COMPREPLY=( $(compgen -W "1 2" -- ${cur}) ) + return 0 + ;; + -p | --parity) + COMPREPLY=( $(compgen -W "even odd none" -- ${cur}) ) + return 0 + ;; + -o | --output-delay) + COMPREPLY=( $(compgen -W "1 10 100" -- ${cur}) ) + return 0 + ;; + -O | --output-line-delay) + COMPREPLY=( $(compgen -W "1 10 100" -- ${cur}) ) + return 0 + ;; + --line-pulse-duration) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + -n | --no-autoconnect) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + -e | --local-echo) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + -l | --log) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + --log-file) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + --log-strip) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + -m | --map) + COMPREPLY=( $(compgen -W "ICRNL IGNCR INLCR INLCRNL OCRNL ODELBS ONLCRNL MSB2LSB" -- ${cur}) ) + return 0 + ;; + -t | --timestamp) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + --timestamp-format) + COMPREPLY=( $(compgen -W "24hour 24hour-start 24hour-delta iso8601" -- ${cur}) ) + return 0 + ;; + -L | --list-devices) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + -c | --color) + COMPREPLY=( $(compgen -W "$(seq 0 255) none list" -- ${cur}) ) + return 0 + ;; + -S | --socket) + COMPREPLY=( $(compgen -W "unix: inet: inet6:" -- ${cur}) ) + return 0 + ;; + -x | --hexadecimal) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + -r | --response-wait) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + --response-timeout) + COMPREPLY=( $(compgen -W "1 10 100" -- ${cur}) ) + return 0 + ;; + --rs-485) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + --rs-485-config) + COMPREPLY=( $(compgen -W "RTS_ON_SEND RTS_AFTER_SEND RTS_DELAY_BEFORE_SEND RTS_DELAY_AFTER_SEND RX_DURING_TX" -- ${cur}) ) + return 0 + ;; + --alert) + COMPREPLY=( $(compgen -W "none bell blink" -- ${cur}) ) + return 0 + ;; + --mute) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + -v | --version) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + -h | --help) + COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) + return 0 + ;; + *) + ;; + esac + case "${cur}" in + -*) + COMPREPLY=($(compgen -W "${opts}" -- ${cur})) + return 0 + ;; + esac + + sub_configs="`tio --complete-sub-configs`" + + if [ -d /dev/serial/by-id ]; then + ttys=$(printf '%s\n' /dev/tty* /dev/serial/by-id/*) + else + ttys=$(printf '%s\n' /dev/tty*) + fi + COMPREPLY=( $(compgen -W "${ttys} ${sub_configs}" -- ${cur}) ) + return 0 +} + +# Bind completion to tio command +complete -o default -F _tio tio diff --git a/src/configfile.c b/src/configfile.c new file mode 100644 index 0000000..d3dbd16 --- /dev/null +++ b/src/configfile.c @@ -0,0 +1,493 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2020-2022 Liam Beguin + * Copyright (c) 2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#define _GNU_SOURCE + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "options.h" +#include "configfile.h" +#include "misc.h" +#include "options.h" +#include "error.h" +#include "print.h" +#include "rs485.h" +#include "timestamp.h" +#include "alert.h" + +struct config_t +{ + const char *user; + + char *path; + char *section_name; + char *match; + + char *tty; + char *flow; + char *parity; + char *log_filename; + char *socket; + char *map; +}; + +static struct config_t c; + +static int get_match(const char *input, const char *pattern, char **match) +{ + int ret; + int len = 0; + regex_t re; + regmatch_t m[2]; + char err[128]; + + /* compile a regex with the pattern */ + ret = regcomp(&re, pattern, REG_EXTENDED); + if (ret) + { + regerror(ret, &re, err, sizeof(err)); + tio_error_printf("Regex failure: %s", err); + return ret; + } + + /* try to match on input */ + ret = regexec(&re, input, 2, m, 0); + if (!ret) + { + len = m[1].rm_eo - m[1].rm_so; + } + + regfree(&re); + + if (len) + { + asprintf(match, "%s", &input[m[1].rm_so]); + } + + return len; +} + +static bool read_boolean(const char *value, const char *name) +{ + const char *true_values[] = { "true", "enable", "on", "yes", "1", NULL }; + const char *false_values[] = { "false", "disable", "off", "no", "0", NULL }; + + for (int i = 0; true_values[i] != NULL; i++) + if (strcmp(value, true_values[i]) == 0) + return true; + + for (int i = 0; false_values[i] != NULL; i++) + if (strcmp(value, false_values[i]) == 0) + return false; + + tio_error_printf("Invalid value '%s' for option '%s' in configuration file", + value, name); + exit(EXIT_FAILURE); +} + +static long read_integer(const char *value, const char *name, long min_value, long max_value) +{ + errno = 0; + char *endptr; + long result = strtol(value, &endptr, 10); + + if (errno || endptr == value || *endptr != '\0' || result < min_value || result > max_value) + { + tio_error_printf("Invalid value '%s' for option '%s' in configuration file", + value, name); + exit(EXIT_FAILURE); + } + + return result; +} + +/** + * data_handler() - walk config file to load parameters matching user input + * + * INIH handler used to get all parameters from a given section + */ +static int data_handler(void *user, const char *section, const char *name, + const char *value) +{ + UNUSED(user); + + // If section matches current section being parsed + if (!strcmp(section, c.section_name)) + { + // Set configuration parameter if found + if (!strcmp(name, "device") || !strcmp(name, "tty")) + { + asprintf(&c.tty, value, c.match); + option.tty_device = c.tty; + } + else if (!strcmp(name, "baudrate")) + { + option.baudrate = read_integer(value, name, 0, LONG_MAX); + } + else if (!strcmp(name, "databits")) + { + option.databits = read_integer(value, name, 5, 8); + } + else if (!strcmp(name, "flow")) + { + asprintf(&c.flow, "%s", value); + option.flow = c.flow; + } + else if (!strcmp(name, "stopbits")) + { + option.stopbits = read_integer(value, name, 1, 2); + } + else if (!strcmp(name, "parity")) + { + asprintf(&c.parity, "%s", value); + option.parity = c.parity; + } + else if (!strcmp(name, "output-delay")) + { + option.output_delay = read_integer(value, name, 0, LONG_MAX); + } + else if (!strcmp(name, "output-line-delay")) + { + option.output_line_delay = read_integer(value, name, 0, LONG_MAX); + } + else if (!strcmp(name, "line-pulse-duration")) + { + line_pulse_duration_option_parse(value); + } + else if (!strcmp(name, "no-autoconnect")) + { + option.no_autoconnect = read_boolean(value, name); + } + else if (!strcmp(name, "log")) + { + option.log = read_boolean(value, name); + } + else if (!strcmp(name, "log-file")) + { + asprintf(&c.log_filename, "%s", value); + option.log_filename = c.log_filename; + } + else if (!strcmp(name, "log-strip")) + { + option.log_strip = read_boolean(value, name); + } + else if (!strcmp(name, "local-echo")) + { + option.local_echo = read_boolean(value, name); + } + else if (!strcmp(name, "hexadecimal")) + { + option.hex_mode = read_boolean(value, name); + } + else if (!strcmp(name, "timestamp")) + { + option.timestamp = read_boolean(value, name) ? + TIMESTAMP_24HOUR : TIMESTAMP_NONE; + } + else if (!strcmp(name, "timestamp-format")) + { + option.timestamp = timestamp_option_parse(value); + } + else if (!strcmp(name, "map")) + { + asprintf(&c.map, "%s", value); + option.map = c.map; + } + else if (!strcmp(name, "color")) + { + if (!strcmp(value, "list")) + { + // Ignore + return 0; + } + else if (!strcmp(value, "none")) + { + option.color = -1; // No color + return 0; + } + else if (!strcmp(value, "bold")) + { + option.color = 256; // Bold + return 0; + } + + option.color = atoi(value); + if ((option.color < 0) || (option.color > 255)) + { + option.color = -1; // No color + } + } + else if (!strcmp(name, "socket")) + { + asprintf(&c.socket, "%s", value); + option.socket = c.socket; + } + else if (!strcmp(name, "prefix-ctrl-key")) + { + if (ctrl_key_code(value[0]) > 0) + { + option.prefix_code = ctrl_key_code(value[0]); + option.prefix_key = value[0]; + } + } + else if (!strcmp(name, "response-wait")) + { + option.response_wait = read_boolean(value, name); + } + else if (!strcmp(name, "response-timeout")) + { + option.response_timeout = read_integer(value, name, 0, LONG_MAX); + } + else if (!strcmp(name, "rs-485")) + { + option.rs485 = read_boolean(value, name); + } + else if (!strcmp(name, "rs-485-config")) + { + rs485_parse_config(value); + } + else if (!strcmp(name, "alert")) + { + option.alert = alert_option_parse(value); + } + else if (!strcmp(name, "mute")) + { + option.mute = read_boolean(value, name); + } + else + { + tio_warning_printf("Unknown option '%s' in configuration file, ignored", name); + } + } + + return 0; +} + +/** + * section_pattern_search_handler() - walk config file to find section matching user input + * + * INIH handler used to resolve the section matching the user's input. + * This will look for the pattern element of each section and try to match it + * with the user input. + */ +static int section_pattern_search_handler(void *user, const char *section, const char *varname, + const char *varval) +{ + UNUSED(user); + + if (strcmp(varname, "pattern")) + return 0; + + if (!strcmp(varval, c.user)) + { + /* pattern matches as plain text */ + asprintf(&c.section_name, "%s", section); + } + else if (get_match(c.user, varval, &c.match) > 0) + { + /* pattern matches as regex */ + asprintf(&c.section_name, "%s", section); + } + + return 0; +} + +/** + * section_pattern_search_handler() - walk config file to find section matching user input + * + * INIH handler used to resolve the section matching the user's input. + * This will try to match the user input against a section with the name of the user input. + */ +static int section_name_search_handler(void *user, const char *section, const char *varname, + const char *varval) +{ + UNUSED(user); + UNUSED(varname); + UNUSED(varval); + + if (!strcmp(section, c.user)) + { + /* section name matches as plain text */ + asprintf(&c.section_name, "%s", section); + } + + return 0; +} + +static int section_name_print_handler(void *user, const char *section, const char *varname, + const char *varval) +{ + UNUSED(user); + UNUSED(varname); + UNUSED(varval); + + static char *section_previous = ""; + + if (strcmp(section, section_previous) != 0) + { + printf("%s ", section); + section_previous = strdup(section); + } + + return 0; +} + +static int resolve_config_file(void) +{ + char *xdg = getenv("XDG_CONFIG_HOME"); + if (xdg) + { + asprintf(&c.path, "%s/tio/config", xdg); + if (access(c.path, F_OK) == 0) + { + return 0; + } + free(c.path); + } + + char *home = getenv("HOME"); + if (home) + { + asprintf(&c.path, "%s/.config/tio/config", home); + if (access(c.path, F_OK) == 0) + { + return 0; + } + free(c.path); + + asprintf(&c.path, "%s/.tioconfig", home); + if (access(c.path, F_OK) == 0) + { + return 0; + } + free(c.path); + } + + c.path = NULL; + return -EINVAL; +} + +void config_file_show_sub_configurations(void) +{ + memset(&c, 0, sizeof(struct config_t)); + + // Find config file + if (resolve_config_file() != 0) + { + // None found - stop parsing + return; + } + + ini_parse(c.path, section_name_print_handler, NULL); +} + +void config_file_parse(void) +{ + int ret; + + memset(&c, 0, sizeof(struct config_t)); + + // Find config file + if (resolve_config_file() != 0) + { + // None found - stop parsing + return; + } + + // Set user input which may be tty device or sub config + c.user = option.tty_device; + + if (!c.user) + { + return; + } + + // Parse default (unnamed) settings + asprintf(&c.section_name, "%s", ""); + ret = ini_parse(c.path, data_handler, NULL); + if (ret < 0) + { + tio_error_printf("Unable to parse configuration file (%d)", ret); + exit(EXIT_FAILURE); + } + free(c.section_name); + c.section_name = NULL; + + // Find matching section + ret = ini_parse(c.path, section_pattern_search_handler, NULL); + if (!c.section_name) + { + ret = ini_parse(c.path, section_name_search_handler, NULL); + if (!c.section_name) + { + tio_debug_printf("Unable to match user input to configuration section (%d)", ret); + return; + } + } + + // Parse settings of found section (sub config) + ret = ini_parse(c.path, data_handler, NULL); + if (ret < 0) + { + tio_error_printf("Unable to parse configuration file (%d)", ret); + exit(EXIT_FAILURE); + } + + atexit(&config_exit); +} + +void config_exit(void) +{ + free(c.tty); + free(c.flow); + free(c.parity); + free(c.log_filename); + free(c.map); + + free(c.match); + free(c.section_name); + free(c.path); +} + +void config_file_print(void) +{ + if (c.path != NULL) + { + tio_printf(" Active configuration file: %s", c.path); + if (c.section_name != NULL) + { + tio_printf(" Active sub-configuration: %s", c.section_name); + } + } +} diff --git a/src/configfile.h b/src/configfile.h new file mode 100644 index 0000000..74e1b6e --- /dev/null +++ b/src/configfile.h @@ -0,0 +1,28 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2020 Liam Beguin + * Copyright (c) 2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +void config_file_print(void); +void config_file_parse(void); +void config_exit(void); +void config_file_show_sub_configurations(void); diff --git a/src/error.c b/src/error.c new file mode 100644 index 0000000..dfe32aa --- /dev/null +++ b/src/error.c @@ -0,0 +1,101 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include "options.h" +#include "print.h" +#include "error.h" +#include "timestamp.h" + +static char error[2][1000]; +static bool in_session = false; + +void error_enter_session_mode(void) +{ + in_session = true; +} + +void error_printf_(const char *format, ...) +{ + va_list args; + char *line; + + va_start(args, format); + vasprintf(&line, format, args); + + if (in_session) + { + if (print_tainted) + { + putchar('\n'); + } + ansi_error_printf("[%s] %s", timestamp_current_time(), line); + } + else + { + fprintf(stderr, "%s\n", line); + } + + va_end(args); + + print_tainted = false; + free(line); +} + +void tio_error_printf(const char *format, ...) +{ + va_list args; + + va_start(args, format); + vsnprintf(error[0], 1000, format, args); + va_end(args); +} + +void tio_error_printf_silent(const char *format, ...) +{ + va_list args; + + va_start(args, format); + vsnprintf(error[1], 1000, format, args); + va_end(args); +} + +void error_exit(void) +{ + if (error[0][0] != 0) + { + /* Print error */ + error_printf_("Error: %s", error[0]); + } + else if ((error[1][0] != 0) && (option.no_autoconnect)) + { + /* Print silent error */ + error_printf_("Error: %s", error[1]); + } +} diff --git a/src/error.h b/src/error.h new file mode 100644 index 0000000..109d002 --- /dev/null +++ b/src/error.h @@ -0,0 +1,30 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +#define TIO_SUCCESS 0 +#define TIO_ERROR 1 + +void tio_error_printf(const char *format, ...); +void tio_error_printf_silent(const char *format, ...); +void error_exit(void); +void error_enter_session_mode(void); diff --git a/src/log.c b/src/log.c new file mode 100644 index 0000000..d0cf543 --- /dev/null +++ b/src/log.c @@ -0,0 +1,206 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#define __STDC_WANT_LIB_EXT2__ 1 // To access vasprintf + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "options.h" +#include "print.h" +#include "error.h" + +#define IS_ESC_CSI_INTERMEDIATE_CHAR(c) ((c >= 0x20) && (c <= 0x3F)) +#define IS_ESC_END_CHAR(c) ((c >= 0x30) && (c <= 0x7E)) +#define IS_CTRL_CHAR(c) ((c >= 0x00) && (c <= 0x1F)) + +static FILE *fp = NULL; +static char file_buffer[BUFSIZ]; +static const char *log_filename = NULL; + +static char *date_time(void) +{ + static char date_time_string[50]; + struct tm *tm; + struct timeval tv; + + gettimeofday(&tv, NULL); + + tm = localtime(&tv.tv_sec); + strftime(date_time_string, sizeof(date_time_string), "%Y-%m-%dT%H:%M:%S", tm); + + return date_time_string; +} + +int log_open(const char *filename) +{ + static char automatic_filename[400]; + + if (filename == NULL) + { + // Generate filename if none provided ("tio_DEVICE_YYYY-MM-DDTHH:MM:SS.log") + sprintf(automatic_filename, "tio_%s_%s.log", basename((char *)option.tty_device), date_time()); + filename = automatic_filename; + } + + log_filename = filename; + + // Open log file in append write mode + fp = fopen(filename, "a+"); + if (fp == NULL) + { + tio_warning_printf("Could not open log file %s (%s)", filename, strerror(errno)); + return -1; + } + + // Enable line buffering + setvbuf(fp, file_buffer, _IOLBF, BUFSIZ); + + return 0; +} + +bool log_strip(char c) +{ + static char previous_char = 0; + static bool esc_sequence = false; + bool strip = false; + + /* Detect if character should be stripped or not */ + switch (c) + { + case 0xa: + /* Line feed / new line */ + /* Reset ESC sequence just in case something went wrong with the + * escape sequence parsing. */ + esc_sequence = false; + break; + + case 0x1b: + /* Escape */ + strip = true; + break; + + case 0x5b: + /* Left bracket */ + if (previous_char == 0x1b) + { + // Start of ESC sequence + esc_sequence = true; + strip = true; + } + break; + + default: + if (IS_CTRL_CHAR(c)) + { + /* Strip ASCII control characters */ + strip = true; + break; + } + else + if ((esc_sequence) && (IS_ESC_CSI_INTERMEDIATE_CHAR(c))) + { + strip = true; + break; + } + else + if ((esc_sequence) && (IS_ESC_END_CHAR(c))) + { + esc_sequence = false; + strip = true; + break; + } + break; + } + + previous_char = c; + + return strip; +} + +void log_printf(const char *format, ...) +{ + if (fp == NULL) + { + return; + } + + char *line; + + va_list(args); + va_start(args, format); + vasprintf(&line, format, args); + va_end(args); + + fwrite(line, strlen(line), 1, fp); + + free(line); +} + +void log_putc(char c) +{ + if (fp == NULL) + { + return; + } + + if (option.log_strip) + { + if (!log_strip(c)) + { + fputc(c, fp); + } + } + else + { + fputc(c, fp); + } +} + +void log_close(void) +{ + if (fp != NULL) + { + fclose(fp); + fp = NULL; + log_filename = NULL; + } +} + +void log_exit(void) +{ + if (option.log) + { + tio_printf("Saved log to file %s", log_filename); + log_close(); + } +} + +const char *log_get_filename(void) +{ + return log_filename; +} diff --git a/src/log.h b/src/log.h new file mode 100644 index 0000000..b24114e --- /dev/null +++ b/src/log.h @@ -0,0 +1,29 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +int log_open(const char *filename); +void log_printf(const char *format, ...); +void log_putc(char c); +void log_close(void); +void log_exit(void); +const char * log_get_filename(void); diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..ddf8848 --- /dev/null +++ b/src/main.c @@ -0,0 +1,145 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "config.h" +#include +#include +#include +#include "options.h" +#include "configfile.h" +#include "tty.h" +#include "log.h" +#include "error.h" +#include "print.h" +#include "signals.h" +#include "socket.h" + +int main(int argc, char *argv[]) +{ + int status = 0; + + /* Handle received signals */ + signal_handlers_install(); + + /* Add error exit handler */ + atexit(&error_exit); + + /* Parse command-line options (1st pass) */ + options_parse(argc, argv); + + if (option.complete_sub_configs) + { + config_file_show_sub_configurations(); + return status; + } + + /* Parse configuration file */ + config_file_parse(); + + /* Parse command-line options (2nd pass) */ + options_parse_final(argc, argv); + + /* Configure tty device */ + tty_configure(); + + /* Configure input terminal */ + if (isatty(fileno(stdin))) + { + stdin_configure(); + } + else + { + // Enter non interactive mode + interactive_mode = false; + + // Mute tio text in response mode + if (option.response_wait) + { + option.mute = true; + } + } + + /* Configure output terminal */ + if (isatty(fileno(stdout))) + { + stdout_configure(); + } + else + { + // No color when piping + option.color = -1; + } + + /* Add log exit handler */ + atexit(&log_exit); + + /* Create log file */ + if (option.log) + { + log_open(option.log_filename); + } + + /* Initialize ANSI text formatting (colors etc.) */ + print_init_ansi_formatting(); + + /* Change error printing mode */ + error_enter_session_mode(); + + /* Print launch hints */ + tio_printf("tio v%s", VERSION); + if (interactive_mode) + { + tio_printf("Press ctrl-%c q to quit", option.prefix_key); + } else + { + tio_printf("Non-interactive mode enabled"); + tio_printf("Press ctrl-c to quit"); + } + + /* Open socket */ + if (option.socket) + { + socket_configure(); + } + + /* Spawn input handling into separate thread */ + tty_input_thread_create(); + + /* Wait for input to be ready */ + tty_input_thread_wait_ready(); + + /* Connect to tty device */ + if (option.no_autoconnect) + { + status = tty_connect(); + } + else + { + /* Enter connect loop */ + while (true) + { + tty_wait_for_device(); + status = tty_connect(); + } + } + + return status; +} diff --git a/src/meson.build b/src/meson.build new file mode 100644 index 0000000..cec9429 --- /dev/null +++ b/src/meson.build @@ -0,0 +1,50 @@ +config_h = configuration_data() +config_h.set_quoted('VERSION', meson.project_version()) +config_h.set('BAUDRATE_CASES', baudrate_cases) +configure_file(output: 'config.h', configuration: config_h) + +tio_sources = [ + 'error.c', + 'log.c', + 'main.c', + 'options.c', + 'misc.c', + 'tty.c', + 'print.c', + 'configfile.c', + 'signals.c', + 'socket.c', + 'setspeed.c', + 'rs485.c', + 'timestamp.c', + 'alert.c' +] + +tio_dep = [ + dependency('threads', required: true), + dependency('inih', required: true, + fallback : ['libinih', 'inih_dep'], + default_options: ['default_library=static', 'distro_install=false']) +] + +tio_c_args = ['-Wno-unused-result'] + +if enable_setspeed2 + tio_c_args += '-DHAVE_TERMIOS2' +endif + +if enable_iossiospeed + tio_c_args += '-DHAVE_IOSSIOSPEED' +endif + +if enable_rs485 + tio_c_args += '-DHAVE_RS485' +endif + +executable('tio', + tio_sources, + c_args: tio_c_args, + dependencies: tio_dep, + install: true ) + +subdir('bash-completion') diff --git a/src/misc.c b/src/misc.c new file mode 100644 index 0000000..1983950 --- /dev/null +++ b/src/misc.c @@ -0,0 +1,72 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include "error.h" +#include "print.h" +#include "options.h" + +void delay(long ms) +{ + struct timespec ts; + + if (ms <= 0) + { + return; + } + + ts.tv_sec = ms / 1000; + ts.tv_nsec = (ms % 1000) * 1000000; + + nanosleep(&ts, NULL); +} + +long string_to_long(char *string) +{ + long result; + char *end_token; + + errno = 0; + result = strtol(string, &end_token, 10); + if ((errno != 0) || (*end_token != 0)) + { + printf("Error: Invalid digit\n"); + exit(EXIT_FAILURE); + } + + return result; +} + +int ctrl_key_code(unsigned char key) +{ + if ((key >= 'a') && (key <= 'z')) + { + return key & ~0x60; + } + + return -1; +} diff --git a/src/misc.h b/src/misc.h new file mode 100644 index 0000000..6fe5368 --- /dev/null +++ b/src/misc.h @@ -0,0 +1,31 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +#define UNUSED(expr) do { (void)(expr); } while (0) + +char * current_time(void); +void delay(long ms); +long string_to_long(char *string); +int ctrl_key_code(unsigned char key); +void alert_connect(void); +void alert_disconnect(void); diff --git a/src/options.c b/src/options.c new file mode 100644 index 0000000..eb75144 --- /dev/null +++ b/src/options.c @@ -0,0 +1,489 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "options.h" +#include "error.h" +#include "misc.h" +#include "print.h" +#include "tty.h" +#include "rs485.h" +#include "timestamp.h" +#include "alert.h" +#include "log.h" + +enum opt_t +{ + OPT_NONE, + OPT_TIMESTAMP_FORMAT, + OPT_LOG_FILE, + OPT_LOG_STRIP, + OPT_LINE_PULSE_DURATION, + OPT_RESPONSE_TIMEOUT, + OPT_RS485, + OPT_RS485_CONFIG, + OPT_ALERT, + OPT_COMPLETE_SUB_CONFIGS, + OPT_MUTE, +}; + +/* Default options */ +struct option_t option = +{ + .tty_device = "", + .baudrate = 115200, + .databits = 8, + .flow = "none", + .stopbits = 1, + .parity = "none", + .output_delay = 0, + .output_line_delay = 0, + .dtr_pulse_duration = 100, + .rts_pulse_duration = 100, + .cts_pulse_duration = 100, + .dsr_pulse_duration = 100, + .dcd_pulse_duration = 100, + .ri_pulse_duration = 100, + .no_autoconnect = false, + .log = false, + .log_filename = NULL, + .log_strip = false, + .local_echo = false, + .timestamp = TIMESTAMP_NONE, + .socket = NULL, + .map = "", + .color = 256, // Bold + .hex_mode = false, + .prefix_code = 20, // ctrl-t + .prefix_key = 't', + .response_wait = false, + .response_timeout = 100, + .mute = false, + .rs485 = false, + .rs485_config_flags = 0, + .rs485_delay_rts_before_send = -1, + .rs485_delay_rts_after_send = -1, + .alert = ALERT_NONE, + .complete_sub_configs = false, +}; + +void print_help(char *argv[]) +{ + UNUSED(argv); + + printf("Usage: tio [] \n"); + printf("\n"); + printf("Connect to TTY device directly or via sub-configuration.\n"); + printf("\n"); + printf("Options:\n"); + printf(" -b, --baudrate Baud rate (default: 115200)\n"); + printf(" -d, --databits 5|6|7|8 Data bits (default: 8)\n"); + printf(" -f, --flow hard|soft|none Flow control (default: none)\n"); + printf(" -s, --stopbits 1|2 Stop bits (default: 1)\n"); + printf(" -p, --parity odd|even|none|mark|space Parity (default: none)\n"); + printf(" -o, --output-delay Output character delay (default: 0)\n"); + printf(" -O, --output-line-delay Output line delay (default: 0)\n"); + printf(" --line-pulse-duration Set line pulse duration\n"); + printf(" -n, --no-autoconnect Disable automatic connect\n"); + printf(" -e, --local-echo Enable local echo\n"); + printf(" -t, --timestamp Enable line timestamp\n"); + printf(" --timestamp-format Set timestamp format (default: 24hour)\n"); + printf(" -L, --list-devices List available serial devices by ID\n"); + printf(" -l, --log Enable log to file\n"); + printf(" --log-file Set log filename\n"); + printf(" --log-strip Strip control characters and escape sequences\n"); + printf(" -m, --map Map characters\n"); + printf(" -c, --color 0..255|bold|none|list Colorize tio text (default: bold)\n"); + printf(" -S, --socket Redirect I/O to socket\n"); + printf(" -x, --hexadecimal Enable hexadecimal mode\n"); + printf(" -r, --response-wait Wait for line response then quit\n"); + printf(" --response-timeout Response timeout (default: 100)\n"); + printf(" --rs-485 Enable RS-485 mode\n"); + printf(" --rs-485-config Set RS-485 configuration\n"); + printf(" --alert bell|blink|none Alert on connect/disconnect (default: none)\n"); + printf(" --mute Mute tio\n"); + printf(" -v, --version Display version\n"); + printf(" -h, --help Display help\n"); + printf("\n"); + printf("Options and sub-configurations may be set via configuration file.\n"); + printf("\n"); + printf("See the man page for more details.\n"); +} + +void line_pulse_duration_option_parse(const char *arg) +{ + bool token_found = true; + char *token = NULL; + char *buffer = strdup(arg); + + while (token_found == true) + { + if (token == NULL) + { + token = strtok(buffer,","); + } + else + { + token = strtok(NULL, ","); + } + + if (token != NULL) + { + char keyname[11]; + unsigned int value; + sscanf(token, "%10[^=]=%d", keyname, &value); + + if (!strcmp(keyname, "DTR")) + { + option.dtr_pulse_duration = value; + } + else if (!strcmp(keyname, "RTS")) + { + option.rts_pulse_duration = value; + } + else if (!strcmp(keyname, "CTS")) + { + option.cts_pulse_duration = value; + } + else if (!strcmp(keyname, "DSR")) + { + option.dsr_pulse_duration = value; + } + else if (!strcmp(keyname, "DCD")) + { + option.dcd_pulse_duration = value; + } + else if (!strcmp(keyname, "RI")) + { + option.ri_pulse_duration = value; + } + } + else + { + token_found = false; + } + } + free(buffer); +} + +void options_print() +{ + tio_printf(" Device: %s", option.tty_device); + tio_printf(" Baudrate: %u", option.baudrate); + tio_printf(" Databits: %d", option.databits); + tio_printf(" Flow: %s", option.flow); + tio_printf(" Stopbits: %d", option.stopbits); + tio_printf(" Parity: %s", option.parity); + tio_printf(" Local echo: %s", option.local_echo ? "enabled" : "disabled"); + tio_printf(" Timestamp: %s", timestamp_state_to_string(option.timestamp)); + tio_printf(" Output delay: %d", option.output_delay); + tio_printf(" Output line delay: %d", option.output_line_delay); + tio_printf(" Auto connect: %s", option.no_autoconnect ? "disabled" : "enabled"); + tio_printf(" Pulse duration: DTR=%d RTS=%d CTS=%d DSR=%d DCD=%d RI=%d", option.dtr_pulse_duration, + option.rts_pulse_duration, + option.cts_pulse_duration, + option.dsr_pulse_duration, + option.dcd_pulse_duration, + option.ri_pulse_duration); + tio_printf(" Hexadecimal mode: %s", option.hex_mode ? "enabled" : "disabled"); + if (option.map[0] != 0) + tio_printf(" Map flags: %s", option.map); + if (option.log) + tio_printf(" Log file: %s", log_get_filename()); + if (option.socket) + tio_printf(" Socket: %s", option.socket); +} + +void options_parse(int argc, char *argv[]) +{ + int c; + + if (argc == 1) + { + print_help(argv); + exit(EXIT_SUCCESS); + } + + while (1) + { + static struct option long_options[] = + { + {"baudrate", required_argument, 0, 'b' }, + {"databits", required_argument, 0, 'd' }, + {"flow", required_argument, 0, 'f' }, + {"stopbits", required_argument, 0, 's' }, + {"parity", required_argument, 0, 'p' }, + {"output-delay", required_argument, 0, 'o' }, + {"output-line-delay" , required_argument, 0, 'O' }, + {"line-pulse-duration", required_argument, 0, OPT_LINE_PULSE_DURATION }, + {"no-autoconnect", no_argument, 0, 'n' }, + {"local-echo", no_argument, 0, 'e' }, + {"timestamp", no_argument, 0, 't' }, + {"timestamp-format", required_argument, 0, OPT_TIMESTAMP_FORMAT }, + {"list-devices", no_argument, 0, 'L' }, + {"log", no_argument, 0, 'l' }, + {"log-file", required_argument, 0, OPT_LOG_FILE }, + {"log-strip", no_argument, 0, OPT_LOG_STRIP }, + {"socket", required_argument, 0, 'S' }, + {"map", required_argument, 0, 'm' }, + {"color", required_argument, 0, 'c' }, + {"hexadecimal", no_argument, 0, 'x' }, + {"response-wait", no_argument, 0, 'r' }, + {"response-timeout", required_argument, 0, OPT_RESPONSE_TIMEOUT }, + {"rs-485", no_argument, 0, OPT_RS485 }, + {"rs-485-config", required_argument, 0, OPT_RS485_CONFIG }, + {"alert", required_argument, 0, OPT_ALERT }, + {"mute", no_argument, 0, OPT_MUTE }, + {"version", no_argument, 0, 'v' }, + {"help", no_argument, 0, 'h' }, + {"complete-sub-configs", no_argument, 0, OPT_COMPLETE_SUB_CONFIGS}, + {0, 0, 0, 0 } + }; + + /* getopt_long stores the option index here */ + int option_index = 0; + + /* Parse argument using getopt_long */ + c = getopt_long(argc, argv, "b:d:f:s:p:o:O:netLlS:m:c:xrvh", long_options, &option_index); + + /* Detect the end of the options */ + if (c == -1) + break; + + switch (c) + { + case 0: + /* If this option sets a flag, do nothing else now */ + if (long_options[option_index].flag != 0) + break; + printf("option %s", long_options[option_index].name); + if (optarg) + printf(" with arg %s", optarg); + printf("\n"); + break; + + case 'b': + option.baudrate = string_to_long(optarg); + break; + + case 'd': + option.databits = string_to_long(optarg); + break; + + case 'f': + option.flow = optarg; + break; + + case 's': + option.stopbits = string_to_long(optarg); + break; + + case 'p': + option.parity = optarg; + break; + + case 'o': + option.output_delay = string_to_long(optarg); + break; + + case 'O': + option.output_line_delay = string_to_long(optarg); + break; + + case OPT_LINE_PULSE_DURATION: + line_pulse_duration_option_parse(optarg); + break; + + case 'n': + option.no_autoconnect = true; + break; + + case 'e': + option.local_echo = true; + break; + + case 't': + option.timestamp = TIMESTAMP_24HOUR; + break; + + case OPT_TIMESTAMP_FORMAT: + option.timestamp = timestamp_option_parse(optarg); + break; + + case 'L': + list_serial_devices(); + exit(EXIT_SUCCESS); + break; + + case 'l': + option.log = true; + break; + + case OPT_LOG_FILE: + option.log_filename = optarg; + break; + + case OPT_LOG_STRIP: + option.log_strip = true; + break; + + case 'S': + option.socket = optarg; + break; + + case 'm': + option.map = optarg; + break; + + case 'c': + if (!strcmp(optarg, "list")) + { + // Print available color codes + printf("Available color codes:\n"); + for (int i=0; i<=255; i++) + { + printf(" \e[1;38;5;%dmThis is color code %d\e[0m\n", i, i); + } + exit(EXIT_SUCCESS); + } + else if (!strcmp(optarg, "none")) + { + option.color = -1; // No color + break; + } + else if (!strcmp(optarg, "bold")) + { + option.color = 256; // Bold + break; + } + + option.color = string_to_long(optarg); + if ((option.color < 0) || (option.color > 255)) + { + tio_error_printf("Invalid color code"); + exit(EXIT_FAILURE); + } + break; + + case 'x': + option.hex_mode = true; + break; + + case 'r': + option.response_wait = true; + break; + + case OPT_RESPONSE_TIMEOUT: + option.response_timeout = string_to_long(optarg); + break; + + case OPT_RS485: + option.rs485 = true; + break; + + case OPT_RS485_CONFIG: + rs485_parse_config(optarg); + break; + + case OPT_ALERT: + option.alert = alert_option_parse(optarg); + break; + + case OPT_MUTE: + option.mute = true; + break; + + case 'v': + printf("tio v%s\n", VERSION); + exit(EXIT_SUCCESS); + break; + + case 'h': + print_help(argv); + exit(EXIT_SUCCESS); + break; + + case OPT_COMPLETE_SUB_CONFIGS: + option.complete_sub_configs = true; + break; + + case '?': + /* getopt_long already printed an error message */ + exit(EXIT_FAILURE); + break; + + default: + exit(EXIT_FAILURE); + } + } + + /* Assume first non-option is the tty device name */ + if (strcmp(option.tty_device, "")) + optind++; + else if (optind < argc) + option.tty_device = argv[optind++]; + + if (option.complete_sub_configs) + { + return; + } + + if (strlen(option.tty_device) == 0) + { + tio_error_printf("Missing tty device or sub-configuration name"); + exit(EXIT_FAILURE); + } + + /* Print any remaining command line arguments (unknown options) */ + if (optind < argc) + { + fprintf(stderr, "Error: Unknown argument "); + while (optind < argc) + { + fprintf(stderr, "%s ", argv[optind++]); + } + fprintf(stderr, "\n"); + exit(EXIT_FAILURE); + } +} + +void options_parse_final(int argc, char *argv[]) +{ + /* Preserve tty device which may have been set by configuration file */ + const char *tty_device = option.tty_device; + + /* Do 2nd pass to override settings set by configuration file */ + optind = 1; // Reset option index to restart scanning of argv + options_parse(argc, argv); + + /* Restore tty device */ + option.tty_device = tty_device; +} diff --git a/src/options.h b/src/options.h new file mode 100644 index 0000000..8ae556d --- /dev/null +++ b/src/options.h @@ -0,0 +1,78 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include "timestamp.h" +#include "alert.h" + +/* Options */ +struct option_t +{ + const char *tty_device; + unsigned int baudrate; + int databits; + char *flow; + int stopbits; + char *parity; + int output_delay; + int output_line_delay; + unsigned int dtr_pulse_duration; + unsigned int rts_pulse_duration; + unsigned int cts_pulse_duration; + unsigned int dsr_pulse_duration; + unsigned int dcd_pulse_duration; + unsigned int ri_pulse_duration; + bool no_autoconnect; + bool log; + bool log_strip; + bool local_echo; + enum timestamp_t timestamp; + const char *log_filename; + const char *map; + const char *socket; + int color; + bool hex_mode; + unsigned char prefix_code; + unsigned char prefix_key; + bool response_wait; + int response_timeout; + bool mute; + bool rs485; + uint32_t rs485_config_flags; + int32_t rs485_delay_rts_before_send; + int32_t rs485_delay_rts_after_send; + enum alert_t alert; + bool complete_sub_configs; +}; + +extern struct option_t option; + +void options_print(); +void options_parse(int argc, char *argv[]); +void options_parse_final(int argc, char *argv[]); + +void line_pulse_duration_option_parse(const char *arg); diff --git a/src/print.c b/src/print.c new file mode 100644 index 0000000..b5ad48c --- /dev/null +++ b/src/print.c @@ -0,0 +1,75 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include +#include +#include +#include +#include "options.h" +#include "print.h" + +bool print_tainted = false; +char ansi_format[30]; + +void print_hex(char c) +{ + printf("%02x ", (unsigned char) c); +} + +void print_normal(char c) +{ + putchar(c); +} + +void print_init_ansi_formatting() +{ + if (option.color == 256) + { + // Set bold text with no color changes + sprintf(ansi_format, "\e[1m"); + } + else + { + // Set bold text with user defined ANSI color + sprintf(ansi_format, "\e[1;38;5;%dm", option.color); + } +} + +void tio_printf_array(const char *array) +{ + int i = 0, j = 0; + + tio_printf(""); + + while (array[i]) + { + if (array[i] == '\n') + { + const char *line = &array[j]; + char *line_copy = strndup(line, i-j); + tio_printf_raw("%s\r", line_copy); + free(line_copy); + j = i; + } + i++; + } + tio_printf(""); +} diff --git a/src/print.h b/src/print.h new file mode 100644 index 0000000..c870f17 --- /dev/null +++ b/src/print.h @@ -0,0 +1,118 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +#include +#include +#include "misc.h" +#include "error.h" +#include "options.h" +#include "timestamp.h" + +extern bool print_tainted; +extern char ansi_format[]; + +#define ANSI_RESET "\e[0m" + +#define ansi_printf(format, args...) \ +{ \ + if (!option.mute) \ + { \ + if (option.color < 0) \ + fprintf (stdout, "\r" format "\r\n", ## args); \ + else \ + fprintf (stdout, "\r%s" format ANSI_RESET "\r\n", ansi_format, ## args); \ + } \ +} + +#define ansi_error_printf(format, args...) \ +{ \ + if (!option.mute) \ + { \ + if (option.color < 0) \ + fprintf (stderr, "\r" format "\r\n", ## args); \ + else \ + fprintf (stderr, "\r%s" format ANSI_RESET "\r\n", ansi_format, ## args); \ + fflush(stderr); \ + } \ +} + +#define ansi_printf_raw(format, args...) \ +{ \ + if (!option.mute) \ + { \ + if (option.color < 0) \ + fprintf (stdout, format, ## args); \ + else \ + fprintf (stdout, "%s" format ANSI_RESET, ansi_format, ## args); \ + } \ +} + +#define tio_warning_printf(format, args...) \ +{ \ + if (!option.mute) \ + { \ + if (print_tainted) \ + putchar('\n'); \ + if (option.color < 0) \ + fprintf (stdout, "\r[%s] Warning: " format "\r\n", timestamp_current_time(), ## args); \ + else \ + ansi_printf("[%s] Warning: " format, timestamp_current_time(), ## args); \ + } \ +} + +#define tio_printf(format, args...) \ +{ \ + if (!option.mute) \ + { \ + if (print_tainted) \ + putchar('\n'); \ + ansi_printf("[%s] " format, timestamp_current_time(), ## args); \ + print_tainted = false; \ + } \ +} + +#define tio_printf_raw(format, args...) \ +{ \ + if (!option.mute) \ + { \ + if (print_tainted) \ + putchar('\n'); \ + ansi_printf_raw("[%s] " format, timestamp_current_time(), ## args); \ + print_tainted = false; \ + } \ +} + +#ifdef DEBUG +#define tio_debug_printf(format, args...) \ + fprintf(stdout, "[debug] " format, ## args) +#define tio_debug_printf_raw(format, args...) \ + fprintf(stdout, "" format, ## args) +#else +#define tio_debug_printf(format, args...) +#define tio_debug_printf_raw(format, args...) +#endif + +void print_hex(char c); +void print_normal(char c); +void print_init_ansi_formatting(void); +void tio_printf_array(const char *array); diff --git a/src/rs485.c b/src/rs485.c new file mode 100644 index 0000000..e364b13 --- /dev/null +++ b/src/rs485.c @@ -0,0 +1,200 @@ +/* + * tio - a simple serial device I/O tool + * + * Copyright (c) 2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include +#include +#include +#include +#include +#include "options.h" +#include "print.h" +#include "error.h" + +#ifdef HAVE_RS485 + +#include + +static struct serial_rs485 rs485_config_saved; +static struct serial_rs485 rs485_config; +static bool rs485_config_written = false; + +void rs485_parse_config(const char *arg) +{ + bool token_found = true; + char *token = NULL; + char *buffer = strdup(arg); + + while (token_found == true) + { + if (token == NULL) + { + token = strtok(buffer,","); + } + else + { + token = strtok(NULL, ","); + } + + if (token != NULL) + { + char keyname[31]; + unsigned int value; + sscanf(token, "%30[^=]=%d", keyname, &value); + + if (!strcmp(keyname, "RTS_ON_SEND")) + { + if (value) + { + + /* Set logical level for RTS pin equal to 1 when sending */ + option.rs485_config_flags |= SER_RS485_RTS_ON_SEND; + } + else + { + /* Set logical level for RTS pin equal to 0 when sending */ + option.rs485_config_flags &= ~(SER_RS485_RTS_ON_SEND); + } + } + else if (!strcmp(keyname, "RTS_AFTER_SEND")) + { + if (value) + { + /* Set logical level for RTS pin equal to 1 after sending */ + option.rs485_config_flags |= SER_RS485_RTS_AFTER_SEND; + } + else + { + /* Set logical level for RTS pin equal to 0 after sending */ + option.rs485_config_flags &= ~(SER_RS485_RTS_AFTER_SEND); + } + } + else if (!strcmp(keyname, "RTS_DELAY_BEFORE_SEND")) + { + /* Set RTS delay before send */ + option.rs485_delay_rts_before_send = value; + } + else if (!strcmp(keyname, "RTS_DELAY_AFTER_SEND")) + { + /* Set RTS delay after send */ + option.rs485_delay_rts_after_send = value; + } + else if (!strcmp(keyname, "RX_DURING_TX")) + { + /* Receive data even while sending data */ + option.rs485_config_flags |= SER_RS485_RX_DURING_TX; + } + } + else + { + token_found = false; + } + } + free(buffer); +} + +void rs485_print_config(void) +{ + tio_printf(" RS-485 Configuration:"); + tio_printf(" RTS_ON_SEND: %s", (rs485_config.flags & SER_RS485_RTS_ON_SEND) ? "high" : "low"); + tio_printf(" RTS_AFTER_SEND: %s", (rs485_config.flags & SER_RS485_RTS_AFTER_SEND) ? "high" : "low"); + tio_printf(" RTS_DELAY_BEFORE_SEND = %d", rs485_config.delay_rts_before_send); + tio_printf(" RTS_DELAY_AFTER_SEND = %d", rs485_config.delay_rts_after_send); + tio_printf(" RX_DURING_TX: %s", (rs485_config.flags & SER_RS485_RX_DURING_TX) ? "enabled" : "disabled"); +} + +int rs485_mode_enable(int fd) +{ + /* Save existing RS-485 configuration */ + ioctl (fd, TIOCGRS485, &rs485_config_saved); + + /* Prepare new RS-485 configuration */ + rs485_config.flags = SER_RS485_ENABLED; + rs485_config.flags |= option.rs485_config_flags; + + if (option.rs485_delay_rts_before_send > 0) + { + rs485_config.delay_rts_before_send = option.rs485_delay_rts_before_send; + } + else + { + rs485_config.delay_rts_before_send = rs485_config_saved.delay_rts_before_send; + } + + if (option.rs485_delay_rts_after_send > 0) + { + rs485_config.delay_rts_after_send = option.rs485_delay_rts_after_send; + } + else + { + rs485_config.delay_rts_after_send = rs485_config_saved.delay_rts_after_send; + } + + /* Write new RS-485 configuration */ + if (ioctl(fd, TIOCSRS485, &rs485_config) < 0) + { + tio_warning_printf("RS-485 mode is not supported by your device (%s)", strerror(errno)); + return -1; + } + + rs485_config_written = true; + + return 0; +} + +void rs485_mode_restore(int fd) +{ + if (rs485_config_written) + { + /* Write saved RS-485 configuration */ + if (ioctl(fd, TIOCSRS485, &rs485_config_saved) < 0) + { + tio_warning_printf("TIOCGRS485 ioctl failed (%s)", strerror(errno)); + } + } +} + +#else + +void rs485_parse_config(const char *arg) +{ + UNUSED(arg); + return; +} + +void rs485_print_config(void) +{ + return; +} + +int rs485_mode_enable(int fd) +{ + UNUSED(fd); + tio_error_printf("RS485 mode is not supported on your system"); + exit(EXIT_FAILURE); +} + +void rs485_mode_restore(int fd) +{ + UNUSED(fd); + return; +} + +#endif diff --git a/src/rs485.h b/src/rs485.h new file mode 100644 index 0000000..b7a4882 --- /dev/null +++ b/src/rs485.h @@ -0,0 +1,27 @@ +/* + * tio - a simple serial device I/O tool + * + * Copyright (c) 2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +void rs485_parse_config(const char *arg); +int rs485_mode_enable(int fd); +void rs485_mode_restore(int fd); +void rs485_print_config(void); diff --git a/src/setspeed.c b/src/setspeed.c new file mode 100644 index 0000000..745bd4b --- /dev/null +++ b/src/setspeed.c @@ -0,0 +1,68 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2017-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include + +#ifdef HAVE_TERMIOS2 +#define termios asmtermios +#include +#undef termios +#include +#include + +#elif HAVE_IOSSIOSPEED +#include +#include +#endif + + +#ifdef HAVE_TERMIOS2 +int setspeed(int fd, int baudrate) +{ + struct termios2 tio; + int status; + + status = ioctl(fd, TCGETS2, &tio); + + // Set baudrate speed using termios2 interface + tio.c_cflag &= ~CBAUD; + tio.c_cflag |= BOTHER; + tio.c_ispeed = baudrate; + tio.c_ospeed = baudrate; + + status = ioctl(fd, TCSETS2, &tio); + + return status; +} + +#elif HAVE_IOSSIOSPEED +int setspeed(int fd, int baudrate) +{ + return ioctl(fd, IOSSIOSPEED, (char *)&baudrate); +} + +#else +int setspeed(int fd, int baudrate) +{ + errno = EINVAL; + return -1; +} +#endif diff --git a/src/setspeed.h b/src/setspeed.h new file mode 100644 index 0000000..c201f6e --- /dev/null +++ b/src/setspeed.h @@ -0,0 +1,24 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +int setspeed(int fd, int baudrate); diff --git a/src/signals.c b/src/signals.c new file mode 100644 index 0000000..6829b44 --- /dev/null +++ b/src/signals.c @@ -0,0 +1,51 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "config.h" +#include +#include +#include +#include +#include "error.h" +#include "print.h" +#include "misc.h" +#include "tty.h" + +static void signal_handler(int signum) +{ + switch (signum) + { + case SIGHUP: + tio_printf("Received SIGHUP signal!"); + break; + case SIGINT: + tio_printf("Received SIGINT signal!"); + break; + } + exit(EXIT_FAILURE); +} + +void signal_handlers_install(void) +{ + signal(SIGHUP, signal_handler); + signal(SIGINT, signal_handler); + signal(SIGPIPE, SIG_IGN); +} diff --git a/src/signals.h b/src/signals.h new file mode 100644 index 0000000..8d8d70f --- /dev/null +++ b/src/signals.h @@ -0,0 +1,24 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +void signal_handlers_install(); diff --git a/src/socket.c b/src/socket.c new file mode 100644 index 0000000..16d9621 --- /dev/null +++ b/src/socket.c @@ -0,0 +1,352 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * Copyright (c) 2022 Google LLC + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "socket.h" +#include "options.h" +#include "print.h" + +#define MAX_SOCKET_CLIENTS 16 +#define SOCKET_PORT_DEFAULT 3333 + +static int sockfd; +static int clientfds[MAX_SOCKET_CLIENTS]; +static int socket_family = AF_UNSPEC; +static int port_number = SOCKET_PORT_DEFAULT; + +static const char *socket_filename(void) +{ + /* skip 'unix:' */ + return option.socket + 5; +} + +static int socket_inet_port(void) +{ + /* skip 'inet:' */ + int port_number = atoi(option.socket + 5); + if (port_number == 0) + { + port_number = SOCKET_PORT_DEFAULT; + } + return port_number; +} + +static int socket_inet6_port(void) +{ + /* skip 'inet6:' */ + int port_number = atoi(option.socket + 6); + if (port_number == 0) + { + port_number = SOCKET_PORT_DEFAULT; + } + return port_number; +} + +static void socket_exit(void) +{ + if (socket_family == AF_UNIX) + { + unlink(socket_filename()); + } +} + +static bool socket_stale(const char *path) +{ + struct sockaddr_un addr; + bool stale = false; + int sockfd; + + /* Test if socket file exists */ + if (access(path, F_OK) == 0) + { + /* Create test socket */ + sockfd = socket(AF_UNIX, SOCK_STREAM, 0); + if (sockfd < 0) + { + tio_warning_printf("Failure opening socket (%s)", strerror(errno)); + return false; + } + + /* Prepare address */ + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); + + /* Perform connect to test if socket is active */ + if (connect(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)) == -1) + { + if (errno == ECONNREFUSED) + { + // No one is listening on socket file + stale = true; + } + } + + /* Cleanup */ + close(sockfd); + } + + return stale; +} + +void socket_configure(void) +{ + struct sockaddr_un sockaddr_unix = {}; + struct sockaddr_in sockaddr_inet = {}; + struct sockaddr_in6 sockaddr_inet6 = {}; + struct sockaddr *sockaddr_p; + socklen_t socklen; + + /* Parse socket string */ + + if (strncmp(option.socket, "unix:", 5) == 0) + { + socket_family = AF_UNIX; + + if (strlen(socket_filename()) == 0) + { + tio_error_printf("Missing socket filename"); + exit(EXIT_FAILURE); + } + + if (strlen(socket_filename()) > sizeof(sockaddr_unix.sun_path) - 1) + { + tio_error_printf("Socket file path %s too long", option.socket); + exit(EXIT_FAILURE); + } + } + + if (strncmp(option.socket, "inet:", 5) == 0) + { + socket_family = AF_INET; + + port_number = socket_inet_port(); + + if (port_number < 0) + { + tio_error_printf("Invalid port number: %d", port_number); + exit(EXIT_FAILURE); + } + } + + if (strncmp(option.socket, "inet6:", 6) == 0) + { + socket_family = AF_INET6; + + port_number = socket_inet6_port(); + + if (port_number < 0) + { + tio_error_printf("Invalid port number: %d", port_number); + exit(EXIT_FAILURE); + } + } + + if (socket_family == AF_UNSPEC) + { + tio_error_printf("%s: Invalid socket scheme, must be prefixed with 'unix:', 'inet:', or 'inet6:'", option.socket); + exit(EXIT_FAILURE); + } + + /* Configure socket */ + + switch (socket_family) + { + case AF_UNIX: + sockaddr_unix.sun_family = AF_UNIX; + strncpy(sockaddr_unix.sun_path, socket_filename(), sizeof(sockaddr_unix.sun_path) - 1); + sockaddr_p = (struct sockaddr *) &sockaddr_unix; + socklen = sizeof(sockaddr_unix); + + /* Test for stale unix socket file */ + if (socket_stale(socket_filename())) + { + tio_printf("Cleaning up old socket file"); + unlink(socket_filename()); + } + + break; + + case AF_INET: + sockaddr_inet.sin_family = AF_INET; + sockaddr_inet.sin_addr.s_addr = INADDR_ANY; + sockaddr_inet.sin_port = htons(port_number); + sockaddr_p = (struct sockaddr *) &sockaddr_inet; + socklen = sizeof(sockaddr_inet); + break; + + case AF_INET6: + sockaddr_inet6.sin6_family = AF_INET6; + sockaddr_inet6.sin6_addr = in6addr_any; + sockaddr_inet6.sin6_port = htons(port_number); + sockaddr_p = (struct sockaddr *) &sockaddr_inet6; + socklen = sizeof(sockaddr_inet6); + break; + + default: + tio_error_printf("Invalid socket family (%d)", socket_family); + exit(EXIT_FAILURE); + break; + } + + /* Create socket */ + sockfd = socket(socket_family, SOCK_STREAM, 0); + if (sockfd < 0) + { + tio_error_printf("Failed to create socket (%s)", strerror(errno)); + exit(EXIT_FAILURE); + } + + /* Bind */ + if (bind(sockfd, sockaddr_p, socklen) < 0) + { + tio_error_printf("Failed to bind to socket (%s)", strerror(errno)); + exit(EXIT_FAILURE); + } + + /* Listen */ + if (listen(sockfd, MAX_SOCKET_CLIENTS) < 0) + { + tio_error_printf("Failed to listen on socket (%s)", strerror(errno)); + exit(EXIT_FAILURE); + } + + memset(clientfds, -1, sizeof(clientfds)); + atexit(socket_exit); + + if (socket_family == AF_UNIX) + { + tio_printf("Listening on socket %s", socket_filename()); + } + else + { + tio_printf("Listening on socket port %d", port_number); + } +} + +void socket_write(char input_char) +{ + if (!option.socket) + { + return; + } + + for (int i = 0; i != MAX_SOCKET_CLIENTS; ++i) + { + if (clientfds[i] != -1) + { + if (write(clientfds[i], &input_char, 1) <= 0) + { + tio_error_printf_silent("Failed to write to socket (%s)", strerror(errno)); + close(clientfds[i]); + clientfds[i] = -1; + } + } + } +} + +int socket_add_fds(fd_set *rdfs, bool connected) +{ + if (!option.socket) + { + return 0; + } + + int numclients = 0, maxfd = 0; + for (int i = 0; i != MAX_SOCKET_CLIENTS; ++i) + { + if (clientfds[i] != -1) + { + /* let clients block if they try to send while we're disconnected */ + if (connected) + { + FD_SET(clientfds[i], rdfs); + maxfd = MAX(maxfd, clientfds[i]); + } + numclients++; + } + } + /* don't bother to accept clients if we're already full */ + if (numclients != MAX_SOCKET_CLIENTS) + { + FD_SET(sockfd, rdfs); + maxfd = MAX(maxfd, sockfd); + } + return maxfd; +} + +bool socket_handle_input(fd_set *rdfs, char *output_char) +{ + if (!option.socket) + { + return false; + } + + if (FD_ISSET(sockfd, rdfs)) + { + int clientfd = accept(sockfd, NULL, NULL); + /* this loop should always succeed because we don't select on sockfd when full */ + for (int i = 0; i != MAX_SOCKET_CLIENTS; ++i) + { + if (clientfds[i] == -1) + { + clientfds[i] = clientfd; + break; + } + } + } + for (int i = 0; i != MAX_SOCKET_CLIENTS; ++i) + { + if (clientfds[i] != -1 && FD_ISSET(clientfds[i], rdfs)) + { + int status = read(clientfds[i], output_char, 1); + if (status == 0) + { + close(clientfds[i]); + clientfds[i] = -1; + continue; + } + if (status < 0) + { + tio_error_printf_silent("Failed to read from socket (%s)", strerror(errno)); + close(clientfds[i]); + clientfds[i] = -1; + continue; + } + /* match the behavior of a terminal in raw mode */ + if (*output_char == '\n') + { + *output_char = '\r'; + } + return true; + } + } + return false; +} diff --git a/src/socket.h b/src/socket.h new file mode 100644 index 0000000..2caffaf --- /dev/null +++ b/src/socket.h @@ -0,0 +1,31 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * Copyright (c) 2022 Google LLC + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +#include +#include + +void socket_configure(void); +void socket_write(char input_char); +int socket_add_fds(fd_set *fds, bool connected); +bool socket_handle_input(fd_set *fds, char *output_char); diff --git a/src/timestamp.c b/src/timestamp.c new file mode 100644 index 0000000..b8a2198 --- /dev/null +++ b/src/timestamp.c @@ -0,0 +1,152 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include "error.h" +#include "print.h" +#include "options.h" +#include "timestamp.h" + +#define TIME_STRING_SIZE_MAX 24 + +char *timestamp_current_time(void) +{ + static char time_string[TIME_STRING_SIZE_MAX]; + static struct timeval tv, tv_now, tv_start, tv_previous; + static bool first = true; + struct tm *tm; + size_t len; + + // Get current time value + gettimeofday(&tv_now, NULL); + + if (first) + { + tv_start = tv_now; + first = false; + } + + // Add formatted timestap + switch (option.timestamp) + { + case TIMESTAMP_NONE: + case TIMESTAMP_24HOUR: + // "hh:mm:ss.sss" (24 hour format) + tv = tv_now; + tm = localtime(&tv.tv_sec); + len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm); + break; + case TIMESTAMP_24HOUR_START: + // "hh:mm:ss.sss" (24 hour format relative to start time) + timersub(&tv_now, &tv_start, &tv); + tm = gmtime(&tv.tv_sec); + len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm); + break; + case TIMESTAMP_24HOUR_DELTA: + // "hh:mm:ss.sss" (24 hour format relative to previous time stamp) + timersub(&tv_now, &tv_previous, &tv); + tm = gmtime(&tv.tv_sec); + len = strftime(time_string, sizeof(time_string), "%H:%M:%S", tm); + break; + case TIMESTAMP_ISO8601: + // "YYYY-MM-DDThh:mm:ss.sss" (ISO-8601) + tv = tv_now; + tm = localtime(&tv.tv_sec); + len = strftime(time_string, sizeof(time_string), "%Y-%m-%dT%H:%M:%S", tm); + break; + default: + return NULL; + } + + // Append milliseconds to all timestamps + if (len) + { + len = snprintf(time_string + len, TIME_STRING_SIZE_MAX - len, ".%03ld", (long)tv.tv_usec / 1000); + } + + // Save previous time value for next run + tv_previous = tv_now; + + return (len < TIME_STRING_SIZE_MAX) ? time_string : NULL; +} + +const char* timestamp_state_to_string(enum timestamp_t timestamp) +{ + switch (timestamp) + { + case TIMESTAMP_NONE: + return "disabled"; + break; + + case TIMESTAMP_24HOUR: + return "24hour"; + break; + + case TIMESTAMP_24HOUR_START: + return "24hour-start"; + break; + + case TIMESTAMP_24HOUR_DELTA: + return "24hour-delta"; + break; + + case TIMESTAMP_ISO8601: + return "iso8601"; + break; + + default: + return "unknown"; + break; + } +} + +enum timestamp_t timestamp_option_parse(const char *arg) +{ + enum timestamp_t timestamp = TIMESTAMP_24HOUR; // Default + + if (arg != NULL) + { + if (strcmp(arg, "24hour") == 0) + { + return TIMESTAMP_24HOUR; + } + else if (strcmp(arg, "24hour-start") == 0) + { + return TIMESTAMP_24HOUR_START; + } + else if (strcmp(arg, "24hour-delta") == 0) + { + return TIMESTAMP_24HOUR_DELTA; + } + else if (strcmp(arg, "iso8601") == 0) + { + return TIMESTAMP_ISO8601; + } + } + + return timestamp; +} diff --git a/src/timestamp.h b/src/timestamp.h new file mode 100644 index 0000000..ee23ce6 --- /dev/null +++ b/src/timestamp.h @@ -0,0 +1,36 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +enum timestamp_t +{ + TIMESTAMP_NONE, + TIMESTAMP_24HOUR, + TIMESTAMP_24HOUR_START, + TIMESTAMP_24HOUR_DELTA, + TIMESTAMP_ISO8601, + TIMESTAMP_END, +}; + +char *timestamp_current_time(void); +const char* timestamp_state_to_string(enum timestamp_t timestamp); +enum timestamp_t timestamp_option_parse(const char *arg); diff --git a/src/tty.c b/src/tty.c new file mode 100644 index 0000000..f5ffc35 --- /dev/null +++ b/src/tty.c @@ -0,0 +1,1541 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "config.h" +#include "configfile.h" +#include "tty.h" +#include "print.h" +#include "options.h" +#include "misc.h" +#include "log.h" +#include "error.h" +#include "socket.h" +#include "setspeed.h" +#include "rs485.h" +#include "alert.h" +#include "timestamp.h" +#include "misc.h" + +#if defined(__APPLE__) +#define PATH_SERIAL_DEVICES "/dev/" +#define PREFIX_TTY_DEVICES "tty." +#elif defined(__CYGWIN__) +#define PATH_SERIAL_DEVICES "/dev/" +#define PREFIX_TTY_DEVICES "ttyS" +#else +#define PATH_SERIAL_DEVICES "/dev/serial/by-id/" +#define PREFIX_TTY_DEVICES "" +#endif + +#ifndef CMSPAR +#define CMSPAR 010000000000 +#endif + +#define KEY_0 0x30 +#define KEY_1 0x31 +#define KEY_2 0x32 +#define KEY_3 0x33 +#define KEY_4 0x34 +#define KEY_5 0x35 +#define KEY_QUESTION 0x3f +#define KEY_B 0x62 +#define KEY_C 0x63 +#define KEY_E 0x65 +#define KEY_F 0x66 +#define KEY_SHIFT_F 0x46 +#define KEY_G 0x67 +#define KEY_H 0x68 +#define KEY_L 0x6C +#define KEY_SHIFT_L 0x4C +#define KEY_M 0x6D +#define KEY_P 0x70 +#define KEY_Q 0x71 +#define KEY_S 0x73 +#define KEY_T 0x74 +#define KEY_U 0x55 +#define KEY_V 0x76 +#define KEY_Z 0x7a + +enum line_mode_t +{ + LINE_OFF, + LINE_TOGGLE, + LINE_PULSE +}; + +const char random_array[] = +{ +0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x20, 0x28, 0x0A, 0x20, +0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x29, 0x20, 0x29, 0x0A, 0x20, +0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, 0x2E, +0x2E, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7C, 0x20, 0x20, 0x20, +0x20, 0x20, 0x20, 0x7C, 0x5D, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, +0x5C, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2F, 0x0A, 0x20, 0x20, 0x20, 0x20, +0x20, 0x20, 0x20, 0x20, 0x60, 0x2D, 0x2D, 0x2D, 0x2D, 0x27, 0x0A, 0x0A, 0x54, +0x69, 0x6D, 0x65, 0x20, 0x66, 0x6F, 0x72, 0x20, 0x61, 0x20, 0x63, 0x6F, 0x66, +0x66, 0x65, 0x65, 0x20, 0x62, 0x72, 0x65, 0x61, 0x6B, 0x21, 0x0A, 0x20, 0x0A, +0x00 +}; + +bool interactive_mode = true; + +static struct termios tio, tio_old, stdout_new, stdout_old, stdin_new, stdin_old; +static unsigned long rx_total = 0, tx_total = 0; +static bool connected = false; +static bool standard_baudrate = true; +static void (*print)(char c); +static int fd; +static bool map_i_nl_crnl = false; +static bool map_o_cr_nl = false; +static bool map_o_nl_crnl = false; +static bool map_o_del_bs = false; +static bool map_o_ltu = false; +static bool map_o_msblsb = false; +static char hex_chars[2]; +static unsigned char hex_char_index = 0; +static char tty_buffer[BUFSIZ*2]; +static size_t tty_buffer_count = 0; +static char *tty_buffer_write_ptr = tty_buffer; +static pthread_t thread; +static int pipefd[2]; +static pthread_mutex_t mutex_input_ready = PTHREAD_MUTEX_INITIALIZER; + +static void optional_local_echo(char c) +{ + if (!option.local_echo) + { + return; + } + print(c); + if (option.log) + { + log_putc(c); + } +} + +inline static bool is_valid_hex(char c) +{ + return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); +} + +inline static unsigned char char_to_nibble(char c) +{ + if(c >= '0' && c <= '9') + { + return c - '0'; + } + else if (c >= 'a' && c <= 'f') + { + return c - 'a' + 10; + } + else if (c >= 'A' && c <= 'F') + { + return c - 'A' + 10; + } + else + { + return 0; + } +} + +void tty_sync(int fd) +{ + ssize_t count; + + while (tty_buffer_count > 0) + { + count = write(fd, tty_buffer, tty_buffer_count); + if (count < 0) + { + // Error + tio_debug_printf("Write error while flushing tty buffer (%s)", strerror(errno)); + break; + } + tty_buffer_count -= count; + fsync(fd); + tcdrain(fd); + } + + // Reset + tty_buffer_write_ptr = tty_buffer; + tty_buffer_count = 0; +} + +ssize_t tty_write(int fd, const void *buffer, size_t count) +{ + ssize_t retval = 0, bytes_written = 0; + size_t i; + + if (map_o_ltu) + { + // Convert lower case to upper case + for (i = 0; i BUFSIZ) + { + tty_sync(fd); + } + + // Copy bytes to tty write buffer + memcpy(tty_buffer_write_ptr, buffer, count); + tty_buffer_write_ptr += count; + tty_buffer_count += count; + bytes_written = count; + } + + return bytes_written; +} + +void *tty_stdin_input_thread(void *arg) +{ + UNUSED(arg); + char input_buffer[BUFSIZ]; + ssize_t byte_count; + ssize_t bytes_written; + + // Create FIFO pipe + if (pipe(pipefd) == -1) + { + tio_error_printf("Failed to create pipe"); + exit(EXIT_FAILURE); + } + + // Signal that input pipe is ready + pthread_mutex_unlock(&mutex_input_ready); + + // Input loop for stdin + while (1) + { + /* Input from stdin ready */ + byte_count = read(STDIN_FILENO, input_buffer, BUFSIZ); + if (byte_count < 0) + { + tio_warning_printf("Could not read from stdin (%s)", strerror(errno)); + } + else if (byte_count == 0) + { + // Close write end to signal EOF in read end + close(pipefd[1]); + pthread_exit(0); + } + + if (interactive_mode) + { + static char previous_char = 0; + char input_char; + + // Process quit and flush key command + for (int i = 0; i 0) + { + tio_printf("Waiting %d ms", duration); + delay(duration); + } + toggle_line(line_name, mask, LINE_TOGGLE); + } +} + +void handle_command_sequence(char input_char, char *output_char, bool *forward) +{ + char unused_char; + bool unused_bool; + int state; + static enum line_mode_t line_mode = LINE_OFF; + static char previous_char = 0; + + /* Ignore unused arguments */ + if (output_char == NULL) + { + output_char = &unused_char; + } + + if (forward == NULL) + { + forward = &unused_bool; + } + + if (line_mode) + { + // Handle line toggle number action + *forward = false; + switch (input_char) + { + case KEY_0: + toggle_line("DTR", TIOCM_DTR, line_mode); + break; + case KEY_1: + toggle_line("RTS", TIOCM_RTS, line_mode); + break; + case KEY_2: + toggle_line("CTS", TIOCM_CTS, line_mode); + break; + case KEY_3: + toggle_line("DSR", TIOCM_DSR, line_mode); + break; + case KEY_4: + toggle_line("DCD", TIOCM_CD, line_mode); + break; + case KEY_5: + toggle_line("RI", TIOCM_RI, line_mode); + break; + default: + tio_warning_printf("Invalid line number"); + break; + } + + line_mode = LINE_OFF; + + return; + } + + /* Handle escape key commands */ + if (previous_char == option.prefix_code) + { + /* Do not forward input char to output by default */ + *forward = false; + + /* Handle special double prefix key input case */ + if (input_char == option.prefix_code) + { + /* Forward prefix character to tty */ + *output_char = option.prefix_code; + *forward = true; + previous_char = 0; + return; + } + + switch (input_char) + { + case KEY_QUESTION: + tio_printf("Key commands:"); + tio_printf(" ctrl-%c ? List available key commands", option.prefix_key); + tio_printf(" ctrl-%c b Send break", option.prefix_key); + tio_printf(" ctrl-%c c Show configuration", option.prefix_key); + tio_printf(" ctrl-%c e Toggle local echo mode", option.prefix_key); + tio_printf(" ctrl-%c f Toggle log to file", option.prefix_key); + tio_printf(" ctrl-%c F Flush data I/O buffers", option.prefix_key); + tio_printf(" ctrl-%c g Toggle serial port line", option.prefix_key); + tio_printf(" ctrl-%c h Toggle hexadecimal mode", option.prefix_key); + tio_printf(" ctrl-%c l Clear screen", option.prefix_key); + tio_printf(" ctrl-%c L Show line states", option.prefix_key); + tio_printf(" ctrl-%c m Toggle MSB to LSB bit order", option.prefix_key); + tio_printf(" ctrl-%c p Pulse serial port line", option.prefix_key); + tio_printf(" ctrl-%c q Quit", option.prefix_key); + tio_printf(" ctrl-%c s Show statistics", option.prefix_key); + tio_printf(" ctrl-%c t Toggle line timestamp mode", option.prefix_key); + tio_printf(" ctrl-%c U Toggle conversion to uppercase on output", option.prefix_key); + tio_printf(" ctrl-%c v Show version", option.prefix_key); + tio_printf(" ctrl-%c ctrl-%c Send ctrl-%c character", option.prefix_key, option.prefix_key, option.prefix_key); + break; + + case KEY_SHIFT_L: + if (ioctl(fd, TIOCMGET, &state) < 0) + { + tio_warning_printf("Could not get line state (%s)", strerror(errno)); + break; + } + tio_printf("Line states:"); + tio_printf(" DTR: %s", (state & TIOCM_DTR) ? "HIGH" : "LOW"); + tio_printf(" RTS: %s", (state & TIOCM_RTS) ? "HIGH" : "LOW"); + tio_printf(" CTS: %s", (state & TIOCM_CTS) ? "HIGH" : "LOW"); + tio_printf(" DSR: %s", (state & TIOCM_DSR) ? "HIGH" : "LOW"); + tio_printf(" DCD: %s", (state & TIOCM_CD) ? "HIGH" : "LOW"); + tio_printf(" RI : %s", (state & TIOCM_RI) ? "HIGH" : "LOW"); + break; + + case KEY_F: + if (option.log) + { + log_close(); + option.log = false; + } + else + { + if (log_open(option.log_filename) == 0) + { + option.log = true; + } + } + tio_printf("Switched log to file %s", option.log ? "on" : "off"); + break; + + case KEY_SHIFT_F: + break; + + case KEY_G: + tio_printf("Please enter which serial line number to toggle:"); + tio_printf(" DTR (0)"); + tio_printf(" RTS (1)"); + tio_printf(" CTS (2)"); + tio_printf(" DSR (3)"); + tio_printf(" DCD (4)"); + tio_printf(" RI (5)"); + // Process next input character as part of the line toggle step + line_mode = LINE_TOGGLE; + break; + + case KEY_P: + tio_printf("Please enter which serial line number to pulse:"); + tio_printf(" DTR (0)"); + tio_printf(" RTS (1)"); + tio_printf(" CTS (2)"); + tio_printf(" DSR (3)"); + tio_printf(" DCD (4)"); + tio_printf(" RI (5)"); + // Process next input character as part of the line pulse step + line_mode = LINE_PULSE; + break; + + case KEY_B: + tcsendbreak(fd, 0); + break; + + case KEY_C: + tio_printf("Configuration:"); + options_print(); + config_file_print(); + if (option.rs485) + { + rs485_print_config(); + } + break; + + case KEY_E: + option.local_echo = !option.local_echo; + tio_printf("Switched local echo %s", option.local_echo ? "on" : "off"); + break; + + case KEY_H: + /* Toggle hexadecimal printing mode */ + if (!option.hex_mode) + { + print = print_hex; + option.hex_mode = true; + tio_printf("Switched to hexadecimal mode"); + } + else + { + print = print_normal; + option.hex_mode = false; + tio_printf("Switched to normal mode"); + } + break; + + case KEY_L: + /* Clear screen using ANSI/VT100 escape code */ + printf("\033c"); + break; + + case KEY_M: + /* Toggle bit order */ + if (!map_o_msblsb) + { + map_o_msblsb = true; + tio_printf("Switched to reverse bit order"); + } + else + { + map_o_msblsb = false; + tio_printf("Switched to normal bit order"); + } + break; + + case KEY_Q: + /* Exit upon ctrl-t q sequence */ + exit(EXIT_SUCCESS); + + case KEY_S: + /* Show tx/rx statistics upon ctrl-t s sequence */ + tio_printf("Statistics:"); + tio_printf(" Sent %lu bytes", tx_total); + tio_printf(" Received %lu bytes", rx_total); + break; + + case KEY_T: + option.timestamp += 1; + switch (option.timestamp) + { + case TIMESTAMP_NONE: + break; + case TIMESTAMP_24HOUR: + tio_printf("Switched to 24hour timestamp mode"); + break; + case TIMESTAMP_24HOUR_START: + tio_printf("Switched to 24hour-start timestamp mode"); + break; + case TIMESTAMP_24HOUR_DELTA: + tio_printf("Switched to 24hour-delta timestamp mode"); + break; + case TIMESTAMP_ISO8601: + tio_printf("Switched to iso8601 timestamp mode"); + break; + case TIMESTAMP_END: + option.timestamp = TIMESTAMP_NONE; + tio_printf("Switched timestamp off"); + break; + } + break; + + case KEY_U: + map_o_ltu = !map_o_ltu; + break; + + case KEY_V: + tio_printf("tio v%s", VERSION); + break; + + case KEY_Z: + tio_printf_array(random_array); + break; + + default: + /* Ignore unknown ctrl-t escaped keys */ + break; + } + } + + previous_char = input_char; +} + +void stdin_restore(void) +{ + tcsetattr(STDIN_FILENO, TCSANOW, &stdin_old); +} + +void stdin_configure(void) +{ + int status; + + /* Save current stdin settings */ + if (tcgetattr(STDIN_FILENO, &stdin_old) < 0) + { + tio_error_printf("Saving current stdin settings failed"); + exit(EXIT_FAILURE); + } + + /* Prepare new stdin settings */ + memcpy(&stdin_new, &stdin_old, sizeof(stdin_old)); + + /* Reconfigure stdin (RAW configuration) */ + cfmakeraw(&stdin_new); + + /* Control characters */ + stdin_new.c_cc[VTIME] = 0; /* Inter-character timer unused */ + stdin_new.c_cc[VMIN] = 1; /* Blocking read until 1 character received */ + + /* Activate new stdin settings */ + status = tcsetattr(STDIN_FILENO, TCSANOW, &stdin_new); + if (status == -1) + { + tio_error_printf("Could not apply new stdin settings (%s)", strerror(errno)); + exit(EXIT_FAILURE); + } + + /* Make sure we restore old stdin settings on exit */ + atexit(&stdin_restore); +} + +void stdout_restore(void) +{ + tcsetattr(STDOUT_FILENO, TCSANOW, &stdout_old); +} + +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) + { + tio_error_printf("Saving current stdio settings failed"); + exit(EXIT_FAILURE); + } + + /* Prepare new stdout settings */ + memcpy(&stdout_new, &stdout_old, sizeof(stdout_old)); + + /* Reconfigure stdout (RAW configuration) */ + cfmakeraw(&stdout_new); + + /* Allow ^C / SIGINT (to allow termination when piping to tio) */ + if (!interactive_mode) + { + stdout_new.c_lflag |= ISIG; + } + + /* Control characters */ + stdout_new.c_cc[VTIME] = 0; /* Inter-character timer unused */ + stdout_new.c_cc[VMIN] = 1; /* Blocking read until 1 character received */ + + /* Activate new stdout settings */ + status = tcsetattr(STDOUT_FILENO, TCSANOW, &stdout_new); + if (status == -1) + { + tio_error_printf("Could not apply new stdout settings (%s)", strerror(errno)); + exit(EXIT_FAILURE); + } + + /* At start use normal print function */ + print = print_normal; + + /* Make sure we restore old stdout settings on exit */ + atexit(&stdout_restore); +} + +void tty_configure(void) +{ + bool token_found = true; + char *token = NULL; + char *buffer; + int status; + speed_t baudrate; + + memset(&tio, 0, sizeof(tio)); + + /* Set speed */ + switch (option.baudrate) + { + /* The macro below expands into switch cases autogenerated by meson + * configure. Each switch case verifies and configures the baud + * rate and is of the form: + * + * case $baudrate: baudrate = B$baudrate; break; + * + * Only switch cases for baud rates detected supported by the host + * system are inserted. + * + * To see which baud rates are being probed see meson.build + */ + BAUDRATE_CASES + + default: +#if defined (HAVE_TERMIOS2) || defined (HAVE_IOSSIOSPEED) + standard_baudrate = false; + break; +#else + tio_error_printf("Invalid baud rate"); + exit(EXIT_FAILURE); +#endif + } + + if (standard_baudrate) + { + // Set input speed + status = cfsetispeed(&tio, baudrate); + if (status == -1) + { + tio_error_printf("Could not configure input speed (%s)", strerror(errno)); + exit(EXIT_FAILURE); + } + + // Set output speed + status = cfsetospeed(&tio, baudrate); + if (status == -1) + { + tio_error_printf("Could not configure output speed (%s)", strerror(errno)); + exit(EXIT_FAILURE); + } + } + + /* Set databits */ + tio.c_cflag &= ~CSIZE; + switch (option.databits) + { + case 5: + tio.c_cflag |= CS5; + break; + case 6: + tio.c_cflag |= CS6; + break; + case 7: + tio.c_cflag |= CS7; + break; + case 8: + tio.c_cflag |= CS8; + break; + default: + tio_error_printf("Invalid data bits"); + exit(EXIT_FAILURE); + } + + /* Set flow control */ + if (strcmp("hard", option.flow) == 0) + { + tio.c_cflag |= CRTSCTS; + tio.c_iflag &= ~(IXON | IXOFF | IXANY); + } + else if (strcmp("soft", option.flow) == 0) + { + tio.c_cflag &= ~CRTSCTS; + tio.c_iflag |= IXON | IXOFF; + } + else if (strcmp("none", option.flow) == 0) + { + tio.c_cflag &= ~CRTSCTS; + tio.c_iflag &= ~(IXON | IXOFF | IXANY); + } + else + { + tio_error_printf("Invalid flow control"); + exit(EXIT_FAILURE); + } + + /* Set stopbits */ + switch (option.stopbits) + { + case 1: + tio.c_cflag &= ~CSTOPB; + break; + case 2: + tio.c_cflag |= CSTOPB; + break; + default: + tio_error_printf("Invalid stop bits"); + exit(EXIT_FAILURE); + } + + /* Set parity */ + if (strcmp("odd", option.parity) == 0) + { + tio.c_cflag |= PARENB; + tio.c_cflag |= PARODD; + } + else if (strcmp("even", option.parity) == 0) + { + tio.c_cflag |= PARENB; + tio.c_cflag &= ~PARODD; + } + else if (strcmp("none", option.parity) == 0) + { + tio.c_cflag &= ~PARENB; + } + else if ( strcmp("mark", option.parity) == 0) + { + tio.c_cflag |= PARENB; + tio.c_cflag |= PARODD; + tio.c_cflag |= CMSPAR; + } + else if ( strcmp("space", option.parity) == 0) + { + tio.c_cflag |= PARENB; + tio.c_cflag &= ~PARODD; + tio.c_cflag |= CMSPAR; + } + else + { + tio_error_printf("Invalid parity"); + exit(EXIT_FAILURE); + } + + /* Control, input, output, local modes for tty device */ + tio.c_cflag |= CLOCAL | CREAD; + tio.c_oflag = 0; + tio.c_lflag = 0; + + /* Control characters */ + tio.c_cc[VTIME] = 0; // Inter-character timer unused + tio.c_cc[VMIN] = 1; // Blocking read until 1 character received + + /* Configure any specified input or output mappings */ + buffer = strdup(option.map); + while (token_found == true) + { + if (token == NULL) + { + token = strtok(buffer,","); + } + else + { + token = strtok(NULL, ","); + } + + if (token != NULL) + { + if (strcmp(token,"INLCR") == 0) + { + tio.c_iflag |= INLCR; + } + else if (strcmp(token,"IGNCR") == 0) + { + tio.c_iflag |= IGNCR; + } + else if (strcmp(token,"ICRNL") == 0) + { + tio.c_iflag |= ICRNL; + } + else if (strcmp(token,"OCRNL") == 0) + { + map_o_cr_nl = true; + } + else if (strcmp(token,"ODELBS") == 0) + { + map_o_del_bs = true; + } + else if (strcmp(token,"INLCRNL") == 0) + { + map_i_nl_crnl = true; + } + else if (strcmp(token, "ONLCRNL") == 0) + { + map_o_nl_crnl = true; + } + else if (strcmp(token, "OLTU") == 0) + { + map_o_ltu = true; + } + else if (strcmp(token, "MSB2LSB") == 0) + { + map_o_msblsb = true; + } + else + { + printf("Error: Unknown mapping flag %s\n", token); + exit(EXIT_FAILURE); + } + } + else + { + token_found = false; + } + } + free(buffer); +} + +void tty_wait_for_device(void) +{ + fd_set rdfs; + int status; + int maxfd; + struct timeval tv; + static char input_char; + static bool first = true; + static int last_errno = 0; + + /* Loop until device pops up */ + while (true) + { + if (interactive_mode) + { + /* In interactive mode, while waiting for tty device, we need to + * read from stdin to react on input key commands. */ + if (first) + { + /* Don't wait first time */ + tv.tv_sec = 0; + tv.tv_usec = 1; + first = false; + } + else + { + /* Wait up to 1 second for input */ + tv.tv_sec = 1; + tv.tv_usec = 0; + } + + FD_ZERO(&rdfs); + FD_SET(pipefd[0], &rdfs); + maxfd = MAX(pipefd[0], socket_add_fds(&rdfs, false)); + + /* Block until input becomes available or timeout */ + status = select(maxfd + 1, &rdfs, NULL, NULL, &tv); + if (status > 0) + { + if (FD_ISSET(pipefd[0], &rdfs)) + { + /* Input from stdin ready */ + + /* Read one character */ + status = read(pipefd[0], &input_char, 1); + if (status <= 0) + { + tio_error_printf("Could not read from stdin"); + exit(EXIT_FAILURE); + } + + /* Handle commands */ + handle_command_sequence(input_char, NULL, NULL); + } + socket_handle_input(&rdfs, NULL); + } + else if (status == -1) + { + tio_error_printf("select() failed (%s)", strerror(errno)); + exit(EXIT_FAILURE); + } + } + + /* Test for accessible device file */ + status = access(option.tty_device, R_OK); + if (status == 0) + { + last_errno = 0; + return; + } + else if (last_errno != errno) + { + tio_warning_printf("Could not open tty device (%s)", strerror(errno)); + tio_printf("Waiting for tty device.."); + last_errno = errno; + } + + if (!interactive_mode) + { + /* In non-interactive mode we do not need to handle input key + * commands so we simply sleep 1 second between checking for + * presence of tty device */ + sleep(1); + } + } +} + +void tty_disconnect(void) +{ + if (connected) + { + tio_printf("Disconnected"); + flock(fd, LOCK_UN); + close(fd); + connected = false; + + /* Fire alert action */ + alert_disconnect(); + } +} + +void tty_restore(void) +{ + tcsetattr(fd, TCSANOW, &tio_old); + + if (option.rs485) + { + /* Restore original RS-485 mode */ + rs485_mode_restore(fd); + } + + if (connected) + { + tty_disconnect(); + } +} + +void forward_to_tty(int fd, char output_char) +{ + int status; + + /* Map output character */ + if ((output_char == 127) && (map_o_del_bs)) + { + output_char = '\b'; + } + if ((output_char == '\r') && (map_o_cr_nl)) + { + output_char = '\n'; + } + + /* Map newline character */ + if ((output_char == '\n' || output_char == '\r') && (map_o_nl_crnl)) + { + const char *crlf = "\r\n"; + + optional_local_echo(crlf[0]); + optional_local_echo(crlf[1]); + status = tty_write(fd, crlf, 2); + if (status < 0) + { + tio_warning_printf("Could not write to tty device"); + } + + tx_total += 2; + } + else + { + if (option.hex_mode) + { + output_hex(output_char); + } + else + { + /* Send output to tty device */ + optional_local_echo(output_char); + status = tty_write(fd, &output_char, 1); + if (status < 0) + { + tio_warning_printf("Could not write to tty device"); + } + + /* Update transmit statistics */ + tx_total++; + } + } +} + +int tty_connect(void) +{ + fd_set rdfs; /* Read file descriptor set */ + int maxfd; /* Maximum file descriptor used */ + char input_char, output_char; + char input_buffer[BUFSIZ]; + static bool first = true; + int status; + bool next_timestamp = false; + char* now = NULL; + struct timeval tv; + struct timeval *tv_p = &tv; + bool ignore_stdin = false; + + /* Open tty device */ + fd = open(option.tty_device, O_RDWR | O_NOCTTY | O_NONBLOCK); + if (fd < 0) + { + tio_error_printf_silent("Could not open tty device (%s)", strerror(errno)); + goto error_open; + } + + /* Make sure device is of tty type */ + if (!isatty(fd)) + { + tio_error_printf("Not a tty device"); + exit(EXIT_FAILURE);; + } + + /* Lock device file */ + status = flock(fd, LOCK_EX | LOCK_NB); + if ((status == -1) && (errno == EWOULDBLOCK)) + { + tio_error_printf("Device file is locked by another process"); + exit(EXIT_FAILURE); + } + + /* Flush stale I/O data (if any) */ + tcflush(fd, TCIOFLUSH); + + /* Print connect status */ + tio_printf("Connected"); + connected = true; + print_tainted = false; + + /* Fire alert action */ + alert_connect(); + + if (option.timestamp) + { + next_timestamp = true; + } + + /* Manage print output mode */ + if (option.hex_mode) + { + print = print_hex; + } + else + { + print = print_normal; + } + + /* Save current port settings */ + if (tcgetattr(fd, &tio_old) < 0) + { + tio_error_printf_silent("Could not get port settings (%s)", strerror(errno)); + goto error_tcgetattr; + } + +#ifdef HAVE_IOSSIOSPEED + if (!standard_baudrate) + { + /* OS X wants these fields left alone before setting arbitrary baud rate */ + tio.c_ispeed = tio_old.c_ispeed; + tio.c_ospeed = tio_old.c_ospeed; + } +#endif + + /* Manage RS-485 mode */ + if (option.rs485) + { + rs485_mode_enable(fd); + } + + /* Make sure we restore tty settings on exit */ + if (first) + { + atexit(&tty_restore); + first = false; + } + + /* Activate new port settings */ + status = tcsetattr(fd, TCSANOW, &tio); + if (status == -1) + { + tio_error_printf_silent("Could not apply port settings (%s)", strerror(errno)); + goto error_tcsetattr; + } + + /* Set arbitrary baudrate (only works on supported platforms) */ + if (!standard_baudrate) + { + if (setspeed(fd, option.baudrate) != 0) + { + tio_error_printf_silent("Could not set baudrate speed (%s)", strerror(errno)); + goto error_setspeed; + } + } + + /* Input loop */ + while (true) + { + FD_ZERO(&rdfs); + FD_SET(fd, &rdfs); + if (!ignore_stdin) + { + FD_SET(pipefd[0], &rdfs); + } + maxfd = MAX(fd, pipefd[0]); + maxfd = MAX(maxfd, socket_add_fds(&rdfs, true)); + + /* Manage timeout */ + if ((option.response_wait) && (option.response_timeout != 0)) + { + // Set response timeout + tv_p->tv_sec = 0; + tv_p->tv_usec = option.response_timeout * 1000; + } + else + { + // No timeout + tv_p = NULL; + } + + /* Block until input becomes available */ + status = select(maxfd + 1, &rdfs, NULL, NULL, tv_p); + if (status > 0) + { + bool forward = false; + if (FD_ISSET(fd, &rdfs)) + { + /* Input from tty device ready */ + ssize_t bytes_read = read(fd, input_buffer, BUFSIZ); + if (bytes_read <= 0) + { + /* Error reading - device is likely unplugged */ + tio_error_printf_silent("Could not read from tty device"); + goto error_read; + } + + /* Update receive statistics */ + rx_total += bytes_read; + + /* Process input byte by byte */ + for (int i=0; id_name, ".")) && (strcmp(dir->d_name, ".."))) + { + if (!strncmp(dir->d_name, PREFIX_TTY_DEVICES, sizeof(PREFIX_TTY_DEVICES) - 1)) + { + printf("%s%s\n", PATH_SERIAL_DEVICES, dir->d_name); + } + } + } + closedir(d); + } +} diff --git a/src/tty.h b/src/tty.h new file mode 100644 index 0000000..c4b6797 --- /dev/null +++ b/src/tty.h @@ -0,0 +1,35 @@ +/* + * tio - a simple serial terminal I/O tool + * + * Copyright (c) 2014-2022 Martin Lund + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#pragma once + +#include + +extern bool interactive_mode; + +void stdout_configure(void); +void stdin_configure(void); +void tty_configure(void); +int tty_connect(void); +void tty_wait_for_device(void); +void list_serial_devices(void); +void tty_input_thread_create(void); +void tty_input_thread_wait_ready(void); diff --git a/subprojects/libinih.wrap b/subprojects/libinih.wrap new file mode 100644 index 0000000..8a7447c --- /dev/null +++ b/subprojects/libinih.wrap @@ -0,0 +1,4 @@ +[wrap-git] +directory=libinih +url=https://github.com/benhoyt/inih.git +revision=r56