从TTY到PHP的AWK管道输出

时间:2021-08-12 03:48:17

I have a tty device (/dev/ttyUSB0), which occasionally outputs a string in the form of Cycle 1: 30662 ms, 117.41 W. I'm using a simple bash script to process it:

我有一个tty设备(/ dev / ttyUSB0),偶尔输出一个循环1:30662 ms,117.41 W形式的字符串。我正在使用一个简单的bash脚本来处理它:

#!/bin/sh
stty -F /dev/ttyUSB0 57600

cd /home/pi
while true; do
 cat /dev/ttyUSB0 | awk '{ print $0 > "/dev/stderr"; if (/^Cycle/) { print "update kWh.rrd N:" $5 } }' | php5 test.php
 sleep 1
done

The test.php script looks like this:

test.php脚本如下所示:

<?php
stream_set_blocking(STDIN, 0);
$line = trim(fgets(STDIN));

$file = 'kwhoutput.txt';
$current = file_get_contents($file);
$current .= $line;
file_put_contents($file, $current);
?>

however, the kwhoutput.txt remains empty. Why is this not working?

但是,kwhoutput.txt仍为空。为什么这不起作用?

1 个解决方案

#1


1  

awk is buffering your data. Use fflush() to flush the buffers after each output line:

awk正在缓冲你的数据。使用fflush()在每个输出行后刷新缓冲区:

awk '{
  print $0 > "/dev/stderr"; 
  if (/^Cycle/) { 
    print "update kWh.rrd N:" $5;
    fflush(); 
  } 
}'  < /dev/ttyUSB0  | php5 test.php

Also make sure that /dev/ttyUSB0 actually outputs a line (terminated by \n), and not just a string of data.

还要确保/ dev / ttyUSB0实际输出一行(以\ n结尾),而不仅仅是一串数据。

You should also fix up your php script to:

您还应该修复您的PHP脚本:

  1. Read multiple lines and append them one by one (otherwise, the script will skip every other line).
  2. 读取多行并逐个追加(否则,脚本将跳过其他所有行)。
  3. Find out how to append to a file in php. Reading the whole file, concatenating a string in memory, then writing the whole file is not the way to go.
  4. 了解如何在php中附加到文件。读取整个文件,在内存中连接一个字符串,然后编写整个文件是不可取的。

#1


1  

awk is buffering your data. Use fflush() to flush the buffers after each output line:

awk正在缓冲你的数据。使用fflush()在每个输出行后刷新缓冲区:

awk '{
  print $0 > "/dev/stderr"; 
  if (/^Cycle/) { 
    print "update kWh.rrd N:" $5;
    fflush(); 
  } 
}'  < /dev/ttyUSB0  | php5 test.php

Also make sure that /dev/ttyUSB0 actually outputs a line (terminated by \n), and not just a string of data.

还要确保/ dev / ttyUSB0实际输出一行(以\ n结尾),而不仅仅是一串数据。

You should also fix up your php script to:

您还应该修复您的PHP脚本:

  1. Read multiple lines and append them one by one (otherwise, the script will skip every other line).
  2. 读取多行并逐个追加(否则,脚本将跳过其他所有行)。
  3. Find out how to append to a file in php. Reading the whole file, concatenating a string in memory, then writing the whole file is not the way to go.
  4. 了解如何在php中附加到文件。读取整个文件,在内存中连接一个字符串,然后编写整个文件是不可取的。