<?
/**
 * @package PowerControl Manager
 * @author Akash Heimlich
 * @description This sets up the system with inverters and power meters automatically
 * @date    2024-04-17
 * 2018-11-21: Added instantaneous logging options
 * 2018-11-22: Added ws102 and pyra300 packages
 *             Added powercontrol and devices on dashboard
 */
max_execution_time(90);
$ezconfig_version='20250417';
// this will take care of the package management functions and call the right function based on the get parameters

function in_array($arr, $val) {
    for ($i=0;$i<sizeof($arr);$i++) {
        if ($arr[$i]==$val) return 1;
    }
    return 0;
}
    
include("/app/config.inc");
$bodyid='rootscope';
$angular_controller="EZConfigWidget"; 
$title=lang('PAGE_TITLE','ezconfig');
$config_file="EZConfig.ini";
$config_section="config";
$num_inverters=$_GLOBALS['inverter_count']?$_GLOBALS['inverter_count']:1;

if ($_SERVER['HW_PLATFORM']>=20) {
    define("NUM_TCP_CHANNELS",20);
} else {
    define("NUM_TCP_CHANNELS",10);
}
//max_execution_time(40);
// this will be overwritten if a file called EZConfigTypes.ini exists

$default_pm_types="6400,6410,6444,6445,6454,6455,6630,6640";
$default_inv_types="4506,7000,7006,7010,7026,7034,7070,7072,7078,7080,7088,7094,7096,7099";

include("/app/header.inc");
print('<link href="'.$url_prefix.'/lib/fontawesome/css/font-awesome.css" rel="stylesheet">');
/********************************************************************************************************* STAGE 0 */        
if ($_GET['stage']==0) {
        ?> 
<!-- BREADCRUMBS -->
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/"><? print(lang('HOME','settings')) ?></a></li>
    <li class="breadcrumb-item"><a href="/app/settings.cgi"><? print(lang('CONTROL_PANEL','settings')) ?></a></li>
    <li class="breadcrumb-item active" aria-current="page"><? print(lang('PAGE_TITLE','ezconfig')) ?></li>
  </ol>
</nav>

<!-- NAVBAR -->
<h4><i class="icon-cog"></i>&nbsp;<? print(lang('CONFIGURE_TITLE','ezconfig')) ?> - Version <? print($ezconfig_version); ?></h4>
<ul class="nav justify-content-end">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="collapse" href="#collapseHelp" role="button" aria-expanded="false" aria-controls="collapseExample">
    <? print(lang('HELP','ezconfig')) ?>
  </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" onclick="document.location='/app/roles.cgi';"><i class="icon-remove"></i> <? print(lang('CLOSE','ezconfig')) ?></a>
  </li>
<? if ($_SERVER['HW_PLATFORM']<20 || ($_SERVER['HW_PLATFORM']>=20 && !(disk_status(1)==4 && get_drive()==1))) { 
            
?>
  
<? if (file_exists("/package/QOS.ini")) { ?>
  <li class="nav-item">
    <a class="nav-link {{getClass()}}" ng-hide='loading==1' ng-click="start(1)" ><i class="icon-check"></i> Start with QOS</a>
  </li>
<? } ?>  
<? if (file_exists("/package/Fourth.ini")) { ?>
  <li class="nav-item">
    <a class="nav-link {{getClass()}}" ng-hide='loading==1' ng-click="start(2)" ><i class="icon-check"></i> Start 4PL</a>
  </li>
<? } ?>  

<? if ($_SERVER['HW_PLATFORM']>=8)	{ ?>        

  <li class="nav-item">
    <a class="nav-link {{getClass()}}" ng-hide='loading==1' ng-click="start(0)" ><i class="icon-check"></i> <? print(lang('START','ezconfig')) ?></a>
  </li>
<? }

} else {
    $error_run=1;
}?>                    
  
</ul>
<!-- HELP -->
<div class="collapse" id="collapseHelp">
  <div class="card card-body">
      <? print(lang('HELP1','ezconfig')) ?><br>
    <? print(lang('HELP2','ezconfig')) ?><br>
    <? print(lang('HELP3','ezconfig')) ?><br>
    <? print(lang('HELP4','ezconfig')) ?><br>
    <? print(lang('HELP5','ezconfig')) ?><br>
    <? print(lang('HELP6','ezconfig')) ?><br>
    <? print(lang('HELP7','ezconfig')) ?><br>
  
  </div>
  <br/>
</div>
<div class="alert alert-success" ng-cloak ng-show="successmsg"> <button type="button" class="close" ng-click='successmsg=""'>&times;</button>{{successmsg}}</div>
<div class="alert alert-danger" ng-cloak ng-show="errormsg"> <button type="button" class="close" ng-click='errormsg=""'>&times;</button>{{errormsg}}</div>
<div class="alert alert-info" ng-cloak ng-show="infomsg"> <button type="button" class="close" data-dismiss="alert">&times;</button>{{infomsg}}</div>
<div class="alert alert-secondary" ng-cloak ng-show="loading"><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></div>
<? if ($error_run) { ?>
<div class='alert alert-danger'>You are not able to run EZConfig since your flash is currently locked.  Please unlock it and run this again.</div>
<? 

} ?>

<form name="form" class="css-form form-horizontal" novalidate>

<!-- VARIABLES -->        
<div class="card">
    <div class="card-body">
        <h5 class="card-title"><? print(lang('ABOUT','devicetypeedit')) ?></h5>
        <p class="card-text">    
<? print(lang('ABOUT1','ezconfig')) ?>        
<? print(lang('ABOUT2','ezconfig')) ?>		
		<p>
<? if ($_SERVER['HW_PLATFORM']<7)	{ ?>
		<div class='alert alert-danger'><? print(lang('ABOUT4','ezconfig')) ?> </div>
<? } ?>		
        </p>
        <? if (!$error_run) { ?>
        After updating WattmonOS or the Power Control package, it is suggested to re-generate the driver list by clicking the button below:
        <a class="nav-link active" onclick="document.location='/app/ezconfig.cgi?stage=0&action=regenerate';"><i class="icon-check"></i> REGENERATE FILES</a>
        <? } ?>
<? if (!$error_run && (!file_exists('/config/devicetypes.ini') || $_GET['action']=='regenerate')) {
        print("Regenerating Device List...");
        unlink('/config/devicetypes.ini');
        $curdir=getcwd();
        $maxid=0;
        //print("RESCAN");
        chdir("/dev/");  
        
        $arr=findfirst("*.ini",255-8);
        
        $dev_arr=array();
        $dev_arr['Inverter']=array();
        $dev_arr['Meter']=array();
        $dev_arr['Other']=array();
        $idx=0;
        //print("<pre>");
        while ($arr) {
            $devname=ini_get('/dev/'.$arr['filename'],'config','name');
            $devtype=ini_get('/dev/'.$arr['filename'],'config','device_type_id',0);
            $devcat=ini_get('/dev/'.$arr['filename'],'config','dev_category',0);
            
            if ($devtype>0) {
                if ($devcat==0) {
                    $devcatname="Inverter";
                    $dev_arr['Rating'][$devtype]=ini_get('/dev/'.$arr['filename'],'config','dev_rating',0);
                } else if ($devcat==1) {
                    $devcatname="Meter";
                } else $devcatname="Other";
                //print($devcatname." ".$devtype." ".$devname." \r\n");
                if (strlen($devname)) {//$devtype>1) {
                    
                    $dev_arr[$devcatname][strval($devtype)] = $devname;
                    $idx++;
                }
            }
            $arr=findnext();   
        }
        
        //print_r($dev_arr);
        //print("</pre>");
        ini_put_array('/config/devicetypes.ini',$dev_arr);
        chdir($curdir);
        print("DONE!  <strong>Listed ".$idx." devices.</strong><p/>\r\n");
        //sleep(5000);
        print("Regenerating Packages...");
        include("/app/package.inc");
        $res=scanPackages();
        print("DONE!  <p/>");
    }  
    ?>
        
        <h5>Changelog</h5>
        <pre>
<? 
if (file_exists("/config/PC.ini")) {
    
   $inv_cnt=ini_get("/config/EZConfig.ini","config",'inv_count',0);
   $pm_cnt=ini_get("/config/EZConfig.ini","config",'pm_count',0);
   $other_cnt=ini_get("/config/EZConfig.ini","config",'other_count',0);
            
//   $ez_arr = ini_get_array("/config/EZConfig.ini","config");
   
   $pc_arr = ini_get_array("/config/PC.ini","config");
   
   for ($i=0; $i < $pc_arr['pm_count']; $i++) {
       $idx=$pc_arr['pm'.$i.'_device_idx'];
       $dev = mb_get_dev_by_index($idx);
       $name = $dev['name'];
       ini_set("/config/PC.ini","config",'pm'.$i.'_name',$name);
   }
   
    for ($i=0; $i < $pc_arr['inv_count']; $i++) {
       $idx=$pc_arr['inv'.$i.'_device_idx'];
       $dev = mb_get_dev_by_index($idx);
       $name = $dev['name'];
       ini_set("/config/PC.ini","config",'inv'.$i.'_name',$name);
   }
}
     

    $f=fopen("/changelog_pc.txt","r");
    if ($f) {
        while(!feof($f)) {
            print(fgets($f)."\r\n");
        }
        fclose($f);
    } 
     
    
?>
        </pre>
	</div>
</div>	
</form>
<script>
var gItems,gHttp;
var count=0;
var app = angular.module('myApp', []);

function EZConfigWidget($scope, $timeout,$http) {
   var self = this;
   

   $scope.start=function(qos) {
          if (qos==1) {
            document.location='/app/ezconfig.cgi?stage=1&qos=1';
          } else if (qos==2) {
            document.location='/app/ezconfig.cgi?stage=1&fourth=1';
          } else document.location='/app/ezconfig.cgi?stage=1';
          return data;
   }
}
   </script>
</div>
<?
      include("/app/footer.inc");?>
<?
    die();
}

