#!/usr/bin/php continue watching return false; slog('Motor start', 'motheure-simple:loop', 'motheure'); /* [3] Wait for machine to stop =========================================================*/ /* (0) Userful variables */ $offset = 0; // offset (number of 0 reads) $loop_ts = 0; // loop start time $stop_ts = microtime(true); // last active time for now while( $offset <= $THRESHOLD ){ // exit when motor active for $threshold cycles /* (1) Start loop timer */ $loop_ts = microtime(true); /* (2) If stopped -> increment offset */ if( !motheure_read() ){ $offset++; slog("Motor offset: $offset/$THRESHOLD", 'motheure-simple:loop', 'motheure'); /* (3) If not stopped */ }else{ $offset = 0; $stop_ts = microtime(true); // last active time for now } /* (4) Wait for loop to last @LOOP_FREQ seconds (if not already elapsed) */ while( microtime(true) - $loop_ts < ($LOOP_FREQ/1000) ); } /* [2] Main loop =========================================================*/ /* (1) Log action to default log file */ $f_data->fwrite( "[" . floor( $stop_ts - $start_ts ) ."]\n" ); slog("Motor stop", 'motheure-simple:loop', 'motheure'); /* (2) Return status */ return true; } function motheure_setup(){ /* [0] Initialize global variables =========================================================*/ /* (1) File descriptiors */ global $f_data; /* (3) Useful data */ global $FEATURE; global $MOTOR_PIN; /* [1] Open file descriptors on useful files =========================================================*/ /* (1) Append accesses (logs) */ if( !file_exists(DATA_DIR."/$FEATURE") ) file_put_contents(DATA_DIR."/$FEATURE", ''); $f_data = new SplFileObject(DATA_DIR."/$FEATURE", 'a'); /* [2] Set up GPIO pin =========================================================*/ /* (1) Set all inputs as inputs */ foreach($MOTOR_PIN as $PIN){ if( !syscall(SOURCE_DIR."/lib/gpio/in $PIN") ){ slog("Cannot set up motor pin $PIN as INPUT", 'motheure-simple:setup'); return 127; } } return 0; } /* [1] Set up daemon =========================================================*/ /* (1) Set up */ $exec = motheure_setup(); /* (2) Manage error */ if( $exec != 0 ){ slog('cannot set up the daemon', 'motheure-simple:loop'); die($exec); } /* (3) Success message */ slog('daemon started (loop)', 'motheure-simple:loop'); /* [2] Daemon loop =========================================================*/ while( true ){ /* (1) Store time */ $start_ts = microtime(true); /* (2) Execute loop code */ motheure_loop(); } ?>