<?php

/**
 * Ok, this is a probably an ugly prototype of the processing daemon for this project, 
 * but it kinda works pretty okay-ish. 
 *
 * Because I get about 5-15 events for a single pulse, I have do to some hacking to count
 * it as a single pulse. I now trigger when the value has been above 200 and below 10. 
 * These values will vary a bit from LED to LED, but they work fine for me.
 *
 * Hopefully this is simple enough, even for non-php people. The idea is pretty simple.
 *
 * Harald Nesland <hn@nesland.net>
 */

$socket socket_create(AF_INETSOCK_DGRAMSOL_UDP);
socket_bind$socket"192.168.5.100"9696);

function 
getcount() {
    return 
trim(file_get_contents("sikringsskap_maaler.txt"));
}

function 
setcount($var) {
    
file_put_contents("sikringsskap_maaler.txt"$var);
}

function 
getcountA() {
    return 
trim(file_get_contents("sikringsskap_maaler_self.txt"));
}

function 
setcountA($var) {
    
file_put_contents("sikringsskap_maaler_self.txt"$var);
}

$buff='';
$name='asd';
$port=9696;

$thismtime microtime(true);
$oldmtime $thismtime;

$a=0;
while(
true) {
   
// Waits for a value from the Nokia 770-application. The value contains the LUX received
   // from the sensor.
    
socket_recvfrom$socket $buff10000$name$port);

   
// This value might need tweaking, depending on your LED etc.
    
if( 200 < (int)$buff ) {
        
$levelReached true;
    }

    if( 
$levelReached && $buff 10 ) {

        
$levelReached false;

        
$thismtime microtime(true);
        
$deltatime $thismtime $oldmtime;
        
$oldmtime $thismtime;

        
$cnt getcount();
        
$_cnt getcountA();
        
$_cnt += 1;

      
// 1000 pulses is 1 kWh, increment hour kWh counter.
        
if( $_cnt == 1000 ) { $cnt += 1$_cnt 1; }

        
setcountA($_cnt);
        
setcount($cnt);

      
// Watt-hours between this pulse and last pulse.
        
$currentWatt = (60/$deltatime) * 60;
        
      
// Increase this if you want an average of more than 10 pulses
        
if( $a 10 ) {
            
$a=0;
        }
        
        
$currentWatts[$a] = $currentWatt;
        
$a++;

        
file_put_contents("sikringsskap_currentwatt.txt"round($avgWatt,2) );
        
        
$avgWatt array_sum($currentWatts) / count($currentWatts);
        
        echo 
date("H:i:s") . ": [$cnt] [$_cnt] " . (60/$deltatime) . " pulses/min ($currentWatt Wh / $avgWatt avg Wh)\n";

        
$lastsec $thissec;
        
$lastmin $thismin;

    } 
    
    
$lastbuff $buff;
}