Does someone can helpme to configure openhab so I can “tail” a text file and grep a special pattern to update a state of the item. For exemple, my alarm generates a text file and I a have a section that is “chime : true” and I would like to update the CHIME item to ON and if I grep “chime : false” and I would like to update the CHIME item to OFF.
Can it be done…
#!/bin/php
<?php
function sendCommand($item, $data) {
$url = "http://localhost:8080/rest/items/" . $item;
$options = array( 'http' => array(
'header' => "Content-type: text/plain\r\n",
'method' => 'POST',
'content' => $data));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
$file = "/tmp/logfile.log"; // put the file to be monitored here
$handle = popen("tail -f ".$file." 2>&1", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
if (strpos($buffer,"chime : true") !== false)
sendCommand("CHIME","ON");
if (strpos($buffer,"chime : false") !== false)
sendCommand("CHIME","OFF");
flush();
}
pclose($handle);
?>
Speaking of tail I assumed you have linux-like system.
This PHP script invokes tail -f on a file provided in $file, reads from it’s output and checks for chime : true or chime : false in lines added/appended to the $file. You can run in in the background and monitor $file as it grows.
Data is posted to openHAB via REST api, assuming openHAB is accesible at localhost port 8080.
This PHP script was tested on PHP 5.4.16 on CentOS 7. To keep it as simple as possible there are no checks for errors, I assumed the file exists an is readible, openHAB is accessible and there is a switch item CHIME.
Please let me know if it worked for you.
Since i’m not a php expert I do need your help to improve it for my special
need. Can i add also a search for a special string and find the next word
into a variable that i can push it to openhab. The string is : ,ALARM 02
FRONT DOOR and i need to capture 02 to push it into openhab item
memory_zone
I am not sure if I undersood what you want to achieve. An item memory_zone should be set to what? 02?
if (strpos($buffer,",ALARM 02 FRONT DOOR") !== false)
sendCommand("memory_zone","02");
A value that appear after ,ALARM?
if (($pos = strpos($buffer,",ALARM")) !== false) {
$a = explode(" ", substr($buffer, $pos)); // Split buffer from position of ,Alarm
// dividing with space
if (count($a) >= 2) // Are there more than two words?
sendCommand("memory_zone",$a[1]); // If so, post the second one
}
Please note that the above code is just a sketch, I have not tested it.