我有一个名为rtl_433的程序,它输出JSON的行--可能每分钟输出一到两次,而它正在运行。我需要将这些数据作为HTTP POST数据传输到curl。
更复杂的是,这个字符串需要封装在单引号中,而不是单引号,所以我需要在将它发送到curl之前添加它。
现在,事情是这样的:这个很好:
echo '{"qwer":98}' | curl -vvv -u pi:<password> http://data:1880/rtl433 -H "Content-Type: application/json" -d @-这将接受JSON字符串'{"qwer":98}'并将其发送到服务器(Node-RED),并在那里接收到它。现在,不幸的是,我不得不自己添加那些单引号,所以我找到了一个sed命令,它就是这样做的,我使用ping运行了一个测试。
$ ping 8.8.8.8 | sed -e "s/.*/'&'/"
'PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.'
'64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=18.8 ms'
'64 bytes from 8.8.8.8: icmp_seq=2 ttl=59 time=19.1 ms'
'64 bytes from 8.8.8.8: icmp_seq=3 ttl=59 time=20.4 ms'
'64 bytes from 8.8.8.8: icmp_seq=4 ttl=59 time=18.9 ms'
^C太棒了!这正是我所需要的--现在我需要在rtl_433的输出上使用sed
$ rtl_433 -M level -F json | sed -e "s/.*/'&'/"
rtl_433 version unknown inputs file rtl_tcp RTL-SDR SoapySDR
Use -h for usage help and see https://triq.org/ for documentation.
Trying conf file at "rtl_433.conf"...
Trying conf file at "/home/pi/.config/rtl_433/rtl_433.conf"...
Trying conf file at "/usr/local/etc/rtl_433/rtl_433.conf"...
Trying conf file at "/etc/rtl_433/rtl_433.conf"...
Registered 145 out of 175 device decoding protocols [ 1-4 8 11-12 15-17 19-21 23 25-26 29-36 38-60 63 67-71 73-100 102-105 108-116 119 121 124-128 130-149 151-161 163-168 170-175 ]
Detached kernel driver
Found Rafael Micro R820T tuner
Exact sample rate is: 250000.000414 Hz
[R82XX] PLL not locked!
Sample rate set to 250000 S/s.
Tuner gain set to Auto.
Tuned to 433.920MHz.
Allocating 15 zero-copy buffers
'{"time" : "2022-02-16 09:15:40", "model" : "AlectoV1-Rain", "id" : 130, "channel" : 0, "battery_ok" : 1, "rain_mm" : 273.500, "mic" : "CHECKSUM", "mod" : "ASK", "freq" : 433.911, "rssi" : -1.516, "snr" : 40.628, "noise" : -42.144}'完美!现在我要做的就是把它导入curl
$ rtl_433 -M level -F json | sed -e "s/.*/'&'/" | curl -vvv -u pi:<password> http://data:1880/rtl433 -H "Content-Type: application/json" -d @-然后-什么都没有!什么都没有。rtl_433打印所有最初的内容,然后几分钟内什么也不打印。而Node-RED也没有收到任何消息。
我在这里真是不知所措。每件事都是独立运作的,但当我把它组合在一起时,我什么也得不到。连一条错误信息都没有。我遗漏了什么?
编辑:我看到了将--unbuffered添加到sed命令中的建议,但这并没有改变任何事情。
发布于 2022-02-16 08:42:46
这里的问题是,rtl_433永远不会退出,它只会为接收到的每一条消息保持打印行。
这是一个问题,因为curl要等到收到EOF (文件结束)标记时才知道它什么时候收到了它需要在HTTP请求中发送的所有有效负载,但是它当然永远不会收到这个标记。当rtl_433退出时,EOF将自动添加。
您最好的选择是从一行脚本移动到一个正确的bash命令,每次从rtl_433读取一行,然后在该行上运行sed,然后将其传递给curl。
例如:
#!/bin/bash
rtl_433 -M level -F json | {
while IFS= read -r line
do
echo $line | sed -e "s/.*/'&'/" | curl -vvv -u pi:<password> http://data:1880/rtl433 -H "Content-Type: application/json" -d @-
done
}https://stackoverflow.com/questions/71138400
复制相似问题