我有一個程式,rtl_433它在運行時輸出 JSON 行 - 可能每分鐘一次或兩次。我需要將該資料作為HTTP POST要卷曲的資料進行管道傳輸。
使事情復雜化的是,這個字串需要用單引號封裝,而事實并非如此,所以我需要在將其發送到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
完美的!這正是我所需要的——現在我需要在以下輸出上使用 sed rtl_433:
$ 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命令的建議,但這并沒有改變任何東西。
uj5u.com熱心網友回復:
這里的問題是它rtl_433永遠不會退出,它只是為它收到的每條訊息保留列印行。
這是一個問題,因為curl它會等到它收到一個 EOF(檔案結束)標記才能知道它何時收到了它需要在 HTTP 請求中發送到的所有有效負載,但當然它永遠不會得到這個。rtl_433退出時將自動添加 EOF 。
您最好的選擇可能是從單行腳本轉換為一次從rtl_433一行讀取的正確 bash 命令,然后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://www.uj5u.com/qianduan/427231.html
上一篇:如何在不暴露url中的訪問令牌的情況下從Gitlab下載私有存盤庫?
下一篇:Flask第二個引數回傳null
