I want to be able to send the command "AT+CSQ" to /dev/ttyUSB1 every 5 seconds, and log out response to a text file. I can do it manually via screen (screen /dev/ttyUSB1 and type in AT+CSQ and see the response), but how do I do this as a bash script?
2 Answers
Below is an example script with some logic for logging and cleanup when the script terminates (the trap
command). Important trick is to keep the input from the serial port open otherwise the input from the time the port was closed could get lost.
#!/bin/bash
LOGFILE=/var/tmp/modemlog
MODEM=/dev/ttyUSB1
MODEMCMD=AT+CSQ
INTERVAL=5
LOGDATE="date +%Y%m%dT%H%M%S"
# write command to modem
wrmodem () {
echo -ne "$*"'\r\n' >"$MODEM"
log "--- sent: $*"
}
# log message to a logfile
log () {
echo "$($LOGDATE) $@" >>"$LOGFILE"
}
# logger
{
trap 'log "=== logger stopped $BASHPID"' EXIT
log "=== logger started: $BASHPID"
while true ; do
if read ; then
log "$(tr -d \\r <<<"$REPLY")"
fi
done
} <"$MODEM" &
LOGGERPID=$!
trap 'kill $LOGGERPID' EXIT
# requester
while true ; do
wrmodem "$MODEMCMD"
sleep $INTERVAL
done
The expect
tool is designed for just this sort of task. man expect
will get you started.