<?
init_watchdog(300);
error_reporting(0);
max_execution_time(0);
if (!$_GLOBALS['loaded']) {
    $_GLOBALS['PKG_NAME']="WattmonOS";
    $_GLOBALS['PKG_VERSION']="3.20";
    $_GLOBALS['PKG_PATCH']="20250909";
    $_GLOBALS['APP_INFO']=$_GLOBALS['PKG_NAME']." ".$_GLOBALS['PKG_VERSION']."-".$_GLOBALS['PKG_PATCH'];
	$prefix='';

    if ($_SERVER['HW_PLATFORM']==0)
        $_GLOBALS['APP_INFO'].=" (WM-60)";
    if ($_SERVER['HW_PLATFORM']==1)
        $_GLOBALS['APP_INFO'].=" (WM-PRO)";
    if ($_SERVER['HW_PLATFORM']==2)
        $_GLOBALS['APP_INFO'].=" (WM-MINI)";
    if ($_SERVER['HW_PLATFORM']==8)
        $_GLOBALS['APP_INFO'].=" (WM-MINI3)";
    if ($_SERVER['HW_PLATFORM']==9)
        $_GLOBALS['APP_INFO'].=" (WM-MINI2)";
    if ($_SERVER['HW_PLATFORM']==10)
        $_GLOBALS['APP_INFO'].=" (WM-MEGA)";
    if ($_SERVER['HW_PLATFORM']==11) {
        $_GLOBALS['APP_INFO'].=" (WM-M2)";
		$prefix='0:';
	}
    if ($_SERVER['HW_PLATFORM']==12)
        $_GLOBALS['APP_INFO'].=" (WM-MINI3-4G)";
	
    if ($_SERVER['HW_PLATFORM']==20) {
        $_GLOBALS['APP_INFO'].=" (WM-ULTRA)";
    }
    if ($_SERVER['HW_PLATFORM']==21)
        $_GLOBALS['APP_INFO'].=" (WM-MEGA2)";
    if ($_SERVER['HW_PLATFORM']==22)
        $_GLOBALS['APP_INFO'].=" (WM-MEGA2-4G)";
    $_GLOBALS['boot_drive']=0;
    if ($_SERVER['HW_PLATFORM']>=20) {
        if (disk_status(1)==0 || disk_status(1)==4) { // flash available (possibly locked = 4)
            $fstat=flash_status();
            if ($fstat['booted']) {
                $_GLOBALS['boot_drive']=1;
            }
        }
        $_GLOBALS['log_drive']=ini_get("/config/uphp.ini","debug","log_drive",0);
        if (disk_status($_GLOBALS['log_drive']) && $_GLOBALS['log_drive']==0)
            $_GLOBALS['log_drive']=2;
        $prefix=intval($_GLOBALS['log_drive']).':';
    }


    $_GLOBALS['DEV_NAME']=ini_get("/config/user.ini","user","device","Wattmon");
    $console=ini_get("/config/uphp.ini","debug","console",0)==1;
    
    $log_level=ini_get("/config/uphp.ini","debug","level",0);
    
    //debug("In RUNONCE script, system just rebooted!");
    log("Wattmon Firmware ".$_GLOBALS['VERMAJOR'].".".$_GLOBALS["VERMINOR"]." Software ".$_GLOBALS['APP_INFO']." (".getmac().")");
    
    // restart the dongle (if required)
    setusbpower(0);
    if (ini_get("/config/usb.ini","usb","usb_enabled",0)) {
        if ($log_level==2) 
            log("[usb] Powering up USB");
        sleep(100);
        setusbpower(1);
        
    } else if ($log_level==2) log("[usb] USB is disabled");
    
    $_GLOBALS['firmware_logging']=ini_get("/config/uphp.ini","debug","firmware_logging",0);
    if ($log_level==2) {
        if ($_GLOBALS['firmware_logging'])
            log('[logging] Firmware logging is enabled');
    }
/* Watchdog timer in software  to reboot after 5 minutes */
    $wd_interval=ini_get("/config/uphp.ini","debug","watchdog_interval",-1);
	if (($_GLOBALS['VERMAJOR']==1) && ($_GLOBALS["VERMINOR"]>=1112)) {
	        if ($wd_interval==-1) 
			    init_watchdog(300);
	}
	if (($_GLOBALS['VERMAJOR']==2) && ($_GLOBALS["VERMINOR"]>=1113)) {
	        if ($wd_interval==-1)
			    init_watchdog(300);
	}
/*
* Load all groups into a global array, since values will be consolidated.
*/
    $num_groups=ini_get("/config/groups.ini","groups","num_groups",0);
    $_GLOBALS['grp']=array();
    $_GLOBALS['sw']=array();
    for ($i=0;$i<$num_groups;$i++) {
        $arr=array();
        $arr["name"]=ini_get("/config/groups.ini","groups","group".$i,"");
        $arr["type"]=ini_get("/config/groups.ini","groups","group".$i."type",0);
        $arr["show"]=ini_get("/config/groups.ini","groups","group".$i."show",0);
        
        $arr["color"]=ini_get("/config/groups.ini","groups","group".$i."color","#000000");
        if ($arr['type']<=1) {
            /* indexes are:
            0: ah_in
            1: ah_hout
            2: ahd_in            
            3: ahd_out
            4: wd_in
            5: wd_out
            6: kwh_in
            7: kwh_out
            8: am_in
            9: am_out
            10: a_in
            11: a_out
            12: w_in
            13: w_out
            14: wm_in
            15: wm_out
            */
            $arr['vals']=indexed_array(4,16);
            $arr['vals'][0]=(ini_get($prefix."/logs/ahcount.ini","data","grp".$i."_ahin",0.0));
            $arr['vals'][1]=(ini_get($prefix."/logs/ahcount.ini","data","grp".$i."_ahout",0.0));
    	    $arr['vals'][2]=(ini_get($prefix."/logs/ahcount.ini","data","grp".$i."_ahdin",0.0));
    	    $arr['vals'][3]=(ini_get($prefix."/logs/ahcount.ini","data","grp".$i."_ahdout",0.0));
    	    $arr['vals'][4]=(ini_get($prefix."/logs/ahcount.ini","data","grp".$i."_wdin",0.0));
    	    $arr['vals'][5]=(ini_get($prefix."/logs/ahcount.ini","data","grp".$i."_wdout",0.0));
    	    $arr['vals'][6]=(ini_get($prefix."/logs/ahcount.ini","data","grp".$i."_kwhin",0.0));
	        $arr['vals'][7]=(ini_get($prefix."/logs/ahcount.ini","data","grp".$i."_kwhout",0.0));
	        //log(ini_get("/logs/ahcount.ini","data","grp".$i."_ahdin",0));
	        /*$st="Group ".$i.": ";
    	    for ($x=0;$x<8;$x++) {
    	        $st.=$x."=".$arr['vals'][$x].",";
    	    }
    	    log($st);*/
    	    $arr["rated_watts"]=ini_get("/config/groups.ini","groups","group".$i."rated_watts",0);
            $arr["c"]=array();
            $arr["w"]=array();
            $arr["v"]=0;
        } else {
            if ($arr['type']==2) { // tank
                $arr['h']=0;
                $arr['m']=0;
                $arr['l']=0;
                $arr['out']=0;
		$arr['c']=0;
            }
        }
        $_GLOBALS['grp'][]=$arr;
    }
    if ($_SERVER['HW_PLATFORM']>=20) {
        $role_arr=ini_get_array("/config/roles.ini","roles");
        $num_roles=val_or_default($role_arr["num_roles"],0);
        $_GLOBALS['roles']=array();
        
        for ($i=0;$i<$num_roles;$i++) {
            $visible=val_or_default($role_arr["role".$i."show"],0);
            if ($visible) {
                $arr=array();
                $arr["name"]=val_or_default($role_arr["role".$i],"");
                $arr["role"]=$i;
                $_GLOBALS['roles'][]=$arr;
            }
            if (val_or_default($role_arr["role".$i."type"],0)==5) {   // this is a 'variable role'
            
            // the role group is used for consolation purposes
                $role_group=val_or_default($role_arr["role".$i."group"],0);
                $role_group_type=$_GLOBALS['grp'][$role_group]['type'];
                $role_type=5;//ini_get("/config/roles.ini","roles","role".$i."type",0);
                $role_def=val_or_default($role_arr["role".$i."def"],0);
                
                if ($role_group_type<=1) {  // not consolidated, or consolidated as battery
                // type 1 = current
                    if ($role_def==1) {
                        $newdev=array();
                        $newdev['role']=$i;
                        $newdev['varname']=val_or_default($role_arr["role".$devarr['role'+$j]],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['c'][]=$newdev;
                    }
                    if ($role_def==2) {  // voltage
                            // if the group has a voltage that is consolidated to the battery, calculate watts=v*a for this group.  Otherwise, set it as a global variable
                            if (($role_group_type==1) || ($role_group>0)) {
                                $_GLOBALS['grp'][$role_group]['v']=$i;
                            } else {
                                $_GLOBALS['v_role']=$i;
                            }
                    }
                    if ($role_def==7) {  // watts
                        $newdev=array();
                        $newdev['role']=$i;
                        $newdev['scale']=1;
                        $newdev['max']=1;
                        $newdev['varname']=val_or_default($role_arr["role".$devarr['role'+$j]],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['w'][]=$newdev;
                    }
                    if ($role_def==8) {  // kilowatts
                        $newdev=array();
                        $newdev['role']=$i;
                        $newdev['scale']=1000;
                        $newdev['varname']=val_or_default($role_arr["role".$devarr['role'+$j]],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['w'][]=$newdev;
                    }
                }
            }
        }
    } else {
        $num_roles=ini_get("/config/roles.ini","roles","num_roles",0);
        $_GLOBALS['roles']=array();
        
        for ($i=0;$i<$num_roles;$i++) {
            $visible=ini_get("/config/roles.ini","roles","role".$i."show",0);
            if ($visible) {
                $arr=array();
                $arr["name"]=ini_get("/config/roles.ini","roles","role".$i,"");
                $arr["role"]=$i;
                $_GLOBALS['roles'][]=$arr;
            }
            if (ini_get("/config/roles.ini","roles","role".$i."type",0)==5) {   // this is a 'variable role'
            
            // the role group is used for consolation purposes
                $role_group=ini_get("/config/roles.ini","roles","role".$i."group",0);
                $role_group_type=$_GLOBALS['grp'][$role_group]['type'];
                $role_type=5;//ini_get("/config/roles.ini","roles","role".$i."type",0);
                $role_def=ini_get("/config/roles.ini","roles","role".$i."def",0);
                
                if ($role_group_type<=1) {  // not consolidated, or consolidated as battery
                // type 1 = current
                    if ($role_def==1) {
                        $newdev=array();
                        $newdev['role']=$i;
                        $newdev['varname']=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['c'][]=$newdev;
                    }
                    if ($role_def==2) {  // voltage
                            // if the group has a voltage that is consolidated to the battery, calculate watts=v*a for this group.  Otherwise, set it as a global variable
                            if (($role_group_type==1) || ($role_group>0)) {
                                $_GLOBALS['grp'][$role_group]['v']=$i;
                            } else {
                                $_GLOBALS['v_role']=$i;
                            }
                    }
                    if ($role_def==7) {  // watts
                        $newdev=array();
                        $newdev['role']=$i;
                        $newdev['scale']=1;
                        $newdev['max']=1;
                        $newdev['varname']=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['w'][]=$newdev;
                    }
                    if ($role_def==8) {  // kilowatts
                        $newdev=array();
                        $newdev['role']=$i;
                        $newdev['scale']=1000;
                        $newdev['varname']=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['w'][]=$newdev;
                    }
                }
            }
        }
    }
    // ultra
    function val_or_default($val,$def) {
        if (!$val) return $def;
        return $val;
    }
    if ($_SERVER['HW_PLATFORM']>=20) {
        // get the actions
        $action_arr=ini_get_array("/config/actions.ini","actions");
        $num_actions=intval($action_arr["num_actions"]);
        for ($i=0;$i<$num_actions;$i++) {
            $act=intval($action_arr["a".$i."status"]);
            print("action ".$idx." type=".$act."\r\n");
            if ($act==5) { // Manually triggered
                $arr=array();
                
                $arr['role']=$i;
                $arr['name']=val_or_default($action_arr["a".$i."name"],'action');
                
                $arr['type']=1;
                $_GLOBALS['sw'][]=$arr;
            }
        }
        $action_arr=0;
    } else {
        // get the actions
        $num_actions=ini_get("/config/actions.ini","actions","num_actions",0);
        for ($i=0;$i<$num_actions;$i++) {
            $act=ini_get("/config/actions.ini","actions","a".$i."status",0);
            print("action ".$idx." type=".$act."\r\n");
            if ($act==5) { // Manually triggered
                $arr=array();
                
                $arr['role']=$i;
                $arr['name']=ini_get("/config/actions.ini","actions","a".$i."name","action");
                $arr['type']=1;
                $_GLOBALS['sw'][]=$arr;
            }
        }
    }
/*    // iterate through all devices and build up the array of current sensors
    // and optional voltage sensors
    if ($_SERVER['HW_PLATFORM']>=20) {
        $nbdev=mb_num_devices();
        $role_arr=ini_get_array("/config/roles.ini","roles");
        
        for ($dev=0;$dev<$nbdev;$dev++) {
            $devarr=mb_get_dev_by_index($dev);
    	    $info=0;
            //$info=ini_get_array("/dev/dev"+$devarr['device_type_id']+".ini","config");
            for ($j=0;$j < $devarr['num_roles']; $j++) {
                // the role group is used for consolation purposes
                $role_group=val_or_default($role_arr["role".$devarr['role'+$j]."group"],0);
                $role_group_type=$_GLOBALS['grp'][$role_group]['type'];
                $role_type=val_or_default($role_arr["role".$devarr['role'+$j]."type"],0);
                $role_def=val_or_default($role_arr["role".$devarr['role'+$j]."def"],0);
                
                if ($role_group_type<=1) {  // not consolidated, or consolidated as battery
                // type 1 = current
                    if (($role_type>1) && ($role_def==1)) {
                        $newdev=array();
                        $newdev['role']=$devarr['role'+$j];
                        $newdev['devname']=$devarr['name'];
                        $newdev['devid']=$devarr['slave_id'];
                        $newdev['varname']=ini_get("/dev/dev"+$devarr['device_type_id']+".ini","config",'role_var_'+$j,'');//$info['role_var_'+$j];
                        $_GLOBALS['grp'][$role_group]['c'][]=$newdev;
                    } else {
                        // type 2 = voltage
                        //print("Found Role Type ".$role_type."\r\n");
                        if ($role_def==2) {
                            // if the group has a voltage that is consolidated to the battery, calculate watts=v*a for this group.  Otherwise, set it as a global variable
                            if ($role_group_type==1) {
                                $_GLOBALS['grp'][$role_group]['v']=$devarr['role'+$j];
                            } else {
                                $_GLOBALS['v_role']=$devarr['role'+$j];
                            }
                        }
                        // type 6 = wind speed
                        if ($role_def==6) {
                            $_GLOBALS['wind_role']=$devarr['role'+$j];
                        }
                 // type 7 = wattage
                	 if ($role_def==7) {  // watts
                        $newdev=array();
                        $newdev['role']=$devarr['role'+$j];
                        $newdev['scale']=1;
                        $newdev['varname']=val_or_default($role_arr["role".$devarr['role'+$j]],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['w'][]=$newdev;
                    }
                    if ($role_def==8) {  // kilowatts
                        $newdev=array();
                        $newdev['role']=$devarr['role'+$j];
                        $newdev['scale']=1000;
                        $newdev['varname']=val_or_default($role_arr["role".$devarr['role'+$j]],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['w'][]=$newdev;
                    }
    
                        // for switches
                        if (($role_type==0) && ($devarr['role'+$j])) {
                                $arr=array();
                                $arr['role']=$devarr['role'+$j];
                                $arr['name']=val_or_default($role_arr["role".$devarr['role'+$j]],"");
                                if ($arr['name'])
                                    $_GLOBALS['sw'][]=$arr;
                        }
                    }
                } else {
                    if (($role_group_type==2) && ($role_type==1)) {  // role_group_type
                      
                         if ($role_def==1) {  // high
                            $_GLOBALS['grp'][$role_group]['h']=$devarr['role'+$j];
                         }
                         if ($role_def==2) {  // mid
                            $_GLOBALS['grp'][$role_group]['m']=$devarr['role'+$j];
                         }
                         if ($role_def==3) {  // low
                            $_GLOBALS['grp'][$role_group]['l']=$devarr['role'+$j];
                         }
                    } else {
                       if ($role_type==0) {
                            if ($role_def==1) {  // relay
                              $_GLOBALS['grp'][$role_group]['out']=$devarr['role'+$j];
                            }
                        }
                    }
            // for switches
                if (($role_type==0) && ($devarr['role'+$j])) {
                    $arr=array();
                    $arr['role'] = $devarr['role'+$j];
                    $arr['name'] = val_or_default($role_arr["role".$devarr['role'+$j]],"");
                    if ($arr['name'])
                        $_GLOBALS['sw'][]=$arr;
                }
    		    if ($role_type==2) {
                                if ($role_def==1) {   // current for tank
                                    $_GLOBALS['grp'][$role_group]['c']=$devarr['role'+$j];
                                }
                            }
                                
                }
            }
            
        }
        $role_arr=0;
    } else {
         $nbdev=mb_num_devices();
        for ($dev=0;$dev<$nbdev;$dev++) {
            $devarr=mb_get_dev_by_index($dev);
    	    $info=0;
            //$info=ini_get_array("/dev/dev"+$devarr['device_type_id']+".ini","config");
            for ($j=0;$j < $devarr['num_roles']; $j++) {
                // the role group is used for consolation purposes
                $role_group=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j]."group",0);
                $role_group_type=$_GLOBALS['grp'][$role_group]['type'];
                $role_type=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j]."type",0);
                $role_def=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j]."def",0);
                
                if ($role_group_type<=1) {  // not consolidated, or consolidated as battery
                // type 1 = current
                    if (($role_type>1) && ($role_def==1)) {
                        $newdev=array();
                        $newdev['role']=$devarr['role'+$j];
                        $newdev['devname']=$devarr['name'];
                        $newdev['devid']=$devarr['slave_id'];
                        $newdev['varname']=ini_get("/dev/dev"+$devarr['device_type_id']+".ini","config",'role_var_'+$j,'');//$info['role_var_'+$j];
                        $_GLOBALS['grp'][$role_group]['c'][]=$newdev;
                    } else {
                        // type 2 = voltage
                        //print("Found Role Type ".$role_type."\r\n");
                        if ($role_def==2) {
                            // if the group has a voltage that is consolidated to the battery, calculate watts=v*a for this group.  Otherwise, set it as a global variable
                            if ($role_group_type==1) {
                                $_GLOBALS['grp'][$role_group]['v']=$devarr['role'+$j];
                            } else {
                                $_GLOBALS['v_role']=$devarr['role'+$j];
                            }
                        }
                        // type 6 = wind speed
                        if ($role_def==6) {
                            $_GLOBALS['wind_role']=$devarr['role'+$j];
                        }
                 // type 7 = wattage
                	 if ($role_def==7) {  // watts
                        $newdev=array();
                        $newdev['role']=$devarr['role'+$j];
                        $newdev['scale']=1;
                        $newdev['varname']=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['w'][]=$newdev;
                    }
                    if ($role_def==8) {  // kilowatts
                        $newdev=array();
                        $newdev['role']=$devarr['role'+$j];
                        $newdev['scale']=1000;
                        $newdev['varname']=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j],'role'.$i);
                        $_GLOBALS['grp'][$role_group]['w'][]=$newdev;
                    }
    
                        // for switches
                        if (($role_type==0) && ($devarr['role'+$j])) {
                                $arr=array();
                                $arr['role']=$devarr['role'+$j];
                                $arr['name']=ini_get("/config/roles.ini","roles","role".$devarr['role'+$j],"");
                                if ($arr['name'])
                                    $_GLOBALS['sw'][]=$arr;
                        }
                    }
                } else {
                    if (($role_group_type==2) && ($role_type==1)) {  // role_group_type
                      
                         if ($role_def==1) {  // high
                            $_GLOBALS['grp'][$role_group]['h']=$devarr['role'+$j];
                         }
                         if ($role_def==2) {  // mid
                            $_GLOBALS['grp'][$role_group]['m']=$devarr['role'+$j];
                         }
                         if ($role_def==3) {  // low
                            $_GLOBALS['grp'][$role_group]['l']=$devarr['role'+$j];
                         }
                    } else {
                       if ($role_type==0) {
                            if ($role_def==1) {  // relay
                              $_GLOBALS['grp'][$role_group]['out']=$devarr['role'+$j];
                            }
                        }
                    }
            // for switches
                if (($role_type==0) && ($devarr['role'+$j])) {
                    $arr=array();
                    $arr['role'] = $devarr['role'+$j];
                    $arr['name'] = ini_get("/config/roles.ini","roles","role".$devarr['role'+$j],"");
                    if ($arr['name'])
                        $_GLOBALS['sw'][]=$arr;
                }
    		    if ($role_type==2) {
                                if ($role_def==1) {   // current for tank
                                    $_GLOBALS['grp'][$role_group]['c']=$devarr['role'+$j];
                                }
                            }
                                
                }
            }
        }
    }
*/    
    if ($_SERVER['HW_PLATFORM']>=20) {
        $datalog_arr=ini_get_array("/config/datalog.ini","data");
        
    	$num_logs = intval($datalog_arr["num_groups"]);
        $cur_group=-1;
        
        $_GLOBALS['num_logs']=$num_logs;
        for ($i=0;$i<$num_logs;$i++) {
            $_GLOBALS['log'.$i.'buf']='';
            $_GLOBALS['log'.$i.'interval']=val_or_default($datalog_arr["group".$i."interval"],1);
            $_GLOBALS['log'.$i.'mins']=val_or_default($datalog_arr["group".$i."mins"],1);
            $_GLOBALS['log'.$i.'curmin']=0;
            if ($_GLOBALS['firmware_logging']==0) {    
                if (val_or_default($datalog_arr["group".$i."status"],0)==1) {
                  $cur_group=$i;
            // check to see if some values require averaging
                    $grpnvar=val_or_default($datalog_arr["group".$cur_group.'numvar'],0);
                    $_GLOBALS['minval'.$i]=indexed_array(4,$grpnvar);
        // use a short if there are more than 256 roles
        			if ($num_roles>255) {
        	            $_GLOBALS['minrole'.$i]=indexed_array(2,$grpnvar);
        			} else $_GLOBALS['minrole'.$i]=indexed_array(1,$grpnvar);
                    $_GLOBALS['minfn'.$i]=indexed_array(1,$grpnvar);
                    $_GLOBALS['minvt'.$i]=indexed_array(1,$grpnvar);
                    $_GLOBALS['logmin'.$i]=indexed_array(4,$grpnvar);
                    $_GLOBALS['logmax'.$i]=indexed_array(4,$grpnvar);
                    for ($j=0;$j<$grpnvar;$j++) {
                        $_GLOBALS['minfn'.$i][$j]=val_or_default($datalog_arr["group".$cur_group.'var'+$j+'varfn'],0);
                        $_GLOBALS['minvt'.$i][$j]=val_or_default($datalog_arr["group".$cur_group.'var'+$j+'vartype'],0);
                        $_GLOBALS['logmin'.$i][$j]=val_or_default($datalog_arr["group".$cur_group.'var'+$j+'min'],0.0);
                        $_GLOBALS['logmax'.$i][$j]=val_or_default($datalog_arr["group".$cur_group.'var'+$j+'max'],0.0);
                        // only assign the role id if it's a device var
                        if ($_GLOBALS['minvt'.$i][$j]==2) 
                            $_GLOBALS['minrole'.$i][$j]=val_or_default($datalog_arr["group".$cur_group.'var'+$j+'varval'],0);
                            
                    }
                }
            }
            
        }
        $datalog_arr=0;
    } else {
	    $num_logs = ini_get("/config/datalog.ini","data","num_groups",0);
        $cur_group=-1;
        
        $_GLOBALS['num_logs']=$num_logs;
        for ($i=0;$i<$num_logs;$i++) {
            $_GLOBALS['log'.$i.'buf']='';
            $_GLOBALS['log'.$i.'interval']=ini_get("/config/datalog.ini","data","group".$i."interval",1);
            $_GLOBALS['log'.$i.'mins']=ini_get("/config/datalog.ini","data","group".$i."mins",1);
            $_GLOBALS['log'.$i.'curmin']=0;
            if ($_GLOBALS['firmware_logging']==0) {    
                if (ini_get("/config/datalog.ini","data","group".$i."status",0)==1) {
                  $cur_group=$i;
            // check to see if some values require averaging
                    $grpnvar=ini_get("/config/datalog.ini","data","group".$cur_group.'numvar',0);
                    $_GLOBALS['minval'.$i]=indexed_array(4,$grpnvar);
        // use a short if there are more than 256 roles
        			if ($num_roles>255) {
        	            $_GLOBALS['minrole'.$i]=indexed_array(2,$grpnvar);
        			} else $_GLOBALS['minrole'.$i]=indexed_array(1,$grpnvar);
                    $_GLOBALS['minfn'.$i]=indexed_array(1,$grpnvar);
                    $_GLOBALS['minvt'.$i]=indexed_array(1,$grpnvar);
                    $_GLOBALS['logmin'.$i]=indexed_array(4,$grpnvar);
                    $_GLOBALS['logmax'.$i]=indexed_array(4,$grpnvar);
                    for ($j=0;$j<$grpnvar;$j++) {
                        $_GLOBALS['minfn'.$i][$j]=ini_get("/config/datalog.ini","data","group".$cur_group.'var'+$j+'varfn',0);
                        $_GLOBALS['minvt'.$i][$j]=ini_get("/config/datalog.ini","data","group".$cur_group.'var'+$j+'vartype',0);
                        $_GLOBALS['logmin'.$i][$j]=ini_get("/config/datalog.ini","data","group".$cur_group.'var'+$j+'min',0.0);
                        $_GLOBALS['logmax'.$i][$j]=ini_get("/config/datalog.ini","data","group".$cur_group.'var'+$j+'max',0.0);
                        // only assign the role id if it's a device var
                        if ($_GLOBALS['minvt'.$i][$j]==2) 
                            $_GLOBALS['minrole'.$i][$j]=ini_get("/config/datalog.ini","data","group".$cur_group.'var'+$j+'varval',0);
                            
                    }
                }
            }
        }        
    }
    
            
    $_GLOBALS['localonly']=ini_get("/config/uphp.ini","debug","local_only",1);    
    $_GLOBALS['ajax_refresh_time']=intval(ini_get("/config/uphp.ini","debug","ajax_refresh_time",1)*1000);
    
    // for internal voltage reference
    $_GLOBALS['v_adc_mul']=ini_get("/config/battery.ini","battery","v_adc_mul");
    $_GLOBALS['v_adc_offset']=ini_get("/config/battery.ini","battery","v_adc_offset");
    $_GLOBALS['battery_met_time']=ini_get("/config/battery.ini","battery","met_time",0);
    $_GLOBALS['battery_return_amps']=ini_get("/config/battery.ini","battery","return_amps_pc",0);
    
    // if return amps is used, then set the threshold
    if ($_GLOBALS['battery_return_amps']) {
        $_GLOBALS['battery_return_amps']=ini_get("/config/battery.ini","battery","battery_ah",0)*$_GLOBALS['battery_return_amps']/100;
    }
    
    $_GLOBALS['battery_full_voltage']=ini_get("/config/battery.ini","battery","battery_full_voltage",0.0);
    
    $_GLOBALS['battery_cur_ah']=floatval(ini_get($prefix."/logs/ahcount.ini","data","battery_cur_ah"));
    $_GLOBALS['battery_percent']=floatval(ini_get($prefix."/logs/ahcount.ini","data","battery_percent"));
    $_GLOBALS['charge_cycles']=floatval(ini_get($prefix."/logs/ahcount.ini","data","charge_cycles"));
    $_GLOBALS['discharge_cycles']=floatval(ini_get($prefix."/logs/ahcount.ini","data","discharge_cycles"));
    $_GLOBALS['charge_mode']=floatval(ini_get($prefix."/logs/ahcount.ini","data","charge_mode"));
    
        
    $_GLOBALS['battery_ah']=ini_get("/config/battery.ini","battery","battery_ah",180);
 	$_GLOBALS['battery_percent']=floatval(100*$_GLOBALS['battery_cur_ah']/$_GLOBALS['battery_ah']);

    $_GLOBALS['inverter_watts_total']=ini_get("/config/solar.ini","solar","inverter_watts");
    $_GLOBALS['solar_watts_total']=ini_get("/config/solar.ini","solar","solar_watts");
    $_GLOBALS['wind_watts_total']=ini_get("/config/wind.ini","wind","wind_watts");
    
    $_GLOBALS['log_level']=ini_get("/config/uphp.ini","debug","level",0);
    // if an anemometer is connected, load the config settings for it
    if ($_GLOBALS['wind_role']) {
        $_GLOBALS['wind_offset']=ini_get("/config/anemometer.ini","anemometer","anemometer_offset",0);
        $_GLOBALS['wind_mul']=ini_get("/config/anemometer.ini","anemometer","anemometer_mul",1);
        $_GLOBALS['wind_div']=ini_get("/config/anemometer.ini","anemometer","anemometer_scale",10);
    }
	debug("Loaded global settings from file:\r\nAH="+$_GLOBALS['ah']+"\r\nDAY AH="+$_GLOBALS['ahd']);
	
 
    $_GLOBALS['hooks']=array();
    $_GLOBALS['hooks']['min']=array();
    $_GLOBALS['hooks']['minlog']=array();
    $_GLOBALS['hooks']['minpre']=array();
    $_GLOBALS['hooks']['sec']=array();
	$_GLOBALS['hooks']['day']=array();
    $_GLOBALS['hooks']['ajax']=array();
    $_GLOBALS['hooks']['cpanel']=array();
    $_GLOBALS['hooks']['home']=array();
    $_GLOBALS['loaded']=1; 

    $hooks = ini_get_array("/config/hooks.ini","config");
    for ($i=0;$i<sizeof($hooks);$i++) {
        $fn = array_key($hooks,$i);
        $val=$hooks[$fn];
        if (strpos($val,"|")) {
            $val_arr=explode($val,"|");
            $val=$val_arr[0];
        }
        if ($val==1) { // Run Once 
            log("Loading hook ".$fn);
            include($fn);
        }
        if ($val==2) { // once per sec
            $_GLOBALS['hooks']['sec'][]=$fn;
        }
        if ($val==3) { // once per min
            $_GLOBALS['hooks']['min'][]=$fn;
        }
        if ($val==4) { // ajax
            $_GLOBALS['hooks']['ajax'][]=$fn;
        }
        if ($val==5) { // home
            $a=array();
            $a['fn']=$fn;
            $a['title']=$val_arr[1];
            $a['style']=$val_arr[2];
            $a['pos']=$val_arr[3];
            if ($val_arr[4]<1) $val_arr[4]=1;
            $a['width']=$val_arr[4];
            
            $_GLOBALS['hooks']['home'][]=$a;
        }
        
    }
    
    $_GLOBALS['md5_sync']=ini_get("/config/uphp.ini","debug","md5_sync",0);
    $_GLOBALS['md5_sync_changed']=ini_get("/logs/md5.ini",'config','md5_sync_changed',1);
    $_GLOBALS['md5_check_errors']=ini_get("/logs/md5.ini",'config','md5_check_errors',0);  
    
    mkdir($prefix."/logs");
    mkdir($prefix."/ini");
    $ota_stage=ini_get($prefix."/logs/ota.ini","config","ota_stage",0);
    if ($ota_stage) {
        ini_set($prefix."/logs/ota.ini","config","ota_stage",0);
    }
    include("/app/package.inc");
    $packages=getPackageList();
    $keys=array_keys($packages);
    for ($vi=0;$vi<sizeof($packages);$vi++) {
        if ($packages[$keys[$vi]]==2) {  // active, enabled
            log("Loading module "."/package/".$keys[$vi].".cgi");
            if (file_exists("/package/".$keys[$vi].".cgi")) {
                include("/package/".$keys[$vi].".cgi");
                if (function_exists($keys[$vi]."_init")) {
                    call_user_func($keys[$vi]."_init");
                }
            }
        }
    }
    
    $run_once=ini_get("/config/runonce.ini","config","file","");
    if ($run_once) {
        log("Executing one-time script: ".$run_once);
        unlink("/config/runonce.ini");
        include($run_once);
    }
    // check if we need to call cronday.cgi
    $logdir=$prefix."/logs/"+strftime("%Y",time())."/".strftime("%m",time());
    $logfile = $logdir."/".strftime("%Y%m%d",time())."_0.csv";
    
    
    if (($cur_group>=0) && !file_exists($logfile)) {
        $lastrun=ini_get($prefix."/logs/boot.ini","config","curdate",""); 
        if (strftime("%Y-%m-%d",time())!=$lastrun) {
            log("Running cronday since this is the first boot since ".$lastrun);
            exec("/scripts/cronday.cgi",500);
        }
    }
    
    if ($log_level==2) {
        log("System booted");
    }
    
}


?>








