簡體   English   中英

通過 curl 到 sed 的故障管道

[英]Trouble piping to curl through sed

我有一個程序rtl_433 ,它在運行時輸出 JSON 的行 - 可能一分鍾一次或兩次。 我需要將 pipe 數據作為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 的 output 上使用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}'

完美的! 現在我需要做的就是將 pipe 轉換為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命令的建議,但這並沒有改變任何東西。

這里的問題是rtl_433永遠不會退出,它只是為收到的每條消息保留打印行。

這是一個問題,因為curl將等到它收到一個 EOF(文件結尾)標記才能知道它何時收到了它需要在 HTTP 請求中發送到的所有有效載荷,但當然它永遠不會得到這個。 EOF 將在rtl_433退出時自動添加。

你最好的選擇可能是從單行腳本轉移到正確的 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM