Advertisement
Guest User

Untitled

a guest
Jun 29th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 13.57 KB | None | 0 0
  1. <?php
  2. /**
  3. RegVar-Script für APCUPSD status text
  4. www.tdressler.net/ipsymcon
  5. V0.9 13.11.2011
  6. */
  7.  #######Begin Config
  8. //IPS Variablen IDs
  9.  $regvars=array(50949 /*[APC HTServer\APC-RegVar HTServer]*/);
  10.  $GLOBALS['parent']=20380 /*[Scripte]*/; //parent ID of master category
  11.  $GLOBALS['catname']='USV-APC'; //master category name
  12.  $GLOBALS['idname']='SERIALNO'; //unique ID parameter
  13.  
  14.  $logfile='apc.log';
  15.  ######End Config
  16. /*
  17. hardcoded NOMPOWER values related to Modelname digit value
  18.                              !!!
  19. first line Smart-UPS 700 ->480W
  20. */
  21.  $nomvals=array(
  22.    700=>480,
  23.     750=>500, //smart ups xxx
  24.     1000=>670,
  25.     1500=>980,
  26.     2200=>1580,
  27.     3000=>2700,
  28.     420=>260, //Smart ups SC xxx
  29.     450=>280,
  30.     620=>390,
  31.     350=>210, //Back UPS CS/ES
  32.     400=>240,
  33.     500=>300,
  34.     550=>330,
  35.     800=>540); //Back UPS RS
  36.  
  37. $GLOBALS['nomvals']=$nomvals;
  38. $vartypes=array(
  39.     'ID'=>array('type'=>3,'profile'=>''),
  40.     'VoltIn'=>array('type'=>1,'profile'=>'Volt'),
  41.     'FreqIn'=>array('type'=>2,'profile'=>'Freq.netz'),
  42.     'VoltOut'=>array('type'=>1,'profile'=>'Volt'),
  43.     'LoadPct'=>array('type'=>1,'profile'=>'~Battery.100'),
  44.     'Charged'=>array('type'=>1,'profile'=>'~Battery.100'),
  45.     'Watt'=>array('type'=>1,'profile'=>'Watt'),
  46.     'NomPower'=>array('type'=>1,'profile'=>'Watt'),
  47.     'TimeLeft'=>array('type'=>2,'profile'=>'Time.min'),
  48.     'LastOn'=>array('type'=>3,'profile'=>'~String'),
  49.     'Model'=>array('type'=>3,'profile'=>'~String'),
  50.     'Name'=>array('type'=>3,'profile'=>'~String'),
  51.     'Status'=>array('type'=>3,'profile'=>'~String'),
  52.    'Temperatur'=>array('type'=>2,'profile'=>'~Temperature'),
  53.    'OnLine'=>array('type'=>0,'profile'=>'~Alert.Reversed')
  54. );
  55. $GLOBALS['vartypes']=$vartypes;
  56. $GLOBALS['varids']=null;
  57.  
  58.  //NonStandard Profiles (needed for Webfront)
  59. check_profile('Time.min',2,null,' min',null,null,null,1);
  60. check_profile('Freq.netz',2,null,' Hz',45,55,1,1);
  61.             //Standard-Regvar Handling
  62.  if ($IPS_SENDER == "RegisterVariable")
  63. {
  64.     $reg=$IPS_INSTANCE;
  65.    // bereits im Puffer der Instanz vorhandene Daten in $data kopieren
  66.     $data  = RegVar_GetBuffer($reg);
  67.     // neu empfangene Daten an $data anhängen
  68.     $data .= $IPS_VALUE;
  69.     RegVar_SetBuffer($reg, $data);
  70. }else{
  71.     foreach($regvars as $reg)
  72.     {
  73.         $in=null;
  74.          $id=IPS_GetParent($reg);
  75.     //Nicht registervariable, also manuell
  76.     //socket öffnen
  77.         CSCK_SetOpen($id,true);
  78.         IPS_ApplyChanges($id);
  79.     //befehl senden
  80.         RegVar_SendText($reg,chr(0).chr(6)."status");
  81.     //warten
  82.         sleep (1);
  83.     //Socket schliessen
  84.         CSCK_SetOpen($id,false);
  85.         IPS_ApplyChanges($id);
  86.     //Rückgabe abholen
  87.         $in  = RegVar_GetBuffer($reg);
  88.     //RegVar bereinigen
  89.         RegVar_SetBuffer($reg, "");
  90.     //Ausgabe in Array wandeln
  91.        $apc=format_data($in);
  92.     //loggen
  93.         logge($logfile,$apc);
  94.     //parsen
  95.        if (isset($apc['SERIALNO'])) {
  96.             parse_apc($apc);
  97.         }else {
  98.            $msg='no valid data';
  99.             if (isset($apc['SERIALNO'])) ':'.$msg.$apc['SERIALNO'];
  100.             ips_logmessage('SERIALNO',$msg);
  101.         }
  102.     }
  103. }
  104. /**
  105. * parses APCUPSD status parameter
  106. * @param array APC parameter
  107. */
  108. function parse_apc($apc) {
  109.  
  110.     $catname=$GLOBALS['catname'];
  111.     $nomvals=$GLOBALS['nomvals'];
  112.     $idname=$GLOBALS['idname'];
  113.     //extract data into array
  114.  
  115.     //Status auswerten
  116.     $vartypes=$GLOBALS['vartypes'];
  117.     $varids=null;
  118.     //define null values as default
  119.     $status=null;
  120.     $model=null;
  121.     $name=null;
  122.     $lv=null;
  123.     $lf=null;
  124.     $ov=null;
  125.     $lpct=null;
  126.     $temp=null;
  127.     $np=null;
  128.     $dev=null;
  129.     $load=null;
  130.     $online=null;
  131.     $lo=null;
  132.     $ch=null;
  133.     //try to update values with real parameter from APC
  134.     if (isset($apc[$idname])){
  135.         $dev=$apc[$idname];
  136.     }else{
  137.        IPS_LOGMessage('APC',"Identifier $idname not found");
  138.        return;
  139.     }
  140.     if (isset($apc['LINEV'])) { list($lv,$rest)=explode(' ',$apc['LINEV'],2);}
  141.     if (isset($apc['LINEFREQ'])) {list($lf,$rest)=explode(' ',$apc['LINEFREQ'],2);}
  142.     if (isset($apc['OUTPUTV'])){ list($ov,$rest)=explode(' ',$apc['OUTPUTV'],2);}
  143.     if (isset($apc['LOADPCT'])){list($lpct,$rest)=explode(' ',$apc['LOADPCT'],2);}
  144.     if (isset($apc['ITEMP'])){list($temp,$rest)=explode(' ',$apc['ITEMP'],2);}
  145.    if (isset($apc['MODEL'])) {$model=$apc['MODEL'];}
  146.    if (isset($apc['STATUS'])) {$status=$apc['STATUS'];}
  147.    if (isset($apc['UPSNAME'])) {$name=$apc['UPSNAME'];}
  148.    if (isset($apc['TIMELEFT'])){ list($tl,$rest)=explode(' ',$apc['TIMELEFT'],2);}
  149.    if (isset($apc['BCHARGE'])){ list($ch,$rest)=explode(' ',$apc['BCHARGE'],2);}
  150.     //retrieve nominal power from APC
  151.     if (isset($apc['NOMPOWER'])) {
  152.                //value is supplied by APC
  153.                 list($np,$rest)=explode(' ',$apc['NOMPOWER'],2);
  154.     }else{
  155.                //try to use hardcoded power table based on digits in model name(ex. SMART UPS 750)
  156.                if (!is_null($model)) {
  157.                     preg_match("/(\d{3,4})/",$model,$result);
  158.                     if (isset($result[0]) && (isset($nomvals[$result[0]]))){
  159.                         $np=$nomvals[$result[0]];
  160.                         //IPS_Logmessage('APC',"$model: NOMPOWER from Model=$np");
  161.                     }
  162.                 }
  163.     }
  164.  
  165.     //format last on battery value, if any
  166.     if (isset($apc['XONBATT'])) {
  167.                 list($date,$time, $rest)=explode(' ',$apc['XONBATT'],4);
  168.                 $lo="$date $time";
  169.     }
  170.     $online=($status=='ONLINE');
  171.     $sensorname=$model;
  172.     if ((is_null($model)) || (is_null($dev))) {
  173.                IPS_Logmessage('APC',"Missing Modelname ($model) od DeviceID($dev)");
  174.     }else{
  175.           $GLOBALS['varids']=null;
  176.          IPS_Logmessage('APC',"Dev:$dev Name: $sensorname");
  177.             get_ips_vars($dev,$vartypes,$catname,$sensorname);
  178.             $varids=$GLOBALS['varids'];
  179.             if (is_null($varids)) {
  180.                //Error, no vars created
  181.             IPS_LogMessage($catname,'No VarIDs!');
  182.             }else{
  183.                 //give $np a pseudo value to fill variable, if not found until now
  184.                if (is_null($np)){ $np=500;}
  185.             //NominalPower defined in IPS has priority over Device Value
  186.                 $np=(isset($varids['NomPower']['val']) &&($varids['NomPower']['val']>0))?$varids['NomPower']['val']:$np;
  187.                 //calculate current power based on nominal power and load percent values if available
  188.                 if ((! is_null($np)) && (! is_null($lpct))) {
  189.                     $load=$np*$lpct/100;
  190.                 }
  191.             //store
  192.                 storevars($varids,'OnLine',$online);
  193.                 storevars($varids,'Status',$status);
  194.                 storevars($varids,'Model',$model);
  195.                 storevars($varids,'Name',$name);
  196.                 storevars($varids,'NomPower',$np);
  197.                 storevars($varids,'LastOn',$lo);
  198.                 storevars($varids,'VoltIn',$lv);
  199.                 storevars($varids,'FreqIn',$lf);
  200.                 storevars($varids,'VoltOut',$ov);
  201.                 storevars($varids,'LoadPct',$lpct);
  202.                 storevars($varids,'Watt',$load);
  203.                 storevars($varids,'TimeLeft',$tl);
  204.                 storevars($varids,'Charged',$ch);
  205.                 storevars($varids,'Temperatur',$temp);
  206.             }
  207.     }
  208. }
  209. /**
  210. * Check if is Varaible available and store value
  211. * deletes variable if value is null, meens parameter not supplied by apc
  212. * recreate variable if value is set, but no variable ID, means value supplied now
  213. * @param array current variable ids in tree
  214. * @param string name of variable
  215. * @param variant value to store
  216. */
  217. function storevars($ids,$name,$val) {
  218.     $vartypes=$GLOBALS['vartypes'];
  219.     $parent=$ids['%parent%']['id'];
  220.     $vid=isset($ids[$name]['id'])?$ids[$name]['id']:null;
  221.     $typ=$vartypes[$name]['type'];
  222.     //IPS_Logmessage('APC',"$vid:$name=$val"); //debug
  223.     if (is_null($val)) {
  224.        if (isset($vid)) {
  225.           if (IPS_VariableExists($vid)) IPS_DeleteVariable($vid);
  226.         }
  227.     }else{
  228.        //check value variable id
  229.         if (is_null($vid)) {
  230.            //not there, recreate
  231.            $vid=createvarfromtypes($name,$parent);
  232.            $pname=IPS_GetName($parent);
  233.            IPS_Logmessage('APC',"$pname: Variable $name not found, recreated as ID $vid");
  234.         }
  235.         //recheck
  236.         if (isset($vid)) {
  237.         switch ($typ) {
  238.               case 2: $val=floatval($val);break;
  239.               case 1:  $val=intval($val); break;
  240.            }
  241.             if (IPS_VariableExists($vid)) SetValue($vid,$val);
  242.         }
  243.     }
  244. }
  245. /**
  246. * creates variables with help of typinfo array by name
  247. * @param string name of variable
  248. * @param integer parent ID of parent object
  249. */
  250. function createvarfromtypes($name,$parent) {
  251.     $vartypes=$GLOBALS['vartypes'];
  252.     $typ=isset($vartypes[$name]['type'])?$vartypes[$name]['type']:null;
  253.    $vid=null;
  254.    if (($name>'')&&($parent>-1) && (!is_null($typ))) {
  255.         $vid=IPS_CreateVariable($typ);
  256.         ips_setname($vid,$name);
  257.         ips_setParent($vid,$parent);
  258.         if (isset($vartypes[$name]['profile'])) {
  259.         $profile=$vartypes[$name]['profile'];
  260.             IPS_SetVariableCustomProfile($vid,$profile);
  261.         }
  262.         $GLOBALS['varids'][$name]['id']=$vid;
  263.         $GLOBALS['varids'][$name]['val']=0;
  264.       ips_logmessage('APC',"Created Var $name: Parent:$parent, Type:$typ, ID:$vid");
  265.    }else{
  266.       ips_logmessage('APC',"Missing Values for create Var $name: Parent:$parent, Type:$typ");
  267.     }
  268.     return $vid;
  269. }
  270. /**
  271. * IPS Variablen handler
  272. * creates variables as needed
  273. * returns assoc. Array with IPS Variable ID and Value
  274. * @param integer Sensor Address
  275. * @param array Array with Variable Names, Types and Profiles
  276. * @param string Sensor Group Master Categorie Name
  277. * @param string Sensor default name, will be extended with $addr
  278. */
  279. function get_ips_vars($addr,$vartypes,$cat,$sens) {
  280.     $varids=null;
  281.     $parent=(isset($GLOBALS['parent']) && IPS_ObjectExists($GLOBALS['parent']))?$GLOBALS['parent']:0;
  282.     //master category
  283.      $master=@IPS_GetObjectIDByName($cat,$parent);
  284.     //no master cat, create new
  285.      if (!$master) {
  286.     $master=IPS_CreateCategory();
  287.     IPS_SetName($master,$cat);
  288.     IPS_SetParent($master,$parent);
  289.         if ($master>0) {
  290.         IPS_LogMessage('APC', "Master category created, ID=$master\n");
  291.     }else{
  292.             IPS_LogMessage('APC', "Can't create Master Category\n");
  293.             return null;
  294.         }
  295.     }
  296.     //check childrens for varable with name "ID"
  297.   $id=0;
  298.   if ($master>0) {
  299.   //get chilren sensors
  300.    $Sensors=IPS_GetChildrenIDs($master);
  301.    foreach($Sensors as $sid) {
  302.     $name=IPS_GetName($sid);
  303.       //print "$sid:".$name."\n"; //debug
  304.         //get vars for each sensor
  305.         $vars=IPS_GetChildrenIDs($sid);
  306.       foreach($vars as $vid) {
  307.        $obj=IPS_GetObject($vid);
  308.          $vname=$obj['ObjectName'];
  309.          $typ=$obj['ObjectType'];
  310.           //Variable
  311.           if ($typ==2) { //Variable
  312.             //if ID, here is the address
  313.             if ($vname=="ID") {
  314.                 $i=GetValue($vid);
  315.                 //go out if matches, $id returns the sensor categorie id
  316.                 if ($i===$addr) {
  317.                 $id=$sid;
  318.                 break;
  319.                 }
  320.             }
  321.          }
  322.       }
  323.       if ($id>0) break;
  324.    }
  325.    //if variable ID doesnt exists assume we have to create all
  326.     if ($id==0) {
  327.         //Sensor with address $addr not found in IPS, create new sensor
  328.        $id=ips_createCategory();
  329.        ips_setName($id,$sens);
  330.        ips_setParent($id,$master);
  331.         //creates all needed variables for the new sensor
  332.         foreach (array_keys($vartypes) as $name) {
  333.            $vid=createvarfromtypes($name,$id);
  334.          //preload variables
  335.             SetValue($vid,0);
  336.             $varids[$name]['id']=$vid;
  337.         $varids[$name]['val']=0;
  338.             //Store address in $ID for next time
  339.          if ($name=='ID') {
  340.              SetValue($vid,$addr);
  341.           $varids[$name]['val']=$addr;
  342.             }
  343.         }
  344.     }else{
  345.        //found matching cat, collect ids and vals for this sensor
  346.        $vars=IPS_GetChildrenIDs($id);
  347.       foreach($vars as $vid) {
  348.          $obj=IPS_GetObject($vid);
  349.          $name=$obj['ObjectName'];
  350.          $typ=$obj['ObjectType'];
  351.          if ($typ==2) { //Variable
  352.             $val=GetValue($vid);
  353.             $varids[$name]['id']=$vid;
  354.             $varids[$name]['val']=$val;
  355.          }
  356.       }
  357.     }
  358.     //store parent
  359.     $varids['%parent%']['id']=$id;
  360.     $GLOBALS['varids']=$varids;
  361.     //returns IDs and Values of this Sensor, Name is Key
  362.     return $varids;
  363.  }
  364. }
  365. /**
  366. *
  367. * @param string $text output from apcupsd
  368. * @return array $apc Array Key/Values
  369. */
  370. function format_data($text){
  371.     $entry=explode("\n",$text); //Satztrenner
  372.         $apc=array();
  373.         foreach($entry as $line) {
  374.            if (! $line || strlen($line)<2) continue;
  375.             $p1=ord($line[0]); //immer 00
  376.             $p2=ord($line[1]); //Kennziffer
  377.             if ($p2>0) {
  378.                     $content=substr($line,2);
  379.                     //Key /Value Paare durch ':' getrennt
  380.                     if (strpos($content,":")>0) {
  381.                         list($key,$value)=explode(":",$content,2);
  382.                         $apc[trim($key)]=trim($value);
  383.                     }
  384.             }
  385.         }
  386.         return $apc;
  387. }
  388. //#############################
  389. /**
  390. * do simple logging
  391. * @param string $logfile Filename for logfile
  392. * @param string $text
  393. * @returns void
  394. */
  395.  
  396. function logge($logfile,$apc) {
  397.     if (strlen($logfile)>0) {
  398.         $log=fopen($logfile,"a+");
  399.         if ($log) {
  400.         $d=date("r");
  401.         fwrite($log,"#----$d\r\n");
  402.           foreach ($apc as $key=>$value) {
  403.             fwrite($log, "$key:$value\r\n");
  404.          }
  405.             fflush($log);
  406.             fclose($log);
  407.         }
  408.     }
  409. }
  410. /**
  411. * Get ID by name if exists, else create
  412. * @Param String Name
  413. * @param integer Parent-ID
  414. * @param integer Variable Typ (0..3)
  415. * @return integer ID
  416. */
  417. function getVid($name,$par,$typ) {
  418.     $vid = @IPS_GetVariableIDByName($name, $par);
  419.     if ($vid === false) {
  420.         $vid=IPS_CreateVariable($typ);
  421.         ips_setname($vid,$name);
  422.         ips_setParent($vid,$par);
  423.         setValue($vid,'');
  424.     }
  425.     return $vid;
  426. }
  427. /**
  428. * Check profile by name if exists, else create
  429. * @Param String Name
  430. * @param integer Variable Typ (0..3)
  431. * @param String prefix befor value
  432. * @param String suffix after value
  433. * @param integer min value
  434. * @param integer max value
  435. * @param integer step value
  436. * @param integer digits for formatting
  437. */
  438.  
  439. function check_profile($pname,$typ,$prefix,$suffix,$min,$max,$step,$digit=0) {
  440. if (!IPS_VariableProfileExists($pname)) {
  441.     if (IPS_CreateVariableProfile($pname,$typ)) {
  442.        IPS_SetVariableProfileText($pname,$prefix,$suffix);
  443.         if (isset($min) && isset($max) && isset($step)) {
  444.         IPS_SetVariableProfileValues($pname,$min,$max,$step);
  445.        }
  446.         if (isset($digit)) {
  447.         IPS_SetVariableProfileDigits($pname,$digit);
  448.        }
  449.     }
  450. }
  451. }
  452. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement