<?php

include_once(dirname(__FILE__).'/SSHClient.php');

class ConfigAirOSSignal extends NetworkConfigItem
{
  function ReadWirelessRegistration(): void
  {
    $Time = time();
    $NetworkMac = new NetworkMac($this->System);

    // Load netwatch status from all DHCP routers
    $DbResult3 = $this->Database->query('SELECT `Id`, `LoginName`, `LoginPassword`, '.
      '(SELECT `LocalIP` FROM `NetworkInterface` WHERE `NetworkInterface`.`Device` = `NetworkDevice`.`Id` LIMIT 1) AS `LocalIP`, `Name` '.
      'FROM `NetworkDevice` WHERE (`API` = 2) AND (`Used` = 1)');
    while ($Device = $DbResult3->fetch_assoc())
    {
      echo($Device['LocalIP'].' ('.$Device['Name']."): ");
      $SSHClient = new SSHClient($Device['LocalIP'], $Device['LoginName'], $Device['LoginPassword']);
      //$SSHClient->Debug = true;
      $Result = $SSHClient->Execute('wstalist');
      if (count($Result) > 0)
      {
        $Array = json_decode(implode("\n", $Result), true);
        foreach ($Array as $Properties)
        {
          $DbResult = $this->Database->select('NetworkInterface', 'Id', '`MAC`="'.$Properties['mac'].'"');
          if ($DbResult->num_rows > 0)
          {
            $DbRow = $DbResult->fetch_assoc();
            $Interface = $DbRow['Id'];
          } else $Interface = null;

          $Strength = $Properties['signal'];
          $RemoteSignal = $Properties['remote']['signal'];
          $RateRx = $Properties['rx'];
          $RateTx = $Properties['tx'];
          $MacRef = $NetworkMac->GetIndex($Properties['mac']);
          $this->Database->insert('NetworkSignal', array('MAC' => $MacRef,
            'Value' => $Strength, 'Remote' => $RemoteSignal, 'RateRx' => $RateRx, 'RateTx' => $RateTx,
            'Time' => TimeToMysqlDateTime($Time), 'Interface' => $Interface, 'Device' => $Device['Id']));
          echo('.');
        }
        echo("\n");
      } else echo("Empty response\n");
    }
  }

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