<?php

class ConfigRouterOSSignal extends NetworkConfigItem
{
  function ReadWirelessRegistration()
  {
    $Time = time();
    $Queries = array();

    // Load netwatch status from all DHCP routers
    $DbResult3 = $this->Database->query('SELECT `Id`, '.
        '(SELECT `LocalIP` FROM `NetworkInterface` WHERE `NetworkInterface`.`Device` = `NetworkDevice`.`Id` LIMIT 1) AS `LocalIP` '.
        'FROM `NetworkDevice` WHERE (`API` = 1) AND (`Used` = 1)');
    while($Device = $DbResult3->fetch_assoc())
    {
      echo($Device['LocalIP']."\n");
      $Routerboard = new RouterosAPI();
      //$Routerboard->SSL = true;
      //$Routerboard->Port = 8729;
      $Routerboard->Connect($Device['LocalIP'], $this->System->Config['API']['UserName'], $this->System->Config['API']['Password']);
      if(!$Routerboard->Connected) continue;
      $Routerboard->Write('/interface/wireless/registration-table/getall', false);
      $Routerboard->Write('=.proplist=signal-strength,mac-address,rx-rate,tx-rate', false);
      $Routerboard->Write('=stats=');
      $Read = $Routerboard->Read(false);
      $Array = $Routerboard->ParseResponse($Read);
      foreach($Array as $Properties)
      {
        $DbResult = $this->Database->select('NetworkInterface', 'Id', 'MAC="'.$Properties['mac-address'].'"');
        if($DbResult->num_rows > 0)
        {
          $DbRow = $DbResult->fetch_assoc();
          $Interface = $DbRow['Id'];
        } else $Interface = 'NULL';

        if(strpos($Properties['signal-strength'], '@') === false)
        {
          $Strength = $Properties['signal-strength'];
        } else {
          $Parts = explode('@', $Properties['signal-strength']);
          if(substr($Parts[0], -3) == 'dBm')
            $Strength = substr($Parts[0], 0, -3); // without dBm
            else $Strength = $Parts[0];
        }
        $RateRx = $this->StripUnits($Properties['rx-rate']);
        $RateTx = $this->StripUnits($Properties['tx-rate']);
        $Queries[] = 'INSERT INTO `NetworkSignal` (`MAC`, `Value`, `RateRx`, `RateTx`, `Time`, `Interface`, `Device`) VALUES '.
          '("'.$Properties['mac-address'].'", '.$Strength.', '.$RateRx.', '.$RateTx.', "'.
          TimeToMysqlDateTime($Time).'", '.$Interface.', '.$Device['Id'].')';
        /*
         $DbResult = $this->Database->select('Measure', 'Id', '`Name` = "'.$Properties['mac-address'].'"');
         if($DbResult->num_rows > 0)
         {
         $this->Database->insert('Measure', array('Name' => $Properties['mac-address']));
         $Id = $this->Database->LastInsertId;
         } else {
         $DbRow = $DbResult->fetch_assoc();
         $Id = $DbRow['Id'];
         }
         $Measure = new Measure($Id);
         $Measure->Load($Id);
         $Measure->AddValue($Properties['signal-strength']);
         */
      }
    }
    $this->Database->Transaction($Queries);
  }
  
  function StripUnits($Value)
  {
    if (strpos($Value, '-') !== false) $Value = substr($Value, 0, strpos($Value, '-') - 1); // without channel info
    if (substr($Value, -3, 3) == "MHz") $Value = substr($Value, 0, -3); // without MHz unit
    if (substr($Value, -4, 4) == "Mbps") $Value = substr($Value, 0, -4); // without Mbps unit    
    if (substr($Value, -3, 3) == "Mbp") $Value = substr($Value, 0, -3); // without Mbp unit    
    if (substr($Value, -1, 1) == "M") $Value = substr($Value, 0, -1); // without M unit
    return($Value);
  }

  function Run()
  {
    RepeatFunction(60 * 60, array($this, 'ReadWirelessRegistration'));
  }
}