SATS/lib/global-state/source/set.php

103 lines
2.1 KiB
PHP
Raw Permalink Normal View History

#!/usr/bin/php
<?php
require_once __DIR__.'/../../include/php/const';
function globalstate_set($p_id_chip, $p_state){
$g_pins = null;
$g_state = null;
/* [1] Cache chips
=========================================================*/
/* (1) Get file handler */
$f_chips = new SplFileObject(CHIPS_CONF, 'r');
/* (2) Parse line by line */
while( !$f_chips->eof() ){
// {1} Try to parse current line //
$parsed = json_decode($f_chips->fgets(), true);
// {2} If cannot parse, go to next //
if( is_null($parsed) )
continue;
// {3} Check if choosen pin //
if( $parsed[0] == $p_id_chip ){
// store pin list
$g_pins = $parsed[1];
/* (3) Check if choosen state */
foreach($parsed[2] as $state=>$pinValues){
if( "$state" === "$p_state" ){
// store state values
$g_state = $pinValues;
break;
}
}
break;
}
}
/* (3) If chip not found -> abort */
if( is_null($g_pins) || is_null($g_state) ){
slog("Chip $p_id_chip not found", 'global-state:set');
return 127;
}
/* [2] Set chip to choosen state
=========================================================*/
/* (1) Activate pin + set OUT mode */
foreach($g_pins as $pinNumber)
2017-02-20 21:17:48 +00:00
// if failed -> propagate error
if( syscall(SOURCE_DIR."/lib/gpio/out {$pinNumber}") == false ){
slog("Chip $p_id_chip cannot be set to OUT mode", 'global-state:set');
return 127;
}
/* (2) For each pin, set the associated value */
foreach($g_state as $pinIndex=>$pinValue){
// set value to HIGH if not 0 //
if( $pinValue !== 0 )
syscall(SOURCE_DIR."/lib/gpio/high ".$g_pins[$pinIndex]);
else
syscall(SOURCE_DIR."/lib/gpio/low ".$g_pins[$pinIndex]);
}
return 0;
}
/* [1] Check argument (chip position, chip state)
=========================================================*/
if( $argc < 3 || !preg_match('@^\d+$@', $argv[1]) || !preg_match('@^[A-Za-z0-9]{1}$@', $argv[2]) ){
echo 127;
die(127);
}
/* [2] Launch main script
=========================================================*/
$exec = globalstate_set($argv[1], $argv[2]);
echo $exec;
die($exec);
?>