/********************************************************************************************************* STAGE 1 */        
if ($_GET['stage']==1) {
$use_qos=0;
if ($_GET['qos']==1) {
    $use_qos=1;
}
if ($_GET['fourth']==1) {
    $use_fourth=1;
}
?> 
<style type='text/css'>
[ng-cloak].splash {
    display: block !important;
}
.splash {
    display: none;
}

.panel-heading  a:before {
   font-family: 'Arial';
   content: "^";
   float: right;
   transition: all 0.5s;
}
.panel-heading.active a:before {
	-webkit-transform: rotate(180deg);
	-moz-transform: rotate(180deg);
	transform: rotate(180deg);
} 

</style>
<!-- BREADCRUMBS -->
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/"><? print(lang('HOME','settings')) ?></a></li>
    <li class="breadcrumb-item"><a href="/app/settings.cgi"><? print(lang('CONTROL_PANEL','settings')) ?></a></li>
    <li class="breadcrumb-item active" aria-current="page"><? print(lang('PAGE_TITLE','ezconfig')) ?></li>
  </ol>
</nav>

<!-- NAVBAR -->
<h4><i class="icon-cog"></i>&nbsp;<? print(lang('STAGE1_TITLE','ezconfig')) ?>: <? print(lang('S1_TITLE','ezconfig')) ?></h4>
<ul class="nav justify-content-end">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="collapse" href="#collapseHelp" role="button" aria-expanded="false" aria-controls="collapseExample">
    <? print(lang('HELP','ezconfig')) ?>
  </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" onclick="document.location='/app/settings.cgi';"><i class="icon-remove"></i> <? print(lang('CLOSE','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="saveSettings(0)" ><i class="icon-check"></i> <? print(lang('APPLY','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="saveSettings(1)" ><i class="icon-arrow-right"></i> <? print(lang('SAVE_NEXT','ezconfig')) ?></a>
  </li>
  
</ul>
<!-- HELP -->
<div class="collapse" id="collapseHelp">
  <div class="card card-body">
      <? print(lang('HELP1','ezconfig')) ?><br>
    <? print(lang('HELP2','ezconfig')) ?><br>
    <? print(lang('HELP3','ezconfig')) ?><br>
    <? print(lang('HELP4','ezconfig')) ?><br>
    <? print(lang('HELP5','ezconfig')) ?><br>
    <? print(lang('HELP6','ezconfig')) ?><br>
    <? print(lang('HELP7','ezconfig')) ?><br>
  
  </div>
  <br/>
</div>
<div class="alert alert-success" ng-cloak ng-show="successmsg"> <button type="button" class="close" ng-click='successmsg=""'>&times;</button>{{successmsg}}</div>
<div class="alert alert-danger" ng-cloak ng-show="errormsg"> <button type="button" class="close" ng-click='errormsg=""'>&times;</button>{{errormsg}}</div>
<div class="alert alert-info" ng-cloak ng-show="infomsg"> <button type="button" class="close" data-dismiss="alert">&times;</button>{{infomsg}}</div>
<div class="alert alert-secondary" ng-cloak ng-show="loading"><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></div>
<div class="splash" ng-cloak="">
    <p><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></p>
  </div>
<form name="form" class="css-form form-horizontal" novalidate ng-cloak>

<!-- VARIABLES -->
<?
max_execution_time(60);
include("/app/package.inc");
include("/lib/uphp/array.inc");
        // package manager option
$all_rating = ini_get_array('/config/devicetypes.ini','Rating');

$all_inverters = ini_get_array('/config/devicetypes.ini','Inverter');
$all_inverters = quick_sort($all_inverters,1); // sort by value

$all_meters = ini_get_array('/config/devicetypes.ini','Meter');
$all_meters = quick_sort($all_meters,1); // sort by value

$all_other = ini_get_array('/config/devicetypes.ini','Other');
$all_other = quick_sort($all_other,1); // sort by value


            $inv_cnt=ini_get("/config/EZConfig.ini","config",'inv_count',0);
            $pm_cnt=ini_get("/config/EZConfig.ini","config",'pm_count',0);
            $other_cnt=ini_get("/config/EZConfig.ini","config",'other_count',0);
            
            $ez_arr = ini_get_array("/config/EZConfig.ini","config");
            if (!$ez_arr['packages']) {
                $ez_package_list=array("EZDisplay","Devices");
            } else
                $ez_package_list=explode($ez_arr['packages'],',');
            
            

                $packages=getPackageList();
                $packages=array_keys($packages);
                
            // onewire support - only on mega, ultra, M2
             $has_onewire=0;
             if ($_SERVER['HW_PLATFORM']==11 || $_SERVER['HW_PLATFORM']==20 || $_SERVER['HW_PLATFORM']==10) { 
                $has_onewire=1;
                $dev=array();
                $arr=ow_first();
                $cnt=0;
                if ($arr) {
                    //print_r($arr);
                    $dev[0]=$arr;
                    $cnt++;
                    while ($arr=ow_next()) {
                        //print_r($arr);
                        $dev[$cnt]=$arr;
                        $cnt++;
                    }
                }
                //print("Found a total of "+$cnt+" devices!\r\n");
                
                for ($i=0;$i<sizeof($dev);$i++) {
                    $devname=sprintf("%02X%02X%02X%02X%02X%02X%02X%02X",$dev[$i][0],$dev[$i][1],$dev[$i][2],$dev[$i][3],$dev[$i][4],$dev[$i][5],$dev[$i][6],$dev[$i][7]);
                    $nbdev=ini_get("/config/onewire.ini","general","num_devices",0);
                    $found=0;
                    $idx=0;
                    for ($j=0;$j<$nbdev;$j++) {
                        $tmpname=ini_get("/config/onewire.ini","Device".$j,"address","");
                        if ($tmpname==$devname) {
                            $found=1;
                            $idx=$j;
                        }
                    }
                    if (!$found) {
                        ini_set("/config/onewire.ini","Device".$nbdev,"address",$devname);
                        ini_set("/config/onewire.ini","Device".$nbdev,"name","onewire".$nbdev);
                        ini_set("/config/onewire.ini","Device".$nbdev,"device_type_id",$dev[$i][0]);
                        ini_set("/config/onewire.ini","Device".$nbdev,"status",1);
                        ini_set("/config/onewire.ini","Device".$nbdev,"poll_interval",300);
                        $nbdev++;
                        ini_set("/config/onewire.ini","general","num_devices",$nbdev);
                        
                       // $_GLOBALS['needreboot']=1;
                    } else {
                        ini_set("/config/onewire.ini","Device".$idx,"status",1); // re-enable it
                       // print("Re-activing device ".$idx);
                    }
                }
             }
//            } else {
            //print("<pre>");
            //print_r($packages);die();
            //$st=implode($keys,',');
            //print($st);die();
            //print_r($keys);die();
  //              $allowed_packages=ini_get('/config/EZConfigTypes.ini','config','packages',$st);//PC,EZDisplay,Devices,Pyranometer,WS102,QOS,MQTT,FTP,VariableWidget');
            
        //$res=scanPackages();
        //$packages=getPackageList();
        //$keys=array_keys($packages);
    //            $packages=explode($allowed_packages,',');
            //}
            $keys=$packages;
            $num_packages=sizeof($packages);

            
            for ($i=0;$i<$num_packages;$i++) {
                print('<div ng-init="package.push({index:\'pkg'+$i+'\''+
                    ',name:\''+$keys[$i]+'\''+
                    ',edit:1'+
                    ',selected:'+(in_array($ez_package_list,$keys[$i])?"true":"false").
                    ',description:\''+ini_get('/package/'.$keys[$i].'.ini','package','description')+'\''+
                    ',version:\''+ini_get('/package/'.$keys[$i].'.ini','package','version')+'\''+
                    '})"></div>'
                    );
            }
        
            // load power meter values
            for ($i=0;$i<$pm_cnt;$i++) {
                $cat=$ez_arr['pm'+$i+'_category'];
                if (!$cat) $cat='ENERGY_METER';
                print('<div ng-init="pm.push({device_idx:'+$ez_arr['pm'+$i+'_device_idx']+
                    ',bus:'+intval($ez_arr['pm'+$i+'_bus'])+
                    ',device_type_id:'+intval($ez_arr['pm'+$i+'_device_type_id'])+
                    ',edit:1'+
                    ',type:'+intval($ez_arr['pm'+$i+'_type'])+
                    ',dg_rating:'+intval($ez_arr['pm'+$i+'_dg_rating'])+
                    ',id:\''+intval($ez_arr['pm'+$i+'_id'])+'\''+
                    ',device_name:\''+$ez_arr['pm'+$i+'_device_name'] + '\',category:\''+$cat + '\'})"></div>'
                    );
            } 
            
            // load inverter values
            for ($i=0;$i<$inv_cnt;$i++) {
                $cat=$ez_arr['inv'+$i+'_category'];
                if (!$cat) $cat='PV_INVERTER';
                print('<div ng-init="inv.push({device_idx:'+
                
                    $ez_arr['inv'+$i+'_device_idx']+
                    ',device_type_id:'+$ez_arr['inv'+$i+'_device_type_id']+
                    ',bus:'+intval($ez_arr['inv'+$i+'_bus'])+
                    ',edit:1'+
                    ',rating:\''+$ez_arr['inv'+$i+'_rating']+'\''+
                    ',id:\''+intval($ez_arr['inv'+$i+'_id'])+'\',device_name:\''+$ez_arr['inv'+$i+'_device_name'] + '\',category:\''+$cat + '\'})"></div>'
                    );
            } 
            
            // load inverter values
            for ($i=0;$i<$other_cnt;$i++) {
                $cat=$ez_arr['other'+$i+'_category'];
                if (!$cat) $cat='WEATHER_STATION';
                
                print('<div ng-init="other.push({device_idx:'+
                    $ez_arr['other'+$i+'_device_idx']+
                    ',device_type_id:'+$ez_arr['other'+$i+'_device_type_id']+
                    ',bus:'+
                    intval($ez_arr['other'+$i+'_bus'])+',edit:1'+',id:\''+
                    intval($ez_arr['other'+$i+'_id'])+'\',device_name:\''+$ez_arr['other'+$i+'_device_name'] + '\',category:\''+$cat + '\'})"></div>'
                    );
            }
        ?>            
<div ng-init="inv_count=<? print($inv_cnt); ?>;">
<div ng-init="other_count=<? print($other_cnt); ?>;">
<div ng-init="pm_count=<? print($pm_cnt); ?>;">
<div ng-init="pyranometer=<? print(intval($ez_arr['pyranometer'])); ?>;">
<div ng-init="dc_plant_size='<? print(floatval($ez_arr['dc_plant_size'])); ?>';">
<div ng-init="fixed_pr='<? print(floatval($ez_arr['fixed_pr'])); ?>';">
<div ng-init="ws102=<? print(intval($ez_arr['ws102'])); ?>;">
<? if ($has_onewire) {?>
<div ng-init="use_temp=<? print(intval($ez_arr['use_temp'])); ?>;">
<? } else { ?>
<div ng-init="use_temp=0;">
<? } ?>
<div ng-init="static_header=1<? 
//print(intval($ez_arr['static_header'])); 
?>;">
<div ng-init="num_temp=<? 
$num_onewire=ini_get("/config/onewire.ini","general","num_devices",0);
//if (intval($ez_arr['num_temp'])<$num_onewire)
// print(intval($ez_arr['sync_power_control'])); 
    $ez_arr['num_temp']=$num_onewire;
print(intval($ez_arr['num_temp'])); 
?>;">
<div ng-init="log_interval=<? 
if (!$ez_arr['log_interval']) $ez_arr['log_interval']=1;
print(intval($ez_arr['log_interval'])); ?>;">
<div ng-init="log_write_interval=<? 
if (!$ez_arr['log_write_interval']) $ez_arr['log_write_interval']=1;
print(intval($ez_arr['log_write_interval'])); ?>;">

<div ng-init="log_drive=<? print(intval($ez_arr['log_drive'])); ?>;">
<div ng-init="module_power_control=<? print(intval($ez_arr['module_power_control'])); ?>;">
<div ng-init="sync_power_control=0;">
<div ng-init="track_curtailment=<? print(intval($ez_arr['track_curtailment'])); ?>;">

<div ng-init="module_devices=<? print(intval($ez_arr['module_devices'])); ?>;">
<div ng-init="poll_interval=<? print($ez_arr['poll_interval']>0?$ez_arr['poll_interval']:"1000"); ?>;">
<div ng-init="parity=<? print($ez_arr['parity']>0?$ez_arr['parity']:"0"); ?>;">
<div ng-init="baud_rate=<? print($ez_arr['baud_rate']>0?$ez_arr['baud_rate']:"9600"); ?>;">
<div ng-init="retry=<? print($ez_arr['retry']>0?$ez_arr['retry']:"1"); ?>;">
<div ng-init="retry_interval=<? print($ez_arr['retry_interval']>0?$ez_arr['retry_interval']:"15"); ?>;">
<div ng-init="short_timeout=<? print($ez_arr['short_timeout']>0?$ez_arr['short_timeout']:"30"); ?>;">
<div ng-init="timeout=<? print($ez_arr['timeout']>0?$ez_arr['timeout']:"300"); ?>;">
<div ng-init="interval=<? print($ez_arr['interval']>0?$ez_arr['interval']:"10"); ?>;">
<div ng-init="timeout2=<? print($ez_arr['timeout2']>0?$ez_arr['timeout2']:"300"); ?>;">
<div ng-init="interval2=<? print($ez_arr['interval2']>0?$ez_arr['interval2']:"10"); ?>;">
<div ng-init="retry2=<? print($ez_arr['retry2']>0?$ez_arr['retry2']:"1"); ?>;">
<div ng-init="retry_interval2=<? print($ez_arr['retry_interval2']>0?$ez_arr['retry_interval2']:"15"); ?>;">
<div ng-init="enabled2=<? print($ez_arr['enabled2']>0?$ez_arr['enabled2']:"0"); ?>;">


<div ng-init="auth=<? print($ez_arr['auth']>0?$ez_arr['auth']:"1"); ?>;">
<div ng-init="client_id=<? print($ez_arr['client_id']>0?$ez_arr['client_id']:"32"); ?>;">
<div ng-init="password='<? print($ez_arr['password']?$ez_arr['password']:"ABCD0001"); ?>';">
<div ng-init="rs232_baud=<? print($ez_arr['rs232_baud']>0?$ez_arr['rs232_baud']:"9600"); ?>;">
<div ng-init="rs232_enabled=<? print($ez_arr['rs232_enabled']>0?$ez_arr['rs232_enabled']:"0"); ?>;">

      
<div ng-init="parity2=<? print($ez_arr['parity2']>0?$ez_arr['parity2']:"0"); ?>;">
<div ng-init="baud_rate2=<? print($ez_arr['baud_rate2']>0?$ez_arr['baud_rate2']:"9600"); ?>;">
<div ng-init="tcp_enabled=<? print(intval($ez_arr['tcp_enabled'])); ?>;">

<div ng-init="tcp_retry=<? print($ez_arr['tcp_retry']>0?$ez_arr['tcp_retry']:"1"); ?>;">
<div ng-init="tcp_retry_interval=<? print($ez_arr['tcp_retry_interval']>0?$ez_arr['tcp_retry_interval']:"15"); ?>;">
<div ng-init="tcp_timeout=<? print($ez_arr['tcp_timeout']>0?$ez_arr['tcp_timeout']:"300"); ?>;">
<div ng-init="tcp_interval=<? print($ez_arr['tcp_interval']>0?$ez_arr['tcp_interval']:"10"); ?>;">

<? if ($use_qos) { ?>
<div ng-init="qos_username='<? print(strval($ez_arr['qos_username'])); ?>';">
<div ng-init="qos_password='<? print(str_replace('"','',strval($ez_arr['qos_password']))); ?>';">
<div ng-init="qos_path='<? print(strval($ez_arr['qos_path'])); ?>';">
<div ng-init="qos_server='<? print(strval($ez_arr['qos_server'])); ?>';">
<div ng-init="qos_prefix='<? print(strval($ez_arr['qos_prefix'])); ?>';">
<? } ?>
<? if ($use_fourth) {  ?>
<div ng-init="sim_number='<? print(strval($ez_arr["sim_number"])); ?>';">
<div ng-init="custom_url='<? print(strval($ez_arr["custom_url"])?$ez_arr['custom_url']:'wattmon.siteshuttle.in/test.php'); ?>';">
<div ng-init="max_lines=<? print($ez_arr['max_lines']>0?$ez_arr['max_lines']:"5"); ?>;">
<div ng-init="export_interval=<? print($ez_arr['export_interval']>0?$ez_arr['export_interval']:"5"); ?>;">
<div ng-init="apn='<? print(strval($ez_arr["apn"])); ?>';">
<div ng-init="apn_custom='<? print(strval($ez_arr["apn_custom"])); ?>';">
<div ng-init="apn_mode=<? print($ez_arr['apn_mode']>0?$ez_arr['apn_mode']:"4"); ?>;">
<div ng-init="mqtt_mode=<? print($ez_arr['mqtt_mode']>0?$ez_arr['mqtt_mode']:"0"); ?>;">
<div ng-init="mqtt_enabled=<? print($ez_arr['mqtt_enabled']); ?>;">
<div ng-init="mqtt_channel='<? print(strlen($ez_arr["mqtt_channel"])?$ez_arr['mqtt_channel']:'/fourth/siteX'); ?>';">
<div ng-init="mqtt_port=<? print($ez_arr['mqtt_port']>0?$ez_arr['mqtt_port']:1883); ?>;"></div>
<div ng-init="mqtt_server='<? print(strlen($ez_arr["mqtt_server"])?$ez_arr['mqtt_server']:'mqtt.wattmon.com'); ?>';"></div>
<div ng-init="mqtt_user='<? print(strlen($ez_arr["mqtt_user"])?$ez_arr['mqtt_user']:'');?>';"></div>
<div ng-init="mqtt_password='<? print(strlen($ez_arr["mqtt_password"])?$ez_arr['mqtt_password']:'');?>';"></div>
<div ng-init="subscribe_timeout_interval=<? print($ez_arr['subscribe_timeout_interval']>0?$ez_arr['subscribe_timeout_interval']:60); ?>;"></div>
<div ng-init="subscribe_timeout_percent=<? print($ez_arr['subscribe_timeout_percent']>0?$ez_arr['subscribe_timeout_percent']:5); ?>;"></div>

<? } 

$license_key=$ez_arr['license_key'];
if (!$license_key) {
    $license_key=ini_get("/config/license.ini","config","key1","");
}
?>
<div ng-init="license_key='<? print(($license_key)); ?>'">
<div ng-init="snapshot=1<? //print(intval($ez_arr['snapshot'])); 
?>;">
<div ng-init="firmware_logging=1<? //print(intval($ez_arr['firmware_logging'])); 
?>;">
<div ng-init="ota_packages=<? print(intval($ez_arr['ota_packages'])); ?>;">
<div ng-init="ota_firmware=<? print(intval($ez_arr['ota_firmware'])); ?>;">
<div ng-init="ota_healing=<? print(intval($ez_arr['ota_healing'])); ?>;">
<? for ($x=0; $x < NUM_TCP_CHANNELS; $x++)  { ?>
<div ng-init="tcp<? print($x."_ip='".(strlen($ez_arr['tcp'.$x.'_ip'])?$ez_arr['tcp'.$x.'_ip']:'0.0.0.0')); ?>';">
<div ng-init="tcp<? print($x."_s='".intval($ez_arr['tcp'.$x.'_s'])); ?>';">
<div ng-init="tcp<? print($x."_port='".intval($ez_arr['tcp'.$x.'_port'])); ?>';">
<? } ?>
<div class="card">
    <div class="card-body">
        <h5 class="card-title"><? print(lang('S1_TITLE','ezconfig')) ?></h5>
        <p class="card-text">    
            <? print(lang('S1_1','ezconfig')) ?>
        </p>
    </div>
</div>
<br/>

<div id="accordion">
<? if ($use_qos) { ?>
<div class="card">
    <div class="card-header panel-heading" id="headingQOS">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseQOS" aria-expanded="false" aria-controls="collapseQOS">
          QOS Configuration&nbsp;<i class='icon icon-caret-down'></i>
        </button>
      </h5>
    </div>
    <div id="collapseQOS" class="collapse" aria-labelledby="headingQOS" data-parent="#accordion">
    <div class="card-body">
        <h6 class="card-subtitle mb-2 text-muted">QOS Settings</h6>
        <p class="card-text">    
            <div class="form-group">
                <label for="qos_path">QOS Path on server</label>
                <input class="form-control" type='text' ng-model="qos_path"  class='span12' name='qos_path' integer aria-describedby="bHelp" placeholder="Server path">
                <small id="bHelp" class="form-text text-muted">Server path with trailing /</small>
            </div>
            <div class="form-group">
                <label for="qos_server">QOS FTP Server</label>
                <input class="form-control" type='text' ng-model="qos_server"  class='span12' name='qos_server' integer aria-describedby="bHelp" placeholder="Server URL (i.e. ftp.qos.com)">
                <small id="bHelp" class="form-text text-muted">FTP server name</small>
            </div>
            <div class="form-group">
                <label for="qos_username">QOS FTP Username</label>
                <input class="form-control" type='text' ng-model="qos_username"  class='span12' name='qos_username' integer aria-describedby="bHelp" placeholder="FTP Username">
                <small id="bHelp" class="form-text text-muted">FTP username</small>
            </div>
            <div class="form-group">
                <label for="qos_password">QOS FTP Password</label>
                <input class="form-control" type='text' ng-model="qos_password"  class='span12' name='qos_password' integer aria-describedby="bHelp" placeholder="FTP Password">
                <small id="bHelp" class="form-text text-muted">FTP password</small>
            </div>
            <div class="form-group">
                <label for="qos_prefix">QOS Prefix</label>
                <input class="form-control" type='text' ng-model="qos_prefix"  class='span12' name='qos_prefix' integer aria-describedby="bHelp" placeholder="File Prefix">
                <small id="bHelp" class="form-text text-muted">QOS File Prefix i.e QOS_</small>
            </div>
        </p>		            	
	</div>
	</div>
<? } ?>  
<? if ($use_fourth) { ?>
<div class="card">
    <div class="card-header panel-heading" id="headingTwo">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Fourth Partner Export Configuration
        </button>
      </h5>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
        <div class="card-body">
            <h6 class="card-subtitle mb-2 text-muted">Export Settings</h6>
            <p class="card-text">
                <div class="form-group">
                    <label for="custom_url">Export URL</label>
                    <input class="form-control" type='text' ng-model="custom_url"  class='span12' name='custom_url' integer aria-describedby="bHelp" placeholder="URL to export to">
                    <small id="bHelp" class="form-text text-muted">Export URL</small>
                </div>
               <div class="form-group">
                    <label for="max_lines">Max Lines</label>
                    <input class="form-control" type='number' ng-model="max_lines"  class='span12' name='max_lines' required min="1" max="30" integer aria-describedby="bHelp" placeholder="Max lines to export per time">
                    <small id="bHelp" class="form-text text-muted">Max lines</small>
                </div>
                <div class="form-group">
                    <label for="export_interval">Export Interval</label>
                    <input class="form-control" type='number' ng-model="export_interval"  class='span12' name='export_interval' required min="1" max="30" integer aria-describedby="bHelp" placeholder="Export interval">
                    <small id="bHelp" class="form-text text-muted">Export interval</small>
                </div>
            </p>
        </div>
        <div class="card-body">
            <h6 class="card-subtitle mb-2 text-muted">SIM Settings</h6>
            <p class="card-text">

                        <div class="form-group">
                            <label  for='apn'>APN</label>
                            <select  ng-model="apn"  class="custom-select">
                            	<option value='airtelgprs.com'>Airtel</option>
								<option value='internet'>Idea</option>
								<option value='www'>Vodafone</option>
								<option value='jionet'>JIO</option>
								<option value='airtellive'>Airtel Sri Lanka</option>
								<option value='dialogbb'>Dialog Sri Lanka</option>	
								<option value='other'>Other</option>
                            </select>
                            <small id="flangdH" class="form-text text-muted">APN from provider</small>
                        </div>
                        <div class="form-group" ng-show='apn=="other"'>
                            <label for="apn_custom">Cluster Server</label>
                            <input type="text" class="form-control" id="apn_custom" ng-model="apn_custom" aria-describedby="aaagsgl" placeholder="Custom APN">
                            <small id="aaagsgl" class="form-text text-muted">Custom APN</small>
                        </div>
			            <div class="form-group">
                            <label  for='apn_mode'>Connection Mode</label>
                            <select  ng-model="apn_mode"  class="custom-select">
					
    			                <option value='0'>GPRS/Edge 2G Mode Only</option>
                                <option value='1'>3G Mode Only</option>
                                <option value='2'>Prefer GPRS/Edge 2G Mode</option>
                                <option value='3'>Prefer 3G Mode</option>
    							<option value='4'>4G Mode</option>

                            </select>
                            <small id="aaagsgl" class="form-text text-muted">Select connection mode</small>
			            </div>
                    </p>
                    
            </p>		            	
	    </div>
        <div class="card-body">
            <h6 class="card-subtitle mb-2 text-muted">MQTT Sync Settings</h6>
            <p class="card-text">
                <div class="form-group">
                    <label  for='mqtt_enabled'>MQTT Enabled</label>
                    <select  ng-model="mqtt_enabled"  class="custom-select">
    		            <option value='0'>Disabled</option>
                        <option value='1'>Enabled</option>
                    </select>
                    <small id="aaagsgl" class="form-text text-muted">Enable MQTT</small>
			    </div>
                <div class="form-group" ng-show='mqtt_enabled==1'>
                    <label  for='mqtt_mode'>MQTT Mode</label>
                    <select  ng-model="mqtt_mode"  class="custom-select">
    		            <option value='0'>Publish Meter Data</option>
                        <option value='1'>Receive Meter data</option>
                    </select>
                    <small id="aaagsgl" class="form-text text-muted">Choose MQTT mode (publish or receive)</small>
			    </div>
			    <div class="form-group" ng-show='mqtt_enabled==1'>
                    <label for="mqtt_channel">MQTT Channel</label>
                    <input type="text" class="form-control" id="mqtt_channel" ng-model="mqtt_channel" aria-describedby="aaagsgl" placeholder="Channel name (without trailing /)">
                    <small id="aaagsgl" class="form-text text-muted">Channel name</small>
                </div>
                
            <div class="form-group" ng-show='mqtt_enabled==1 && mqtt_mode==1'>
                <label for="subscribe_timeout_interval">Heartbeat Timeout Interval</label>
                <input class="form-control" type='text' ng-model="subscribe_timeout_interval"  class='span12' name='subscribe_timeout_interval' integer aria-describedby="bHelp" placeholder="">
                <small id="bHelp" class="form-text text-muted">Heartbeat timeout in seconds</small>
            </div>
            <div class="form-group" ng-show='mqtt_enabled==1 && mqtt_mode==1'>
                <label for="subscribe_timeout_percent">Timeout Fallback Percent</label>
                <input class="form-control" type='text' ng-model="subscribe_timeout_percent"  class='span12' name='subscribe_timeout_percent' integer aria-describedby="bHelp" placeholder="">
                <small id="bHelp" class="form-text text-muted">Inverter fallback percent if connection goes out for longer than the timeout</small>
            </div>
                
                <div class="mb-3 row" ng-show='mqtt_enabled==1'>
                        <label class="col-form-label col-sm-2 text-sm-end">MQTT Server</label>
                        <div class="col-sm-10">
                            <input type='text' class="form-control" id="mqtt_server" ng-model="mqtt_server" aria-describedby="buserHelp" placeholder="MQTT Server">
                        <small id="buserHelp" class="form-text text-muted">MQTT Server host name</small>
                        <small ng-cloak class='text-danger' ng-show="form.mqtt_server.$invalid">Invalid server name</small>
                        </div>

                </div>
                <div class="mb-3 row" ng-show='mqtt_enabled==1'>
                        <label class="col-form-label col-sm-2 text-sm-end">MQTT Port</label>
                        <div class="col-sm-10">
                            <input type='text' class="form-control" id="mqtt_port" size='4' integer minval="10" maxval="65535" ng-model="mqtt_port" aria-describedby="buserHelp" placeholder="MQTT Port Number">
                        <div ng-cloak class='small text-danger' ng-show="form.mqtt_port.$invalid"><strong>Invalid Port Number</strong></div>
                        <small id="buserHelp" class="form-text text-muted">Enter Server Port number</small>
                        </div>

                </div>

                <div class="mb-3 row" ng-show='mqtt_enabled==1'>
                        <label class="col-form-label col-sm-2 text-sm-end">MQTT Username</label>
                        <div class="col-sm-10">
                            <input type='text' class="form-control" id="mqtt_user" ng-model="mqtt_user" aria-describedby="buserHelp" placeholder="MQTT Username">
                             <small id="dnHelp" class="form-text text-muted">MQTT Username - leave blank if not required</small>
                            <small ng-cloak class='text-danger' ng-show="form.mqtt_user.$invalid">Invalid user name</small>
                        </div>
                    </div>
                    <div class="mb-3 row" ng-show='mqtt_enabled==1'>
                        <label class="col-form-label col-sm-2 text-sm-end">MQTT Username</label>
                        <div class="col-sm-10">
                            <input type='password' class="form-control" id="mqtt_password" ng-model="mqtt_password" aria-describedby="buserHelp" placeholder="MQTT Password">
                             <small id="dnHelp" class="form-text text-muted">MQTT Password - leave blank if not required</small>
                            <small ng-cloak class='text-danger' ng-show="form.mqtt_password.$invalid">Invalid Password</small>
                        </div>
                    </div>

            </p>
        </div>

	</div>
<? } ?>  
  <div class="card">
    <div class="card-header panel-heading" id="headingOne">
      <h5 class="mb-0">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          <? print(lang('MODBUS_RTU','ezconfig')) ?> <? print(lang('CONFIGURATION','ezconfig')) ?>&nbsp;<i class='icon icon-caret-down'></i>
        </button>
      </h5>
    </div>

    <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordion">
      <div class="card-body">
        <h6 class="card-subtitle mb-2 text-muted"><? print(lang('MODBUS_RTU_SUBTITLE','ezconfig')) ?></h6>
        <p class="card-text">    
            <div class="form-group">
                <label for="baud_rate"><? print(lang('BAUD','ezconfig')) ?></label>
                <input class="form-control" type='number' ng-model="baud_rate"  class='span12' name='baud_rate' required min="1200" max="115200" integer aria-describedby="bHelp" placeholder="<? print(lang('BAUD','ezconfig')) ?>">
                <small id="bHelp" class="form-text text-muted"><? print(lang('BAUD_HELP','ezconfig')) ?></small>
                <small ng-cloak class='text-danger' ng-show="form.baud_rate.$invalid"><? print(lang('BAUD_INVALID','ezconfig')) ?></small>
            </div>
            <div class="form-group">
                <label for="parity"><small class='text-muted'><? print(lang('PARITY','ezconfig')) ?></small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="parity" id="parity0" value="0">
                  <label class="form-check-label" for="parity0">
                    &nbsp;<? print(lang('PARITY_NONE','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="parity" id="parity1" value="1">
                  <label class="form-check-label" for="parity1">
                    &nbsp;<? print(lang('PARITY_EVEN','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="parity" id="parity2" value="2">
                  <label class="form-check-label" for="parity2">
                    &nbsp;<? print(lang('PARITY_ODD','ezconfig')) ?>
                  </label>
                </div>  
                
                <small id="pHelp" class="form-text text-muted"><? print(lang('PARITY_HELP','ezconfig')) ?></small>
            </div>                  
           <div class="form-group">
                <label for="interval">Inter-packet delay</label>
                <input class="form-control" type='number' ng-model="interval"  class='span12' name='interval' required min="5" max="300" integer aria-describedby="bHelp" placeholder="Inter packet delay">
                <small id="bHelp" class="form-text text-muted">Inter packet delay</small>
                <small ng-cloak class='text-danger' ng-show="form.interval.$invalid">Interpacket delay is our of range</small>
            </div>
           <div class="form-group">
                <label for="short_timeout">Short Timeout</label>
                <input class="form-control" type='number' ng-model="short_timeout"  class='span12' name='short_timeout' required min="5" max="5000" integer aria-describedby="bHelp" placeholder="Short timeout">
                <small id="bHelp" class="form-text text-muted">Short timeout in ms, if data is not received within this time it will skip</small>
                <small ng-cloak class='text-danger' ng-show="form.interval.$invalid">Short timeout wrong</small>
            </div>
            <div class="form-group">
                <label for="timeout">Reply Timeout</label>
                <input class="form-control" type='number' ng-model="timeout"  class='span12' name='timeout' required min="100" max="5000" integer aria-describedby="bHelp" placeholder="timeout">
                <small id="bHelp" class="form-text text-muted">Modbus reply timeout in ms</small>
                <small ng-cloak class='text-danger' ng-show="form.timeout.$invalid">Timeout out of range</small>
            </div> 
            <div class="form-group">
                <label for="retry">Retry</label>
                <input class="form-control" type='number' ng-model="retry"  class='span12' name='retry' required min="1" max="5" integer aria-describedby="bHelp" placeholder="retry">
                <small id="bHelp" class="form-text text-muted">Number of retries</small>
                <small ng-cloak class='text-danger' ng-show="form.retry.$invalid">Retries out of range</small>
            </div> 
            <div class="form-group">
                <label for="retry_interval">Retry Interval</label>
                <input class="form-control" type='number' ng-model="retry_interval"  class='span12' name='retry_interval' required min="5" max="1000" integer aria-describedby="bHelp" placeholder="retry_interval">
                <small id="bHelp" class="form-text text-muted">Time in ms after which a failed packet is resent</small>
                <small ng-cloak class='text-danger' ng-show="form.retry_interval.$invalid">Retry interval out of range</small>
            </div> 
            <div class="form-group">
                <label for="poll_interval"><? print(lang('POLL_INTERVAL','ezconfig')) ?></label>
                <input class="form-control" type='number' ng-model="poll_interval"  class='span12' name='poll_interval' required min="100" max="60000" integer aria-describedby="tHelp" placeholder="<? print(lang('POLL_INTERVAL','ezconfig')) ?>">
                <small id="tHelp" class="form-text text-muted"><? print(lang('POLL_INTERVAL_HELP','ezconfig')) ?></small>
                <small ng-cloak class='text-danger' ng-show="form.poll_interval.$invalid"><? print(lang('POLL_INTERVAL_INVALID','ezconfig')) ?></small>
            </div>   		
        </p>		            	
      </div>
    </div>
  </div>
<? if ($_SERVER['HW_PLATFORM']==11 || $_SERVER['HW_PLATFORM']>=20) { ?>
<div class="card">
    <div class="card-header panel-heading" id="headingTwo">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          <? print(lang('MODBUS_RTU','ezconfig')) ?> 2 <? print(lang('CONFIGURATION','ezconfig')) ?>&nbsp;<i class='icon icon-caret-down'></i>
        </button>
      </h5>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
    <div class="card-body">
        <h6 class="card-subtitle mb-2 text-muted"><? print(lang('MODBUS_RTU_SUBTITLE','ezconfig')) ?></h6>
        <p class="card-text">    
            <div class="form-group">
                <label for="enabled2"><small class='text-muted'><? print(lang('STATUS','modbusconfig')) ?></small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="enabled2" id="exampleRadios2" value="1">
                  <label class="form-check-label" for="exampleRadios2">
                    &nbsp;<? print(lang('STATUS_ENABLED','modbusconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="enabled2" id="exampleRadios1" value="0">
                  <label class="form-check-label" for="exampleRadios1">
                    &nbsp;<? print(lang('STATUS_DISABLED','modbusconfig')) ?>
                  </label>
                </div>
<? if ($_GLOBALS['VERMINOR'] >= 1297) { ?>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="enabled2" id="exampleRadios3" value="2">
                  <label class="form-check-label" for="exampleRadios3">
                    &nbsp;RTU Bridge
                  </label>
                </div>  
<? } ?>                
                <small id="dnHelp" class="form-text text-muted"><? print(lang('STATUS_HELP','modbusconfig')) ?></small>
            </div>
        
            <div class="form-group">
                <label for="baud_rate2"><? print(lang('BAUD','ezconfig')) ?></label>
                <input class="form-control" type='number' ng-model="baud_rate2"  class='span12' name='baud_rate2' required min="1200" max="115200" integer aria-describedby="bHelp" placeholder="<? print(lang('BAUD','ezconfig')) ?>">
                <small id="bHelp" class="form-text text-muted"><? print(lang('BAUD_HELP','ezconfig')) ?></small>
                <small ng-cloak class='text-danger' ng-show="form.baud_rate2.$invalid"><? print(lang('BAUD_INVALID','ezconfig')) ?></small>
            </div>
            <div class="form-group">
                <label for="parity2"><small class='text-muted'><? print(lang('PARITY','ezconfig')) ?></small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="parity2" id="parity02" value="0">
                  <label class="form-check-label" for="parity02">
                    &nbsp;<? print(lang('PARITY_NONE','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="parity2" id="parity12" value="1">
                  <label class="form-check-label" for="parity12">
                    &nbsp;<? print(lang('PARITY_EVEN','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="parity2" id="parity22" value="2">
                  <label class="form-check-label" for="parity22">
                    &nbsp;<? print(lang('PARITY_ODD','ezconfig')) ?>
                  </label>
                </div>  
                
                <small id="pHelp" class="form-text text-muted"><? print(lang('PARITY_HELP','ezconfig')) ?></small>
            </div>                  
        </p>		            	
           <div class="form-group">
                <label for="interval2">Inter-packet delay</label>
                <input class="form-control" type='number' ng-model="interval2"  class='span12' name='interval2' required min="5" max="300" integer aria-describedby="bHelp" placeholder="Inter packet delay">
                <small id="bHelp" class="form-text text-muted">Inter packet delay</small>
                <small ng-cloak class='text-danger' ng-show="form.interval2.$invalid">Interpacket delay is our of range</small>
            </div>
            <div class="form-group">
                <label for="timeout2">Reply Timeout</label>
                <input class="form-control" type='number' ng-model="timeout2"  class='span12' name='timeout' required min="100" max="5000" integer aria-describedby="bHelp" placeholder="timeout">
                <small id="bHelp" class="form-text text-muted">Modbus reply timeout in ms</small>
                <small ng-cloak class='text-danger' ng-show="form.timeout2.$invalid">Timeout out of range</small>
            </div> 
            <div class="form-group">
                <label for="retry2">Retries</label>
                <input class="form-control" type='number' ng-model="retry2"  class='span12' name='retry2' required min="1" max="5" integer aria-describedby="bHelp" placeholder="retry">
                <small id="bHelp" class="form-text text-muted">Number of retries</small>
                <small ng-cloak class='text-danger' ng-show="form.retry2.$invalid">Retries out of range</small>
            </div> 
	        <div class="form-group">
                <label for="retry_interval2">Retry Interval</label>
                <input class="form-control" type='number' ng-model="retry_interval2"  class='span12' name='retry_interval2' required min="5" max="1000" integer aria-describedby="bHelp" placeholder="retry_interval2">
                <small id="bHelp" class="form-text text-muted">Time in ms after which a failed packet is resent</small>
                <small ng-cloak class='text-danger' ng-show="form.retry_interval2.$invalid">Retry interval out of range</small>
            </div> 

	</div>
	</div>
<? } ?>  
<? if ($_SERVER['HW_PLATFORM']==20) { ?>
<div class="card">
    <div class="card-header panel-heading" id="heading232">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapse232" aria-expanded="false" aria-controls="collapse232">
          RS-232 <? print(lang('CONFIGURATION','ezconfig')) ?>&nbsp;<i class='icon icon-caret-down'></i>
        </button>
      </h5>
    </div>
    <div id="collapse232" class="collapse" aria-labelledby="heading232" data-parent="#accordion">
    <div class="card-body">
        <h6 class="card-subtitle mb-2 text-muted"><? print(lang('MODBUS_RTU_SUBTITLE','ezconfig')) ?></h6>
        <p class="card-text">    
            <div class="form-group">
                <label for="enabled2"><small class='text-muted'><? print(lang('STATUS','modbusconfig')) ?></small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="rs232_enabled" id="exampleRadios1" value="0">
                  <label class="form-check-label" for="exampleRadios1">
                    &nbsp;<? print(lang('STATUS_DISABLED','modbusconfig')) ?>
                  </label>
                </div>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="rs232_enabled" id="exampleRadios3" value="3">
                  <label class="form-check-label" for="exampleRadios3">
                    &nbsp;DLMS Mode
                  </label>
                </div>  
                <small id="dnHelp" class="form-text text-muted"><? print(lang('STATUS_HELP','modbusconfig')) ?></small>
            </div>

            <div class="form-group">
                <label for="enabled2"><small class='text-muted'>DLMS Authentication</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="auth" id="exampleRadios1x" value="0">
                  <label class="form-check-label" for="exampleRadios1x">
                    &nbsp;None
                  </label>
                </div>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="auth" id="exampleRadios3x" value="1">
                  <label class="form-check-label" for="exampleRadios3x">
                    &nbsp;Low
                  </label>
                </div>  
                <small id="dnHelp" class="form-text text-muted">Select Low Authentication with the password below</small>
            </div>
            <div class="form-group">
                <label for="rs232_baud">Auth password</label>
                <input class="form-control" type='text' ng-model="password"  class='span12' name='password'  aria-describedby="bHelp" placeholder="Password">
                <small id="bHelp" class="form-text text-muted">The default password is usually ABCD0001</small>
            </div>
            <div class="form-group">
                <label for="client_id">Client ID</label>
                <input class="form-control" type='text' ng-model="password"  class='span12' name='client_id'  aria-describedby="bHelp" placeholder="Client ID">
                <small id="bHelp" class="form-text text-muted">Enter the client id</small>
            </div>
        
            <div class="form-group">
                <label for="rs232_baud"><? print(lang('BAUD','modbusconfig')) ?></label>
                <input class="form-control" type='number' ng-model="rs232_baud"  class='span12' name='rs232_baud' required min="1200" max="115200" integer aria-describedby="bHelp" placeholder="<? print(lang('BAUD','modbusconfig')) ?>">
                <small id="bHelp" class="form-text text-muted"><? print(lang('BAUD_HELP','modbusconfig')) ?></small>
                <small ng-cloak class='text-danger' ng-show="form.rs232_baud.$invalid"><? print(lang('BAUD_INVALID','modbusconfig')) ?></small>
            </div>
            
        
        </p>		            	

	</div>
	</div>
<? } ?>  

  <div class="card">
    <div class="card-header panel-heading" id="headingThree">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          <? print(lang('MODBUS_TCP','ezconfig')) ?> <? print(lang('CONFIGURATION','ezconfig')) ?>&nbsp;<i class='icon icon-caret-down'></i>
        </button>
      </h5>
    </div>
    
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
      <div class="card-body">
        <h6 class="card-subtitle mb-2 text-muted"><? print(lang('MODBUS_TCP_SUBTITLE','ezconfig')) ?></h6>
        <p class="card-text">    
        <div class="form-group">
                <label for="tcp_enabled"><small class='text-muted'>Enabled</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="tcp_enabled" id="tcp_enabled0" value="0">
                  <label class="form-check-label" for="tcp_enabled0">
                    &nbsp;Disabled
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="tcp_enabled" id="tcp_enabled1" value="1">
                  <label class="form-check-label" for="tcp_enabled1">
                    &nbsp;Enabled
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted"><? print(lang('PARITY_HELP','ezconfig')) ?></small>
            </div>
           <div class="form-group">
                <label for="tcp_interval">Inter-packet delay</label>
                <input class="form-control" type='number' ng-model="tcp_interval"  class='span12' name='tcp_interval' required min="1" max="300" integer aria-describedby="bHelp" placeholder="Inter packet delay">
                <small id="bHelp" class="form-text text-muted">Inter packet delay</small>
                <small ng-cloak class='text-danger' ng-show="form.tcp_interval.$invalid">Interpacket delay is our of range</small>
            </div>
            <div class="form-group">
                <label for="tcp_timeout">Reply Timeout</label>
                <input class="form-control" type='number' ng-model="tcp_timeout"  class='span12' name='tcp_timeout' required min="100" max="5000" integer aria-describedby="bHelp" placeholder="timeout">
                <small id="bHelp" class="form-text text-muted">Modbus TCP reply timeout in ms</small>
                <small ng-cloak class='text-danger' ng-show="form.tcp_timeout.$invalid">Timeout out of range</small>
            </div> 
            <div class="form-group">
                <label for="tcp_retry">Retries</label>
                <input class="form-control" type='number' ng-model="tcp_retry"  class='span12' name='tcp_retry' required min="1" max="5" integer aria-describedby="bHelp" placeholder="retry">
                <small id="bHelp" class="form-text text-muted">Number of retries</small>
                <small ng-cloak class='text-danger' ng-show="form.tcp_retry.$invalid">Retries out of range</small>
            </div> 
            <div class="form-group">
                <label for="tcp_retry_interval">Retry Interval</label>
                <input class="form-control" type='number' ng-model="tcp_retry_interval"  class='span12' name='tcp_retry_interval' required min="5" max="1000" integer aria-describedby="bHelp" placeholder="tcp_retry_interval">
                <small id="bHelp" class="form-text text-muted">Time in ms after which a failed packet is resent</small>
                <small ng-cloak class='text-danger' ng-show="form.tcp_retry_interval.$invalid">Retry interval out of range</small>
            </div> 
        
        <? for ($x=0;$x<NUM_TCP_CHANNELS;$x++) { ?>
        
        <div class="card">
            <div class="card-body">
                <h5 class="card-title"><? print(lang('MODBUS_TCP_CHANNEL','modbusconfig')." ".($x+1)) ?></h5>
                <p class="card-text">    
                	<div class="form-group">
                        <label for="tcp<? print($x); ?>_s">TCP Server Mode</label>
                        
                        <input type="checkbox" ng-model="tcp<? print($x); ?>_s" ng-true-value="1" ng-false-value="0">
        
                        <small id="dnHelp<? print($x); ?>" class="form-text text-muted">Select this to turn this channel into a Modbus TCP Listener server</small>
                    </div>
                   
                	<div class="form-group" ng-hide="tcp<? print($x); ?>_s==1">
                        <label for="tcp<? print($x); ?>_ip"><? print(lang('IP_ADDRESS','modbusconfig')) ?></label>
                        <input type="text" class="form-control" ng-model="tcp<? print($x); ?>_ip"  class='span12' name='tcp<? print($x); ?>_ip' required aria-describedby="dnHelp<? print($i); ?>" my-directive placeholder="<? print(lang('IP_ADDRESS','modbusconfig')) ?>">
                        <small id="dnHelp<? print($x); ?>" class="form-text text-muted"><? print(lang('IP_ADDRESS_HELP','modbusconfig')) ?></small>
                        <small ng-cloak class='text-danger' ng-show="form.tcp<? print($x); ?>_ip.$invalid"><? print(lang('IP_ADDRESS_INVALID','modbusconfig')) ?></small>
                    </div>
                	<div class="form-group">
                        <label for="tcp<? print($x); ?>_port"><? print(lang('PORT','modbusconfig')) ?></label>
                        <input type="text" class="form-control" ng-model="tcp<? print($x); ?>_port"  class='span12' name='tcp<? print($x); ?>_port'  aria-describedby="dnpHelp<? print($x); ?>"  placeholder="<? print(lang('PORT','modbusconfig')) ?>">
                        <small id="dnpHelp<? print($x); ?>" class="form-text text-muted"><? print(lang('PORT_HELP','modbusconfig')) ?></small>
                        
                    </div>
                </p>
            </div>
        </div>		

        
        <? } ?>            
        </p>
      </div>
    </div>
  </div>
</div>


<br/>

<div class="card">
    <div class="card-body">
        <h5 class="card-title text-warning"><? print(lang('POWER_METERS','ezconfig')) ?></h5>
        <h6 class="card-subtitle mb-2 text-muted"><? print(lang('POWER_METERS_COUNT','ezconfig')) ?>: <strong>{{pm_count}}</strong></h6>
        <p class="card-text">    
            <div class='pull-right'><a name='addpm'></a><ng-button ng-disabled='power_meters.length==0' class="btn btn-primary" ng-click="addPM()"><i class="icon-plus"></i>&nbsp;<? print(lang('ADD','ezconfig')) ?></ng-button></div>
            <table class='table table-striped' summary="Meters" >
                <tr>
                    <td scope="col"></td>
                    <td scope="col"><? print(lang('DEVICE','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('ADDRESS','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('BUS','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('NAME','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('TYPE','ezconfig')) ?>&nbsp;<a href="#addpm" data-toggle="tooltip" title="Select where your meter is hooked up physically for the visualization widget to show it properly."><span class='badge badge-dark'>?</span></a></td>
                    <td scope="col">Rating (kVA)&nbsp;<a href="#addpm" data-toggle="tooltip" title="Enter the rating of the DG in kVA to calculate miminum loading"><span class='badge badge-dark'>?</span></a></td>
<? if ($use_qos) { ?>                    
                    <td scope="col">QOS Type</td>
<? } ?>                
                    <td scope="col"><? print(lang('OPTIONS','ezconfig')) ?></td>
                </tr>
                <tr ng-repeat="item in pm">
                    <td>
                        <a name='pm{{$index}}'></a><span class="badge badge-warning badge-pill">{{$index+1}}</span>
                    </td>
                    <td>
                        <div ng-show='item.edit!=1'><strong>{{get_pm_name(item.device_type_id)}}</strong></div><div ng-show='item.edit==1'>
                        <select class="form-control" ng-options="vitem.device_type_id as vitem.name for vitem in power_meters" ng-model="item.device_type_id" class='span12'>
                		      <option value="{{vitem.device_type_id}}">{{vitem.name}}</option>       
                		 </select>
                        </div>
                    </td>            
                    <td><div ng-show='item.edit!=1'><span class='badge badge-secondary'>{{item.id}}</span></div><div ng-show='item.edit==1'>
                         <input class="form-control" type='text' class='span12' ng-model='item.id'>
                        </div></td>
                
                    <td><div ng-show='item.edit!=1'>{{makeBus(item.bus)}}</div><div ng-show='item.edit==1'>
                          <select class="form-control" ng-options="vbus2.idx as vbus2.name for vbus2 in bus" ng-model="item.bus">
                		      <option value="{{vbus2.idx}}">{{vbus2.name}}</option>       
                		 </select>
                        </div></td>
                    <td><div ng-show='item.edit!=1'>{{item.device_name}}</div><div ng-show='item.edit==1'>
                         <input type='text' class="form-control" ng-model='item.device_name'>
                        </div></td>
                    <td><div ng-show='item.edit!=1'><i>{{makeType(item.type)}}</i></div><div ng-show='item.edit==1'>
                            <select ng-model="item.type" class="form-control">
                    		               <option value="0"><? print(lang('UNDEFINED','ezconfig')) ?></option>
                    		               <option value="1"><? print(lang('GENSET','ezconfig')) ?></option>       
                    		               <option value="2"><? print(lang('INCOMER','ezconfig')) ?></option>       
                    		               <option value="3"><? print(lang('INVERTER_OUTPUT','ezconfig')) ?></option>       
                    		               <option value="4"><? print(lang('BUILDING_LOAD','ezconfig')) ?></option>
                    		               <option value="5">ESS (Battery)</option>
                    		               
                    		    </select>
                            </div>
                        </td>   
                        <td><div ng-show='item.edit!=1 && item.type==1'>{{item.dg_rating}}</div><div ng-show='item.edit==1  && item.type==1'>
                          <input type='text' class="form-control" ng-model='item.dg_rating'>
                        </div></td>
<? if ($use_qos) { ?>           

                     <td><div ng-show='item.edit!=1'>{{item.category}}</div>
                     <div ng-show='item.edit==1'>
                                <select ng-model="item.category" class='form-control'>
                                    <option value='PV_INVERTER'>PV INVERTER</option>
                                    <option value='BATTERY_INVERTER'>BATTERY_INVERTER</option>
                                    <option value='ENERGY_METER'>ENERGY_METER</option>
                                    <option value='SWITCHGEAR'>SWITCHGEAR</option>
                                    <option value='NETWORK_PROTECTION'>NETWORK_PROTECTION</option>
                                    <option value='TRACKER'>TRACKER</option>
                                    <option value='BATTERY'>BATTERY</option>
                                    <option value='GENSET'>GENSET</option>
                                    <option value='STRING_MONITORING'>STRING_MONITORING</option>
                                    <option value='COMBINER_BOX'>COMBINER_BOX</option>
                                    <option value='WEATHER_STATION'>WEATHER_STATION</option>
                                    <option value='UPS'>UPS</option>
                                    <option value='POWER_PLANT_CONTROLER'>POWER_PLANT_CONTROLER</option>
                                </select>

                    </div></td>   
<? } ?>                    
                    <td>
                        <div class="dropdown">
                            <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <? print(lang('ACTION','ezconfig')) ?> <span class="caret"></span>
                            </button>
                        
                            <div class="dropdown-menu dropdown-menu-right text-dark" >
                                <a class="dropdown-item" ng-show='item.edit!=1' ng-click='item.edit=1' href='javascript:void(0);'><i class="icon-pencil"></i>&nbsp;<? print(lang('EDIT','ezconfig')) ?></a>
                                <a class="dropdown-item" ng-show='item.edit==1' ng-click='item.edit=0' href='javascript:void(0);'><i class="icon-pencil"></i>&nbsp;<? print(lang('STOP_EDIT','ezconfig')) ?></a>
                                <a class="dropdown-item" ng-click='delPM($index)' href='#addpm'><i class="icon-remove"></i>&nbsp;<? print(lang('DELETE','ezconfig')) ?></a>                                    
                                </div>
                            </div>
                        </div>
                    </td>
                    
                </tr>
            </table> 
        </p>
    </div>
</div>

<br/>
<div class="card">
    <div class="card-body">
        <h5 class="card-title text-success"><? print(lang('INVERTERS','ezconfig')) ?></h5>
        <h6 class="card-subtitle mb-2 text-muted"><? print(lang('INVERTER_COUNT','ezconfig')) ?>: <strong>{{inv_count}}</strong></h6>
        <p class="card-text">    
            <div class='pull-right'><a name='addinv'></a><ng-button ng-disabled='inverters.length==0' class="btn btn-primary" ng-click="addInv()"><i class="icon-plus"></i>&nbsp;<? print(lang('ADD','ezconfig')) ?></ng-button></div>
            <table class='table table-striped' summary="Inverters" > 
                <tr>
                    <td scope="col"></td>
                    <td scope="col">Make</td>
                    <td scope="col">Model</td>
                    <td scope="col"><? print(lang('ADDRESS','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('BUS','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('NAME','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('RATING','ezconfig')) ?> <a href="#addinv" data-toggle="tooltip" title="Select the inverter rating in kW - this can be used for power control."><span class='badge badge-dark'>?</span></a></td>
<? if ($use_qos) { ?>                                        
                    <td scope="col">QOS Type</td>
<? } ?>                    
                    <td scope="col"><? print(lang('OPTIONS','ezconfig')) ?></td>
                </tr>
                <tr ng-repeat="item in inv">
                    <td><a name='inv{{$index}}'></a><span class="badge badge-success badge-pill">{{$index+1}}</span></td>
                    <td><div ng-show='item.edit!=1'><strong>{{get_inv_make(item.device_type_id)}}</strong></div><div ng-show='item.edit==1'>
                        <select class="form-control" ng-options="vitem.make as vitem.make for vitem in inverter_makes" ng-model="item.make" class='span12'>
                		      <option value="{{vitem.make}}">{{vitem.make}}</option>       
                		 </select>
                        </div>
                		 
                	</td>
                	<td><div ng-show='item.edit!=1'><strong>{{get_inv_model(item.device_type_id)}}</strong></div><div ng-show='item.edit==1'>
                        <select class="form-control" ng-change='setModel($index)' ng-options="vitem.device_type_id as vitem.model for vitem in inverters | filter:{make:item.make}" ng-model="item.device_type_id" class='span12'>
                		      <option value="{{vitem.device_type_id}}">{{vitem.model}}</option>       
                		 </select>
                        </div>
<!--                        <select class="form-control" ng-options="vitem.device_type_id as vitem.name for vitem in inverters" ng-model="item.device_type_id" class='span12'>
                		      <option value="{{vitem.device_type_id}}">{{vitem.name}}</option>       
                		 </select>-->
                    </td>            
                    <td><div ng-show='item.edit!=1'><span class="badge badge-secondary">{{item.id}}</span></div><div ng-show='item.edit==1'>
                         <input class="form-control" type='text' class='span12' ng-model='item.id'>
                        </div></td>
                
                    <td><div ng-show='item.edit!=1'>{{makeBus(item.bus)}}</div><div ng-show='item.edit==1'>
                          <select class="form-control" ng-options="vbus.idx as vbus.name for vbus in bus" ng-model="item.bus" class='span12'>
                		      <option value="{{vbus.idx}}">{{vbus.name}}</option>       
                		 </select>
                        </div></td>
                    <td><div ng-show='item.edit!=1'>{{item.device_name}}</div><div ng-show='item.edit==1'>
                         <input class="form-control" type='text' class='span12' ng-model='item.device_name'>
                        </div></td>
                    <td><div ng-show='item.edit!=1'>{{item.rating}}</div><div ng-show='item.edit==1'>
                         <input class="form-control" type='text' class='span12' ng-model='item.rating'>
                        </div>
                    </td>
<? if ($use_qos) { ?>                                        
                    <td>{{item.category}}
                     <div ng-show='item.edit==1'>
                                <select ng-model="item.category" class='form-control'>
                                    <option value='PV_INVERTER'>PV INVERTER</option>
                                    <option value='BATTERY_INVERTER'>BATTERY_INVERTER</option>
                                    <option value='ENERGY_METER'>ENERGY_METER</option>
                                    <option value='SWITCHGEAR'>SWITCHGEAR</option>
                                    <option value='NETWORK_PROTECTION'>NETWORK_PROTECTION</option>
                                    <option value='TRACKER'>TRACKER</option>
                                    <option value='BATTERY'>BATTERY</option>
                                    <option value='GENSET'>GENSET</option>
                                    <option value='STRING_MONITORING'>STRING_MONITORING</option>
                                    <option value='COMBINER_BOX'>COMBINER_BOX</option>
                                    <option value='WEATHER_STATION'>WEATHER_STATION</option>
                                    <option value='UPS'>UPS</option>
                                    <option value='POWER_PLANT_CONTROLER'>POWER_PLANT_CONTROLER</option>
                                </select>

                    </div></td> 
<? } ?>                    
                    <td>
                    <div class="dropdown">
                        <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                <? print(lang('ACTION','ezconfig')) ?> <span class="caret"></span>
                        </button>
                        
                        <div class="dropdown-menu dropdown-menu-right text-dark" >
                                <a class="dropdown-item" ng-show='item.edit!=1' ng-click='item.edit=1' href='javascript:void(0);'><i class="icon-pencil"></i>&nbsp;<? print(lang('EDIT','ezconfig')) ?></a>
                                <a class="dropdown-item" ng-show='item.edit==1' ng-click='item.edit=0' href='javascript:void(0);'><i class="icon-pencil"></i>&nbsp;<? print(lang('STOP_EDIT','ezconfig')) ?></a>
                                <a class="dropdown-item" ng-click='delInv($index)' href='#addinv'><i class="icon-remove"></i>&nbsp;<? print(lang('DELETE','ezconfig')) ?></a>                                    
                                </div>
                            </div>
                        </div>
                    </td>    
                </tr>
            </table> 
        </p>
    </div>
</div>    
<br/>
<div class="card">
    <div class="card-body">
        <h5 class="card-title text-primary"><? print(lang('OTHER_DEVICES','ezconfig')) ?></h5>
        <h6 class="card-subtitle mb-2 text-muted"><? print(lang('OTHER_DEVICES_COUNT','ezconfig')) ?>: <strong>{{other_count}}</strong></h6>
        <p class="card-text">    
            <div class='pull-right'><a name='addod'></a><ng-button ng-disabled='other_devices.length==0' class="btn btn-primary" ng-click="addOD()"><i class="icon-plus"></i>&nbsp;<? print(lang('ADD','ezconfig')) ?></ng-button></div>
            <table class='table table-striped' summary="Other devices" >
                <tr>
                    <td scope="col"></td>
                    <td scope="col"><? print(lang('DEVICE','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('ADDRESS','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('BUS','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('NAME','ezconfig')) ?></td>
<? if ($use_qos) { ?>                                        
                    <td scope="col">QOS Type</td>
<? } ?>                    
                    <td scope="col"><? print(lang('OPTIONS','ezconfig')) ?></td>
                </tr>
                <tr ng-repeat="item in other">
                    <td>
                        <a name='other{{$index}}'></a><span class="badge badge-primary badge-pill">{{$index+1}}</span>
                    </td>
                    <td>
                        <div ng-show='item.edit!=1'><strong>{{get_other_name(item.device_type_id)}}</strong></div><div ng-show='item.edit==1'>
                        <select class="form-control" ng-options="vitem.device_type_id as vitem.name for vitem in other_devices | orderBy: 'name'" ng-model="item.device_type_id" class='span12'>
                		      <option value="{{vitem.device_type_id}}">{{vitem.name}} ({{vitem.device_type_id}})</option>       
                		 </select>
                        </div>
                    </td>            
                    <td><div ng-show='item.edit!=1'><span class='badge badge-secondary'>{{item.id}}</span></div><div ng-show='item.edit==1'>
                         <input class="form-control" type='text' class='span12' ng-model='item.id'>
                        </div></td>
                
                    <td><div ng-show='item.edit!=1'>{{makeBus(item.bus)}}</div><div ng-show='item.edit==1'>
                          <select class="form-control" ng-options="vbus2.idx as vbus2.name for vbus2 in bus" ng-model="item.bus">
                		      <option value="{{vbus2.idx}}">{{vbus2.name}}</option>       
                		 </select>
                        </div></td>
                    <td><div ng-show='item.edit!=1'>{{item.device_name}}</div><div ng-show='item.edit==1'>
                         <input type='text' class="form-control" ng-model='item.device_name'>
                        </div></td>
<? if ($use_qos) { ?>                                            
                        <td>{{item.category}}
                     <div ng-show='item.edit==1'>
                                <select ng-model="item.category" class='form-control'>
                                    <option value='PV_INVERTER'>PV INVERTER</option>
                                    <option value='BATTERY_INVERTER'>BATTERY_INVERTER</option>
                                    <option value='ENERGY_METER'>ENERGY_METER</option>
                                    <option value='SWITCHGEAR'>SWITCHGEAR</option>
                                    <option value='NETWORK_PROTECTION'>NETWORK_PROTECTION</option>
                                    <option value='TRACKER'>TRACKER</option>
                                    <option value='BATTERY'>BATTERY</option>
                                    <option value='GENSET'>GENSET</option>
                                    <option value='STRING_MONITORING'>STRING_MONITORING</option>
                                    <option value='COMBINER_BOX'>COMBINER_BOX</option>
                                    <option value='WEATHER_STATION'>WEATHER_STATION</option>
                                    <option value='UPS'>UPS</option>
                                    <option value='POWER_PLANT_CONTROLER'>POWER_PLANT_CONTROLER</option>
                                </select>

                    </div></td>
<? } ?>                    
                    <td>
                        <div class="dropdown">
                            <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <? print(lang('ACTION','ezconfig')) ?> <span class="caret"></span>
                            </button>
                        
                            <div class="dropdown-menu dropdown-menu-right text-dark" >
                                <a class="dropdown-item" ng-show='item.readonly!=1 && item.edit!=1' ng-click='item.edit=1' href='javascript:void(0);'><i class="icon-pencil"></i>&nbsp;<? print(lang('EDIT','ezconfig')) ?></a>
                                <a class="dropdown-item" ng-show='item.readonly!=1 && item.edit==1' ng-click='item.edit=0' href='javascript:void(0);'><i class="icon-pencil"></i>&nbsp;<? print(lang('STOP_EDIT','ezconfig')) ?></a>
                                <a class="dropdown-item" ng-click='delOD($index)' href='#addpm'><i class="icon-remove"></i>&nbsp;<? print(lang('DELETE','ezconfig')) ?></a>                                    
                                </div>
                            </div>
                        </div>
                    </td>
                    
                </tr>
            </table> 
        </p>
    </div>
</div>
<br/>
<div class="card" ng-show='use_temp>0'>
    <div class="card-body">
        <h5 class="card-title text-primary">1-Wire Temperature Sensors</h5>
        <h6 class="card-subtitle mb-2 text-muted">Number of 1-Wire Sensors: <strong>{{ow_count}}</strong></h6>
        <p class="card-text">    
            <table class='table table-striped' summary="Other devices" >
                <tr>
                    <td scope="col"></td>
                    <td scope="col"><? print(lang('DEVICE','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('NAME','ezconfig')) ?></td>
                    <td scope="col"><? print(lang('OPTIONS','ezconfig')) ?></td>
                </tr>
                <tr ng-repeat="item in ow">
                    <td>
                        <a name='ow{{$index}}'></a><span class="badge badge-primary badge-pill">{{$index+1}}</span>
                    </td>
                    <td>
                        <div ng-show='item.edit!=1'><strong>{{item.device_address}} ({{ow_sensors[item.device_idx].temperature|number:1}}&deg;C)</strong></div><div ng-show='item.edit==1'>
                        <select class="form-control" ng-options="vitem.device_address as vitem.device_address for vitem in ow_sensors" ng-model="item.device_address" class='span12'>
                		      <option value="{{vitem.device_address}}">{{vitem.device_address}} ({{vitem.temperature}}&deg;C)</option>       
                		 </select>
                        </div>
                    </td>            
                    <td><div ng-show='item.edit!=1'>{{item.name}}</div><div ng-show='item.edit==1'>
                         <input type='text' class="form-control" ng-model='item.name'>
                        </div></td>
                    <td>
                        <div class="dropdown">
                            <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <? print(lang('ACTION','ezconfig')) ?> <span class="caret"></span>
                            </button>
                        
                            <div class="dropdown-menu dropdown-menu-right text-dark" >
                                <a class="dropdown-item" ng-show='item.readonly!=1 && item.edit!=1' ng-click='item.edit=1' href='javascript:void(0);'><i class="icon-pencil"></i>&nbsp;<? print(lang('EDIT','ezconfig')) ?></a>
                                <a class="dropdown-item" ng-show='item.readonly!=1 && item.edit==1' ng-click='item.edit=0' href='javascript:void(0);'><i class="icon-pencil"></i>&nbsp;<? print(lang('STOP_EDIT','ezconfig')) ?></a>
                                <a class="dropdown-item" ng-click='delOW($index)' href='#addow'><i class="icon-remove"></i>&nbsp;<? print(lang('DELETE','ezconfig')) ?></a>
                                </div>
                            </div>
                        </div>
                    </td>
                    
                </tr>
            </table> 
        </p>
    </div>
</div>
<br/>
<div id="accordion">
  <div class="card">
    <div class="card-header panel-heading" id="headingPkg">
      <h5 class="mb-0">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapsePkg" aria-expanded="true" aria-controls="collapsePkg">
          ADDITIONAL PACKAGES&nbsp;<i class='icon icon-caret-down'></i>
        </button>
      </h5>
    </div>

    <div id="collapsePkg" class="collapse" aria-labelledby="headingPkg" data-parent="#accordion">
      <div class="card-body">
        <h6 class="card-subtitle mb-2 text-muted">Select the packages you wish to install</h6>
        <p class="card-text">    
            <table class='table table-striped' summary="Packages" >
                <tr>
                    <td scope="col"></td>
                    <td scope="col">Install</td>
                    <td scope="col">Name</td>
                    <td scope="col">Description</td>
                    <td scope="col">Version</td>
                </tr>
                <tr ng-repeat="item in package">
                    <td>
                        <a name='pkg{{$index}}'></a><span class="badge badge-primary badge-pill">{{$index+1}}</span>
                    </td>
                    <td>
                        <input ng-checkbox type='checkbox' ng-model="item.selected" ng-click='pkgChanged(item)'>
                    </td>
                    <td>
                        {{item.name}}
                    </td>
                    <td>
                        {{item.description}}
                    </td>
                    <td>
                        {{item.version}}
                    </td>
                </tr>
            </table>
        </p>
    </div>
  </div>
</div>
    
</br>


<div class="card">
    <div class="card-body">
        <h5 class="card-title text-info"><? print(lang('ADDITIONAL_OPTIONS','ezconfig')) ?></h5>
        <p class="card-text">    
<!--        
            <div class="form-group">
                <label for="static_header"><small class='text-muted'>Use Static Headers</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="static_header" id="static_headers0" value="0">
                  <label class="form-check-label" for="static_headers0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="static_header" id="static_headers1" value="1">
                  <label class="form-check-label" for="static_headers1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted">Use this option to reduce processing overheads when uploading data to the cloud.  If you modify the data log manually you will need to delete /config/csv_headers.txt manually to regenerate it.</small>
            </div>
            
            <div class="form-group">
                <label for="firmware_logging"><small class='text-muted'>Firmware Logging</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="firmware_logging" id="firmware_logging0" value="0">
                  <label class="form-check-label" for="firmware_logging0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="firmware_logging" id="firmware_logging1" value="1">
                  <label class="form-check-label" for="firmware_logging1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted">Generate CSV lines for logging through the firmware - FW x.200 + only</small>
            </div>             
            -->
            <div class="form-group">
                <label for="pyranometer"><small class='text-muted'><strong><? print(lang('PYRA300','ezconfig')) ?></strong></small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="pyranometer" id="pyranometer0" value="0">
                  <label class="form-check-label" for="pyranometer0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="pyranometer" id="pyranometer1" value="1">
                  <label class="form-check-label" for="pyranometer1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted"><? print(lang('PYRA300_HELP','ezconfig')) ?></small>
            </div> 
            
            <div class="form-group" ng-show='pyranometer==1'>
                <label for="dc_plant_size">DC Plant Size</label>
                <input class="form-control" type='text' ng-model="dc_plant_size"  class='span12' name='dc_plant_size' aria-describedby="bHelp" placeholder="Plant size kw">
                <small id="bHelp" class="form-text text-muted">DC Plant size in kWp</small>
            </div>
            <div class="form-group" ng-show='pyranometer==1'>
                <label for="fixed_pr">Fixed PR</label>
                <input class="form-control" type='text' ng-model="fixed_pr"  class='span12' name='fixed_pr' aria-describedby="bHelp" placeholder="PR">
                <small id="bHelp" class="form-text text-muted">Fixed PR for Potential kW calculation.  Set to 0.8 as starting point.</small>
            </div>
            <div class="form-group">
                <label for="log_interval">CSV Log Interval</label>
                <select ng-model="log_interval" class='form-control'>
                    <option value='1'>1 Minute</option>
                    <option value='5'>5 Minutes</option>
                    <option value='10'>10 Minutes</option>
                    <option value='15'>15 Minutes</option>
                </select>
                <small id="bHelp" class="form-text text-muted">Choose the log interval in minutes (Only 1 entry in the CSV file every X minutes)</small>
            </div>
            <div class="form-group">
                <label for="log_write_interval">CSV Log Write Interval</label>
                <select ng-model="log_write_interval" class='form-control'>
                    <option value='1'>1 Minute</option>
                    <option value='5'>5 Minutes</option>
                    <option value='10'>10 Minutes</option>
                    <option value='15'>15 Minutes</option>
                </select>
                <small id="bHelp" class="form-text text-muted">To optimize SD card life, you can choose to log to disk at a lower rate than the CSV log interval.  This will mean data will be in memory and could potentially be lost if the device reboots before it is written.</small>
            </div>
            
<hr>    

            <div class="form-group">
                <label for="module_power_control"><small class='text-muted'><strong><? print(lang('POWER_CONTROL','ezconfig')) ?></strong></small></label>
<? if (file_exists("/package/PC.ini")) { ?>                
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="module_power_control" id="module_power_control0" value="0">
                  <label class="form-check-label" for="module_power_control0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="module_power_control" id="module_power_control1" value="1">
                  <label class="form-check-label" for="module_power_control1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted"><? print(lang('POWER_CONTROL_HELP','ezconfig')) ?></small>
<? } else { ?>
            <br/><strong>The PC (Power control) package was not found.  Please install it through the WattmonOS update page if required.</strong>
<? } ?>
            </div>      
            <div class="form-group" ng-show='module_power_control==1'>
                <label for="license_key">License Key</label>
                <input class="form-control" type='text' ng-model="license_key"  class='span12' name='license_key' aria-describedby="bHelp" placeholder="Enter License Key">
                <small id="bHelp" class="form-text text-muted">Enter a license key supplied by Wattmon to activate power control</small>
            </div>
            
            <div class="form-group" ng-show='module_power_control==1'>
                <label for="track_curtailment"><small class='text-muted'>Track Curtailment</small></label>
                <span ng-show='pyranometer==1'>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="track_curtailment" id="track_curtailment0" value="0">
                  <label class="form-check-label" for="track_curtailment0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="track_curtailment" id="track_curtailment1" value="1">
                  <label class="form-check-label" for="track_curtailment1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                </span>
                <span ng-show='pyranometer!=1' class="text-muted"> <br><b>No - This feature requires that you use a Pyranometer - please enable the option first</b> </span>
                <small id="pHelp" class="form-text text-muted">Keep track of generation loss due to curtailment</small>
            </div>
            <div class="form-group" ng-show='module_power_control==1'>
                <label for="sync_power_control"><small class='text-muted'>Update Power Control Settings Automatically</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="sync_power_control" id="sync_power_control0" value="0">
                  <label class="form-check-label" for="sync_power_control0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="sync_power_control" id="sync_power_control1" value="1">
                  <label class="form-check-label" for="sync_power_control1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                <span ng-show='sync_power_control==1'><br><div class="alert alert-danger" ng-cloak><div class='row-fluid'><div class='pull-left'><i class="icon-warning-sign icon-2x"></i></div>
            <div style='margin-left:5em'>If you are using advanced power control settings, it is recommended to disable this option to avoid overwriting those options.</div></span></div></div>
                <small id="pHelp" class="form-text text-muted">Automatically update the power control settings with calculated values based on your settings.</small>
            </div>  
<hr>
                    
            <div class="form-group">
                <label for="ws102"><small class='text-muted'><? print(lang('WS102','ezconfig')) ?></small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="ws102" id="ws1020" value="0">
                  <label class="form-check-label" for="ws1020">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="ws102" id="ws1021" value="1">
                  <label class="form-check-label" for="ws1021">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted"><? print(lang('WS102_HELP','ezconfig')) ?></small>
            </div>  
            
            
            <div class="form-group">
                <label for="snapshot"><small class='text-muted'>Create automatic snapshot after generating</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="snapshot" id="snapshot0" value="0">
                  <label class="form-check-label" for="snapshot0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="snapshot" id="snapshot1" value="1">
                  <label class="form-check-label" for="snapshot1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted">This will automatically create a snapshot of your settings that can be restored later.</small>
            </div>       
<? if ($_SERVER['HW_PLATFORM']==20) { ?>            
            <div class="form-group">
                <label for="log_drive"><small class='text-muted'>CSV logging location</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="log_drive" id="log_drive0" value="0">
                  <label class="form-check-label" for="log_drive0">
                    &nbsp;SD Card
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="log_drive" id="log_drive1" value="1">
                  <label class="form-check-label" for="log_drive1">
                    &nbsp;Internal Flash
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted">Internal flash can be used to log CSV data but due to space constraints it is recommended to use an SD card</small>
            </div>             
            
            <div class="form-group" ng-show='use_temp==1'>
                <label for="num_temp"><small class='text-muted'><? print(lang('NUM_TEMP','ezconfig')) ?></small></label>
                <input class="form-control" type='number' min=0 max=15 ng-model="num_temp"  class='span12' name='num_temp' aria-describedby="bHelp" placeholder="<? print(lang('NUM_TEMP','ezconfig')) ?>">
                <small id="bHelp" class="form-text text-muted"><? print(lang('NUM_TEMP_HELP','ezconfig')) ?></small>
            </div>
<? } ?>            
<? if ($has_onewire) { ?>            
            <div class="form-group">
                <label for="use_temp"><small class='text-muted'><? print(lang('TEMP','ezconfig')) ?> (<strong><? print($num_onewire); ?> detected</strong>)</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="use_temp" id="use_temp0" value="0">
                  <label class="form-check-label" for="use_temp0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="use_temp" id="use_temp1" value="1">
                  <label class="form-check-label" for="use_temp1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted"><? print(lang('TEMP_HELP','ezconfig')) ?></small>
            </div>             
            
            <div class="form-group" ng-show='use_temp==1'>
                <label for="num_temp"><small class='text-muted'><? print(lang('NUM_TEMP','ezconfig')) ?></small></label>
                <input class="form-control" type='number' min=0 max=15 ng-model="num_temp"  class='span12' name='num_temp' aria-describedby="bHelp" placeholder="<? print(lang('NUM_TEMP','ezconfig')) ?>">
                <small id="bHelp" class="form-text text-muted"><? print(lang('NUM_TEMP_HELP','ezconfig')) ?></small>
            </div>
<? } ?>
            <div class="form-group">
                <label for="ota_packages"><small class='text-muted'>Automatically Update Packages</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="ota_packages" id="ota_packages0" value="0">
                  <label class="form-check-label" for="ota_packages0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="ota_packages" id="ota_packages1" value="1">
                  <label class="form-check-label" for="ota_packages1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted">When a new package that is installed (i.e. PC) is available online, automatically download and install it</small>
            </div>  
            <div class="form-group">
                <label for="ota_firmware"><small class='text-muted'>Automatically Update Firmware</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="ota_firmware" id="ota_firmware0" value="0">
                  <label class="form-check-label" for="ota_firmware0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="ota_firmware" id="ota_firmware1" value="1">
                  <label class="form-check-label" for="ota_firmware1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted">When a new firmware is available online, automatically download and install it</small>
            </div>  
        <div class="form-group">
                <label for="ota_healing"><small class='text-muted'>Automatic Healing</small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="ota_healing" id="ota_healing0" value="0">
                  <label class="form-check-label" for="ota_healing0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="ota_healing" id="ota_healing1" value="1">
                  <label class="form-check-label" for="ota_healing1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted">Scan all scripts daily and if any mismatch is found, automatically restore it from the repository if available</small>
            </div>  
            <div class="form-group">
                <label for="module_devices"><small class='text-muted'><? print(lang('DEVICE_INFO','ezconfig')) ?></small></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="module_devices" id="module_devices0" value="0">
                  <label class="form-check-label" for="module_devices0">
                    &nbsp;<? print(lang('NO','ezconfig')) ?>
                  </label>
                </div>  
                <div class="form-check">
                  <input class="form-check-input" type="radio" ng-model="module_devices" id="module_devices1" value="1">
                  <label class="form-check-label" for="module_devices1">
                    &nbsp;<? print(lang('YES','ezconfig')) ?>
                  </label>
                </div>  
                
                
                <small id="pHelp" class="form-text text-muted"><? print(lang('DEVICE_INFO_HELP','ezconfig')) ?></small>
            </div>  
        </p>
    </div>
    
</div>
<br/>
<div class="alert alert-success" ng-cloak ng-show="successmsg"> <button type="button" class="close" ng-click='successmsg=""'>&times;</button>{{successmsg}}</div>
<div class="alert alert-danger" ng-cloak ng-show="errormsg"> <button type="button" class="close" ng-click='errormsg=""'>&times;</button>{{errormsg}}</div>
<div class="alert alert-info" ng-cloak ng-show="infomsg"> <button type="button" class="close" data-dismiss="alert">&times;</button>{{infomsg}}</div>
<div class="alert alert-secondary" ng-cloak ng-show="loading"><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></div>
<div class="splash" ng-cloak="">
    <p><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></p>
  </div>
<ul class="nav justify-content-end">
  <li class="nav-item">
    <a class="nav-link" onclick="document.location='/app/settings.cgi';"><i class="icon-remove"></i> <? print(lang('CLOSE','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="saveSettings(0)" ><i class="icon-check"></i> <? print(lang('APPLY','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="saveSettings(1)" ><i class="icon-arrow-right"></i> <? print(lang('SAVE_NEXT','ezconfig')) ?></a>
  </li>
  
</ul>
<br/>
</form>
<script>

 $('.panel-collapse').on('show.bs.collapse', function () {
    $(this).siblings('.panel-heading').addClass('active');
  });

  $('.panel-collapse').on('hide.bs.collapse', function () {
    $(this).siblings('.panel-heading').removeClass('active');
  })
var gItems,gHttp;
var count=0;
var app = angular.module('myApp', []);
  app.directive('myDirective', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, mCtrl) {
      function myValidation(value) {
        console.log(value);
        
        var regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
        if(regex.test(value) == false){
            mCtrl.$setValidity('charE', false);
          
        } else {
            mCtrl.$setValidity('charE', true);
        }
        return value;
      }
      mCtrl.$parsers.push(myValidation);
    }
  };
});
function EZConfigWidget($scope, $timeout,$http) {
   var self = this;
   //alert('init');
   //4028,4099,4098,4024,4023
   $scope.package=[];
   $scope.power_meter_types=[<? 
   $pm_types=implode(array_keys($all_meters),',');
   print($pm_types);
   
   /*$pm_types=ini_get('/config/EZConfigTypes.ini','config','pm_types','');
   
   $done=0;
   $cnt=2;
   while (!$done) {
    $pm_types2=ini_get('/config/EZConfigTypes.ini','config','pm_types'.$cnt,'');
    if ($pm_types2) {
        $pm_types.=",".$pm_types2;
        $cnt++;
    } else $done=1;
   }
   if (!$pm_types) {
        $pm_types=$default_pm_types;
        ini_set('/config/EZConfigTypes.ini','config','pm_types',$default_pm_types);
   };
   print($pm_types);*/ ?>]; 
   //2900,2901,4580,4134,4133,3360,4789,4790
   $scope.inverter_types=[<?
   $inv_types=implode(array_keys($all_inverters),',');
   print( $inv_types);
   /*
   
   $inv_types=ini_get('/config/EZConfigTypes.ini','config','inv_types','');
   $done=0;
   $cnt=2;
   while (!$done) {
    $pm_types2=ini_get('/config/EZConfigTypes.ini','config','inv_types'.$cnt,'');
    if ($pm_types2) {
        $inv_types.=",".$pm_types2;
        $cnt++;
    } else $done=1;
   }
   if (!$inv_types) {
        $inv_types=$default_inv_types;
        ini_set('/config/EZConfigTypes.ini','config','inv_types',$default_inv_types);
   };
   print($inv_types);*/ ?>];
   $scope.pm=[<?
   
   
       $num_pm=ini_get('/config/EZConfig.ini','config','num_pm',0);
       for ($d=0;$d<$num_pm;$d++) {
            $addr=$ez_arr["pm".$d]["address"];
            $bus=intval($ez_arr["pm".$d]["bus"]);
            $type=$ez_arr["pm".$d]["type"];
            $dg_rating=$ez_arr["pm".$d]["dg_rating"];
            $name=$ez_arr["pm".$d]["name"];
            if (!$name) $name="";
            
            $idx=$ez_arr["pm".$d]["idx"];
            $device_type_id=$ez_arr["pm".$d]["device_type_id"];
            if ($use_qos) {            
                $cat=$ez_arr["pm".$d]["category"];
                if (!$cat) $cat='ENERGY_METER';
            }
            $st="{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="device_type_id:".$device_type_id.",";
            $st.="bus:".$bus.",";
            $st.="dg_rating:".$dg_rating.",";
            if ($use_qos) {            
                $st.="category:'".$cat."',";
            }
            $st.="type:".$type.",";
            $st.="name:\"".$name."\"},";
            print($st);
            
       }
   ?>];
    $scope.inv=[<?
       $num_pm=ini_get('/config/EZConfig.ini','config','num_inv',0);
       for ($d=0;$d<$num_pm;$d++) {
            $addr=$ez_arr["inv".$d]["address"];
            $bus=$ez_arr["inv".$d]["bus"];
            $name=$ez_arr["inv".$d]["name"];
            if (!$name) $name="";
            $rating=$ez_arr["inv".$d]["rating"];
            if (!$rating) $rating="";
            $idx=$ez_arr["inv".$d]["idx"];
            $device_type_id=$ez_arr["inv".$d]["device_type_id"];
            if ($use_qos) {            
                $cat=$ez_arr["inv".$d]["category"];
                if (!$cat) $cat='PV_INVERTER';
            }
            $st="{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="bus:".$bus.",";
            $st.="rating:\"".$rating."\",";
            if ($use_qos) {            
                $st.="category:'".$cat."',";
            }
            $st.="name:\"".$name."\"},";
            print($st);
            
       }
   ?>];

    $scope.other=[<?
       $num_other=$ez_arr['num_other'];
       for ($d=0;$d<$num_other;$d++) {
            $addr=$ez_arr["other".$d]["address"];
            $bus=$ez_arr["other".$d]["bus"];
            $name=$ez_arr["other".$d]["name"];
            if (!$name) $name="";
            $idx=$ez_arr["other".$d]["idx"];
            if ($use_qos) {            
                $cat=$ez_arr["other".$d]["category"];
                if (!$cat) $cat='WEATHER_STATION';
            }
            $st="{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="bus:".$bus.",";
            if ($use_qos) {            
                $st.="category:'".$cat."',";
            }
            $st.="name:\"".$name."\"},";
            print($st);
            
       }
       if (!$num_other) {
            // add the mega,ultra, etc
            
       }
   ?>];
   
   $scope.ow_sensors=[<?
   include("/lib/uphp/string.inc");
        $ow_sensors=array();
       for ($d=0;$d<$num_onewire;$d++) {
       
            $addr=ini_get("/config/onewire.ini","Device".$d,"address","");
            $ow_sensors[]=$addr;
            $temp=0;
            $st="{device_address:\"".$addr."\",";
            $st.="device_idx:".($d);
            $st.=",temperature:".($temp);
            $st.="},";
            print($st);
            
       }
   ?>
   ];
   
   $scope.ow_count=<? print(intval($ez_arr['num_temp'])); ?>;
   $scope.ow=[<?
       $num_ow=intval($ez_arr['num_temp']);
       for ($d=0;$d<$num_ow;$d++) {
            $addr=ini_get("/config/EZConfig.ini","config","ow".$d."_device_address",$ow_sensors[$d]);
            
            $name=ini_get("/config/EZConfig.ini","config","ow".$d."_name","Sensor".($d+1));
            
            $st="{device_address:\"".$addr."\",";
            $st.="device_idx:".index_of($ow_sensors,$addr).",";
            $st.="name:\"".$name."\"},";
            print($st);
            
       }
   ?>];
   
   $scope.power_meters=[<?
        $pm_arr=explode($pm_types,',');
        
       
       for ($d=0;$d<sizeof($pm_arr);$d++) {
            $did=array_key($all_meters,$d);
            $st="{device_type_id:".$did.",";
            $st.="device_idx:".$d.",";
            $st.="name:\"".$all_meters[$did]." (".$pm_arr[$d].")\"";
            if ($use_qos) {
                $st.=",qos_category:'METER'},"; //ini_get("/dev/dev".$pm_arr[$d].".ini","config","name","")
            } else $st.="},";
            print($st);
            
       }
   ?>];
   $scope.inverters=[<?
        $inv_arr=explode($inv_types,',');
        $inv_makes=array();
       
       for ($d=0;$d<sizeof($inv_arr);$d++) {
            $did=array_key($all_inverters,$d);
            $st="{device_type_id:".$did.",";
            $st.="device_idx:".$d.",";
            $inv_name=$all_inverters[$did];
            $inv_make=substr($inv_name,0,strpos($inv_name,' '));
            $inv_makes[$inv_make]=$inv_make;
            $inv_model=substr($inv_name,strpos($inv_name,' ')+1);
            $st.="rating:".$all_rating[$did];
            $st.=",name:\"".$all_inverters[$did]." (".$inv_arr[$d].")\"";
            $st.=",make:\"".$inv_make."\"";
            $st.=",model:\"".$inv_model."\"";
            if ($use_qos) {
                $st.=",qos_category:'PV_INVERTER'},"; //ini_get("/dev/dev".$pm_arr[$d].".ini","config","name","")
            } else $st.="},";
            print($st);
            
       }
   ?>];
   $timeout(function() {
                    console.log($scope.inv.length);
   for (i=0;i<$scope.inv.length;i++) {
        console.log($scope.inv[i]);
        for (j=0;j<$scope.inverters.length;j++) {
            if ($scope.inverters[j].device_type_id == $scope.inv[i].device_type_id) {
                $scope.inv[i].make=$scope.inverters[j].make;
                $scope.inv[i].model=$scope.inverters[j].model;
                
            }
        }
   }

            }, 100,true);

   $scope.inverter_makes=[<?

       for ($d=0;$d<sizeof($inv_makes);$d++) {
            $did=array_key($inv_makes,$d);
            $st="{make:\"".$did."\",";
            $st.="name:\"".$did."\"";
            $st.="},";
            print($st);
            
       }
   ?>];
   
    $scope.other_devices=[<?
    
     //$other_arr=explode($_types,',');
        
       
       for ($d=0;$d<sizeof($all_other);$d++) {
            $did=array_key($all_other,$d);
            $st="{device_type_id:".$did.",";
            $st.="device_idx:".$d.",";
            $st.="device_category:'Other',";
            $qoscatname='WEATHER_STATION';

            $st.="name:\"".$all_other[$did]." (".$did.")\"";
            if ($use_qos) {
                $st.=",qos_category:'WEATHER_STATION'},"; //ini_get("/dev/dev".$pm_arr[$d].".ini","config","name","")
            } else $st.="},";
            print($st);
            
       }
       
   ?>];

   $scope.bus=[{idx:0,name:"Modbus RTU (RS-485)"},
<? if (($_SERVER['HW_PLATFORM']==11) || ($_SERVER['HW_PLATFORM']>=20)) { ?>
   
        {idx:1,name:"Modbus RTU 2 (RS-485)"},
<? } ?>        
<? for ($c=0;$c<NUM_TCP_CHANNELS;$c++) { ?>
        {idx:<? print(2+$c); ?>,name:"Modbus TCP Channel <? print(1+$c); ?>"},
<? } ?>        
        {idx:100,name:"Virtual"},
<? if (($_SERVER['HW_PLATFORM']==20)) { ?>
   
        {idx:101,name:"RS-232"},
<? } ?>        
        
    ];
   $scope.pm_count_installed=0;
   $scope.loading=0;
   $gscope=$scope;
   if ($scope.power_meters.length==0) {
        $scope.errormsg="There are currently no power meters defined that support power control.  Please add a Secure 400 or Schneider EM6400 meter.";
   }
   if ($scope.inverters.length==0) {
        if ($scope.errormsg.length>0) $scope.errormsg+="\r\n";
        $scope.errormsg+="There are currently no inverters defined that support power control.  Please add a supported inverter or contact us.";
   }
   
   $scope.makeBus=function(idx) {
     for (i=0;i<$scope.bus.length;i++) {
        if ($scope.bus[i].idx==idx) 
            return $scope.bus[i].name;
     }
     return "";
   }
   
    $scope.makeType=function(atype_id) {
        switch (Number(atype_id)) {
            case 0:return "<? print(lang('UNDEFINED','ezconfig')) ?>";
            case 1:return "<? print(lang('GENSET','ezconfig')) ?>";
            case 2:return "<? print(lang('INCOMER','ezconfig')) ?>";
            case 3:return "<? print(lang('INVERTER_OUTPUT','ezconfig')) ?>";
            case 4:return "<? print(lang('BUILDING_LOAD','ezconfig')) ?>";
            case 5:return "<? print("ESS (Battery)"); ?>";
            default: return atype_id;
        }
    };
    
    $scope.get_pm_name = function(type_id) {
        if ($scope.power_meters!="undefined") {
        for (k=0;k<$scope.power_meters.length;k++) {
            if ($scope.power_meters[k].device_type_id==type_id) 
                return $scope.power_meters[k].name;
        }
        }
        return "n/a";
    }
    $scope.get_pm_index= function(type_id) {
       // console.log("PM CMNT="+$scope.power_meters.length);
       console.log("in get_pm");
        for (ka=0;ka<$scope.power_meters.length;ka++) {
            console.log(ka+' '+$scope.power_meters[ka].device_type_id);
            if ($scope.power_meters[ka].device_type_id==type_id) {
                console.log("out get_pm");
                return ka;
            }
        }
        return 0;
    }
    
    $scope.get_inv_name = function(type_id) {
        if ($scope.inverters!="undefined") {
        for (k=0;k<$scope.inverters.length;k++) {
            if ($scope.inverters[k].device_type_id==type_id) 
                return $scope.inverters[k].name;
        }
        }
        return "n/a";
    }
    $scope.get_inv_make = function(type_id) {
        if ($scope.inverters!="undefined") {
        for (k=0;k<$scope.inverters.length;k++) {
            if ($scope.inverters[k].device_type_id==type_id) 
                return $scope.inverters[k].make;
        }
        }
        return "n/a";
    }
    $scope.get_inv_model = function(type_id) {
        if ($scope.inverters!="undefined") {
        for (k=0;k<$scope.inverters.length;k++) {
            if ($scope.inverters[k].device_type_id==type_id) 
                return $scope.inverters[k].model;
        }
        }
        return "n/a";
    }


    $scope.get_inv_index= function(type_id) {
       // console.log("PM CMNT="+$scope.power_meters.length);
       console.log("in get_inv");
        for (k=0;k<$scope.inverters.length;k++) {
            console.log(k+' '+$scope.inverters[k].device_type_id);
            if ($scope.inverters[k].device_type_id==type_id) {
                console.log("out inverters - index="+i);
                return k;
            }
        }
        return 0;
    }
    
    $scope.get_other_name = function(type_id) {
        if ($scope.other_devices!="undefined") {
        for (k=0;k<$scope.other_devices.length;k++) {
            if ($scope.other_devices[k].device_type_id==type_id) 
                return $scope.other_devices[k].name;
        }
        }
        console.log(type_id+" not found in get_other_name");
        return "n/a";
    }
    $scope.get_other_index= function(type_id) {
       // console.log("PM CMNT="+$scope.power_meters.length);
       console.log("in get_inv");
        for (k=0;k<$scope.other_devices.length;k++) {
            console.log(k+' '+$scope.other_devices[k].device_type_id);
            if ($scope.other_devices[k].device_type_id==type_id) {
                console.log("out inverters");
                return k;
            }
        }
        return 0;
    }
   $scope.addPM=function() {
    if ($scope.power_meters.length==0) {
        alert("No supported power meters found.  Add the power meter in your devices list first.");
    } else {
        // guess the next meter id
        meter_id=1;
        dbus=0;
        ddevice_idx=0;
        name='meter'+($scope.pm_count+1);
        if ($scope.pm.length) {
            meter_id=Number($scope.pm[$scope.pm.length-1].id)+1;
            ddevice_idx=Number($scope.pm[$scope.pm.length-1].device_idx);
            dbus=Number($scope.pm[$scope.pm.length-1].bus);
            for (i=0;i<$scope.pm.length;i++) {
                if ($scope.pm[i].device_name==name) {
                    name=name+"dup";
                }
            }
        }
        $scope.pm.push({edit:1,id:meter_id,device_idx:ddevice_idx,bus:dbus,device_name:name});
        $scope.pm_count++;
    }
   }
   
   $scope.pkgChanged=function(item) {
    console.log(item);
     //for (i=0;i<$scope.package.length;i++) {
     if (item.name=='Pyranometer') {
            $scope.pyranometer=item.selected?1:0;
     }
     if (item.name=='WS102') {
            $scope.ws102=item.selected?1:0;
     }
     if (item.name=='PC') {
            $scope.module_power_control=item.selected?1:0;
     }
     if (item.name=='Devices') {
            $scope.module_devices=item.selected?1:0;
     }

       // }
   }
   $scope.setModel=function(idx) {
            for (i=0;i<$scope.inverters.length;i++) {
                if ($scope.inverters[i].device_type_id==$scope.inv[idx].device_type_id) {
                    if ($scope.inverters[i].rating!=0)
                        $scope.inv[idx].rating=$scope.inverters[i].rating;
                }
            }
    
    console.log("Model set to "+idx);
   }
   
   $scope.delPM=function(idx) {
        $scope.pm.splice(idx,1);
        $scope.pm_count--;
   }
   $scope.addOD=function() {
    if ($scope.other_devices.length==0) {
        alert("No other devices found.");
    } else {
        // guess the next meter id
        other_id=1;
        dbus=0;
        ddevice_idx=0;
		dcat='';
        name='device'+($scope.other_count+1);
        if ($scope.other.length) {
            other_id=Number($scope.other[$scope.other.length-1].id)+1;
            ddevice_idx=Number($scope.other[$scope.other.length-1].device_idx);
            dbus=Number($scope.other[$scope.other.length-1].bus);
            dcat=$scope.other[$scope.other.length-1].qos_category;
            for (i=0;i<$scope.other.length;i++) {
                if ($scope.other[i].device_name==name) {
                    name=name+"dup";
                }
            }
        }
        $scope.other.push({edit:1,id:other_id,device_idx:ddevice_idx,bus:dbus,device_name:name,category:dcat});
        $scope.other_count++;
    }
   }
   
   $scope.addPyranometer=function() {
        console.log("ADD");
        pyra_index=-1;
        for (i=0;i<$scope.other.length;i++) {
            if ($scope.other_devices[$scope.other[i].device_idx].device_type_id==8010) {
                pyra_index=i;
                break;
            }
        }    
        if (pyra_index==-1) {
            for (i=0;i<$scope.other_devices.length;i++) {
                console.log($scope.other_devices[i]);
                if ($scope.other_devices[i].device_type_id==8010) {
                    
                    console.log({readonly:1,edit:0,id:200,device_idx:i,device_type_id:8010,bus:100,device_name:"Pyranometer"});
                    $scope.other.push({readonly:1,edit:0,id:200,device_idx:i,device_type_id:8010,bus:100,device_name:"Pyranometer"});
                    $scope.other_count++;        
                }
            }
        }
        

   }
   
   $scope.delOD=function(idx) {
        $scope.other.splice(idx,1);
        $scope.other_count--;
   }
    $scope.addInv=function() {
    if ($scope.inverters.length==0) {
        alert("No supported Inverters found.  Add the Inverter in your devices list first.");
    } else {
        // guess the next meter id
        inv_id=1;
        dbus=0;
        ddevice_idx=0;
        name='inverter'+($scope.inv_count+1);
        if ($scope.inv.length) {
            inv_id=Number($scope.inv[$scope.inv.length-1].id)+1;
            ddevice_idx=Number($scope.inv[$scope.inv.length-1].device_idx);
            ddevice_type_id=Number($scope.inv[$scope.inv.length-1].device_type_id);
            dmake=$scope.inv[$scope.inv.length-1].make;
            console.log(dmake);
            dmodel=$scope.inv[$scope.inv.length-1].model;
            dbus=Number($scope.inv[$scope.inv.length-1].bus);
            for (i=0;i<$scope.inverters.length;i++) {
                if ($scope.inverters[i].device_type_id==ddevice_type_id) {
                    drating=$scope.inverters[i].rating;
                }
            }
            //if (!drating) 
                drating=Number($scope.inv[$scope.inv.length-1].rating);
                
            for (i=0;i<$scope.inv.length;i++) {
                if ($scope.inv[i].device_name==name) {
                    name=name+"dup";
                }
            }
             console.log({edit:1,id:inv_id,device_idx:ddevice_idx,bus:dbus,device_name:name,make:dmake,model:dmodel,device_type_id:ddevice_type_id});
            $scope.inv.push({edit:1,id:inv_id,device_idx:ddevice_idx,bus:dbus,device_name:name,make:dmake,model:dmodel,device_type_id:ddevice_type_id,rating:drating});
        } else {
            dmake='Sungrow';
            $scope.inv.push({edit:1,id:inv_id,bus:0,rating:0,make:dmake,device_name:'inverter1'});
        }
       
        
        
        $scope.inv_count++;
    
    }
   }
   $scope.delInv=function(idx) {
        $scope.inv.splice(idx,1);
        $scope.inv_count--;
   }

  /*$scope.$watch('package', function(asyncData) {
  console.log(asyncData);
    if(angular.isDefined(asyncData)) {
        for (i=0;i<$scope.package.length;i++) {
            if ($scope.package[i].name=='PC') {
                $scope.module_power_control=$scope.package[i].selected?1:0;
            }
            if ($scope.package[i].name=='Devices') {
                $scope.module_devices=$scope.package[i].selected?1:0;
            }
            if ($scope.package[i].name=='WS102') {
                $scope.ws102=$scope.package[i].selected?1:0;
            }
            if ($scope.package[i].name=='Pyranometer') {
                $scope.pyranometer=$scope.package[i].selected?1:0;
            }
        }
    }
});*/


$scope.$watch('pyranometer', function(asyncData) {
    if(angular.isDefined(asyncData)) {
        
        for (i=0;i<$scope.package.length;i++) {
            if ($scope.package[i].name=='Pyranometer') {
            
                $scope.package[i].selected=asyncData==1?true:false;
                console.log($scope.package[i]);

            }
        }
        if (asyncData==1) $scope.addPyranometer();
    }
});

$scope.$watch('ws102', function(asyncData) {
    if(angular.isDefined(asyncData)) {
        for (i=0;i<$scope.package.length;i++) {
            if ($scope.package[i].name=='WS102') {
                $scope.package[i].selected=asyncData==1?true:false;
            }
        }
    }
});

$scope.$watch('module_devices', function(asyncData) {
    if(angular.isDefined(asyncData)) {
        for (i=0;i<$scope.package.length;i++) {
            if ($scope.package[i].name=='Devices') {
                $scope.package[i].selected=asyncData==1?true:false;
            }
        }
    }
});
$scope.$watch('module_power_control', function(asyncData) {
    if(angular.isDefined(asyncData)) {
        for (i=0;i<$scope.package.length;i++) {
            if ($scope.package[i].name=='PC') {
                $scope.package[i].selected=asyncData==1?true:false;
            }
        }
    }
});
   $scope.saveSettings=function(move_next) {
        package_str="";
        for (i=0;i<$scope.package.length;i++) {
            
            if ($scope.package[i].selected) {
                if (package_str.length>0) package_str+=",";
                package_str+=$scope.package[i].name;
            }
        }
        //alert(package_str);
        $scope.successmsg="";
           $scope.errormsg="";
           $scope.infomsg="";
        if ($scope.pyranometer==1 && ($scope.other_count<2)) {
            $scope.errormsg="Please add a sensor device to link to the Pyranometer module in Other Devices.";
            return;
            
        }
        if ($scope.form.$invalid) {
            $scope.errormsg="One or more fields have invalid values.  Please fix that and try again.";
            return;
        }
        $scope.loading=1;
       post_data="pm_count="+$scope.pm_count+
                "&inv_count="+$scope.inv_count+
                "&other_count="+$scope.other_count+
                "&parity="+$scope.parity+
                "&baud_rate="+$scope.baud_rate+
                "&interval="+$scope.interval+
                "&timeout="+$scope.timeout+
                "&short_timeout="+$scope.short_timeout+
                "&retry="+$scope.retry+
				"&retry_interval="+$scope.retry_interval+
                "&tcp_enabled="+$scope.tcp_enabled+
                "&tcp_timeout="+$scope.tcp_timeout+
                "&tcp_retry="+$scope.tcp_retry+
				"&tcp_retry_interval="+$scope.tcp_retry_interval+
                "&tcp_interval="+$scope.tcp_interval+
<? if ( $_SERVER['HW_PLATFORM']==20) { ?>
                "&rs232_enabled="+$scope.rs232_enabled+
                "&rs232_baud="+$scope.rs232_baud+
                "&auth="+$scope.auth+
                "&client_id="+$scope.client_id+
                "&password="+$scope.password+
<? } ?>                
<? if ($_SERVER['HW_PLATFORM']==11 || $_SERVER['HW_PLATFORM']>=20) { ?>
                "&parity2="+$scope.parity2+
                "&baud_rate2="+$scope.baud_rate2+
                "&interval2="+$scope.interval2+
                "&enabled2="+$scope.enabled2+
                "&timeout2="+$scope.timeout2+
                "&retry2="+$scope.retry2+
				"&retry_interval2="+$scope.retry_interval2+
                
<? } ?>   
                "&poll_interval="+$scope.poll_interval+
                "&pyranometer="+$scope.pyranometer+
                "&dc_plant_size="+$scope.dc_plant_size+
                "&fixed_pr="+$scope.fixed_pr+
                "&firmware_logging="+$scope.firmware_logging+
                "&ws102="+$scope.ws102+
                "&snapshot="+$scope.snapshot+
                "&use_temp="+$scope.use_temp+
                "&num_temp="+$scope.num_temp+
                "&static_header="+$scope.static_header+
                "&packages="+package_str+
                "&module_power_control="+$scope.module_power_control+
                "&track_curtailment="+$scope.track_curtailment+
                "&license_key="+encodeURIComponent($scope.license_key)+
                "&sync_power_control="+$scope.sync_power_control+
                "&log_drive="+$scope.log_drive+
                "&log_interval="+$scope.log_interval+
                "&log_write_interval="+$scope.log_write_interval+
                "&ota_packages="+$scope.ota_packages+
                "&ota_firmware="+$scope.ota_firmware+
                "&ota_healing="+$scope.ota_healing+
                "&module_devices="+$scope.module_devices;
<? if ($use_qos) { ?>
        post_data+="&qos_username="+$scope.qos_username+
                    "&qos_password="+btoa(encodeURIComponent($scope.qos_password))+
                    "&qos_server="+$scope.qos_server+
                    "&qos_path="+$scope.qos_path+
                    "&qos_prefix="+$scope.qos_prefix;
        post_data+="&encoded_keys=qos_password";                    

<? } ?>
<? if ($use_fourth) { ?>
        post_data+="&sim_number="+$scope.sim_number+
                    "&custom_url="+$scope.custom_url+
                    "&max_lines="+$scope.max_lines+
                    "&export_interval="+$scope.export_interval+
                    "&apn="+$scope.apn+
                    "&apn_mode="+$scope.apn_mode+
                    "&mqtt_enabled="+$scope.mqtt_enabled+
                    "&mqtt_port="+$scope.mqtt_port+
                    "&mqtt_channel="+$scope.mqtt_channel+
                    "&mqtt_mode="+$scope.mqtt_mode+
                    "&apn_custom="+$scope.apn_custom;
        post_data+="&mqtt_server="+$scope.mqtt_server;
        post_data+="&subscribe_timeout_percent="+$scope.subscribe_timeout_percent;
        post_data+="&subscribe_timeout_interval="+$scope.subscribe_timeout_interval;
        
        post_data+="&mqtt_user="+$scope.mqtt_user;                    
       post_data+="&mqtt_password="+btoa(encodeURIComponent($scope.mqtt_password));
       
       post_data+="&encoded_keys=mqtt_password";
        
<? } ?>

        post_data+=<? for ($c=0;$c<NUM_TCP_CHANNELS;$c++) { ?>"&tcp<? print($c); ?>_ip="+$scope.tcp<? print($c); ?>_ip<? if ($c<NUM_TCP_CHANNELS-1) print("+"); else print(";"); ?><? } ?>
        post_data+=<? for ($c=0;$c<NUM_TCP_CHANNELS;$c++) { ?>"&tcp<? print($c); ?>_s="+$scope.tcp<? print($c); ?>_s<? if ($c<NUM_TCP_CHANNELS-1) print("+"); else print(";"); ?><? } ?>
        post_data+=<? for ($c=0;$c<NUM_TCP_CHANNELS;$c++) { ?>"&tcp<? print($c); ?>_port="+$scope.tcp<? print($c); ?>_port<? if ($c<NUM_TCP_CHANNELS-1) print("+"); else print(";"); ?><? } ?>
        
        
        for (i=0;i<$scope.pm.length;i++) {
            post_data+="&pm"+i+"_device_type_id=" + $scope.pm[i].device_type_id;//$scope.power_meters[$scope.get_pm_index($scope.pm[i].device_type_id)].device_type_id;
            post_data+="&pm"+i+"_id=" + $scope.pm[i].id;
            post_data+="&pm"+i+"_type=" + $scope.pm[i].type;     
            post_data+="&pm"+i+"_bus=" + $scope.pm[i].bus;
            post_data+="&pm"+i+"_dg_rating=" + $scope.pm[i].dg_rating;     
            post_data+="&pm"+i+"_device_name=" + $scope.pm[i].device_name;     
<? if ($use_qos) { ?>            
            post_data+="&pm"+i+"_category="+$scope.pm[i].category;     
<? } ?>            
            post_data+="&pm"+i+"_device_idx=" + $scope.get_pm_index($scope.pm[i].device_type_id);                 
        }
        for (i=0;i<$scope.inv.length;i++) {
            post_data+="&inv"+i+"_device_type_id="+$scope.inv[i].device_type_id;//$scope.inverters[$scope.inv[i].device_idx].device_type_id;     
            post_data+="&inv"+i+"_id="+$scope.inv[i].id;     
            post_data+="&inv"+i+"_bus="+$scope.inv[i].bus;     
            post_data+="&inv"+i+"_device_name="+$scope.inv[i].device_name;     
            post_data+="&inv"+i+"_rating="+$scope.inv[i].rating; 
<? if ($use_qos) { ?>                        
            post_data+="&inv"+i+"_category="+$scope.inv[i].category; 
<? } ?>            
            console.log("getting index for "+$scope.inv[i].device_type_id);
            post_data+="&inv"+i+"_device_idx="+$scope.get_inv_index($scope.inv[i].device_type_id);     
            console.log("i is "+i);
            
        }
        for (i=0;i<$scope.other.length;i++) {
            
            post_data+="&other"+i+"_device_type_id="+$scope.other[i].device_type_id;//$scope.other_devices[$scope.other[i].device_idx].device_type_id;     
            post_data+="&other"+i+"_id="+$scope.other[i].id;     
            post_data+="&other"+i+"_bus="+$scope.other[i].bus;     
            post_data+="&other"+i+"_device_name="+$scope.other[i].device_name;     
<? if ($use_qos) { ?>            
            post_data+="&other"+i+"_category="+$scope.other[i].category;     
<? } ?>
            post_data+="&other"+i+"_device_idx="+$scope.get_other_index($scope.other[i].device_type_id);     
        }
        for (i=0;i<$scope.ow.length;i++) {
            
            post_data+="&ow"+i+"_device_address="+$scope.ow[i].device_address;
            post_data+="&ow"+i+"_name="+$scope.ow[i].name;
          
        }
       post_config="EZConfig.ini";
       post_section="config";
       $http.post('/app/configsave.cgi?config='+post_config+'&section='+post_section,post_data)
        .then(function (response) {
          var data = response.data; 
          $scope.successmsg=(Number(data.status)==1)?"Saved Settings":"Error Saving";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          $scope.loading=0;
          if (move_next) 
            document.location='/app/ezconfig.cgi?stage=<? 
            if ($use_qos) print("2&qos=1"); 
            else if ($use_fourth) print("4&fourth=1");
            else print("2");
            ?>';
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
            $scope.loading=0;
        });
   }
   
   
}
</script>
        <? }
        
/********************************************************************************************************* STAGE 2 */        
if ($_GET['stage']==2) {
//max_execution_time(60);
    // all QOS Signals are here
    if ($_SERVER['HW_PLATFORM']>=20) {
    define("NUM_TCP_CHANNELS",20);
} else {
    define("NUM_TCP_CHANNELS",10);
}
    //setpriority(2);
    if ($_GET['qos']) {
        $use_qos=1;
    }
?>

<style type='text/css'>
[ng-cloak].splash {
    display: block !important;
}
.splash {
    display: none;
}
</style>
<!-- BREADCRUMBS -->
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/"><? print(lang('HOME','settings')) ?></a></li>
    <li class="breadcrumb-item"><a href="/app/settings.cgi"><? print(lang('CONTROL_PANEL','settings')) ?></a></li>
    <li class="breadcrumb-item active" aria-current="page"><? print(lang('PAGE_TITLE','ezconfig')) ?></li>
  </ol>
</nav>

<!-- NAVBAR -->
<h4><i class="icon-cog"></i>&nbsp;<? print(lang('STAGE2_TITLE','ezconfig')) ?>: <? print(lang('S2_TITLE','ezconfig')) ?></h4>
<ul class="nav justify-content-end">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="collapse" href="#collapseHelp" role="button" aria-expanded="false" aria-controls="collapseExample">
    <? print(lang('HELP','ezconfig')) ?>
  </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" onclick="document.location='/app/settings.cgi';"><i class="icon-remove"></i> <? print(lang('CLOSE','ezconfig')) ?></a>
  </li>
 <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="prev()" ><i class="icon-back"></i> <? print(lang('PREVIOUS','ezconfig')) ?></a>
  </li>  
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="saveSettings(0)" ><i class="icon-check"></i> <? print(lang('APPLY','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="saveSettings(1)" ><i class="icon-arrow-right"></i> <? print(lang('SAVE_NEXT','ezconfig')) ?></a>
  </li>
  
</ul>
<!-- HELP -->
<div class="collapse" id="collapseHelp">
  <div class="card card-body">
    <? print(lang('HELP1','ezconfig')) ?>
  </div>
  <br/>
</div>
<div class="alert alert-success" ng-cloak ng-show="successmsg"> <button type="button" class="close" ng-click='successmsg=""'>&times;</button>{{successmsg}}</div>
<div class="alert alert-danger" ng-cloak ng-show="errormsg"> <button type="button" class="close" ng-click='errormsg=""'>&times;</button>{{errormsg}}</div>
<div class="alert alert-info" ng-cloak ng-show="infomsg"> <button type="button" class="close" data-dismiss="alert">&times;</button>{{infomsg}}</div>
<div class="alert alert-secondary" ng-cloak ng-show="loading"><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></div>
<div class="splash" ng-cloak="">
    <p><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></p>
  </div>
<form name="form" class="css-form form-horizontal" novalidate ng-cloak>

<!-- VARIABLES -->
<? 
    $inv_cnt=ini_get("/config/EZConfig.ini","config",'inv_count',0);
    $pm_cnt=ini_get("/config/EZConfig.ini","config",'pm_count',0);
    $ez_arr = ini_get_array("/config/EZConfig.ini","config");
//            $=ini_get("/config/EZConfig.ini","config",'pm_count',0);       
?>            
<div ng-init="inv_count=<? print($inv_cnt); ?>;">
<div ng-init="pm_count=<? print($pm_cnt); ?>;">
<div ng-init="use_temp=<? print(intval($ez_arr['use_temp'])); ?>;">
<div class="card">
    <div class="card-body">
        <h5 class="card-title"><? print(lang('S2_TITLE','ezconfig')) ?></h5>
        <p class="card-text">    
            <? print(lang('S2_1','ezconfig')) ?>
            <? print(lang('S2_2','ezconfig')) ?>
        </p>
        <br>
        Total Logged Roles: <strong>{{countLoggedRoles()}}</strong>
    </div>
</div>

<br/>
<div class="card" ng-hide='pm.length==0'>
    <div class="card-body">
        <h5 class="card-title text-danger"><? print(lang('POWER_METERS','ezconfig')) ?></h5>
        <p class="card-text">    
            <table class='table' summary="Meters" >
                <tr ng-repeat="item in power_meters">
                    <td><a name='pm{{$index}}'></a><span class="badge badge-danger badge-pill">{{$index+1}}</span></td>
                    <td><h6><strong class='badge badge-secondary'>{{item.name}}</strong></h6>
                    <table class='table table-striped' summary="Roles" >
                        <tr>
                            <td scope="col"><input type='checkbox' class='form-control' ng-click='toggleAll(item)'></td>
                            <td scope="col"><a name='pm'></a><strong><? print(lang('FUNCTION','datalogedit')) ?> (<a ng-click='setMeterFn(3);' href='#pm'>INSTANTANEOUS</a> - <a ng-click='setMeterFn(0);' href='#pm'>AVERAGE</a>)</strong></td>
                            <td scope="col"><strong><? print(lang('VARIABLE','ezconfig')) ?></strong></td>
                            <td scope="col"><strong><? print(lang('DESCRIPTION','ezconfig')) ?></strong></td>
                            <? if ($use_qos) {  ?>
                            <td scope="col"><strong>QOS Signal</strong></td>
                            <? } ?>
                        </tr>
                        <tr ng-repeat="role in item.roles">
                            <td><input type='checkbox' class='form-control' ng-model='role.selected'></td>
                            <td>
                                <select ng-model="role.logfn" class='form-control' >
                                    <option value='0'><? print(lang('AVERAGE','datalogedit')) ?></option>
                                    <option value='1'><? print(lang('MIN','datalogedit')) ?></option>
                                    <option value='2'><? print(lang('MAX','datalogedit')) ?></option>            
                                    <option value='3'><? print(lang('INSTANTANEOUS','datalogedit')) ?></option>            
                                </select>
                            </td>
                            <td><strong>{{role.role_name}}</strong></td>
                            <td><i>{{role.role_desc}}</i></td>
                            <? if ($use_qos) {  ?>
                            <td>
                                <select ng-model="role.qostype" class='form-control' >
                                    <option ng-repeat='qos_item in qos_signals' ng-value="{{qos_item.name}}">{{qos_item.name}}</option>
                                </select>
                            </td>
                            <? } ?>
                        </tr>
                    </table>
                </td>            
            </tr>
        </table> 
    </div>
</div> 
<br/>
<div class="card" ng-hide='inv.length==0'>
    <div class="card-body">
        <h5 class="card-title text-success"><? print(lang('INVERTERS','ezconfig')) ?></h5>
        <p class="card-text">    
            <table class='table' summary="Inverters" >
                <tr ng-repeat="item in inverters">
                    <td><a name='inv{{$index}}'></a><span class="badge badge-pill badge-success">{{$index+1}}</span></td>
                    <td><h6><strong class='badge badge-secondary'>{{item.name}}</strong></h6>
                    <table class='table table-striped' summary="Roles" >
                        <tr>
                            <td scope="col"><input type='checkbox' class='form-control' ng-click='toggleAll(item)'></td>
                            
                            <td scope="col"><a name='inv'></a><strong><? print(lang('FUNCTION','datalogedit')) ?> (<a ng-click='setInvFn(3);' href='#inv'>INSTANTANEOUS</a> - <a ng-click='setInvFn(0);' href='#inv'>AVERAGE</a>)</strong></td>
                            <td scope="col"><strong><? print(lang('VARIABLE','ezconfig')) ?></strong></td>
                            <td scope="col"><strong><? print(lang('DESCRIPTION','ezconfig')) ?></strong></td>
                            <? if ($use_qos) {  ?><td scope="col"><strong>QOS Signal</strong></td><? } ?>
                        </tr>
                        <tr ng-repeat="role in item.roles">
                            <td><input type='checkbox' class='form-control' ng-model='role.selected'></td>
                            <td>
                                <select ng-model="role.logfn" class='form-control' >
                                    <option value='0'><? print(lang('AVERAGE','datalogedit')) ?></option>
                                    <option value='1'><? print(lang('MIN','datalogedit')) ?></option>
                                    <option value='2'><? print(lang('MAX','datalogedit')) ?></option>            
                                    <option value='3'><? print(lang('INSTANTANEOUS','datalogedit')) ?></option>            
                                </select>
                            </td>
                            <td><strong>{{role.role_name}}</strong></td>
                            <td><i>{{role.role_desc}}</i></td>
                            <? if ($use_qos) {  ?>
                            <td>
                                <select ng-model="role.qostype" class='form-control' >
                                    <option ng-repeat='qos_item in qos_signals' ng-value="{{qos_item.name}}">{{qos_item.name}}</option>
                                    <? /*for ($i=0;$i<sizeof($qos_signals);$i++) {
                                        print("<option value='".$qos_signals[$i][0]."'>".$qos_signals[$i][0]."</option>");
                                    } 
                                    */ ?>
                                </select>
                            </td>
                            <? } ?>
                        </tr>
                    </table>
                </td>            
            </tr>
        </table> 
    </div>
</div> 
<br/>
<div class="card" ng-hide='other.length==0'>
    <div class="card-body">
        <h5 class="card-title text-primary"><? print(lang('OTHER_DEVICES','ezconfig')) ?></h5>
        <p class="card-text">    
            <table class='table' summary="Other Devices" >
                <tr ng-repeat="item in other_devices">
                    <td><a name='od{{$index}}'></a><span class="badge badge-primary badge-pill">{{$index+1}}</span></td>
                    <td><h6><strong class='badge badge-secondary'>{{item.name}}</strong></h6>
                    <table class='table table-striped' summary="Roles" >
                        <tr>
                            <td scope="col"><input type='checkbox' class='form-control' ng-click='toggleAll(item)'></td>
                            <td scope="col"><a name='od'></a><strong><? print(lang('FUNCTION','datalogedit')) ?> (<a ng-click='setOtherFn(3);' href='#od'>INSTANTANEOUS</a> - <a ng-click='setOtherFn(0);' href='#od'>AVERAGE</a>)</strong></td>
                            <td scope="col"><strong><? print(lang('VARIABLE','ezconfig')) ?></strong></td>
                            <td scope="col"><strong><? print(lang('DESCRIPTION','ezconfig')) ?></strong></td>
                            <? if ($use_qos) {  ?><td scope="col"><strong>QOS Signal</strong></td><? } ?>
                        </tr>
                        <tr ng-repeat="role in item.roles">
                            <td><input type='checkbox' class='form-control' ng-model='role.selected'></td>
                            <td>
                                <select ng-model="role.logfn" class='form-control' >
                                    <option value='0'><? print(lang('AVERAGE','datalogedit')) ?></option>
                                    <option value='1'><? print(lang('MIN','datalogedit')) ?></option>
                                    <option value='2'><? print(lang('MAX','datalogedit')) ?></option>            
                                    <option value='3'><? print(lang('INSTANTANEOUS','datalogedit')) ?></option>            
                                </select>
                            </td>
                            <td><strong><input type='text' class='form-control' ng-model='role.role_name'></input></strong></td>
                            <td><i>{{role.role_desc}}</i></td>
                            <? if ($use_qos) {  ?>
                            <td>
                                <select ng-model="role.qostype" class='form-control' >
                                    <option ng-repeat='qos_item in qos_signals' ng-value="{{qos_item.name}}">{{qos_item.name}}</option>
                                    <? /*
                                    for ($i=0;$i<sizeof($qos_signals);$i++) {
                                        print("<option value='".$qos_signals[$i][0]."'>".$qos_signals[$i][0]."</option>");
                                    } */
                                    
                                    ?>
                                </select>
                            </td>
                            <? } ?>
                        </tr>
                    </table>
                </td>            
            </tr>
        </table> 
    </div>
</div> 
<br/>
<div class="card" ng-show='use_temp>0'>
    <div class="card-body">
        <h5 class="card-title text-primary">Temperature Sensors (1-Wire)</h5>
        <p class="card-text">    
            
            <table class='table' summary="Other Variables" >
                    <table class='table table-striped' summary="Items" >
                        <tr>
                            <td scope="col"><input type='checkbox' class='form-control' ng-click='toggleAll(ow)'></td>
                            <td scope="col"><strong>Function</strong></td>
                            <td scope="col"><strong><? print(lang('VARIABLE','ezconfig')) ?></strong></td>
                            <td scope="col"><strong><? print(lang('DESCRIPTION','ezconfig')) ?></strong></td>
                        </tr>
                        <tr ng-repeat="role in ow.roles">
                            <td><input type='checkbox' class='form-control' ng-model='role.selected'></td>
                            <td>
                                    <? print(lang('INSTANTANEOUS','datalogedit')) ?>
                            </td>
                            <td><strong>{{role.role_name}}</strong></td>
                            <td><i>{{role.role_desc}}</i></td>
                        </tr>
                    </table>
                </td>            
            </tr>
        </table> 
    </div>
</div>   

<br/>
<div class="card">
    <div class="card-body">
        <h5 class="card-title text-primary">Global Variables</h5>
        <p class="card-text">    
            
            Global variables can be logged here - some of the variables are used by custom packages. Make sure you enable the packages in <i>Stage 1</i> so the variables appear here.  You can also choose to log custom variables at this stage if you
            plan to have custom scripts running.
            <div class='pull-right'><a name='addother'></a><ng-button class="btn btn-primary" ng-click="add_global()"><i class="icon-plus"></i>&nbsp;<? print(lang('ADD','ezconfig')) ?></ng-button></div>
            <table class='table' summary="Other Variables" >
                    <table class='table table-striped' summary="Items" >
                        <tr>
                            <td scope="col"><input type='checkbox' class='form-control' ng-click='toggleAll(other_variables)'></td>
                            <td scope="col"><strong>Function</strong></td>
                            <td scope="col"><strong><? print(lang('VARIABLE','ezconfig')) ?></strong></td>
                            <td scope="col"><strong><? print(lang('DESCRIPTION','ezconfig')) ?></strong></td>
                        </tr>
                        <tr ng-repeat="role in other_variables.roles">
                            <td><input type='checkbox' class='form-control' ng-model='role.selected'></td>
                            <td>
                                    <? print(lang('INSTANTANEOUS','datalogedit')) ?>
                            </td>
                            <td><span ng-hide='role.readonly'><strong><input type='text' class='form-control' ng-model='role.role_name'></input></strong></span><span ng-hide='!role.readonly'>{{role.role_name}}</span></td>
                            <td><i>{{role.role_desc}}</i></td>
                        </tr>
                    </table>
                </td>            
            </tr>
        </table> 
    </div>
</div>   
<br/>
<div class="alert alert-success" ng-cloak ng-show="successmsg"> <button type="button" class="close" ng-click='successmsg=""'>&times;</button>{{successmsg}}</div>
<div class="alert alert-danger" ng-cloak ng-show="errormsg"> <button type="button" class="close" ng-click='errormsg=""'>&times;</button>{{errormsg}}</div>
<div class="alert alert-info" ng-cloak ng-show="infomsg"> <button type="button" class="close" data-dismiss="alert">&times;</button>{{infomsg}}</div>
<div class="alert alert-secondary" ng-cloak ng-show="loading"><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></div>
<div class="splash" ng-cloak="">
    <p><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></p>
  </div>
<ul class="nav justify-content-end">
 <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="prev()" ><i class="icon-back"></i> <? print(lang('PREVIOUS','ezconfig')) ?></a>
  </li>  
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="saveSettings(0)" ><i class="icon-check"></i> <? print(lang('APPLY','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="saveSettings(1)" ><i class="icon-arrow-right"></i> <? print(lang('SAVE_NEXT','ezconfig')) ?></a>
  </li>
  
</ul>
<br/> 
</form>
<pre> <? 
include("/lib/uphp/array.inc");
        // package manager option

$all_inverters = ini_get_array('/config/devicetypes.ini','Inverter');

$all_inverters = quick_sort($all_inverters,1); // sort by value
$all_meters = ini_get_array('/config/devicetypes.ini','Meter');
$all_meters = quick_sort($all_meters,1); // sort by value
$all_other = ini_get_array('/config/devicetypes.ini','Other');
$all_other = quick_sort($all_other,1); // sort by value
   $all_variables=array();
   $package_str=ini_get("/config/EZConfig.ini","config","packages","");
   $logged_str=ini_get("/config/EZConfig.ini","config","logged_vars","");
   $lidx=1;
   while (1) {
       $str=ini_get("/config/EZConfig.ini","config","logged_vars".$lidx,"");
       if (!$str) break;
       else {
           $logged_str.=",".$str;
           $lidx++;
       }
       
   }
   $logged_variables=explode($logged_str,',');
   $packages=explode($package_str,',');
   //print_r($packages);
   for ($p=0;$p<sizeof($packages);$p++) {
     if (file_exists('/package/'.$packages[$p].'.cgi')) {
        include('/package/'.$packages[$p].'.cgi');
        if (function_exists($packages[$p]."_globals")) {  //PC_globals
            $res=call_user_func($packages[$p]."_globals");
            //print_r($res);
            if ($_GLOBALS['VERMINOR']>1199) {
                $all_variables=array_merge($all_variables,$res);
            } else {
                include("/lib/uphp/array.inc");
                $all_variables=array_merge2($all_variables,$res);
            }
        }
     }
   }
   $num_logged=sizeof($logged_variables);
   
   // this means read-only
   for ($i=0;$i<sizeof($all_variables);$i++) {
       $all_variables[$i][2]=0;
       $all_variables[$i][3]=1;
       
   }
       
   for ($j=0;$j<$num_logged;$j++) {
       $found=0;
       for ($i=0;$i<sizeof($all_variables);$i++) {
           if ($all_variables[$i][0]==$logged_variables[$j]) {
               $all_variables[$i][2]=1;
               $found=1;
           }
       }
       if (!$found) {
           $all_variables[]=array($logged_variables[$j],'Global Variable',1,0);
       }
   }
   ?></pre>
<script>
<?

?>
var gItems,gHttp;
var count=0;
var app = angular.module('myApp', []);

function EZConfigWidget($scope, $timeout,$http) {
   var self = this;
   //alert('init');
   //4028,4099,4098,4024,4023
   
$scope.qos_signals=[
   <? 
    if ($_GET['qos']) {
        include("/package/qos_signal.inc");
    }
   
   for ($i=0;$i<sizeof($qos_signals);$i++) {
        if ($i) print(",");
        print("{'name':'".$qos_signals[$i][0]."','type':'".$qos_signals[$i][1]."','key':'".array_key($qos_signals,$i)."'}");
   } 
    $qos_signals=0;
    ?>
   ];   
   
   $scope.power_meter_types=[<? 
   $pm_types=implode(array_keys($all_meters),',');
   print($pm_types);
   ?>];
   
   //2900,2901,4580,4134,4133,3360,4789,4790
   $scope.inverter_types=[<?
   $inv_types=implode(array_keys($all_inverters),',');
   print( $inv_types); ?>];
   $scope.pm=[<?
       $num_pm=ini_get('/config/EZConfig.ini','config','pm_count',0);
     //  $pm_used=array();
        $pm_arr=explode($pm_types,',');
        
       $pm_used=indexed_array(1,sizeof($pm_arr));
       $prefix='';
       for ($d=0;$d<$num_pm;$d++) {
            $addr=ini_get("/config/EZConfig.ini","config","pm".$d."_id",0);
            $bus=ini_get("/config/EZConfig.ini","config","pm".$d."_bus",0);
            $name=ini_get("/config/EZConfig.ini","config","pm".$d."_device_name","");
            $idx=ini_get("/config/EZConfig.ini","config","pm".$d."_device_idx",0);
            
            $pm_used[$idx]=1;
            $st=$prefix."{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="bus:".$bus.",";
            $st.="name:\"".$name."\"}";
            $prefix=',';
            print($st);
            
       }
   ?>];
   <?
   //print_r($pm_used); 
   ?>
    $scope.inv=[<?
       $num_pm=ini_get('/config/EZConfig.ini','config','inv_count',0);
      $inv_arr=explode($inv_types,',');
       $inv_used=indexed_array(1,sizeof($inv_arr));
       
       $prefix='';
       for ($d=0;$d<$num_pm;$d++) {
            $addr=ini_get("/config/EZConfig.ini","config","inv".$d."_id",0);
            $bus=ini_get("/config/EZConfig.ini","config","inv".$d."_bus",0);
            $name=ini_get("/config/EZConfig.ini","config","inv".$d."_device_name","");
            $idx=ini_get("/config/EZConfig.ini","config","inv".$d."_device_idx",0);
            $inv_used[$idx]=1;
            $st=$prefix."{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="bus:".$bus.",";
            $st.="name:\"".$name."\"}";
            $prefix=',';

            print($st);
            
       }
   ?>];
    
   $scope.power_meters=[<?
        $pm_arr=explode($pm_types,',');
        
       $prefix2="";
       for ($d=0;$d<sizeof($pm_arr);$d++) {
            if ($pm_used[$d]==1) {
                $pm_roles_str=ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_roles","").ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_roles2","").ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_roles3","");
            
                $pm_logfn_str=ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_logfn","").
		                ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_logfn2","");
                if ($pm_logfn_str) {
                    $pm_logfn=explode($pm_logfn_str,',');
                } else {
                    $pm_logfn=array();
                }
                
                if ($pm_roles_str) {
                    $pm_roles=explode($pm_roles_str,',');
                } else $pm_roles=array();
                if ($use_qos) {
                    $other_qostype_str=ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_qostype","");
                    $cnt=1;
                    $done=0;
                    while (!$done) {
                        $more_qostype_str=ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_qostype".$cnt,"");
                        //print("MORE=".$more_qostype_str);
                        if (strlen($more_qostype_str)) {
                            $other_qostype_str.=",".$more_qostype_str;
                            $cnt++;
                        } else $done=1;
                    }
                    if ($other_qostype_str) {
                        $other_qostype=explode($other_qostype_str,',');
                    } else $other_qostype=array();
                }                
                $st=$prefix2."{device_type_id:".$pm_arr[$d].",";
                $st.="device_idx:".$d.",";
                $st.="name:\"".ini_get("/dev/dev".$pm_arr[$d].".ini","config","name","")." (".$pm_arr[$d].")\"";
                $num_roles=ini_get("/dev/dev".$pm_arr[$d].".ini","config","num_roles",0);
                // fill up the logfn if its blank
                if (!sizeof($pm_logfn)) {
                    for ($r=0;$r<$num_roles;$r++) {
                        $pm_logfn[]=3;
                    }
                }
                $st.=",roles:[";
                 $prefix="";
                for ($r=0;$r<$num_roles;$r++) {
                    // role_var_0=
                    $rt=ini_get("/dev/dev".$pm_arr[$d].".ini","config","role_type_".$r,0);
                    $ri=ini_get("/dev/dev".$pm_arr[$d].".ini","config","role_idx_".$r,0);
                    
                    if ($rt==0) $var="do_desc_".$ri;
                    if ($rt==1) $var="di_desc_".$ri;
                    if ($rt==2) $var="ro_desc_".$ri;
                    if ($rt==3) $var="rw_desc_".$ri;
                    if ($rt==22) $var="ro_desc_".$ri;
                    if ($rt==23) $var="rw_desc_".$ri;
                    if (($rt>=24) && ($rt<=28)) $var="ro_desc_".$ri;
                    if ($rt==29) $var="rw_desc_".$ri;
                    if ($rt==30) $var="rw_desc_".$ri;
                    if ($rt==34) $var="rw_desc_".$ri;
                    if ($rt==35) $var="rw_desc_".$ri;
                    
                    //print("r=".$r."\r\nrt=".$rt."\r\nri=".$ri."\r\nvar=".$var);
                    $role_desc=ini_get("/dev/dev".$pm_arr[$d].".ini","config",$var,"");
                    if (in_array($pm_roles, $r)) 
                        $sel="true";
                    else $sel="false";
                    if ($use_qos) {
                         $role_name=ini_get("/dev/dev".$pm_arr[$d].".ini","config","role_var_".$r,"");
                        //print($r."=".$other_qostype[$r]."\r\n");
                        if (!isset($other_qostype[$r])) {
                            if (is_array($qos_signals[$role_name])) {
                                $other_qostype[$r]=$qos_signals[$role_name][0];
                            }
                        }
                         $st.=$prefix."{role_idx:".$r.",role_name:\"".ini_get("/dev/dev".$pm_arr[$d].".ini","config","role_var_".$r,"")."\",\"role_desc\":\"".$role_desc."\",\"selected\":".$sel.",'logfn':".intval($pm_logfn[$r]).",'qostype':'".($other_qostype[$r])."'}"; //
                    } else {
                        $st.=$prefix."{role_idx:".$r.",role_name:\"".ini_get("/dev/dev".$pm_arr[$d].".ini","config","role_var_".$r,"")."\",\"role_desc\":\"".$role_desc."\",\"selected\":".$sel.",'logfn':".intval($pm_logfn[$r])."}"; //
                    }
                    $prefix=",";
                    print($st);$st='';
                }
                 
                $st.="] }";
                $prefix2=",";
                print($st);
            }
            
       }
   ?>];
   $scope.other=[<?
       $num_other=ini_get('/config/EZConfig.ini','config','other_count',0);
       $other_arr=array();
       for ($d=0;$d<$num_other;$d++) {
            $addr=ini_get("/config/EZConfig.ini","config","other".$d."_id",0);
            $bus=ini_get("/config/EZConfig.ini","config","other".$d."_bus",0);
            $device_type_id=ini_get("/config/EZConfig.ini","config","other".$d."_device_type_id",0);
            $name=ini_get("/config/EZConfig.ini","config","other".$d."_device_name","");
            $idx=ini_get("/config/EZConfig.ini","config","other".$d."_device_idx",0);
            $found=0;
            for ($i=0;$i<sizeof($other_arr);$i++) {
                if ($other_arr[$i]==$device_type_id)
                    $found=1;
            }
            if (!$found)
                $other_arr[]=$device_type_id;

            $st="{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="device_type_id:".$device_type_id.",";
            $st.="bus:".$bus.",";
            $st.="name:\"".$name."\"},";
            print($st);
            
       }
   ?>];
   $scope.other_devices=[<?

       $prefix2="";
       for ($d=0;$d<sizeof($other_arr);$d++) {
                $other_roles_str=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_roles","");
                $other_logfn_str=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_logfn","");
                $other_names_str=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_names","");
                // load all other roles
                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_roles".$x,"");
                  if (strlen($tmp)) {
                    $other_roles_str .=$tmp;
                  } else break;
                  $x++;
                }
                
                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_names".$x,"");
                  if (strlen($tmp)) {
                    $other_names_str .=$tmp;
                  } else break;
                  $x++;
                }
                
                // load all other roles
                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_logfn".$x,"");
                  if (strlen($tmp)) {
                    $other_logfn_str .=$tmp;
                  } else break;
                  $x++;
                }
                

                $other_qostype_str=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_qostype","");
                // load all other roles
                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_qostype".$x,"");
                  if (strlen($tmp)) {
                    $other_qostype_str .=",".$tmp;
                  } else break;
                  $x++;
                }
                
                if ($other_logfn_str) {
                    $other_logfn=explode($other_logfn_str,',');
                } else $other_logfn=array();
                
                if ($other_roles_str) {
                    $other_roles=explode($other_roles_str,',');
                } else $other_roles=array();
                
                if ($other_names_str) {
                    $other_names=explode($other_names_str,',');
                } else $other_names=array();
                
                if ($other_qostype_str) {
                    $other_qostype=explode($other_qostype_str,',');
                } else $other_qostype=array();
                
                $st=$prefix2."{device_type_id:".$other_arr[$d].",";
                $st.="device_idx:".ini_get("/config/EZConfig.ini","config","other".$d."_device_idx",0).","; // $d
                $st.="name:\"".ini_get("/dev/dev".$other_arr[$d].".ini","config","name","")." (".$other_arr[$d].")\"";
                $num_roles=ini_get("/dev/dev".$other_arr[$d].".ini","config","num_roles",0);
                $st.=",roles:[";
                 $prefix="";
                // fill up the logfn if its blank
                if (!sizeof($other_logfn)) {
                    for ($r=0;$r<$num_roles;$r++) {
                        $other_logfn[]=3;
                    }
                }
                 
                for ($r=0;$r<$num_roles;$r++) {
                    // role_var_0=
                    $rt=ini_get("/dev/dev".$other_arr[$d].".ini","config","role_type_".$r,0);
                    $ri=ini_get("/dev/dev".$other_arr[$d].".ini","config","role_idx_".$r,0);
                    
                    if ($rt==0) $var="do_desc_".$ri;
                    if ($rt==1) $var="di_desc_".$ri;
                    if ($rt==2) $var="ro_desc_".$ri;
                    if ($rt==3) $var="rw_desc_".$ri;
                    if ($rt==22) $var="ro_desc_".$ri;
                    if ($rt==23) $var="rw_desc_".$ri;
                    if (($rt>=24) && ($rt<=28)) $var="ro_desc_".$ri;
                    if ($rt==29) $var="rw_desc_".$ri;
                    if ($rt==30) $var="rw_desc_".$ri;
                    if ($rt==34) $var="rw_desc_".$ri;
                    if ($rt==35) $var="rw_desc_".$ri;

                    //print("r=".$r."\r\nrt=".$rt."\r\nri=".$ri."\r\nvar=".$var);
                    $role_desc=ini_get("/dev/dev".$other_arr[$d].".ini","config",$var,"");
                    if (in_array($other_roles, $r)) 
                        $sel="true";
                    else $sel="false";
                    $n=$other_names[$r];
                    if (!$n) 
                        $n=ini_get("/dev/dev".$other_arr[$d].".ini","config","role_var_".$r,"");
                    if ($use_qos) {    
                        $role_name=ini_get("/dev/dev".$other_arr[$d].".ini","config","role_var_".$r,"");
                        if ($other_qostype[$r]==0) {
                            if (is_array($qos_signals[$role_name])) {
                                $other_qostype[$r]=$qos_signals[$role_name][0];
                            }
                        }
        
                        $st.=$prefix."{role_idx:".$r.",role_name:\"".$n."\",\"role_desc\":\"".$role_desc."\",\"selected\":".$sel.",'logfn':".intval($other_logfn[$r]).",'qostype':'".($other_qostype[$r])."'}"; //
                    } else {
                        $st.=$prefix."{role_idx:".$r.",role_name:\"".$n."\",\"role_desc\":\"".$role_desc."\",\"selected\":".$sel.",'logfn':".intval($other_logfn[$r])."}"; //
                    }
                    print($st);$st='';
                    $prefix=",";
                }
                 
                $st.="] }";
                $prefix2=",";
                print($st);
            
            
       }
   ?>];
   
   $scope.inverters=[<?
        $inv_arr=explode($inv_types,',');
        
      $prefix2="";
       for ($d=0;$d<sizeof($inv_arr);$d++) {
            if ($inv_used[$d]) {
                $inv_roles_str=ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_roles","").ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_roles2","").ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_roles3","");
                if ($inv_roles_str) {
                    $inv_roles=explode($inv_roles_str,',');
                } else $inv_roles=array();
                
                $inv_logfn_str=ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_logfn","").ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_logfn2","").ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_logfn3","");
                if ($inv_logfn_str) {
                    $inv_logfn=explode($inv_logfn_str,',');
                } else $inv_logfn=array();
            
            $other_qostype_str=ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_qostype","");
                $cnt=1;
                $done=0;
                while (!$done) {
                    $more_qostype_str=ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_qostype".$cnt,"");
                    //print("MORE=".$more_qostype_str);
                    if (strlen($more_qostype_str)) {
                        $other_qostype_str.=",".$more_qostype_str;
                        $cnt++;
                    } else $done=1;
                }
                
                if ($other_qostype_str) {
                    $other_qostype=explode($other_qostype_str,',');
                } else $other_qostype=array();
                $st=$prefix2."{device_type_id:".$inv_arr[$d].",";
                $st.="device_idx:".$d.",";
                $st.="name:\"".ini_get("/dev/dev".$inv_arr[$d].".ini","config","name","")." (".$inv_arr[$d].")\"";
                $num_roles=ini_get("/dev/dev".$inv_arr[$d].".ini","config","num_roles",0);
                $st.=",roles:[";
                                // fill up the logfn if its blank
                if (!sizeof($inv_logfn)) {
                    for ($r=0;$r<$num_roles;$r++) {
                        $inv_logfn[]=3;
                    }
                }

                $prefix="";
                if ($inv_arr[$d]==7000) {       // Delta Inverter - Special Case
                    $st.=$prefix."{role_idx:0,role_name:\"AC_Voltage_AN\",\"role_desc\":\"AC Voltage Phase A to Neutral\",\"selected\":".(in_array($inv_roles,0)?"true":"false").",\"logfn\":".intval($inv_logfn[0])."},";
                    $st.=$prefix."{role_idx:1,role_name:\"AC_Voltage_BN\",\"role_desc\":\"AC Voltage Phase B to Neutral\",\"selected\":".(in_array($inv_roles,1)?"true":"false").",\"logfn\":".intval($inv_logfn[1])."},";
                    $st.=$prefix."{role_idx:2,role_name:\"AC_Voltage_CN\",\"role_desc\":\"AC Voltage Phase C to Neutral\",\"selected\":".(in_array($inv_roles,2)?"true":"false").",\"logfn\":".intval($inv_logfn[2])."},";
                    $st.=$prefix."{role_idx:3,role_name:\"AC_Current_A\",\"role_desc\":\"AC Current Phase A\",\"selected\":".(in_array($inv_roles,3)?"true":"false").",\"logfn\":".intval($inv_logfn[3])."},";
                    $st.=$prefix."{role_idx:4,role_name:\"AC_Current_B\",\"role_desc\":\"AC Current Phase B\",\"selected\":".(in_array($inv_roles,4)?"true":"false").",\"logfn\":".intval($inv_logfn[4])."},";
                    $st.=$prefix."{role_idx:5,role_name:\"AC_Current_C\",\"role_desc\":\"AC Current Phase C\",\"selected\":".(in_array($inv_roles,5)?"true":"false").",\"logfn\":".intval($inv_logfn[5])."},";
                    $st.=$prefix."{role_idx:6,role_name:\"AC_Active_Power_A\",\"role_desc\":\"AC Active Power Phase A\",\"selected\":".(in_array($inv_roles,6)?"true":"false").",\"logfn\":".intval($inv_logfn[6])."},";
                    $st.=$prefix."{role_idx:7,role_name:\"AC_Active_Power_B\",\"role_desc\":\"AC Active Power Phase B\",\"selected\":".(in_array($inv_roles,7)?"true":"false").",\"logfn\":".intval($inv_logfn[7])."},";
                    $st.=$prefix."{role_idx:8,role_name:\"AC_Active_Power_C\",\"role_desc\":\"AC Active Power Phase C\",\"selected\":".(in_array($inv_roles,8)?"true":"false").",\"logfn\":".intval($inv_logfn[8])."},";
                    $st.=$prefix."{role_idx:9,role_name:\"AC_Frequency_A\",\"role_desc\":\"AC Frequency Phase A\",\"selected\":".(in_array($inv_roles,9)?"true":"false").",\"logfn\":".intval($inv_logfn[9])."},";
                    $st.=$prefix."{role_idx:10,role_name:\"AC_Frequency_B\",\"role_desc\":\"AC Frequency Phase B\",\"selected\":".(in_array($inv_roles,10)?"true":"false").",\"logfn\":".intval($inv_logfn[10])."},";
                    $st.=$prefix."{role_idx:11,role_name:\"AC_Frequency_C\",\"role_desc\":\"AC Frequency Phase C\",\"selected\":".(in_array($inv_roles,11)?"true":"false").",\"logfn\":".intval($inv_logfn[11])."},";
                    print($st);
                    $st="";
                    $st.=$prefix."{role_idx:12,role_name:\"AC_Active_Power\",\"role_desc\":\"Total AC Active Power\",\"selected\":".(in_array($inv_roles,12)?"true":"false").",\"logfn\":".intval($inv_logfn[12])."},";
                    $st.=$prefix."{role_idx:13,role_name:\"DC_Power\",\"role_desc\":\"Total DC Power\",\"selected\":".(in_array($inv_roles,13)?"true":"false").",\"logfn\":".intval($inv_logfn[13])."},";
                    $st.=$prefix."{role_idx:14,role_name:\"DC_Current\",\"role_desc\":\"Total DC Current\",\"selected\":".(in_array($inv_roles,14)?"true":"false").",\"logfn\":".intval($inv_logfn[14])."},";
                    
                    $st.=$prefix."{role_idx:15,role_name:\"kWh_Total_Active\",\"role_desc\":\"Lifetime Generation\",\"selected\":".(in_array($inv_roles,15)?"true":"false").",\"logfn\":".intval($inv_logfn[15])."},";
                    $st.=$prefix."{role_idx:16,role_name:\"kWh_Day_Active\",\"role_desc\":\"Daily Generation\",\"selected\":".(in_array($inv_roles,16)?"true":"false").",\"logfn\":".intval($inv_logfn[16])."},";
                    $st.=$prefix."{role_idx:17,role_name:\"Status_Code\",\"role_desc\":\"Vendor-defined Operating State\",\"selected\":".(in_array($inv_roles,17)?"true":"false").",\"logfn\":".intval($inv_logfn[17])."},";
                
                    $st.=$prefix."{role_idx:18,role_name:\"Event_Code\",\"role_desc\":\"Vendor-defined Events & Errors\",\"selected\":".(in_array($inv_roles,18)?"true":"false").",\"logfn\":".intval($inv_logfn[18])."},";
                    $st.=$prefix."{role_idx:19,role_name:\"Power_Limit_Percent\",\"role_desc\":\"Power Limit Percent\",\"selected\":".(in_array($inv_roles,19)?"true":"false").",\"logfn\":".intval($inv_logfn[19])."}";
                } else {
                    for ($r=0;$r<$num_roles;$r++) {
                            // role_var_0=
                        $rt=ini_get("/dev/dev".$inv_arr[$d].".ini","config","role_type_".$r,0);
                        $ri=ini_get("/dev/dev".$inv_arr[$d].".ini","config","role_idx_".$r,0);
                        
                        if ($rt==0) $var="do_desc_".$ri;
                        if ($rt==1) $var="di_desc_".$ri;
                        if ($rt==2) $var="ro_desc_".$ri;
                        if ($rt==31) $var="ro_desc_".$ri;
                        if ($rt==3) $var="rw_desc_".$ri;
                        if ($rt==22) $var="ro_desc_".$ri;
                        if ($rt==23) $var="rw_desc_".$ri;
                        if (($rt>=24) && ($rt<=28)) $var="ro_desc_".$ri;
                        if ($rt==29) $var="rw_desc_".$ri;
                        if ($rt==30) $var="rw_desc_".$ri;
                        if ($rt==34) $var="rw_desc_".$ri;
                        if ($rt==35) $var="rw_desc_".$ri;
    
                        //print("r=".$r."\r\nrt=".$rt."\r\nri=".$ri."\r\nvar=".$var);
                        if (in_array($inv_roles, $r)) 
                            $sel="true";
                        else $sel="false";
                        $role_desc=ini_get("/dev/dev".$inv_arr[$d].".ini","config",$var,"");                        
                        if ($use_qos) {
                             $role_name=ini_get("/dev/dev".$inv_arr[$d].".ini","config","role_var_".$r,"");
                            if (!isset($other_qostype[$r])) {
                                if (is_array($qos_signals[$role_name])) {
                                    $other_qostype[$r]=$qos_signals[$role_name][0];
                                }
                            }
                            $st.=$prefix."{role_idx:".$r.",role_name:\"".
                                ini_get("/dev/dev".$inv_arr[$d].".ini","config","role_var_".$r,"")."\",\"role_desc\":\"".
                                $role_desc."\",\"selected\":".$sel.",\"logfn\":".intval($inv_logfn[$r]).",'qostype':'".($other_qostype[$r])."'}"; /**/
                        } else {
                        $st.=$prefix."{role_idx:".$r.",role_name:\"".
                                ini_get("/dev/dev".$inv_arr[$d].".ini","config","role_var_".$r,"")."\",\"role_desc\":\"".
                                $role_desc."\",\"selected\":".$sel.",\"logfn\":".intval($inv_logfn[$r])."}"; /**/
                        }

                        
                            $prefix=",";
                        print($st);
                        $st='';
                    }
                }
                
                $st.="] }";
                $prefix2=",";
                print($st);
            }
            
       } ?>
   ];

    $scope.other_variables={"roles": [<?
    for ($i=0;$i<sizeof($all_variables);$i++) {
        if ($i) print(",");
        print("{role_idx:".$i.",role_name:\"".$all_variables[$i][0]."\",\"role_desc\":\"".$all_variables[$i][1]."\",\"selected\":".($all_variables[$i][2]>0?"true":"false").",\"logfn\":3,\"readonly\":".($all_variables[$i][3]>0?"true":"false")."}"); 
    }
    $all_variables=0;
    ?>]};
    
   $scope.ow={"roles": [<?
       $num_ow=intval($ez_arr['num_temp']);
       for ($d=0;$d<$num_ow;$d++) {
            $addr=$ez_arr["ow".$d."_device_address"];
            $name=$ez_arr["ow".$d."_name"];
            $logged=$ez_arr["ow".$d."_logged"];
            $st="{role_idx:".$d.",role_desc:\"".$addr."\",";
            $st.="\"selected\":".($logged>0?"true":"false").",'logfn':3,"; 
            $st.="role_name:\"".$name."\"},";
            if ($name) {
                print($st);
            }
            
       }
   ?>]};    
   $scope.loading=0;
   $gscope=$scope;
 $scope.countLoggedRoles=function() {
        num=0;
        tmpnum=0;
        for (ii=0;ii<$scope.inverters.length;ii++) {
            for (jj=0;jj<$scope.inverters[ii].roles.length;jj++) {
                if ($scope.inverters[ii].roles[jj].selected==true)
                    for (kk=0;kk<$scope.inv.length;kk++) {
                        if ($scope.inv[kk].device_idx==$scope.inverters[ii].device_idx)
                            num++;
                    }
            }
        }
        console.log("Invert roles count:"+(num-tmpnum));
        tmpnum=num;
        for (ii=0;ii<$scope.power_meters.length;ii++) {
            for (jj=0;jj<$scope.power_meters[ii].roles.length;jj++) {
                if ($scope.power_meters[ii].roles[jj].selected==true)
                    for (kk=0;kk<$scope.pm.length;kk++) {
                        if ($scope.pm[kk].device_idx==$scope.power_meters[ii].device_idx)
                            num++;
                    }
            }
        }
        console.log("PM roles count:"+(num-tmpnum));
        tmpnum=num;
        
         for (ii=0;ii<$scope.other_devices.length;ii++) {
            for (jj=0;jj<$scope.other_devices[ii].roles.length;jj++) {
                if ($scope.other_devices[ii].roles[jj].selected==true)
                    for (kk=0;kk<$scope.other.length;kk++) {
                        if ($scope.other[kk].device_idx==$scope.other_devices[ii].device_idx)
                            num++;
                    }
            }
        }
        console.log("Other Dev roles count:"+(num-tmpnum));
        tmpnum=num;
        
        for (jj=0;jj<$scope.other_variables.roles.length;jj++) {
                if ($scope.other_variables.roles[jj].selected==true)
                    num++;
        }
        
        console.log("Other Var count:"+(num-tmpnum));
        tmpnum=num;
        
        for (jj=0;jj<$scope.ow.roles.length;jj++) {
                if ($scope.ow.roles[jj].selected==true)
                    num++;
        }
        console.log("Onewire count:"+(num-tmpnum));
        tmpnum=num;
    
        return num;
    }   
    $scope.add_global=function() {
        $scope.other_variables.roles.push({"role_idx":$scope.other_variables.length,"role_name":"newvar","role_desc":"Global Variable","selected":true,"logfn":3});
        alert("The global variable was added to the bottom of the list.  Please enter the name for the global variable.");
    }
    
    $scope.toggleAll=function(item) {
        item.all_checked=!item.all_checked;
        console.log(item);
        for (i=0;i<item.roles.length;i++) {
            
            item.roles[i].selected=item.all_checked;
        }
    }
    $scope.setMeterFn=function(fntype) {
        for (i=0;i<$scope.power_meters.length;i++) {
            for (j=0;j<$scope.power_meters[i].roles.length;j++) {
                $scope.power_meters[i].roles[j].logfn=fntype;
            }
        }
    }
    $scope.setOtherFn=function(fntype) {
        for (i=0;i<$scope.other_devices.length;i++) {
            for (j=0;j<$scope.other_devices[i].roles.length;j++) {
                $scope.other_devices[i].roles[j].logfn=fntype;
            }
        }
    }
    
    $scope.setInvFn=function(fntype) {
        for (i=0;i<$scope.inverters.length;i++) {
            for (j=0;j<$scope.inverters[i].roles.length;j++) {
                $scope.inverters[i].roles[j].logfn=fntype;
            }
        }
    }
   

   $scope.prev=function() {
        document.location='/app/ezconfig.cgi?stage=1<? if ($use_qos) print("&qos=1"); ?>';
   }
  <? if ($use_qos) { ?>
  $scope.getQOSSignalType=function(str) {
        for (ii=0;ii<$scope.qos_signals.length;ii++) {
            if ($scope.qos_signals[ii].name==str) return $scope.qos_signals[ii].type;
        }
        return "n/a";
    }
    <? } ?>
   $scope.saveSettings=function(moveNext) {
       post_data="";
        //alert('save ');
        for (i=0;i<$scope.power_meters.length;i++) {
            //alert($scope.power_meters[i].roles.length);
            roles="";
            roles2="";
            fn="";
            qosprefix="";
            prefix="";
            qostype="";
            qosdatatype="";
            dataprefix="";
            qos_splitlen=0;
            qos_splitcount=1;
            fnprefix="";

            
            for (r=0;r<$scope.power_meters[i].roles.length;r++) {
            <?           if ($use_qos) { ?>
            //console.log($scope.power_meters[i].roles[r]);
                qostype=qostype + qosprefix + $scope.power_meters[i].roles[r].qostype;
                qosdatatype=qosdatatype+dataprefix+$scope.getQOSSignalType($scope.power_meters[i].roles[r].qostype);
                qosprefix=",";
                if (qostype.length-qos_splitlen>200) {
                    qostype+="&dev"+$scope.power_meters[i].device_type_id+"_qostype"+qos_splitcount+"=";
                    //qosdatatype+="&dev"+$scope.power_meters[i].device_type_id+"_qosdatatype"+qos_splitcount+"=";
                    qosprefix="";
                    qos_splitlen=qostype.length;
                    qos_splitcount++;
                }
                
<?             }  ?>
                //alert($scope.power_meters[i].roles[r].selected);
                fn=fn+(fnprefix+$scope.power_meters[i].roles[r].logfn);
                fnprefix=",";
                dataprefix=",";
                //qosprefix=",";

                if ($scope.power_meters[i].roles[r].selected) {
                    if (roles.length + r > 200) {
                        if (roles2.length==0) {
                            roles2 = prefix+r;
                        } else {
                            if (roles2.length + r > 200) {
                                roles3 = roles3+prefix+r;
                            } else {
                                roles2 = roles2+prefix+r;
                            //console.log("roles2="+roles2);
                            }
                        }
                    } else
                        roles=roles+prefix+r;
                    
                    prefix=",";
                }
            }
            if (post_data.length) post_data=post_data+"&";
            post_data+="dev"+$scope.power_meters[i].device_type_id+"_roles="+roles;
            post_data+="&dev"+$scope.power_meters[i].device_type_id+"_roles2="+roles2;
            post_data+="&dev"+$scope.power_meters[i].device_type_id+"_logfn="+fn;
            <? if ($use_qos) { ?>
                post_data+="&dev"+$scope.power_meters[i].device_type_id+"_qostype="+qostype;
                post_data+="&dev"+$scope.power_meters[i].device_type_id+"_qosdatatype="+qosdatatype;
            <? } ?>
            

        }
        
        for (i=0;i<$scope.other_devices.length;i++) {
            roles="";
            fn="";
            prefix="";
            fnprefix="";
            fnlprefix="";
            names="";
            qosprefix="";
            prefix="";
            rolesprefix="";
            qostype="";
            roles_splitlen=0;
            roles_splitcount=1;
            qosdatatype="";
            dataprefix="";
            qos_splitlen=0;
            names_splitlen=0;
            names_splitcount=1;
            qos_splitcount=1;
            fnprefix="";
            nameprefix="";
            fn_splitlen=0;
            fn_splitcount=1;
            
            for (r=0;r<$scope.other_devices[i].roles.length;r++) {
                //alert($scope.power_meters[i].roles[r].selected);
                if ($scope.other_devices[i].device_type_id==8010) {
                  if (r<2) {
                    $scope.other_devices[i].roles[r].selected=true;
                  }
                }
                if (fn.length-fn_splitlen>200) {
                    fn+="&dev"+$scope.other_devices[i].device_type_id+"_logfn"+fn_splitcount+"=,";
                    fnlprefix="";
                    fn_splitlen=fn.length;
                    fn_splitcount++;
                }
                
                fn=fn+(fnlprefix+$scope.other_devices[i].roles[r].logfn);
                fnlprefix=",";
                fnprefix=",";
                
                if (names.length-names_splitlen>200) {
                    names+="&dev"+$scope.other_devices[i].device_type_id+"_names"+names_splitcount+"=,";
                    //qosdatatype+="&dev"+$scope.power_meters[i].device_type_id+"_qosdatatype"+qos_splitcount+"=";
                    nameprefix="";
                    names_splitlen=names.length;
                    names_splitcount++;
                }
                names=names+nameprefix+$scope.other_devices[i].roles[r].role_name;
                nameprefix=",";
                
<? if ($use_qos) { ?>                
                qostype=qostype+qosprefix+$scope.other_devices[i].roles[r].qostype;
                qosdatatype=qosdatatype+dataprefix+$scope.getQOSSignalType($scope.other_devices[i].roles[r].qostype);
                fnprefix=",";
                dataprefix=",";
                qosprefix=",";
                if (qostype.length-qos_splitlen>200) {
                    qostype+="&dev"+$scope.other_devices[i].device_type_id+"_qostype"+qos_splitcount+"=";
                    //qosdatatype+="&dev"+$scope.power_meters[i].device_type_id+"_qosdatatype"+qos_splitcount+"=";
                    qosprefix="";
                    qos_splitlen=qostype.length;
                    qos_splitcount++;
                }
<? } ?>                
                if ($scope.other_devices[i].roles[r].selected && $scope.other_devices[i].roles[r].role_name.length>0) {
                    //alert("selected "+r);
                    roles=roles+rolesprefix+r;
                    
                    if (roles.length-roles_splitlen>200) {
                        roles+="&dev"+$scope.other_devices[i].device_type_id+"_roles"+roles_splitcount+"=";
                    //qosdatatype+="&dev"+$scope.power_meters[i].device_type_id+"_qosdatatype"+qos_splitcount+"=";
                        rolesprefix="";
                        roles_splitlen=roles.length;
                        roles_splitcount++;
                    }
                    
                    rolesprefix=",";
                    prefix=",";
                }
                
            }
            
            if (post_data.length) post_data=post_data+"&";
            post_data+="dev"+$scope.other_devices[i].device_type_id+"_roles="+roles;
            post_data+="&dev"+$scope.other_devices[i].device_type_id+"_logfn="+fn;
            post_data+="&dev"+$scope.other_devices[i].device_type_id+"_names="+names;
<? if ($use_qos) { ?>                
            post_data+="&dev"+$scope.other_devices[i].device_type_id+"_qostype="+qostype;
            post_data+="&dev"+$scope.other_devices[i].device_type_id+"_qosdatatype="+qosdatatype;
<? } ?>                
            


        }
        for (i=0;i<$scope.inverters.length;i++) {
            roles="";
            roles2="";
            roles3="";
            fn="";
            fn2="";
            fn3="";
            prefix="";
            fnprefix="";
                        fnprefix="";
            qosdatatype="";
            qostype="";
            qos_splitlen=0;
            qos_splitcount=1;
             qosprefix="";
             dataprefix="";

            for (r=0;r<$scope.inverters[i].roles.length;r++) {
                //alert($scope.power_meters[i].roles[r].selected);
                
                if (fn.length<200) {
                    fn=fn+fnprefix+$scope.inverters[i].roles[r].logfn;
                } else {
                    if (!fn2.length) {
                        fn2=fnprefix+$scope.inverters[i].roles[r].logfn;
                    } else {
                        if (fn2.length<200) {
                            fn2=fn2+fnprefix+$scope.inverters[i].roles[r].logfn;
                        } else {
                            if (!fn3.length) {
                                fn3=fnprefix+$scope.inverters[i].roles[r].logfn;
                            } else {
                                fn3=fn3+fnprefix+$scope.inverters[i].roles[r].logfn;
                            }
                            
                        }
                    }
                }
                fnprefix=",";
<? if ($use_qos) { ?>                
                
                qostype=qostype+qosprefix+$scope.inverters[i].roles[r].qostype;
                qosdatatype=qosdatatype+dataprefix+$scope.getQOSSignalType($scope.inverters[i].roles[r].qostype);      
                fnprefix=",";
                qosprefix=",";
                dataprefix=",";
                if (qostype.length-qos_splitlen>200) {
                    qostype+="&dev"+$scope.inverters[i].device_type_id+"_qostype"+qos_splitcount+"=";
                    qosprefix="";
                    qos_splitlen=qostype.length;
					qos_splitcount++;
                }
<? } ?>
                if ($scope.inverters[i].roles[r].selected) {
                    //alert("selected "+r);
                    if (roles.length + r > 200) {
                        if (roles2.length==0) {
                            roles2 = prefix+r;
                        } else {
                            if (roles2.length + r > 200) {
                                roles3 = roles3+prefix+r;
                            } else {
                                roles2 = roles2+prefix+r;
                            //console.log("roles2="+roles2);
                            }
                        }
                    } else
                        roles=roles+prefix+r;
                    
                    prefix=",";
                }
            }
            if (post_data.length) post_data=post_data+"&";
            post_data+="dev"+$scope.inverters[i].device_type_id+"_roles="+roles;
            post_data+="&dev"+$scope.inverters[i].device_type_id+"_roles2="+roles2;
            post_data+="&dev"+$scope.inverters[i].device_type_id+"_roles3="+roles3;
            post_data+="&dev"+$scope.inverters[i].device_type_id+"_logfn="+fn;
            post_data+="&dev"+$scope.inverters[i].device_type_id+"_logfn2="+fn2;
            post_data+="&dev"+$scope.inverters[i].device_type_id+"_logfn3="+fn3;
<? if ($use_qos) { ?>                
            post_data+="&dev"+$scope.inverters[i].device_type_id+"_qostype="+qostype;
            post_data+="&dev"+$scope.inverters[i].device_type_id+"_qosdatatype="+qosdatatype;
<? } ?>
            
        }
            otherprefix=",";
            other_splitlen=0;
            other_splitcount=1;
            
            gvars="";
                
            for (r=0;r<$scope.other_variables.roles.length;r++) {
                if ($scope.other_variables.roles[r].selected && $scope.other_variables.roles[r].role_name.length>0) {
                    if (gvars.length-other_splitlen>200) {
                        gvars+="&logged_vars"+other_splitcount+"=";
                        otherprefix="";
                        other_splitlen=gvars.length;
        				other_splitcount++;
                    }

                    if (gvars.length) gvars=gvars+otherprefix;
                    otherprefix=",";
                    gvars=gvars+$scope.other_variables.roles[r].role_name;
                  
                }
            }
            console.log($scope.ow);
            for (r=0;r<$scope.ow.roles.length;r++) {
                if ($scope.ow.roles[r].selected) {
                  post_data+=post_data.length?'&ow'+r+"_logged=1":'ow'+r+"_logged=1";
                } else post_data+=post_data.length?'&ow'+r+"_logged=0":'ow'+r+"_logged=0";
            }
            
             post_data+="&logged_vars="+gvars;
             if (other_splitcount>0) {
               post_data+="&logged_vars"+(other_splitcount)+"=";
             }
       post_config="EZConfig.ini";
       post_section="config";
       $http.post('/app/configsave.cgi?config='+post_config+'&section='+post_section,post_data)
        .then(function (response) {
          var data = response.data; 
          $scope.successmsg=(Number(data.status)==1)?"Saved Settings":"Error Saving";
          $scope.errormsg=data.error;
          $scope.sysmsg=data.sysmsg;
          if (moveNext) {
            document.location='/app/ezconfig.cgi?stage=3<? if ($use_qos) print("&qos=1"); ?>';
          }
          return data;
        }, function(reason) {
            $scope.errormsg="Error saving settings";
            $scope.successmsg="";
        });
   }
}
</script>
<? } // stage=2

/********************************************************************************************************* STAGE 3 */        
if ($_GET['stage']==3) { 
    if ($_SERVER['HW_PLATFORM']>=20) {
    define("NUM_TCP_CHANNELS",20);
} else {
    define("NUM_TCP_CHANNELS",10);
}
if ($_GET['qos']) $use_qos=1;
?>

<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/"><? print(lang('HOME','settings')) ?></a></li>
    <li class="breadcrumb-item"><a href="/app/settings.cgi"><? print(lang('CONTROL_PANEL','settings')) ?></a></li>
    <li class="breadcrumb-item active" aria-current="page"><? print(lang('PAGE_TITLE','ezconfig')) ?></li>
  </ol>
</nav>

<!-- NAVBAR -->
<h4><i class="icon-cog"></i>&nbsp;<? print(lang('STAGE3_TITLE','ezconfig')) ?>: <? print(lang('S3_TITLE','ezconfig')) ?></h4>
<ul class="nav justify-content-end">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="collapse" href="#collapseHelp" role="button" aria-expanded="false" aria-controls="collapseExample">
        <? print(lang('HELP','ezconfig')) ?>   
  </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" onclick="document.location='/app/settings.cgi';"><i class="icon-remove"></i> <? print(lang('CLOSE','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="prev()" ><i class="icon-back"></i> <? print(lang('PREVIOUS','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="generate()" ><i class="icon-cog"></i> <? print(lang('GENERATE','ezconfig')) ?></a>
  </li>

</ul>
<!-- HELP -->
<div class="collapse" id="collapseHelp">
  <div class="card card-body">
    
    <? print(lang('HELP1','ezconfig')) ?><br>
    <? print(lang('HELP2','ezconfig')) ?><br>
    <? print(lang('HELP3','ezconfig')) ?><br>
    <? print(lang('HELP4','ezconfig')) ?><br>
    <? print(lang('HELP5','ezconfig')) ?><br>
    <? print(lang('HELP6','ezconfig')) ?><br>
    <? print(lang('HELP7','ezconfig')) ?><br>
  </div>
  <br/>
</div>
<div class="alert alert-success" ng-cloak ng-show="successmsg"> <button type="button" class="close" ng-click='successmsg=""'>&times;</button>{{successmsg}}</div>
<div class="alert alert-danger" ng-cloak ng-show="errormsg"> <button type="button" class="close" ng-click='errormsg=""'>&times;</button>{{errormsg}}</div>
<div class="alert alert-info" ng-cloak ng-show="infomsg"> <button type="button" class="close" data-dismiss="alert">&times;</button>{{infomsg}}</div>
<div class="alert alert-secondary" ng-cloak ng-show="loading"><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></div>
<form name="form" class="css-form form-horizontal" novalidate>

<!-- VARIABLES -->
<? 
    $inv_cnt=ini_get("/config/EZConfig.ini","config",'inv_count',0);
    $pm_cnt=ini_get("/config/EZConfig.ini","config",'pm_count',0);
    $ez_arr = ini_get_array("/config/EZConfig.ini","config");
?>            

<div ng-init="inv_count=<? print($inv_cnt); ?>;">
<div ng-init="pm_count=<? print($pm_cnt); ?>;">
<div ng-init="use_temp=<? print(intval($ez_arr['use_temp'])); ?>;">

<div class="card">
    <div class="card-body">
        <h5 class="card-title"><? print(lang('S3_TITLE','ezconfig')) ?></h5>
        <p class="card-text">    
            <? print(lang('S3_2','ezconfig')) ?>
            <div class='alert alert-danger'><div class='row-fluid'><div class='pull-left'><i class="icon-warning-sign icon-4x"></i></div>
            <div style='margin-left:5em'><? print(lang('S3_3','ezconfig')) ?><br>
            <button class="btn btn-outline-secondary btn-large " ng-click="makeBackup()"><i class="icon-check"></i> <? print(lang('BACKUP_NOW','ezconfig')) ?></button></div></div>            
        </p>
    </div>
</div>
<br/>
<div class="card" >
    <div class="card-body">
        <h5 class="card-title"><? print(lang('REVIEW','ezconfig')) ?></h5>
        <h6 class="card-subtitle mb-2 text-muted"><? print(lang('REVIEW_SUB','ezconfig')) ?></h6>
        <p class="card-text">
            Total Logged Roles: {{countLoggedRoles()}}
<?

if ($ez_arr['module_power_control']) {
    $plant_size=0;
    for ($n=0;$n<$ez_arr['inv_count'];$n++) {
        $plant_size += intval($ez_arr['inv'.$n."_rating"]);
    }
    
?>
            <br/>
            <div class="card" ng-hide='inv.length==0'>
                <div class="card-body">
                    <h5 class="card-title text-danger">Power Control</h5>
                    <p class="card-text">
                    <? if ($ez_arr['sync_power_control']) { ?>
                        <table class='table' summary="Meters" >
                        <? for ($m=0;$m<$ez_arr['pm_count'];$m++) { ?>
                            <tr>
                                <td><span class="badge badge-danger badge-pill"><? print($ez_arr['pm'.$m."_id"]); ?></span></td>
                                <td><h5 class='badge badge-secondary'><strong><? print($ez_arr['pm'.$m."_device_name"]); ?></strong></h5></td>
                                <td><strong><? print($ez_arr['pm'.$m."_device_name"]); ?></strong> is connected to <? 
                                    if ($ez_arr['pm'.$m."_type"]==1) {
                                        print("a genset rated at ".$ez_arr['pm'.$m.'_dg_rating']." kVA.  Wattmon has calculated a 30%-35%; minimum loading requirement on the kW Value.  With a default PF of 0.8, the kW value for this genset is calculated as ");
                                        print(intval(($ez_arr['pm'.$m.'_dg_rating']*0.8))." kW. Min/Max set points for this meter are ".intval($ez_arr['pm'.$m.'_dg_rating']*0.8*0.3)." and ".intval($ez_arr['pm'.$m.'_dg_rating']*0.8*0.35)." kW.");
                                    } else if ($ez_arr['pm'.$m."_type"]==2) {
                                        print("the grid. Wattmon has calculated the plant size as ".intval($plant_size)."kW. Min/Max set points for this meter are 5-7%; of the plant size: ".intval($plant_size*0.05)." and ".intval($plant_size*0.07)." kW.");
                                    } else {
                                        print("a meter that does not affect power control.");
                                    };
                                    
                                ?>    
                                
                            </tr>
                        <? } ?>
                        </table> 
                        <? } else { ?>
                        Power control settings will not be modified.   This will mean that you need to manually check the Power COntrol configuration after completing the EZConfig to ensure that settings are properly done.
                        <? } ?>
                    </p>
                </div>
            </div>
<? 
}
?>
            
            <div class="card" ng-hide='pm.length==0'>
                <div class="card-body">
                    <h5 class="card-title text-danger"><? print(lang('POWER_METERS','ezconfig')) ?></h5>
                    <p class="card-text">
                        <table class='table' summary="Inverters" >
                            <tr ng-repeat="item in pm">
                                <td><a name='pm{{$index}}'></a><span class="badge badge-danger badge-pill">{{item.id}}</span></td>
                                
                                <td><h5 class='badge badge-secondary'><strong>{{item.name}} on {{makeBus(item.bus)}}</strong></h5></td>
                                <td><strong>{{power_meters[item.device_idx].name}}</strong>
                                <table class='table table-striped' summary="Roles" >
                                    <tr>
                                    <td scope="col"><strong>Role</strong></td>
                                    <td scope="col"><strong>Description</strong></td>
                                    </tr>
                                    <tr ng-repeat="role in power_meters[item.device_idx].roles" ng-show='role.selected==true'>
                                        <td><strong>{{item.name}}_{{role.role_name}}</strong></td>
                                        <td><i>{{role.role_desc}}</i></td>
                                    </tr>
                                </table>
                                </td>            
                            </tr>
                        </table> 
                    </p>
                </div>
            </div>
            <br/>
            <div class="card" ng-hide='inv.length==0'>
                <div class="card-body">
                    <h5 class="card-title text-danger"><? print(lang('INVERTERS','ezconfig')) ?></h5>
                    <p class="card-text">
                        <table class='table' summary="Inverters" >
                            <tr ng-repeat="item in inv">
                                <td><a name='inv{{$index}}'></a><span class="badge badge-success badge-pill">{{item.id}}</span></td>
                                <td><h5 class='badge badge-secondary'><strong>{{item.name}} on {{makeBus(item.bus)}}</strong></h5></td>
                                <td><strong>{{inverters[item.device_idx].name}}</strong>
                                <table class='table table-striped' summary="Roles" >
                                    <tr>
                                    <td scope="col"><strong>Role</strong></td>
                                    <td scope="col"><strong>Description</strong></td>
                                    </tr>
                                    <tr ng-repeat="role in inverters[item.device_idx].roles" ng-show='role.selected==true'>
                                        <td><strong>{{item.name}}_{{role.role_name}}</strong></td>
                                        <td><i>{{role.role_desc}}</i></td>
                                    </tr>
                                </table>
                                </td>            
                            </tr>
                        </table> 
                    </p>
                </div>
            </div>
            <br/>
            <div class="card" ng-hide='other.length==0'>
                <div class="card-body">
                    <h5 class="card-title text-primary"><? print(lang('OTHER_DEVICES','ezconfig')) ?></h5>
                    <p class="card-text">
                        <table class='table' summary="Other Devices" >
                            <tr ng-repeat="item in other">
                                <td><a name='other{{$index}}'></a><span class="badge badge-primary badge-pill">{{item.id}}</span></td>
                                <td><h5 class='badge badge-secondary'><strong>{{item.name}} on {{makeBus(item.bus)}}</strong></h5></td>
                                <td><strong>{{other_devices[$index].name}}</strong>
                                <table class='table table-striped' summary="Roles" >
                                    <tr>
                                    <td scope="col"><strong>Role</strong></td>
                                    <td scope="col"><strong>Description</strong></td>
                                    </tr>
                                    <tr ng-repeat="role in other_devices[$index].roles" ng-show='role.selected==true'>
                                        <td><strong>{{makeOtherPrefix(item)}}{{role.role_name}}</strong></td>
                                        <td><i>{{role.role_desc}}</i></td>
                                    </tr>
                                </table>
                                </td>            
                            </tr>
                        </table> 
                    </p>
                </div>
            </div>
            <br/>
            <div class="card" ng-hide='other_variables.length==0'>
                <div class="card-body">
                    <h5 class="card-title text-primary">Global Variables</h5>
                    <p class="card-text">
                                <table class='table table-striped' summary="Roles" >
                                    <tr>
                                    <td scope="col"><strong>Variable</strong></td>
                                    </tr>
                                    <tr ng-repeat="role in other_variables.roles">
                                        <td><strong>{{role.role_name}}</strong></td>
                                    </tr>
                                </table>
                    </p>
                </div>
            </div>
            <br/>
            <div class="card" ng-show='use_temp'>
                <div class="card-body">
                    <h5 class="card-title text-primary">1-Wire Temperature Sensors</h5>
                    <p class="card-text">
                                <table class='table table-striped' summary="Roles" >
                                    <tr>
                                    <td scope="col"><strong>Variable</strong></td>
                                    <td scope="col"><strong>Address</strong></td>
                                    </tr>
                                    <tr ng-repeat="role in ow.roles">
                                        <td><strong>{{role.role_name}}</strong></td>
                                        <td><strong>{{role.role_desc}}</strong></td>
                                    </tr>
                                </table>
                    </p>
                </div>
            </div>
        </p>
    </div>
</div>

</form>
<script>
var gItems,gHttp;
var count=0;
var app = angular.module('myApp', []);
<?
include("/lib/uphp/array.inc");
        // package manager option

$all_inverters = ini_get_array('/config/devicetypes.ini','Inverter');
$all_inverters = quick_sort($all_inverters,1); // sort by value

$all_meters = ini_get_array('/config/devicetypes.ini','Meter');
$all_meters = quick_sort($all_meters,1); // sort by value

$all_other = ini_get_array('/config/devicetypes.ini','Other');
$all_other = quick_sort($all_other,1); // sort by value

?>
function EZConfigWidget($scope, $timeout,$http) {
   var self = this;
   //alert('init');
   //4028,4099,4098,4024,4023
    $scope.power_meter_types=[<? 
   $pm_types=implode(array_keys($all_meters),',');
   print($pm_types);
   ?>]; 
   $scope.inverter_types=[<?
   $inv_types=implode(array_keys($all_inverters),',');
   print( $inv_types);
     ?>];
   
   <?  $logged_str=ini_get("/config/EZConfig.ini","config","logged_vars","");
//      $logged_str=ini_get("/config/EZConfig.ini","config","logged_vars","");
   $lidx=1;
   while (1) {
       $str=ini_get("/config/EZConfig.ini","config","logged_vars".$lidx,"");
       if (!$str) break;
       else {
           $logged_str.=",".$str;
           $lidx++;
       }
       
   }

   $logged_variables=explode($logged_str,','); 
   
   ?>
   $scope.other_variables={"roles": [<?
    for ($i=0;$i<sizeof($logged_variables);$i++) {
        if ($i) print(",");
        print("{role_idx:".$i.",role_name:\"".$logged_variables[$i]."\",\"role_desc\":\"".$logged_variables[$i]."\",\"selected\":true,'logfn':3}"); 
    }
    ?>]};

   
 
   $scope.pm=[<?
       $num_pm=ini_get('/config/EZConfig.ini','config','pm_count',0);
     //  $pm_used=array();
        $pm_arr=explode($pm_types,',');
        
       $pm_used=indexed_array(1,sizeof($pm_arr));
       $prefix='';
       for ($d=0;$d<$num_pm;$d++) {
            $addr=ini_get("/config/EZConfig.ini","config","pm".$d."_id",0);
            $bus=ini_get("/config/EZConfig.ini","config","pm".$d."_bus",0);
            $name=ini_get("/config/EZConfig.ini","config","pm".$d."_device_name","");
            $idx=ini_get("/config/EZConfig.ini","config","pm".$d."_device_idx",0);
            
            $pm_used[$idx]=1;
            $st=$prefix."{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="bus:".$bus.",";
            $st.="name:\"".$name."\"}";
            $prefix=',';
            print($st);
            
       }
   ?>];
   <?
   //print_r($pm_used); 
   ?>
    $scope.inv=[<?
       $num_pm=ini_get('/config/EZConfig.ini','config','inv_count',0);
      $inv_arr=explode($inv_types,',');
       $inv_used=indexed_array(1,sizeof($inv_arr));
       
       $prefix='';
       for ($d=0;$d<$num_pm;$d++) {
            $addr=ini_get("/config/EZConfig.ini","config","inv".$d."_id",0);
            $bus=ini_get("/config/EZConfig.ini","config","inv".$d."_bus",0);
            $name=ini_get("/config/EZConfig.ini","config","inv".$d."_device_name","");
            $idx=ini_get("/config/EZConfig.ini","config","inv".$d."_device_idx",0);
            $inv_used[$idx]=1;
            $st=$prefix."{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="bus:".$bus.",";
            $st.="name:\"".$name."\"}";
            $prefix=',';

            print($st);
            
       }
   ?>];

   $scope.power_meters=[<?
        $pm_arr=explode($pm_types,',');
        
       $prefix2="";
       for ($d=0;$d<sizeof($pm_arr);$d++) {
            if ($pm_used[$d]==1) {
                $pm_roles_str=ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_roles","").
                ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_roles2","").ini_get("/config/EZConfig.ini","config","dev".$pm_arr[$d]."_role3","");
                if ($pm_roles_str) {
                    $pm_roles=explode($pm_roles_str,',');
                } else $pm_roles=array();
                
                $st=$prefix2."{device_type_id:".$pm_arr[$d].",";
                $st.="device_idx:".$d.",";
                $st.="name:\"".ini_get("/dev/dev".$pm_arr[$d].".ini","config","name","")." (".$pm_arr[$d].")\"";
                $num_roles=ini_get("/dev/dev".$pm_arr[$d].".ini","config","num_roles",0);
                $st.=",roles:[";
                 $prefix="";
                for ($r=0;$r<$num_roles;$r++) {
                    // role_var_0=
                    $rt=ini_get("/dev/dev".$pm_arr[$d].".ini","config","role_type_".$r,0);
                    $ri=ini_get("/dev/dev".$pm_arr[$d].".ini","config","role_idx_".$r,0);
                    
                    if ($rt==0) $var="do_desc_".$ri;
                    if ($rt==1) $var="di_desc_".$ri;
                    if ($rt==31) $var="ro_desc_".$ri;
                    if ($rt==2) $var="ro_desc_".$ri;
                    if ($rt==3) $var="rw_desc_".$ri;
                    if ($rt==22) $var="ro_desc_".$ri;
                    if ($rt==23) $var="rw_desc_".$ri;
                    if (($rt>=24) && ($rt<=28)) $var="ro_desc_".$ri;
                    if ($rt==29) $var="rw_desc_".$ri;
                    if ($rt==30) $var="rw_desc_".$ri;
                    if ($rt==34) $var="rw_desc_".$ri;
                    if ($rt==35) $var="rw_desc_".$ri;

                    //print("r=".$r."\r\nrt=".$rt."\r\nri=".$ri."\r\nvar=".$var);
                    $role_desc=ini_get("/dev/dev".$pm_arr[$d].".ini","config",$var,"");
                    if (in_array($pm_roles, $r)) 
                        $sel="true";
                    else $sel="false";
                    $st.=$prefix."{role_idx:".$r.",role_name:\"".ini_get("/dev/dev".$pm_arr[$d].".ini","config","role_var_".$r,"")."\",\"role_desc\":\"".$role_desc."\",\"selected\":".$sel."}"; //
                    $prefix=",";
                }
                 
                $st.="] }\r\n";
                $prefix2=",";
                print($st);
            }  else {
                $st=$prefix2."{device_type_id:".$pm_arr[$d]."}\r\n";
                $prefix2=",";
                print($st); 
            }
            
       }
   ?>];
    $scope.other=[<?
       $num_other=ini_get('/config/EZConfig.ini','config','other_count',0);
       $other_arr=array();
       for ($d=0;$d<$num_other;$d++) {
            $addr=ini_get("/config/EZConfig.ini","config","other".$d."_id",0);
            $bus=ini_get("/config/EZConfig.ini","config","other".$d."_bus",0);
            $device_type_id=ini_get("/config/EZConfig.ini","config","other".$d."_device_type_id",0);
            $idx=$d;//ini_get("/config/EZConfig.ini","config","other".$d."_device_idx",0);
            $name=ini_get("/config/EZConfig.ini","config","other".$d."_device_name","");
            //$idx=ini_get("/config/EZConfig.ini","config","other".$d."_idx",0);
            $found=0;
            for ($i=0;$i<sizeof($other_arr);$i++) {
                if ($other_arr[$i]==$device_type_id)
                    $found=1;
            }
//            if (!$found)
                $other_arr[]=$device_type_id;

            $st="{id:".$addr.",";
            $st.="device_idx:".$idx.",";
            $st.="device_type_id:".$device_type_id.",";
            $st.="bus:".$bus.",";
            $st.="name:\"".$name."\"},";
            print($st);
            
       }
   ?>];
   $scope.other_devices=[<?

       $prefix2="";
       for ($d=0;$d<sizeof($other_arr);$d++) {
                $other_roles_str=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_roles","");
                $other_logfn_str=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_logfn","");
                $other_names_str=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_names","");
                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_names".$x,"");
                  if (strlen($tmp)) {
                    $other_names_str .=$tmp;
                  } else break;
                  $x++;
                }

                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_logfn".$x,"");
                  if (strlen($tmp)) {
                    $other_logfn_str .=$tmp;
                  } else break;
                  $x++;
                }

                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_roles".$x,"");
                  if (strlen($tmp)) {
                    $other_roles_str .=$tmp;
                  } else break;
                  $x++;
                }
                
                if ($other_logfn_str) {
                    $other_logfn=explode($other_logfn_str,',');
                } else $other_logfn=array();
                
                if ($other_roles_str) {
                    $other_roles=explode($other_roles_str,',');
                } else $other_roles=array();
                
                if ($other_names_str) {
                    $other_names=explode($other_names_str,',');
                } else $other_names=array();
                
                $st=$prefix2."{device_type_id:".$other_arr[$d].",";
                $st.="device_idx:".$d.",";
                $st.="name:\"".ini_get("/dev/dev".$other_arr[$d].".ini","config","name","")." (".$other_arr[$d].")\"";
                $num_roles=ini_get("/dev/dev".$other_arr[$d].".ini","config","num_roles",0);
                $st.=",roles:[";
                 $prefix="";
                for ($r=0;$r<$num_roles;$r++) {
                    // role_var_0=
                    $rt=ini_get("/dev/dev".$other_arr[$d].".ini","config","role_type_".$r,0);
                    $ri=ini_get("/dev/dev".$other_arr[$d].".ini","config","role_idx_".$r,0);
                    
                    if ($rt==0) $var="do_desc_".$ri;
                    if ($rt==1) $var="di_desc_".$ri;
                    if ($rt==2) $var="ro_desc_".$ri;
                    if ($rt==3) $var="rw_desc_".$ri;
                    if ($rt==22) $var="ro_desc_".$ri;
                    if ($rt==23) $var="rw_desc_".$ri;
                    if (($rt>=24) && ($rt<=28)) $var="ro_desc_".$ri;
                    if ($rt==29) $var="rw_desc_".$ri;
                    if ($rt==30) $var="rw_desc_".$ri;
                    if ($rt==34) $var="rw_desc_".$ri;
                    if ($rt==35) $var="rw_desc_".$ri;

                    //print("r=".$r."\r\nrt=".$rt."\r\nri=".$ri."\r\nvar=".$var);
                    $role_desc=ini_get("/dev/dev".$other_arr[$d].".ini","config",$var,"");
                    if (in_array($other_roles, $r)) 
                        $sel="true";
                    else $sel="false";
                    $n=$other_names[$r];
                    if (!$n) 
                        $n=ini_get("/dev/dev".$other_arr[$d].".ini","config","role_var_".$r,"");
                    $st.=$prefix."{role_idx:".$r.",role_name:\"".$n."\",\"role_desc\":\"".$role_desc."\",\"selected\":".$sel.",'logfn':".intval($other_logfn[$r])."}"; //
                    $prefix=",";
                }
                 
                $st.="] }";
                $prefix2=",";
                print($st);
            
            
       }
   ?>];
   $scope.inverters=[<?
        $inv_arr=explode($inv_types,',');
        
      $prefix2="";
       $module_power_control=ini_get("/config/EZConfig.ini","config","module_power_control",0);
       for ($d=0;$d<sizeof($inv_arr);$d++) {
            if ($inv_used[$d]) {
                $inv_roles_str=ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_roles","").ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_roles2","").ini_get("/config/EZConfig.ini","config","dev".$inv_arr[$d]."_roles3","");
                if ($inv_roles_str) {
                    $inv_roles=explode($inv_roles_str,',');
                } else $inv_roles=array();
            
                $st=$prefix2."{device_type_id:".$inv_arr[$d].",";
                $st.="device_idx:".$d.",";
                $st.="name:\"".ini_get("/dev/dev".$inv_arr[$d].".ini","config","name","")." (".$inv_arr[$d].")\"";
                $num_roles=ini_get("/dev/dev".$inv_arr[$d].".ini","config","num_roles",0);
                $st.=",roles:[";
                $prefix="";
                if ($inv_arr[$d]==7000) {       // Delta Inverter - Special Case
                    $st.=$prefix."{role_idx:0,role_name:\"AC_Voltage_AN\",\"role_desc\":\"AC Voltage Phase A to Neutral\",\"selected\":".(in_array($inv_roles,0)?"true":"false")."},";
                    $st.=$prefix."{role_idx:1,role_name:\"AC_Voltage_BN\",\"role_desc\":\"AC Voltage Phase B to Neutral\",\"selected\":".(in_array($inv_roles,1)?"true":"false")."},";
                    $st.=$prefix."{role_idx:2,role_name:\"AC_Voltage_CN\",\"role_desc\":\"AC Voltage Phase C to Neutral\",\"selected\":".(in_array($inv_roles,2)?"true":"false")."},";
                    $st.=$prefix."{role_idx:3,role_name:\"AC_Current_A\",\"role_desc\":\"AC Current Phase A\",\"selected\":".(in_array($inv_roles,3)?"true":"false")."},";
                    $st.=$prefix."{role_idx:4,role_name:\"AC_Current_B\",\"role_desc\":\"AC Current Phase B\",\"selected\":".(in_array($inv_roles,4)?"true":"false")."},";
                    $st.=$prefix."{role_idx:5,role_name:\"AC_Current_C\",\"role_desc\":\"AC Current Phase C\",\"selected\":".(in_array($inv_roles,5)?"true":"false")."},";
                    $st.=$prefix."{role_idx:6,role_name:\"AC_Active_Power_A\",\"role_desc\":\"AC Active Power Phase A\",\"selected\":".(in_array($inv_roles,6)?"true":"false")."},";
                    $st.=$prefix."{role_idx:7,role_name:\"AC_Active_Power_B\",\"role_desc\":\"AC Active Power Phase B\",\"selected\":".(in_array($inv_roles,7)?"true":"false")."},";
                    $st.=$prefix."{role_idx:8,role_name:\"AC_Active_Power_C\",\"role_desc\":\"AC Active Power Phase C\",\"selected\":".(in_array($inv_roles,8)?"true":"false")."},";
                    $st.=$prefix."{role_idx:9,role_name:\"AC_Frequency_A\",\"role_desc\":\"AC Frequency Phase A\",\"selected\":".(in_array($inv_roles,9)?"true":"false")."},";
                    $st.=$prefix."{role_idx:10,role_name:\"AC_Frequency_B\",\"role_desc\":\"AC Frequency Phase B\",\"selected\":".(in_array($inv_roles,10)?"true":"false")."},";
                    $st.=$prefix."{role_idx:11,role_name:\"AC_Frequency_C\",\"role_desc\":\"AC Frequency Phase C\",\"selected\":".(in_array($inv_roles,11)?"true":"false")."},";
                    print($st);
                    $st="";
                    $st.=$prefix."{role_idx:12,role_name:\"AC_Active_Power\",\"role_desc\":\"Total AC Active Power\",\"selected\":".(in_array($inv_roles,12)?"true":"false")."},";
                    $st.=$prefix."{role_idx:13,role_name:\"DC_Power\",\"role_desc\":\"Total DC Power\",\"selected\":".(in_array($inv_roles,13)?"true":"false")."},";
                    $st.=$prefix."{role_idx:14,role_name:\"DC_Current\",\"role_desc\":\"Total DC Current\",\"selected\":".(in_array($inv_roles,14)?"true":"false")."},";
                    
                    $st.=$prefix."{role_idx:15,role_name:\"kWh_Total_Active\",\"role_desc\":\"Lifetime Generation\",\"selected\":".(in_array($inv_roles,15)?"true":"false")."},";
                    $st.=$prefix."{role_idx:16,role_name:\"kWh_Day_Active\",\"role_desc\":\"Daily Generation\",\"selected\":".(in_array($inv_roles,16)?"true":"false")."},";
                    $st.=$prefix."{role_idx:17,role_name:\"Status_Code\",\"role_desc\":\"Vendor-defined Operating State\",\"selected\":".(in_array($inv_roles,17)?"true":"false")."},";
                
                    $st.=$prefix."{role_idx:18,role_name:\"Event_Code\",\"role_desc\":\"Vendor-defined Events & Errors\",\"selected\":".(in_array($inv_roles,18)?"true":"false")."},";
                    $st.=$prefix."{role_idx:19,role_name:\"Power_Limit_Percent\",\"role_desc\":\"Power Limit Percent\",\"selected\":".(in_array($inv_roles,19)?"true":"false")."}";
                } else {
                    for ($r=0;$r<$num_roles;$r++) {
                        // role_var_0=
                    $rt=ini_get("/dev/dev".$inv_arr[$d].".ini","config","role_type_".$r,0);
                    $ri=ini_get("/dev/dev".$inv_arr[$d].".ini","config","role_idx_".$r,0);
                    
                    if ($rt==0) $var="do_desc_".$ri;
                    if ($rt==1) $var="di_desc_".$ri;
                    if ($rt==2) $var="ro_desc_".$ri;
                    if ($rt==31) $var="ro_desc_".$ri;
                    if ($rt==3) $var="rw_desc_".$ri;
                    if ($rt==22) $var="ro_desc_".$ri;
                    if ($rt==23) $var="rw_desc_".$ri;
                    if (($rt>=24) && ($rt<=28)) $var="ro_desc_".$ri;
                    if ($rt==29) $var="rw_desc_".$ri;
                    if ($rt==30) $var="rw_desc_".$ri;
                    if ($rt==34) $var="rw_desc_".$ri;
                    if ($rt==35) $var="rw_desc_".$ri;
                    
                    //print("r=".$r."\r\nrt=".$rt."\r\nri=".$ri."\r\nvar=".$var);
                    if (in_array($inv_roles, $r)) 
                        $sel="true";
                    else $sel="false";
                    $role_desc=ini_get("/dev/dev".$inv_arr[$d].".ini","config",$var,"");                        
                        $st.=$prefix."{role_idx:".$r.",role_name:\"".
                            ini_get("/dev/dev".$inv_arr[$d].".ini","config","role_var_".$r,"")."\",\"role_desc\":\"".
                            $role_desc."\",\"selected\":".$sel."}"; /**/
                        $prefix=",";
                    }
                    if ($module_power_control) {
                        $st.=$prefix."{role_idx:".$r.",role_name:\"percent\",\"role_desc\":\"Active Power Limit Percent\",\"selected\":true}"; /**/
                    }

                }
                
                $st.="] }";
                $prefix2=",";
                print($st);
            }  else {
                $st=$prefix2."{device_type_id:".$inv_arr[$d]."}\r\n";
                $prefix2=",";
                print($st); 
            }
            
       } ?>
   ];

    $scope.bus=[{idx:0,name:"Modbus RTU (RS-485)"},
<? if ($_SERVER['HW_PLATFORM']==11 || $_SERVER['HW_PLATFORM']>=20) { ?>
   
        {idx:1,name:"Modbus RTU 2 (RS-485)"},
<? } ?>        
<? for ($c=0;$c<NUM_TCP_CHANNELS;$c++) { ?>
        {idx:<? print(2+$c); ?>,name:"Modbus TCP Channel <? print(1+$c); ?>"},
<? } ?>        
        {idx:100,name:"Virtual"},
        
    ];
    $scope.makeBus=function(bus_num) {
        for (i=0;i<$scope.bus.length;i++) {
            if ($scope.bus[i].idx==bus_num) return $scope.bus[i].name;
        }
        return "unknown";
    }
   $scope.loading=0;
   $gscope=$scope;
   $scope.ow={"roles": [<?
       $num_ow=intval($ez_arr['num_temp']);
       for ($d=0;$d<$num_ow;$d++) {
            $addr=$ez_arr["ow".$d."_device_address"];
            $name=$ez_arr["ow".$d."_name"];
            $logged=$ez_arr["ow".$d."_logged"];
            $st="{role_idx:".$d.",role_desc:\"".$addr."\",";
            $st.="\"selected\":".($logged>0?"true":"false").",'logfn':3,"; 
            $st.="role_name:\"".$name."\"},";
            if ($name) {
                print($st);
            }
            
       }
   ?>]};   
   /*
    $scope.countLoggedRoles=function() {
        num=0;
        tmpnum=0;
        for (ii=0;ii<$scope.inverters.length;ii++) {
            for (jj=0;jj<$scope.inverters[ii].roles.length;jj++) {
                if ($scope.inverters[ii].roles[jj].selected==true)
                    for (kk=0;kk<$scope.inv.length;kk++) {
                        if ($scope.inv[kk].device_idx==$scope.inverters[ii].device_idx)
                            num++;
                    }
            }
        }
        console.log("Invert roles count:"+(num-tmpnum));
        tmpnum=num;
        for (ii=0;ii<$scope.power_meters.length;ii++) {
            for (jj=0;jj<$scope.power_meters[ii].roles.length;jj++) {
                if ($scope.power_meters[ii].roles[jj].selected==true)
                    for (kk=0;kk<$scope.pm.length;kk++) {
                        if ($scope.pm[kk].device_idx==$scope.power_meters[ii].device_idx)
                            num++;
                    }
            }
        }
        console.log("PM roles count:"+(num-tmpnum));
        tmpnum=num;
        
         for (ii=0;ii<$scope.other_devices.length;ii++) {
            for (jj=0;jj<$scope.other_devices[ii].roles.length;jj++) {
                if ($scope.other_devices[ii].roles[jj].selected==true)
                    for (kk=0;kk<$scope.other.length;kk++) {
                        if ($scope.other[kk].device_idx==$scope.other_devices[ii].device_idx)
                            num++;
                    }
            }
        }
        console.log("Other Dev roles count:"+(num-tmpnum));
        tmpnum=num;
        
        for (jj=0;jj<$scope.other_variables.roles.length;jj++) {
                if ($scope.other_variables.roles[jj].selected==true)
                    num++;
        }
        
        console.log("Other Var count:"+(num-tmpnum));
        tmpnum=num;
        
        for (jj=0;jj<$scope.ow.roles.length;jj++) {
                if ($scope.ow.roles[jj].selected==true)
                    num++;
        }
        console.log("Onewire count:"+(num-tmpnum));
        tmpnum=num;
    
        return num;
    }   
*/
    $scope.countLoggedRoles=function() {
        num=0;
        tmpnum=0;
        for (i=0;i<$scope.inv.length;i++) {
            //console.log($scope.inverters[i]);
            for (j=0;j<$scope.inverters[$scope.inv[i].device_idx].roles.length;j++) {
                if ($scope.inverters[$scope.inv[i].device_idx].roles[j].selected==true)
                    num++;
            }
        }
         console.log("Invert roles count:"+(num-tmpnum));
        tmpnum=num;
        for (i=0;i<$scope.pm.length;i++) {
            for (j=0;j<$scope.power_meters[$scope.pm[i].device_idx].roles.length;j++) {
                if ($scope.power_meters[$scope.pm[i].device_idx].roles[j].selected==true)
                    num++;
            }
        }
        console.log("PM roles count:"+(num-tmpnum));
        tmpnum=num;
        for (i=0;i<$scope.other.length;i++) {
            for (j=0;j<$scope.other_devices[$scope.other[i].device_idx].roles.length;j++) {
                if ($scope.other_devices[$scope.other[i].device_idx].roles[j].selected==true)
                    num++;
            }
        }
        console.log("Other Dev roles count:"+(num-tmpnum));
        tmpnum=num;
        for (j=0;j<$scope.other_variables.roles.length;j++) {
                if ($scope.other_variables.roles[j].selected==true)
                    num++;
        }
        console.log("Other Var count:"+(num-tmpnum));
        tmpnum=num;
        for (j=0;j<$scope.ow.roles.length;j++) {
                if ($scope.ow.roles[j].selected==true)
                    num++;
        }
        return num;
    }

    
  $scope.makeOtherPrefix=function(item) {
    if (item.device_type_id==8010) return "";
    return item.name+"_";
  }
  $scope.makeBackup=function() {
     window.open("/app/backuprun.cgi?folder=/config/","_blank","scrollbars=yes");
     return true;
  }

   $scope.prev=function() {
        document.location='/app/ezconfig.cgi?stage=2<? if ($use_qos) print("&qos=1"); ?>';
   }

   $scope.generate=function() {
     document.location='/app/ezconfig.cgi?stage=4<? if ($use_qos) print("&qos=1"); ?>';
   }
}
   </script>
</div> 
<? } // stage=3


/********************************************************************************************************* STAGE 4 */        
if ($_GET['stage']==4) { 
$use_qos=$_GET['qos'];
$use_fourth=$_GET['fourth'];
?>

<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/"><? print(lang('HOME','settings')) ?></a></li>
    <li class="breadcrumb-item"><a href="/app/settings.cgi"><? print(lang('CONTROL_PANEL','settings')) ?></a></li>
    <li class="breadcrumb-item active" aria-current="page"><? print(lang('PAGE_TITLE','ezconfig')) ?></li>
  </ol>
</nav>

<!-- NAVBAR -->
<h4><i class="icon-cog"></i>&nbsp;<? print(lang('STAGE4_TITLE','ezconfig')) ?>: <? print(lang('S4_TITLE','ezconfig')) ?></h4>
<ul class="nav justify-content-end">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="collapse" href="#collapseHelp" role="button" aria-expanded="false" aria-controls="collapseExample">
    <? print(lang('HELP','ezconfig')) ?>
  </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" onclick="document.location='/app/settings.cgi';"><i class="icon-remove"></i> <? print(lang('CLOSE','ezconfig')) ?></a>
  </li>
  <li class="nav-item">
    <a class="nav-link " ng-hide='loading==1' ng-click="reboot()" ><i class="icon-check"></i> <? print(lang('REBOOT','ezconfig')) ?></a>
  </li>

</ul>
<!-- HELP -->
<div class="collapse" id="collapseHelp">
  <div class="card card-body">
    <? print(lang('HELP1','ezconfig')) ?>
  </div>
  <br/>
</div>
<div class="alert alert-success" ng-cloak ng-show="successmsg"> <button type="button" class="close" ng-click='successmsg=""'>&times;</button>{{successmsg}}</div>
<div class="alert alert-danger" ng-cloak ng-show="errormsg"> <button type="button" class="close" ng-click='errormsg=""'>&times;</button>{{errormsg}}</div>
<div class="alert alert-info" ng-cloak ng-show="infomsg"> <button type="button" class="close" data-dismiss="alert">&times;</button>{{infomsg}}</div>
<div class="alert alert-secondary" ng-cloak ng-show="loading"><i id='iconRepeatMain' class='icon-spinner icon-spin' style='font-size:36px; color:red'></i>&nbsp;<? print(lang('PLEASE_WAIT','ezconfig')) ?></div>
<form name="form" class="css-form form-horizontal" novalidate>
        <? 
            max_execution_time(90);
            
            $inv_cnt=ini_get("/config/EZConfig.ini","config",'inv_count',0);
            $pm_cnt=ini_get("/config/EZConfig.ini","config",'pm_count',0);
            $other_cnt=ini_get("/config/EZConfig.ini","config",'other_count',0);
            $ez_arr = ini_get_array("/config/EZConfig.ini","config");

    $plant_size=0;
    for ($n=0;$n<$ez_arr['inv_count'];$n++) {
        $plant_size += intval($ez_arr['inv'.$n."_rating"]);
    }
            
            if (!$ez_arr['poll_interval']) $ez_arr['poll_interval']=1000;
            if (!$ez_arr['baud_rate']) $ez_arr['baud_rate']=9600;
            if (!$ez_arr['parity']) $ez_arr['parity']=0;
            
            if (($_SERVER['HW_PLATFORM']==11) || ($_SERVER['HW_PLATFORM']>=20)) {
                if (!$ez_arr['baud_rate2']) $ez_arr['baud_rate2']=9600;
                if (!$ez_arr['parity2']) $ez_arr['parity2']=0;
                
            }
            
            $f_csv_headers=fopen("/config/csv_headers.txt","w");
            $f_datalog=fopen("/config/datalog.ini","w");    
            $f_roles=fopen("/config/roles.ini","w");
            
            // the first role is a dummy
            $num_roles=1;
            
            $role_st="[roles]\r\n".
                "role0=Undefined\r\n".
                "role0_type=0\r\n";
            
            fwrite($f_roles,$role_st);
            
            fwrite($f_csv_headers,"ts");
            $static_header=intval($ez_arr['static_header']);
            
            ini_set("/config/dataexport.ini","export","static_header",$static_header);
            
            $datalog_st="[data]\r\nnum_groups=1\r\ngroup0name=Datalog\r\ngroup0type=0\r\ngroup0status=1\r\ngroup0interval=".$ez_arr['log_interval']."\r\ngroup0mins=".$ez_arr['log_write_interval']."\r\n";
            fwrite($f_datalog,$datalog_st);

            $st_devices="[general]
num_devices=".($inv_cnt+$pm_cnt+$other_cnt)+"
delay=".$ez_arr['interval']."
tcp_delay=".$ez_arr['tcp_interval']."
retry=".$ez_arr['retry_interval']."
tcp_retry=".$ez_arr['tcp_retry_interval']."
max_retries=".$ez_arr['retry']."
short_timeout=".$ez_arr['short_timeout']."
tcp_max_retries=".$ez_arr['tcp_retry']."
parity=".$ez_arr['parity']."
baud=".$ez_arr['baud_rate']."
timeout=".$ez_arr['timeout']."
tcp_timeout=".$ez_arr['tcp_timeout']."
modbus_tcp_enabled=".intval($ez_arr['tcp_enabled'])."
enabled=1
tcp_auto_close=0
";
if ($_SERVER['HW_PLATFORM']==11 || $_SERVER['HW_PLATFORM']>=20) {
    $st_devices.="parity2=".$ez_arr['parity2']."
baud2=".$ez_arr['baud_rate2']."
delay2=".$ez_arr['interval2']."
retry2=".$ez_arr['retry_interval2']."
max_retries2=".$ez_arr['retry2']."
timeout2=".$ez_arr['timeout2']."
enabled2=".$ez_arr['enabled2']."
";
}

if ( $_SERVER['HW_PLATFORM']==20) {
    $st_devices.="rs232_baud=".$ez_arr['rs232_baud']."
rs232_enabled=".$ez_arr['rs232_enabled']."
auth=".$ez_arr['auth']."
password=".$ez_arr['password']."
";
}
set_buffering(0);
for ($i=0;$i<NUM_TCP_CHANNELS;$i++) {
    if (!$ez_arr['tcp'.$i.'_ip']) $ez_arr['tcp'.$i.'_ip']='0.0.0.0';
    $st_devices.="modbus_tcp_port".$i."=".intval($ez_arr['tcp'.$i.'_port'])."\r\nmodbus_tcp_ip_address".$i."=".$ez_arr['tcp'.$i.'_ip'] ."\r\nmodbus_tcp_server".$i."=".intval($ez_arr['tcp'.$i.'_s']). "\r\n";

}
// stage 1 - generate the devices map
            $cur_device_id=0;
            setpriority(1);
            $f_device=fopen("/config/device.ini","w");
            $ts_start=microtime();
            print("Generating inverter data... free=".freemem()."<br>");
            $inverter_indexes=array();
            if ($use_qos) {
                // qos has 5 headers
                $headers1='DEVICE_TYPE';
                $headers2='DEVICE_NAME';
                $headers3='DEVICE_UUID';
                $headers4='SIGNAL_NAME';
                $headers5='SIGNAL_UNIT';
            }
            
            
            for ($i=0;$i<$inv_cnt;$i++) {
                
                //print("inverter ".$i);
                $st_devices.='[Device'.$cur_device_id."]\r\n";
                $st_devices.='name='.$ez_arr['inv'.$i.'_device_name']."\r\n";
                $st_devices.='address='.$ez_arr['inv'.$i.'_id']."\r\n";
                $st_devices.='params='.$ez_arr['inv'.$i.'_bus']."\r\n";
                $st_devices.='poll_interval='.$ez_arr['poll_interval']."\r\n";
                $st_devices.="status=1\r\n";
                $st_devices.='device_type_id='.$ez_arr['inv'.$i.'_device_type_id']."\r\n";
                $inverter_indexes[$i]=$cur_device_id;
                $inv_logfn_str=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['inv'.$i.'_device_type_id']."_logfn","").ini_get("/config/EZConfig.ini","config","dev".$ez_arr['inv'.$i.'_device_type_id']."_logfn2","").ini_get("/config/EZConfig.ini","config","dev".($ez_arr['inv'.$i.'_device_type_id']."_logfn3"?$ez_arr['inv'.$i.'_device_type_id']."_logfn3":""),"");
                if ($inv_logfn_str) {
                    $inv_logfn=explode($inv_logfn_str,',');
                } else $inv_logfn=array();

                
                if ($ez_arr['inv'.$i.'_device_type_id']!=7000) {        // delta gets special privileges
//                    $roles=explode($ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles"].($ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles2"]?$ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles2"]:"") . ($ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles3"]?$ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles3"]:""),",");
                    $roles_string= $ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles"];
                    // Append $roles_string if additional "roles_"-lines exist
	  		$x=2;
		        while (1) {
		        
		          $tmp=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['inv'.$i.'_device_type_id']."_roles".$x,"");
		          if (strlen($tmp)) {
		            $roles_string .= $tmp;
		          } else break;
		          $x++;
		        }		    
                    $roles=explode($roles_string,",");
		    $roles_string='';
                   // print_r($roles);
                    if (!sizeof($roles)) 
                        $roles=array(intval($ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles"]));
                    //print("roles: ".$ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles"]);
                    //print_r($roles);
                    if ($use_qos) {
                        $qos_string=$ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_qostype"];
                        $cnt=1;
                        while (strlen($ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_qostype".$cnt])) {
                            $qos_string.=",".$ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_qostype".$cnt];
                            $cnt++;
                        }
                        $qostypes=explode($qos_string,",");
                        $qosdatatypes=explode($ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_qosdatatype"],",");
                        $qos_string=''; // free memory
                    }
                    if (!$use_fourth) {
                        for ($r=0;$r<sizeof($roles);$r++) {
                            // get the role name.
                            $rn=intval($roles[$r]);
                            $role_name=$ez_arr['inv'.$i.'_device_name']."_".ini_get("/dev/dev".$ez_arr['inv'.$i.'_device_type_id'].".ini","config","role_var_".$rn,"");
                            $rt=ini_get("/dev/dev".$ez_arr['inv'.$i.'_device_type_id'].".ini","config","role_type_".$rn,0);
                            if ($rt==0) $role_type=0;
                            if ($rt==1) $role_type=1;
                            if ($rt==2) $role_type=2;
                            if ($rt==31) $role_type=2;
                            if ($rt==3) $role_type=3;
                            if ($rt==22) $role_type=2;
                            if ($rt==23) $role_type=3;
                            if (($rt>=24) && ($rt<=28)) $role_type=2;
                            if ($rt==29) $role_type=3;
                            if ($rt==30) $role_type=3;
                            if ($rt==34) $role_type=3;
                            if ($rt==35) $role_type=3;
    
                            $st_devices.="role".$rn."_id=".$num_roles."\r\n";
                            $role_ids=$ez_arr['inv'.$i.'_device_type_id'];
                            $role_fn=$inv_logfn[$roles[$r]];
                            if (strpos($role_name,'AC_Active_Power')>=0) {
                                $role_grp=3;
                            } else $role_grp=0;
                            if ($use_qos) {
                                // add qos category
                                $headers1.=','.$ez_arr['inv'.$i.'_category'];
                                $headers2.=','.$ez_arr['inv'.$i.'_device_name'];
                                $headers3.=','.$cur_device_id;//cur_device;
                                $headers4.=','.$qostypes[$rn];
                                $headers5.=','.$qosdatatypes[$rn];
                            }
    
                            log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp);
                            $num_roles++;
    
                        }
                    }
                } else {
//                    $roles=explode($ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles"],",");
//                    if (!sizeof($roles)) 
//                        $roles=array(intval($ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles"]));
		    	$roles_string= $ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles"];
	  		$x=2;
		        while (1) {
		        
		          $tmp=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['inv'.$i.'_device_type_id']."_roles".$x,"");
		          if (strlen($tmp)) {
		            $roles_string .= $tmp;
		          } else break;
		          $x++;
		        }		    
                    $roles=explode($roles_string,",");
//                    print("roles: ".$ez_arr['dev'.$ez_arr['inv'.$i.'_device_type_id']."_roles"]);
  //                  print_r($roles);
                    
                    for ($r=0;$r<sizeof($roles);$r++) {
                        // get the role name.
                        $rn=intval($roles[$r]);
                        if ($rn==0) $role_name="AC_Voltage_AN";
                        if ($rn==1) $role_name="AC_Voltage_BN";
                        if ($rn==2) $role_name="AC_Voltage_CN";
                        if ($rn==3) $role_name="AC_Current_A";
                        if ($rn==4) $role_name="AC_Current_B";
                        if ($rn==5) $role_name="AC_Current_C";
                        if ($rn==6) $role_name="AC_Active_Power_A";
                        if ($rn==7) $role_name="AC_Active_Power_B";
                        if ($rn==8) $role_name="AC_Active_Power_C";
                        if ($rn==9) $role_name="AC_Frequency_A";
                        if ($rn==10) $role_name="AC_Frequency_B";
                        if ($rn==11) $role_name="AC_Frequency_C";
                        if ($rn==12) $role_name="AC_Active_Power";
                        if ($rn==13) $role_name="DC_Power";
                        if ($rn==14) $role_name="DC_Current";
                        if ($rn==15) $role_name="kWh_Total_Active";
                        if ($rn==16) $role_name="kWh_Day_Active";
                        if ($rn==17) $role_name="Status_Code";
                        if ($rn==18) $role_name="Event_Code";
                        if ($rn==19) $role_name="Power_Limit_Percent";
                        $role_name=$ez_arr['inv'.$i.'_device_name']."_".$role_name;
                        $role_type=5;//$inv_logfn[$r];
                        //$role_ids=4580;
                        $role_ids=$ez_arr['inv'.$i.'_device_type_id'];
                        $role_fn=$inv_logfn[$roles[$r]];
                        $role_def=0;
                        if (strpos($role_name,'AC_Active_Power')>=0) {
                            $role_grp=3;
                            $role_def=7;
                        } else $role_grp=0;
                        log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp,$role_def);
                        $num_roles++;

                }
                print("Inv ".$i."... free=".freemem()."<br>");
                //break;
            }
            fwrite($f_device,$st_devices);
            $st_devices='';
            
            if ($ez_arr['module_power_control'] && !$use_fourth) {
                //$role_name='inverter'.($i+1).'_percent';
                $role_name=$ez_arr['inv'.$i.'_device_name']."_percent";
                $role_type=5;
                $role_ids=0;
                $role_grp=0;
                $role_fn=2; // instantaneous
                if ($use_qos) {
                    $headers1.=','.$ez_arr['inv'.$i.'_category'];
                    $headers2.=','.$ez_arr['inv'.$i.'_device_name'];
                    $headers3.=','.$cur_device_id;
                    $headers4.=','.'POWER_LIMIT';
                    $headers5.=','.'%';
                }
                
                log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp);
                $num_roles++;
                
            }
            $cur_device_id++;
        }
        print("Done in ".(microtime()-$ts_start)."ms free=".freemem()."<br>");
        
        $ts=microtime();
        print("Generating other device data...");
        $pyra_done=0;
        $pyra_role_id=-1;
        for ($i=0;$i<$other_cnt;$i++) {
                //print("inverter ".$i);
                $st_devices.='[Device'.$cur_device_id."]\r\n";
                $st_devices.='name='.$ez_arr['other'.$i.'_device_name']."\r\n";
                $st_devices.='address='.$ez_arr['other'.$i.'_id']."\r\n";
                $st_devices.='params='.$ez_arr['other'.$i.'_bus']."\r\n";
                $st_devices.='poll_interval='.$ez_arr['poll_interval']."\r\n";
                $st_devices.="status=1\r\n";
                $st_devices.='device_type_id='.$ez_arr['other'.$i.'_device_type_id']."\r\n";

                $roles=($ez_arr['dev'.$ez_arr['other'.$i.'_device_type_id']."_roles"]);
                
                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['other'.$i.'_device_type_id']."_roles".$x,"");
                  if (strlen($tmp)) {
                    $roles .= $tmp;
                  } else break;
                  $x++;
                }

                $roles=explode($roles,",");
                //print_r($roles);
                if (!sizeof($roles)) 
                    $roles=array(intval($ez_arr['dev'.$ez_arr['other'.$i.'_device_type_id']."_roles"]));
                
                $other_names_str=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['other'.$i.'_device_type_id']."_names","");
            
                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_names".$x,"");
                  if (strlen($tmp)) {
                    $other_names_str .=$tmp;
                  } else break;
                  $x++;
                }
                if ($other_names_str) {
                    $other_names=explode($other_names_str,',');
                } else $other_names=array();


                $other_logfn_str=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['other'.$i.'_device_type_id']."_logfn","");

                $x=1;
                while (1) {
                
                  $tmp=ini_get("/config/EZConfig.ini","config","dev".$other_arr[$d]."_logfn".$x,"");
                  if (strlen($tmp)) {
                    $other_logfn_str .=$tmp;
                  } else break;
                  $x++;
                }

                if ($other_logfn_str) {
                    $other_logfn=explode($other_logfn_str,',');
                } else $other_logfn=array();
                
                
                    
                
                if (!$pyra_done && (intval($ez_arr['other'.$i.'_device_type_id'])==8010 && intval($ez_arr['other'.$i.'_id'])==200)) {
                    
                    ini_set("/config/EZConfig.ini","config","pyra_role_id",$num_roles);
                    $pyra_done=1;
                }
                if ($use_qos) {
                    $qos_string=$ez_arr['dev'.$ez_arr['other'.$i.'_device_type_id']."_qostype"];
                    $cnt=1;
                    while (strlen($ez_arr['dev'.$ez_arr['other'.$i.'_device_type_id']."_qostype".$cnt])) {
                        $qos_string.=",".$ez_arr['dev'.$ez_arr['other'.$i.'_device_type_id']."_qostype".$cnt];
                        $cnt++;
                    }
                    $qostypes=explode($qos_string,",");
                    $qos_string=''; // free memory
                    
                    $qosdatatypes=($ez_arr['dev'.$ez_arr['other'.$i.'_device_type_id']."_qosdatatype"]);
                    $cnt=1;
                    while (strlen($ez_arr['dev'.$ez_arr['other'.$i.'_device_type_id']."_qosdatatype".$cnt])) {
                        $qosdatatypes.=$ez_arr['dev'.$ez_arr['other'.$i.'_device_type_id']."_qosdatatype".$cnt];
                        $cnt++;
                    }
                    $qosdatatypes=explode($qosdatatypes,",");
                    

                }
                if (!$use_fourth) {
                    
                    for ($r=0;$r<sizeof($roles);$r++) {
                        
                        // get the role name.
                        $rn=intval($roles[$r]);
                        $role_name=$other_names[$rn];
    //                    print($role_name.'---'.$ez_arr['other'.$i.'_device_type_id']."\r\n");
                        if (!$role_name) {
                            // only the pyranometer 1
                            if (intval($ez_arr['other'.$i.'_device_type_id'])==8010 && intval($ez_arr['other'.$i.'_id'])==200) {
                                $role_name=ini_get("/dev/dev".$ez_arr['other'.$i.'_device_type_id'].".ini","config","role_var_".$rn,"");
                            } else
                                $role_name=$ez_arr['other'.$i.'_device_name']."_".ini_get("/dev/dev".$ez_arr['other'.$i.'_device_type_id'].".ini","config","role_var_".$rn,"");
                        } else {
                            if (intval($ez_arr['other'.$i.'_device_type_id'])!=8010) {  // do this only for the first pyranometer
                                if (($pyra_role_id==-1) && $role_name=='Active_Irradiance') {
                                    
                                    ini_set("/config/Pyranometer.ini","config","scale",1);
                                    ini_set("/config/Pyranometer.ini","config","plant_size",$ez_arr['dc_plant_size']);
                                    ini_set("/config/Pyranometer.ini","config","pr_ratio",$ez_arr['fixed_pr']);
                                    ini_set("/config/Pyranometer.ini","config","pyra_role",$num_roles);
                                    $pyra_role_id=$num_roles;
                                }
                                $role_name=$ez_arr['other'.$i.'_device_name']."_".$role_name;
                                
                            } else {
                                if (intval($ez_arr['other'.$i.'_id'])!=200) {
                                    $role_name=$ez_arr['other'.$i.'_device_name']."_".$role_name;
                                }
                            }
                        }
                        
                        $rt=ini_get("/dev/dev".$ez_arr['other'.$i.'_device_type_id'].".ini","config","role_type_".$rn,0);
                        if ($rt==0) $role_type=0;
                        if ($rt==1) $role_type=1;
                        if ($rt==2) $role_type=2;
                        if ($rt==31) $role_type=2;
                        if ($rt==3) $role_type=3;
                        if ($rt==22) $role_type=2;
                        if ($rt==23) $role_type=3;
                        if (($rt>=24) && ($rt<=28)) $role_type=2;
                        if ($rt==29) $role_type=3;
                        if ($rt==30) $role_type=3;
                        if ($rt==34) $role_type=3;
                        if ($rt==35) $role_type=3;
    
                        $st_devices.="role".$rn."_id=".$num_roles."\r\n";
                        //$role_types=$role_type;
                        $role_ids=$ez_arr['other'.$i.'_device_type_id'];
                        $role_fn=$other_logfn[$roles[$r]];
                        $role_grp=0;
                        
                        if ($use_qos) {
        					$headers1.=','.$ez_arr['other'.$i.'_category'];
                            $headers2.=','.$ez_arr['other'.$i.'_device_name'];
                            $headers3.=','.$cur_device_id;
                            $headers4.=','.$qostypes[$rn];
                            $headers5.=','.$qosdatatypes[$rn];
                        }
    
                        log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp);
                        $num_roles++;
                        fwrite($f_device,$st_devices);
                        $st_devices='';
                    }
                }
                
            $cur_device_id++;
        }
        print("Done in ".(microtime()-$ts_start)."ms free=".freemem()."<br>");
        
        $ts=microtime();
        
        print("Generating power meter data...");
        
        if ($use_fourth) {
            $pm_indexes=array();
        }
        for ($i=0;$i<$pm_cnt;$i++) {
                //print("inverter ".$i);
                $st_devices.='[Device'.$cur_device_id."]\r\n";
                $st_devices.='name='.$ez_arr['pm'.$i.'_device_name']."\r\n";
                $st_devices.='address='.$ez_arr['pm'.$i.'_id']."\r\n";
                $st_devices.='params='.$ez_arr['pm'.$i.'_bus']."\r\n";
                $st_devices.='auth='.$ez_arr['auth']."\r\n";
                $st_devices.='client_id='.$ez_arr['client_id']."\r\n";
                $st_devices.='password='.$ez_arr['password']."\r\n";
                $st_devices.='poll_interval='.$ez_arr['poll_interval']."\r\n";
                $st_devices.="status=1\r\n";
                $st_devices.='device_type_id='.$ez_arr['pm'.$i.'_device_type_id']."\r\n";
                if ($use_fourth) {
                    $pm_indexes[]=$cur_device_id;
                }
                
                $roles_string=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['pm'.$i.'_device_type_id']."_roles",'');//explode($ez_arr['dev'.$ez_arr['pm'.$i.'_device_type_id']."_roles"],",");
                $x=2;
	        while (1) {
	        
	          $tmp=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['pm'.$i.'_device_type_id']."_roles".$x,"");
	          if (strlen($tmp)) {
	            $roles_string .= $tmp;
	          } else break;
	          $x++;
	        }		    
               $roles=explode($roles_string,",");
              // print($roles_string);
                    
                
                if (!sizeof($roles)) 
                    $roles=array(intval($ez_arr['dev'.$ez_arr['pm'.$i.'_device_type_id']."_roles"]));
                $pm_logfn_str=ini_get("/config/EZConfig.ini","config","dev".$ez_arr['pm'.$i.'_device_type_id']."_logfn","");
                if ($pm_logfn_str) {
                    $pm_logfn=explode($pm_logfn_str,',');
                } else $pm_logfn=array();
                if ($use_qos) {
                    $qos_string=$ez_arr['dev'.$ez_arr['pm'.$i.'_device_type_id']."_qostype"];
                    $cnt=1;
                    while (strlen($ez_arr['dev'.$ez_arr['pm'.$i.'_device_type_id']."_qostype".$cnt])) {
                        $qos_string.=",".$ez_arr['dev'.$ez_arr['pm'.$i.'_device_type_id']."_qostype".$cnt];
                        $cnt++;
                    }
                    $qostypes=explode($qos_string,",");
                    $qos_string=''; // free memory
                    $qosdatatypes=explode($ez_arr['dev'.$ez_arr['pm'.$i.'_device_type_id']."_qosdatatype"],",");
                }
                if (!$use_fourth) {
                    for ($r=0;$r<sizeof($roles);$r++) {
                        // get the role name.
                        $rn=intval($roles[$r]);
                        $role_name=$ez_arr['pm'.$i.'_device_name']."_".ini_get("/dev/dev".$ez_arr['pm'.$i.'_device_type_id'].".ini","config","role_var_".$rn,"");
                        $rt=ini_get("/dev/dev".$ez_arr['pm'.$i.'_device_type_id'].".ini","config","role_type_".$rn,0);
                        if ($rt==0) $role_type=0;
                        if ($rt==1) $role_type=1;
                        if ($rt==2) $role_type=2;
                        if ($rt==31) $role_type=2;
                        if ($rt==3) $role_type=3;
                        if ($rt==22) $role_type=2;
                        if ($rt==23) $role_type=3;
                        if (($rt>=24) && ($rt<=28)) $role_type=2;
                        if ($rt==29) $role_type=3;
                        if ($rt==30) $role_type=3;
                        if ($rt==34) $role_type=3;
                        if ($rt==35) $role_type=3;
    
                        $st_devices.="role".$rn."_id=".$num_roles."\r\n";
                        $role_ids=$ez_arr['pm'.$i.'_device_type_id'];
                        $role_fn=$pm_logfn[$roles[$r]];
                        $role_grp=0;
                        fwrite($f_device,$st_devices);
     					$headers1.=','.$ez_arr['pm'.$i.'_category'];
                        $headers2.=','.$ez_arr['pm'.$i.'_device_name'];
                        $headers3.=','.$cur_device_id;
                        $headers4.=','.$qostypes[$rn];
                         $headers5.=','.$qosdatatypes[$rn];
                        
                        log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp);
                        $num_roles++;
                        $st_devices='';
                    }
                }
           
            
            $cur_device_id++;
        }
        print("Done in ".(microtime()-$ts_start)."ms free=".freemem()."<br>");

        /*if ($ez_arr['pyranometer']) {
            $role_array[]="Active_Irradiance";
            $role_types[]=2;
            $role_ids[]=8010;
            $role_fn[]=3;
            $role_grp[]=0;
            $pyra_role_id=sizeof($role_array)-1;
            ini_set("/config/EZConfig.ini","config","pyra_role_id",$pyra_role_id);

            $role_array[]="kWh_Day_Irradiance";
            $role_types[]=2;
            $role_ids[]=8010;
            $role_fn[]=3;
            $role_grp[]=0;
            $pyra_role_id2=sizeof($role_array)-1;
        }*/
        
        if ($ez_arr['ws102'] && !$use_fourth) {
            $role_name="Wind_Speed";
            $role_type=2;
            $role_ids=8011;
            $role_fn=3;
            $role_grp=0;
            $ws102_role_id=$num_roles;
            if ($use_qos) {
                $headers1.=','.'WEATHER_STATION';
                $headers2.=','.'WATTMON';
                $headers3.=','.'VIRTUAL1';
                $headers4.=','.'WIND_SPEED';
                 $headers5.=','.'m/s';
            }

            log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp);
            $num_roles++;            
            ini_set("/config/EZConfig.ini","config","ws102_role_id",$ws102_role_id);
        }
        /*if (ini_get('/config/PC.ini','config','eb_on',0)) {
            $role_name="eb_state";
            $role_type=5;
            $role_ids=0;
            $role_fn=3;
            $role_grp=0;
            log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp);
            $num_roles++;
        }*/
        
           $logged_str=ini_get("/config/EZConfig.ini","config","logged_vars","");
   $lidx=1;
   while (1) {
       $str=ini_get("/config/EZConfig.ini","config","logged_vars".$lidx,"");
       if (!$str) break;
       else {
           $logged_str.=",".$str;
           $lidx++;
       }
       
   }

        $logged_variables=explode($logged_str,','); 
        if (!$use_fourth) {
            for ($n=0;$n<sizeof($logged_variables);$n++) {
                $role_name=$logged_variables[$n];
                $role_type=5;
                $role_ids=0;
                $role_fn=3;
                $role_grp=0;
                if ($use_qos) {
                            $headers1.=','.'WEATHER_STATION';
                            $headers2.=','.'WATTMON';
                            $headers3.=','.'VIRTUAL2';
                            $headers4.=','.'VAR'.$n;
                            $headers5.=','.'';
                        }
                log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp);
                $num_roles++;
            }
            
            if ($ez_arr['use_temp']) {
                    for ($i=0;$i<$ez_arr['num_temp'];$i++) {
                        $role_name=$ez_arr['ow'.$i."_name"];//Temperature".($i+1);
                        $role_type=4;
                        $role_ids=0;
                        $role_fn=3;
                        $role_grp=0;
                        if ($use_qos) {
                            $headers1.=','.'WEATHER_STATION';
                            $headers2.=','.'WATTMON';
                            $headers3.=','.'VIRTUAL2';
                            $headers4.=','.'TEMPERATURE';
                            $headers5.=','.'degree';
                        }
    
                        log_role($num_roles,$role_name,$role_type,$role_ids,$role_fn,$role_grp);
                        $ow_addr=$ez_arr['ow'.$i."_device_address"];
                        $num_ow=ini_get("/config/onewire.ini","general","num_devices",0);
                        
                        // add the matching role in the onewire.ini file
                        for ($k=0;$k<$num_ow;$k++) {
                            $add=ini_get("/config/onewire.ini","Device".$k,"address",'');
                            if ($add==$ow_addr) {
                                ini_set("/config/onewire.ini","Device".$k,"role0_id",$num_roles);
                                break;
                            }
                        }
                        $num_roles++;
                    }
            }
            
            
            }

            fwrite($f_datalog,"group0numvar=".($num_roles-1)."\r\n");
            fwrite($f_roles,"num_roles=".($num_roles)."\r\n");
            
        /*    print("<pre>");
            print_r($role_grp);
            print_r($role_array);
            
            print($st_devices);
            
            print($datalog_st);
            print($role_st);
            
            print("</p7re>");*/
            fwrite($f_device,$st_devices);
            
            fclose($f_device);
            
            
            fclose($f_roles);
            
            
            fclose($f_datalog);
            fclose($f_csv_headers);
            
            $f_package=fopen("/config/packages.ini","w");
            fwrite($f_package,"[packages]\r\n");
            $packages=explode($ez_arr['packages'],',');
            //print_r($packages);
            for ($k=0;$k<sizeof($packages);$k++) {
                
                if (file_exists("/package/".$packages[$k].".cgi")) {
                    fwrite($f_package,$packages[$k]."=2\r\n");
                }
/*            fwrite($f_package,"EZDisplay=2\r\n");
            if ($ez_arr['module_power_control']) {
                
                if (file_exists("/package/PC.cgi")) {
                    fwrite($f_package,"PC=2\r\n");
                }*/
            
				
            }
            if ($use_qos) {
                fwrite($f_package,"QOS=2\r\n");
            }
            if ($use_fourth) {
                fwrite($f_package,"Fourth=2\r\n");
                if ($ez_arr['mqtt_enabled']) {
                    fwrite($f_package,"MQTT=2\r\n");
                    ini_set("/config/mqtt.ini","config","enabled",1);
                    ini_set("/config/mqtt.ini","config","mqtt_server",$ez_arr['mqtt_server']);
                    ini_set("/config/mqtt.ini","config","mqtt_port",$ez_arr['mqtt_port']);
                    ini_set("/config/mqtt.ini","config","mqtt_user",$ez_arr['mqtt_user']);
                    ini_set("/config/mqtt.ini","config","mqtt_password",$ez_arr['mqtt_password']);
                    if ($ez_arr['mqtt_mode']==0) { // publish
                        ini_set("/config/mqtt.ini","config","mqtt_publish",$ez_arr['mqtt_channel']);
                        ini_set("/config/mqtt.ini","config","publish_inactive",0);
                        ini_set("/config/mqtt.ini","config","publish_heartbeat",1);
                        ini_set("/config/mqtt.ini","config","publish_action",3);
                        ini_set("/config/mqtt.ini","config","subscribe_action",0);
                        ini_set("/config/mqtt.ini","config","publish_interval",5);
                        ini_set("/config/mqtt.ini","config","publish_dev",implode($pm_indexes,','));

                    } else {
                        ini_set("/config/mqtt.ini","config","publish_action",0);
                        ini_set("/config/mqtt.ini","config","mqtt_subscribe",$ez_arr['mqtt_channel'].'/#');
                        ini_set("/config/mqtt.ini","config","subscribe_heartbeat",1);
                        ini_set("/config/mqtt.ini","config","subscribe_timeout_interval",$ez_arr['subscribe_timeout_interval']);
                        ini_set("/config/mqtt.ini","config","subscribe_timeout_percent",$ez_arr['subscribe_timeout_percent']);
                        ini_set("/config/mqtt.ini","config","subscribe_action",4);

                    }
                } else {
                    ini_set("/config/mqtt.ini","config","enabled",0);
                }
                ini_set("/config/Fourth.ini","config","export_interval",$ez_arr['export_interval']);
                ini_set("/config/Foirth.ini","config","max_lines",$ez_arr['max_lines ']);
                
            }
            
           fclose($f_package);
           // free up
           $packages=0;
           if ($use_qos) {
               //$headers=implode($headers1,',');
               
                $f=fopen("/config/qos_header.txt",'w');
                fwrite($f,$headers1);
                $headers1='';
                fwrite($f,"\r\n");
                //$headers='';
                //$headers=implode($headers2,',');
                
                fwrite($f,$headers2);
                $headers2='';
                //$headers='';
                fwrite($f,"\r\n");
                //$headers=implode($headers3,',');
                //$headers3='';
                fwrite($f,$headers3);
                $headers3='';
                fwrite($f,"\r\n");
                //$headers=implode($headers4,',');
                //$headers4='';
                fwrite($f,$headers4);
                $headers4='';
                fwrite($f,"\r\n");
                //$headers=implode($headers5,',');
                //$headers5='';
                fwrite($f,$headers5);
                $headers5='';
                fwrite($f,"\r\n");
                fclose($f);
                
                ini_set("/config/QOS.ini","config","QOS_sitename",$ez_arr['qos_prefix']);
                ini_set("/config/QOS.ini","config","QOS_path",$ez_arr['qos_path']);
                ini_set("/config/QOS.ini","config","QOS_url",$ez_arr['qos_server']);
                ini_set("/config/QOS.ini","config","QOS_username",$ez_arr['qos_username']);
                ini_set("/config/QOS.ini","config","QOS_password",str_replace('"','',$ez_arr['qos_password']));

           }

        /*if ($ez_arr['static_header']) {
            // generate static headers    
            $ini = ini_get_array("/config/dataexport.ini","export");
    
            $num_groups = ini_get("/config/datalog.ini","data","num_groups",0);
            $data='"ts",';
            for ($i=0;$i<$num_groups;$i++) {
                $s=ini_get("/config/datalog.ini","data",'group'+$i+'status',0);
                
                if ($s==1) {
        
                    $logfile2 = "/logs/log_"+$i+".ini";
                    //$arr=ini_get_array($logfile2);
                    
                    $grpnvar=ini_get("/config/datalog.ini","data",'group'+$i+"numvar",0);
                    for ($j=0;$j<$grpnvar;$j++) {
                        $vt=ini_get("/config/datalog.ini","data",'group'+$i+'var'+$j+'vartype',0);
                        $vfn=ini_get("/config/datalog.ini","data",'group'+$i+'var'+$j+'varfn',0);
                        $vval=ini_get("/config/datalog.ini","data",'group'+$i+'var'+$j+'varval',0);
                        if ($vt==1) {  // system
                            $varst=ini_get("/config/sysvars.ini","sysvars","sysvar".$vval."name","");
                            $varr=explode($varst,';');
                            if ($varr[0]=='V') {
                                $varst=$varr[1];
                            } else {
                                if ($varr[0]=='G') {
                                    $varst=$varr[2].$varr[1];
                                }
                            }
                        } else {
                            if ($vt==2) {  // device
                                $varst=ini_get("/config/roles.ini","roles","role".$vval,"");
                            }
                            if ($vt==3) {  // global
                                //$varst=$vval;
                                 $varst=ini_get("/config/datalog.ini","data",'group'+$i+'var'+$j+'varval','');
                            }                
                        }
                        //$data.="\"".$varst."\":\"".$arr['data']['p'.$j]."\"";
                        $data.='"'.$varst.'"';
                        if ($j<($grpnvar-1)) $data.=",";
                    }
        
                }
            }
            $fc=fopen("/config/csv_headers.txt","w");
            fwrite($fc,$data);
            $data='';
            fclose($fc);
        }*/
            $f_widget=fopen("/config/widget.ini","w");
            fwrite($f_widget,"[loggedin.main]\r\nnum_widgets=1\r\nw0_width=12\r\nw0_template=/package/EZDisplay.inc\r\nw0_title=Live Energy Overview\r\nw0_icon=icon-play");
            fclose($f_widget);
            ini_set("/config/setup.ini","setup","newsetup",0);
            ini_set("/config/runonce.ini","config","file","/app/ezconfig_boot.inc");
           
            // Sync power control
        if ($ez_arr['module_power_control']) {
            ini_set("/config/license.ini","config","key1",$ez_arr['license_key']);
            ini_set("/config/packages.ini","packages","PC",2);

        }
        if ($ez_arr['sync_power_control'] || (!file_exists("/config/PC.ini") && $ez_arr['module_power_control'])) {
            
            
            
            if (file_exists("/config/PC.ini")) {
                
                
                $ts=microtime();
                print("Updating Power Control...<br>");
                
               $inv_cnt=ini_get("/config/EZConfig.ini","config",'inv_count',0);
               $pm_cnt=ini_get("/config/EZConfig.ini","config",'pm_count',0);
            
               $pc_arr = ini_get_array("/config/PC.ini","config");
               $num_dev=ini_get("/config/device.ini","general","num_devices",0);
               
               for ($i=0; $i < $pc_arr['pm_count']; $i++) {
                   $pm_name=$pc_arr['pm'.$i.'_name'];
                   
                   for ($j=0;$j < $num_dev;$j++) {
                        $dev_name=ini_get("/config/device.ini","Device".$j,"name","");
                        
                        if ($dev_name==$pm_name) {
                            //print($dev_name." - ".$pm_name."\r\n");
                            ini_set("/config/PC.ini","config",'pm'.$i.'_device_idx',$j);
                            ini_set("/config/PC.ini","config",'pm'.$i.'_plant_size',intval($plant_size));
                            if (!$pc_arr['eb_on']) {
                                ini_set("/config/PC.ini","config",'pm'.$i.'_type',$ez_arr['pm'.$i.'_type']);
                                
                                
                                if ($ez_arr['pm'.$i."_type"]==1) {
                                    
                                    ini_set("/config/PC.ini","config",'pm'.$i.'_type',$ez_arr['pm'.$i.'_type']);
                                    ini_set("/config/PC.ini","config",'pm'.$i.'_min',intval($ez_arr['pm'.$i.'_dg_rating']*0.8*0.3));
                                    ini_set("/config/PC.ini","config",'pm'.$i.'_max',intval($ez_arr['pm'.$i.'_dg_rating']*0.8*0.35));
                                } else if ($ez_arr['pm'.$i."_type"]==2) {
                                    ini_set("/config/PC.ini","config",'pm'.$i.'_min',intval($plant_size*0.05));
                                    ini_set("/config/PC.ini","config",'pm'.$i.'_max',intval($plant_size*0.07));
                                };
                                
                            }
                        }
                   }
                   
               }
               
                $inv_id=$pc_arr['inv'.$i.'_id'];
                
                for ($i=0; $i < $pc_arr['inv_count']; $i++) {
                   $inv_id=$pc_arr['inv'.$i.'_id'];
                   ini_set("/config/PC.ini","config",'inv'.$i.'_default_pc',$pc_arr['inv0_default_pc']);
                   for ($j=0;$j < $num_dev;$j++) {
                        $dev_id=ini_get("/config/device.ini","Device".$j,"address",0);
                        if ($dev_id==$inv_id) {
                            ini_set("/config/PC.ini","config",'inv'.$i.'_device_idx',$j);
                        }
                   }
               }
               //if ($pc_arr['inv_count']<$inv_cnt) {
                   for ($i=0;$i<$inv_cnt;$i++) {
                       ini_set('/config/PC.ini','config','inv'.$i.'_device_idx',$inverter_indexes[$i]);
                       ini_set('/config/PC.ini','config','inv'.$i.'_device_type_id',$ez_arr['inv'.$i.'_device_type_id']);
                       ini_set('/config/PC.ini','config','inv'.$i.'_id',$ez_arr['inv'.$i.'_id']);
                       ini_set('/config/PC.ini','config','inv'.$i.'_bus',$ez_arr['inv'.$i.'_bus']); 
                       ini_set('/config/PC.ini','config','inv'.$i.'_device_name',$ez_arr['inv'.$i.'_device_name']);
                       ini_set('/config/PC.ini','config','inv'.$i.'_rating',$ez_arr['inv'.$i.'_rating']);
                       ini_set('/config/PC.ini','config','inv'.$i.'_default_pc',$pc_arr['inv0_default_pc']);
                   }
               //}
               ini_set('/config/PC.ini','config','inv_count',$inv_cnt);
               print("Done in ".(microtime()-$ts_start)."ms<br>");
               $ts=microtime();
            //        print("Updating Power Control...");
               
            } else if ($ez_arr['module_power_control']) {  // generate a new power control file only if PC is enabled
                $ts=microtime();
                print("Updating Power Control...<br>");
                
                $inv_cnt=$ez_arr['inv_count'];
                $pm_cnt=$ez_arr['pm_count'];
                
                $pc_arr = array();
                $pc_arr["config"]=array();
                $pc_arr["config"]['pm_count']=$pm_cnt;
                $pc_arr["config"]['inv_count']=$inv_cnt;
                $pc_arr["config"]['active']=1;
                $pc_arr["config"]['eb_on']=0;
                $pc_arr["config"]['pf_control']=0;
                $pc_arr["config"]['ramp_mode']=0;
                $pc_arr["config"]['debug']=0;
                $pc_arr["config"]['debug_log']=0;
                $pc_arr["config"]['track_curtailment']=1;
                $pc_arr["config"]['retry']=1;
                $pc_arr["config"]['interval']=5;
                $pc_arr["config"]['meter_timeout=20'];
                $pc_arr["config"]['readjust_interval']=5;
                $pc_arr["config"]['inverter_level_percent=0'];
                $pc_arr["config"]['meter_scale']=1;
                $pc_arr["config"]['power_mode']=0;
                $pc_arr["config"]['reactive_offset']=0.2;
                $pc_arr["config"]['inverter_timeout']=60;
                $pc_arr["config"]['tcp_fail_check']=0;
                $pc_arr["config"]['tcp_fail_interval']=0;
                $pc_arr["config"]['tcp_fail_percent']=0;
                $pc_arr["config"]['set_to_100']=0;
                $pc_arr["config"]['reactive_power_mode']=0;

               $num_dev=ini_get("/config/device.ini","general","num_devices",0);
               
               for ($i=0; $i < $ez_arr['pm_count']; $i++) {
/* ez                   
                   pm1_device_type_id=6453
pm1_id=22
pm1_type=1
pm1_bus=2
*/
                    $pc_arr["config"]['pm'.$i.'_type'] = $ez_arr['pm'.$i.'_type'];
                    $pc_arr["config"]['pm'.$i.'_disabled'] = 0;
                    $pc_arr["config"]['pm'.$i.'_pf'] = 0;
                    $pc_arr["config"]['pm'.$i.'_reactive_threshold'] = 0.0;
                    $pc_arr["config"]['pm'.$i.'_group'] = 0;
                    $pc_arr["config"]['pm'.$i.'_plant_size'] = $plant_size;

                    if ($ez_arr['pm'.$i."_type"]==1) {
                        
                        $pc_arr["config"]['pm'.$i.'_min']=intval($ez_arr['pm'.$i.'_dg_rating']*0.8*0.3);
                        $pc_arr["config"]['pm'.$i.'_max']=intval($ez_arr['pm'.$i.'_dg_rating']*0.8*0.35);
                        $pc_arr["config"]['pm'.$i.'_priority'] = 1;
                        
                    } else if ($ez_arr['pm'.$i."_type"]==2) {
                        $pc_arr["config"]['pm'.$i.'_min']=intval($plant_size*0.05);
                        $pc_arr["config"]['pm'.$i.'_max']=intval($plant_size*0.07);
                        $pc_arr["config"]['pm'.$i.'_priority'] = 0;
                    };
                    
                    for ($j=0; $j < $num_dev; $j++) {
                        
                        $dev_id=ini_get("/config/device.ini","Device".$j,"address",0);
                        $dev_bus=ini_get("/config/device.ini","Device".$j,"params",0);
                        
                        if (($dev_id==$ez_arr['pm'.$i.'_id']) && ($dev_bus==$ez_arr['pm'.$i.'_bus'])) {

                            $pc_arr["config"]['pm'.$i.'_device_idx']=$j;
                            $pc_arr["config"]['pm'.$i.'_name']=ini_get("/config/device.ini","Device".$j,"name","");
                            break;
                        }
                    }
               }
               
                $inv_id=$pc_arr['inv'.$i.'_id'];
                
                for ($i=0; $i < $inv_cnt; $i++) {
                    $pc_arr["config"]['inv'.$i.'_name'] = $ez_arr['inv'.$i.'_device_name'];
                    $pc_arr["config"]['inv'.$i.'_device_name'] = $ez_arr['inv'.$i.'_device_name'];
                    $pc_arr["config"]['inv'.$i.'_id'] = $ez_arr['inv'.$i.'_id'];
                    $pc_arr["config"]['inv'.$i.'_bus'] = $ez_arr['inv'.$i.'_bus'];
                    $pc_arr["config"]['inv'.$i.'_pf'] = 1;
                    $pc_arr["config"]['inv'.$i.'_default_pc'] = 100;
                    $pc_arr["config"]['inv'.$i.'_group'] = 0;
                    $pc_arr["config"]['inv'.$i.'_device_type_id'] = $ez_arr['inv'.$i.'_device_type_id'];
                    $pc_arr["config"]['inv'.$i.'_rating'] = $ez_arr['inv'.$i.'_rating'];

                    for ($j=0; $j < $num_dev; $j++) {
                        
                        $dev_id=ini_get("/config/device.ini","Device".$j,"address",0);
                        $dev_bus=ini_get("/config/device.ini","Device".$j,"params",0);
                        
                        if (($dev_id==$ez_arr['inv'.$i.'_id']) && ($dev_bus==$ez_arr['inv'.$i.'_bus'])) {

                            $pc_arr["config"]['inv'.$i.'_device_idx']=$j;
                            break;
                        }
                    }
                    
/* ez
inv1_device_type_id=7969
inv1_id=3
inv1_bus=2
inv1_device_name=inverter2
inv1_rating=11
inv1_device_idx=97

pc
inv0_name=inverter1
inv0_device_type_id=7092
inv0_id=2
inv0_bus=2
inv0_device_name=inverter1
inv0_device_idx=0
inv0_rating=33
inv0_pf=1
inv0_default_pc=100
inv0_group=0
*/

               }
               ini_put_array('/config/PC.ini',$pc_arr);
               print("Done in ".(microtime()-$ts_start)."ms<br>");
               $ts=microtime();
            //        print("Updating Power Control...");
               
                
            }
        }
        
        // OTA stuff
        ini_set("/config/ota.ini","config","ota_interval",86400);
        
        // don't enable OTA unless one of the things are selected
        if ($ez_arr['ota_packages'] || $ez_arr['ota_firmware']) {
            ini_set("/config/ota.ini","config","ota_enabled",1);
        } else ini_set("/config/ota.ini","config","ota_enabled",1);
        
        ini_set("/config/ota.ini","config","ota_auto_install",1);
        ini_set("/config/ota.ini","config","ota_auto_resync",1);
        
        ini_set("/config/ota.ini","config","ota_packages",$ez_arr['ota_packages']);
        ini_set("/config/ota.ini","config","ota_firmware",$ez_arr['ota_firmware']);
        
        mkdir("/repository");
        mkdir("/logs");
        
        ini_set("/config/uphp.ini","debug","log_drive",$ez_arr['log_drive']);
        
        if ($ez_arr['ota_healing']) {
            ini_set("/config/uphp.ini","debug","md5_sync",1);
            ini_set("/config/uphp.ini","debug","md5_auto_restore",1);
        } else 
            ini_set("/config/uphp.ini","debug","md5_auto_restore",0);
        
        if ($ez_arr['snapshot']) {
            $ts=microtime();
            print("Generating snapshot of configuration...<br>");
            mkdir("/backup");
            $backupfile="/backup/snapshot_"+time().".tar";
            max_execution_time(150);
            $f=fopen($backupfile,"w+");
            
            $dir='/config/';
            
            $start=1;
            $count=0;
            chdir($dir);
            $arr=findfirst("*.*",255-24);  // no directories
                
                
            while ($arr) {
                    
                    // skip directories
                    if ((strpos($arr['filename'],".cgc")<0)) {
                        //printf("Adding ".$dir.$arr['filename']." -  ".$arr['filesize']." bytes \r\n");
                        //flush();
                        tar_put($f,$dir.$arr['filename'],substr($dir,1).$arr['filename']);     
                        $count++;
                    } else {
                        print("Skipping file ".$dir.$arr['filename']."\r\n");
                    }
                    $arr=findnext();
            }
            
            tar_finish($f);
            fclose($f);
            print("Generated snapshot file.  You can find this here: ".$backupfile.". ");
            print("Done in ".(microtime()-$ts_start)."ms<br>");
            ini_set("/config/ezconfig.ini","config","last_snapshot",$backupfile);
        }
        
