简体   繁体   English

从TTY到PHP的AWK管道输出

[英]AWK pipe output from TTY to PHP

I have a tty device (/dev/ttyUSB0), which occasionally outputs a string in the form of Cycle 1: 30662 ms, 117.41 W . 我有一个tty设备(/ dev / ttyUSB0),偶尔会以Cycle 1: 30662 ms, 117.41 W的形式输出一个字符串Cycle 1: 30662 ms, 117.41 W I'm using a simple bash script to process it: 我正在使用一个简单的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. 但是,kwhoutput.txt保持为空。 Why is this not working? 为什么这不起作用?

awk is buffering your data. awk正在缓冲您的数据。 Use fflush() to flush the buffers after each output line: 使用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. Find out how to append to a file in php. 了解如何在php中附加文件。 Reading the whole file, concatenating a string in memory, then writing the whole file is not the way to go. 读取整个文件,在内存中串联一个字符串,然后写入整个文件并不是解决之道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM