bash 发送modem AT命令和解析结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29852742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending modem AT command and parsing result
提问by ogs
I would like to send AT
command to my modem by using shell script and parse the result in order to verify if the OK is returned.
我想AT
使用 shell 脚本向我的调制解调器发送命令并解析结果以验证是否返回 OK。
at=`echo -ne "AT+CFUN1=1\r\n" > /dev/ttyUSB0 | cat /dev/ttyUSB0`
What is the best way to parse the at1 variable and extract "OK" or "ERROR" otherwise ?
解析 at1 变量并以其他方式提取“OK”或“ERROR”的最佳方法是什么?
回答by hlovdal
It is absolutely possible to send AT commands to a modem and capture its output from the command line like you are trying to do, however notby just using plain bash shell scripting. Which is why I wrote the program atinoutspecifically to support scenarios like you ask about.
绝对有可能将 AT 命令发送到调制解调器并像您尝试的那样从命令行捕获其输出,但不能仅使用普通的 bash shell 脚本。这就是为什么我专门编写了atinout程序来支持您所询问的场景。
Test like the following:
测试如下:
MODEM_DEVICE=/dev/ttyUSB0
MODEM_OUTPUT=`echo AT | atinout - $MODEM_DEVICE -`
case $MODEM_OUTPUT
in
*OK*)
echo "Hurray, modem is up and running :)"
;;
*)
echo "Oh no! Something is not working :("
;;
esac
If you intend to parse the output in any more sophisticated way you should save the output to a file instead by giving a filename instead of the last -
and read that.
如果您打算以任何更复杂的方式解析输出,您应该将输出保存到一个文件中,而不是通过提供文件名而不是最后一个-
并读取该文件名。
回答by Robin Dinse
I was unable to communicate with my Huawei E3372h-158 with @hlovdal's solution, so I rolled my own using expect
and screen
, in this case for reading the temperature sensors via ^CHIPTEMP?
:
我无法使用@hlovdal 的解决方案与我的华为 E3372h-158 通信,所以我自己使用expect
and screen
,在这种情况下通过以下方式读取温度传感器^CHIPTEMP?
:
output=$(sudo expect <<EOF
set timeout 5
log_user 0 spawn sudo screen /dev/ttyUSB0-
sleep 1
send "AT\x5ECHIPTEMP?\r"
expect "OK"
puts "\n-->$expect_out(buffer)<--"
# Send C-a \ to end the session
send "\x01"
send "\x5C"
EOF
)
# Strip non-printable control characters
output=$(printf "$output" | tr -dc '[:print:]\n' )
printf "$output\n" | grep -P "^\^CHIPTEMP"
Hints and caveats: Set log_user 1
to get the output of screen
. Not sure screen
works in all cases as it produces some non-printing characters and perhaps repeating output.
提示和警告:设置log_user 1
为获取screen
. 不确定screen
在所有情况下都有效,因为它会产生一些非打印字符并且可能会重复输出。