function log_role($role_num,$role_name,$role_type,$role_ids,$role_fn,$role_grp,$role_def) {
    global $f_csv_headers;
    global $f_datalog;
    global $f_roles;
    $datalog_st="group0var".($role_num-1)."vartype=2\r\ngroup0var".($role_num-1)."varval=".$role_num."\r\ngroup0var".($role_num-1)."varscale=1\r\ngroup0var".($role_num-1)."varfn=". $role_fn."\r\n";
    fwrite($f_datalog,$datalog_st);
    fwrite($f_csv_headers,",".$role_name);
    
    $role_st="role".$role_num."=".$role_name."\r\n";
    $role_st.="role".$role_num."ids=".$role_ids."\r\n";
    $role_st.="role".$role_num."type=".$role_type."\r\n";
    if ($role_grp) 
        $role_st.="role".$role_num."group=".$role_grp."\r\n";
    if ($role_def) 
        $role_st.="role".$role_num."def=".$role_def."\r\n";
        

    fwrite($f_roles,$role_st);

}
        ?>
<div class="card">
    <div class="card-body">
        <h5 class="card-title"><? print(lang('SUCCESS','ezconfig')) ?></h5>
        <p class="card-text">    
            <? print(lang('S4_1','ezconfig')) ?><br>
            <strong><? print(($cur_device_id)); ?> <? print(lang('DEVICES','ezconfig')) ?></strong> <? print(lang('WERE_CREATED','ezconfig')) ?>.<p>
            <strong><? print($num_roles); ?> <? print(lang('ROLES','ezconfig')) ?></strong> <? print(lang('WERE_CREATED','ezconfig')) ?>.<p>
            <? if ($ez_arr['ws102']) { ?>
                <strong> <? print(lang('WS102','ezconfig')) ?></strong> <? print(lang('WAS_INSTALLED','ezconfig')) ?>.<p>
            <? }
                if ($ez_arr['pyranometer']) { ?>
                <strong> <? print(lang('PYRA300','ezconfig')) ?></strong> <? print(lang('WAS_INSTALLED','ezconfig')) ?>.<p>
            <? } 
              if ($ez_arr['module_power_control']) { ?>
                <strong> <? print(lang('POWER_CONTROL','ezconfig')) ?></strong> <? print(lang('WAS_INSTALLED','ezconfig')) ?>.<p>
                <a class="btn btn-success btn-inverse" onclick="document.location='/package/PC.cgi?action=configure';"><i class="icon-check"></i> CONFIGURE</a><br/>
            <? }
                if ($ez_arr['module_devices']) { ?>
                <strong> <? print(lang('DEVICE_INFO','ezconfig')) ?></strong> <? print(lang('WAS_INSTALLED','ezconfig')) ?>.<p>
            <? }?>
                
            
        </p>
    </div>
</div>

</form>
        <script>
var gItems,gHttp;
var count=0;
var app = angular.module('myApp', []);

function EZConfigWidget($scope, $timeout,$http) {
   var self = this;
   //alert('init');
   //4028,4099,4098,4024,4023
   

   $scope.loading=0;
   $gscope=$scope;


   $scope.reboot=function() {
     document.location='/app/task.cgi?action=reboot';
   }
}
 </script>
<? } // stage=4
include("/app/footer.inc");
?>

















