Skip to content

Instantly share code, notes, and snippets.

@jaggzh
Created November 22, 2023 15:51
Show Gist options
  • Save jaggzh/218c2640f87a414854d262a5e127ed95 to your computer and use it in GitHub Desktop.
Save jaggzh/218c2640f87a414854d262a5e127ed95 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
# gist url:
# gist-paste -u https://gist.github.com/jaggzh/218c2640f87a414854d262a5e127ed95
use strict;
use warnings;
use Device::SerialPort;
use Getopt::Std;
use Time::HiRes qw(time sleep);
# Parse command-line options
my %opts;
getopts("t:b:", \%opts);
my $timeout = $opts{t} // 1.5;
my $baudrate = $opts{b} // 115200;
# Check if the serial port is provided
if (@ARGV < 1) {
die "Usage: echo something | send-to-serial [-t timeout_in_seconds] [-b baudrate] /dev/ttyUSB0\n";
}
my $port = $ARGV[0];
# Configure the serial port
my $serial = Device::SerialPort->new($port) || die "Could not open serial port: $!";
$serial->baudrate($baudrate);
$serial->databits(8);
$serial->parity("none");
$serial->stopbits(1);
$serial->write_settings;
# Function to read until there's a delay in the output
sub read_until_delay {
my ($serial, $max_wait, $delay_threshold) = @_;
my $response = "";
my $end_time = time + $max_wait;
my $last_read_time = time;
while (time < $end_time) {
my ($count, $data) = $serial->read(255);
my $current_time = time;
if ($count > 0) {
print STDERR "Read $count bytes at $current_time\n"; # Debugging info
$response .= $data;
$last_read_time = $current_time;
} elsif ($current_time - $last_read_time > $delay_threshold) {
print STDERR "Exiting loop due to delay threshold at $current_time\n"; # Debugging info
last;
}
sleep 0.01;
}
return $response;
}
# Send a blank line to trigger initialization
$serial->write("\n");
# Read the initialization message
print read_until_delay($serial, 5, 2.5);
# Read from stdin
my $input = do { local $/; <STDIN> };
# Send the actual command
$serial->write($input);
# Read the response
print read_until_delay($serial, $timeout, 2.5);
# Close the serial port
undef $serial;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment