///tcp - commmanager ethernet roommanager, levelmanager status cache instance
/**
 * @author robert jarzabek 
 * http://www.isys.pl/
 * http://inteligentny-dom.ehouse.pro/
 * http://www.ehouse.pro/
 * http://sterowanie.biz/
 * 
*/
package org.openremote.controller.protocol.ehouse;
import java.util.Calendar;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class StatusEthernet
  {         public String recent="";        //recent status date/time
            public static String sep=System.getProperty("file.separator");
            public boolean InitializedMatrix=false;
            int STATUS_INDEX = -1;
            static int OUTPUTS_COUNT_RM = 256;
            static int ADC_PROGRAMS_COUNT_RM=24;
            static int INPUTS_COUNT_RM = 128;
            static int SENSORS_COUNT_RM = 16;
            static int ZONES_MAX=21;
            static final int DIMMERS_COUNT_RM=3;
            static final int DIMMERS_RGB_COUNT_RM=1;
            final static int PROGRAMS_COUNT_RM      = 24;
            public String[] ProgramNames        = new String[PROGRAMS_COUNT_RM];
                public String[] ZoneNames        = new String[ZONES_MAX];
            public String[] ADCProgramNames        = new String[ADC_PROGRAMS_COUNT_RM];
            public String[] DimmerNames         = new String[DIMMERS_COUNT_RM];    //name of output
            public String[] DimmerRGBNames      = new String[DIMMERS_RGB_COUNT_RM];    //name of output
            //static int ADC_SENSORS_COUNT = 16;
            static int SENSORS_COUNT_ALARM = 128;
            static int STATUS_SIZE = 256;
            public int[] Dimmer                 = new int[DIMMERS_COUNT_RM];
            public int[] DimmerRGB              = new int[DIMMERS_RGB_COUNT_RM];
        /// All necessary data for visualisation (names and status)
            public String DeviceName;                                   //device name
            public String[] OutputNames     = new String[OUTPUTS_COUNT_RM];    //name of output
            public String[] InputNames      = new String[INPUTS_COUNT_RM];
            public String[] SensorNames     = new String[SENSORS_COUNT_RM];
            public int[] SensorType= new int[SENSORS_COUNT_RM];
//            public Double[] SensorLM335Temps     = new Double[SENSORS_COUNT_RM];
            public Double[] SensorTempsLM35     = new Double[SENSORS_COUNT_RM];
            public Double[] SensorTempsMCP9700     = new Double[SENSORS_COUNT_RM];
            public Double[] SensorTempsMCP9701     = new Double[SENSORS_COUNT_RM];
            public String[] SensorTypeName  = new String[SENSORS_COUNT_RM];
            public int[] SensorABSValues    = new int[SENSORS_COUNT_RM];
            public int[] Calibration        = new int[SENSORS_COUNT_RM]; //calibration * 100
            public Double[] SensorTemps     = new Double[SENSORS_COUNT_RM];      //sensor Temp value calibrated
            public Double[] SensorPercents  = new Double[SENSORS_COUNT_RM];   //sensor percent value
            public Double[] SensorLights    = new Double[SENSORS_COUNT_RM];
            public Double[] SensorVolts     = new Double[SENSORS_COUNT_RM];
            public Boolean[] OutputStates   = new Boolean[OUTPUTS_COUNT_RM];   //output states
            public Boolean[] InputStates    = new Boolean[INPUTS_COUNT_RM];
            public Boolean[] InputInverts    = new Boolean[INPUTS_COUNT_RM];
            public Boolean[] AlarmSensorsActive     = new Boolean[SENSORS_COUNT_ALARM];
            public Boolean[] AlarmSensorsWarning = new Boolean[SENSORS_COUNT_ALARM];
            public Boolean[] AlarmSensorsMonitoring= new Boolean[SENSORS_COUNT_ALARM];
            public Boolean[] MonitoringSensorsWarning = new Boolean[SENSORS_COUNT_ALARM];
            public Boolean[] AlarmSensorsAlarm = new Boolean[SENSORS_COUNT_ALARM];
            public String[] AlarmSensorsNames = new String[SENSORS_COUNT_ALARM];

            public int DevAdrH;                                             //device addr h
            public int DevAdrL;                                             //device addr l
            public String DevAdr;
            public boolean changed;                                            //flag to set if changed value
            public boolean AdcChanged;
            //public static DateTime LastRead;
            public int CurrentProgram;
            public String CurrentProgramName="";
            public int ADCCurrentProgram;
            public String ADCCurrentProgramName="";
            public int CurrentZone;
            public String CurrentZoneName="";
            public Byte[] CurrentStatus = new Byte[STATUS_SIZE];
            //public Byte[] PreviousStatus = new Byte[STATUS_SIZE];
            public boolean IsBatch;
            /*public boolean IsRM;
            public boolean IsHM;
            public boolean IsEM;
            public boolean IsAlarm;
            public boolean IsEthernet;*/
        public boolean IsCommManager;      //communicationManager
        public boolean IsLevelManager;      //communicationManager
        public boolean IsERM;            //TCP roommanager
        public boolean IsEEM;            //TCP indywidual heat manager
        //public boolean IsCM;            //TCP roommanager
        //public boolean IsLM;            //TCP roommanager
        public boolean IsEHM;              //ethernet heat manager                    
        public boolean IsAlarm;
        public boolean IsEthernet;
        public int VCC; //power suply for calibration * 100
        final static int STATUS_EHOUSE1_DEVS		=0+StatusEhouse.STATUS_OFFSET;			//miejsce na status urządzeń podłączonych do RS485
        final static int STATUS_TCP_OFFSET=1;
        final static int STATUS_COMMMANAGER_OFFSET      =70;
        final static int STATUS_ADC_ETH			=0;//STATUS_TCP_OFFSET;			//adc pomiary 16 wejść * 2B
        final static int STATUS_ADC_ETH_END		=32;//+STATUS_TCP_OFFSET;	//84	//104
//STATUS_OUT_ETH			=STATUS_ADC_ETH_END;	//4*8 32				ind 84
//STATUS_INPUTS			=STATUS_OUT_ETH+4;		//4*8 32				ind 88
        final static int STATUS_OUT_I2C			=STATUS_ADC_ETH_END;//STATUS_INPUTS+4;	//2 razy i2c razy 10 rej po 8  //max=160 wyjść	ind 92	//112
        final static int STATUS_INPUTS_I2C		=STATUS_OUT_I2C+20;	//2 razy i2c razy 6 rej po 8	//max 96 wejść	ind 104
        final static int STATUS_ALARM_I2C		=STATUS_INPUTS_I2C+12;	//--|---
        final static int STATUS_WARNING_I2C		=STATUS_ALARM_I2C+12;		//--|---
        final static int STATUS_MONITORING_I2C	        =STATUS_WARNING_I2C+12;	//--|---			//160
        final static int STATUS_PROGRAM_NR		=STATUS_MONITORING_I2C+12; //--|---
        final static int STATUS_ZONE_NR			=STATUS_PROGRAM_NR+1;
        final static int STATUS_ADC_PROGRAM		=STATUS_ZONE_NR+1;
        final static int STATUS_LIGHT_LEVEL		=STATUS_ADC_PROGRAM+2;		//3 ściemniacze
////////////////////////////////////////////////////////////////////////////////////////////////////////////
        final static int ADC_N_OFFSET = 4;
        final static int O_N_OFFSET=ADC_N_OFFSET+16;
        final static int I_N_OFFSET=O_N_OFFSET+35;
//////////////////////////////////////////////////////////////////////////////////////////////////////////        
public void SetStatusIndex(int nr)
          {
          STATUS_INDEX=nr;
          }
//////////////////////////////////////////////////////////////////////////////////////////////////////////      
////////////////////////////////////////////////////////////////////////////////
public String hix(int[] dta,int size)
{
    String res="";
    for (int i=0;i<size;i++)
        {
        res+=ehousecommunication.ConvertAsciHex(dta[i]);
        }
    return res;
}
////////////////////////////////////////////////////////////////////////////////
public String hx(Byte[] dta,int size)
{
    String res="";
    for (int i=0;i<size;i++)
        {
        res+=ehousecommunication.ConvertAsciHex(dta[i]);
        }
    return res;
}
////////////////////////////////////////////////////////////////////////////////
public String i(int data)
{
    return String.valueOf(data);
}
public String bo(boolean data)
{
    if (data) return "1";
    else return "0";
    
}
///////////////////////////////////////////////////////////////////////////////
/***
 * Create XML file with combined status and data of current controller
 * @return 
 */
public String MakeXml()
{
String eol,Event;

eol="\r\n";

String header,footer,body,bodyheader,bodyfooter;    
header="<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \r\n <eHouse xmlns=\"http://www.isys.pl\" \r\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n            xsi:schemaLocation=\"http://www.openremote.org protocol.xsd\">";
header+="<Device>"+eol;
header+="<Name>"+DeviceName+"</Name>"+eol;
header+="<Address>"+DevAdrH+","+DevAdrL+"</Address>"+eol;
header+="<IPAddress>192.168."+DevAdrH+"."+DevAdrL+"</IPAddress>"+eol;            
header+="<AddressCombined>"+DevAdr+"</AddressCombined>"+eol;
header+="<StateModified>"+bo(changed)+"</StateModified>"+eol;
header+="<ADCModified>"+bo(AdcChanged)+"</ADCModified>"+eol;
header+="<CurrentProgram>"+i(CurrentProgram)+"</CurrentProgram>"+eol;
header+="<CurrentProgramName> "+ CurrentProgramName+" </CurrentProgramName>"+eol;
header+="<ADCCurrentProgram>"+i(ADCCurrentProgram)+"</ADCCurrentProgram>"+eol;
header+="<ADCCurrentProgramName> "+ ADCCurrentProgramName+" </ADCCurrentProgramName>"+eol;
header+="<CurrentStatus>"+hx(CurrentStatus,STATUS_SIZE)+"</CurrentStatus>"+eol;
header+="<RecentStatus>"+recent+"</RecentStatus>"+eol;
if (IsERM) header+="<Devicetype>"+"EthernetRoomManager"+"</Devicetype>"+eol;
if (IsCommManager) header+="<Devicetype>"+"CommManager"+"</Devicetype>"+eol;
if (IsEHM ) header+="<Devicetype>"+"EthernetRoomManager"+"</Devicetype>"+eol;
if (IsLevelManager) header+="<Devicetype>"+"LevelManager"+"</Devicetype>"+eol;
if (IsEthernet)  header+="<InterfaceType>"+"Ethernet"+"</InterfaceType>"+eol;;
        if (IsCommManager)       //communicationManager
            {
            header+="<CurrentZone>"+i(CurrentZone)+"</CurrentZone>"+eol;
            header+="<CurrentZoneName>"+ CurrentZoneName+"</CurrentZoneName>"+eol;

            }
bodyheader=eol+"<Outputs>"+eol;
body="";
int maxio=OUTPUTS_COUNT_RM;
if ((IsERM) || (IsEHM) || (IsEEM)) maxio=35;
for (int i=0;i<maxio;i++)
{
    int tmp[]={DevAdrH,DevAdrL,0x21,0,1,0,0,0,0,0};
    tmp[3]=i;
    String state="0"; String value="Off";   if (OutputStates[i]) {state="1";value="On";}
    body+="    <Item>"+eol+
    "        <Name>"+OutputNames[i]+"</Name>"+eol+
    "        <No>"+String.valueOf(i+1)+"</No>"+eol+
    "        <State>"+state+"</State>"+eol+
    "        <Value>"+value+"</Value>"+eol;
    Event=hix(tmp,10);
    body+="        <EventOn>"+Event+"</EventOn>"+eol;
    tmp[4]=0;Event=hix(tmp,10);
    body+="        <EventOff>"+Event+"</EventOff>"+eol;
    tmp[4]=2;Event=hix(tmp,10);
    body+="        <EventToggle>"+Event+"</EventToggle>"+eol            
    +"    </Item>"+eol+eol;
}
bodyfooter=eol+"</Outputs>"+eol;

header+=bodyheader+body+bodyfooter+eol;
bodyheader=eol+"<ADCInputs>"+eol;
body=eol;
bodyfooter=eol+"</ADCInputs>"+eol;
maxio=SENSORS_COUNT_RM;
for (int i=0;i<maxio;i++)
{
    
  body+="    <Item>"+eol+
    "        <Name>"+SensorNames[i]+"</Name>"+eol+
    "        <ADCValue>"+SensorABSValues[i]+"</ADCValue>"+eol+
    "        <ADCTempValue>"+SensorTemps[i]+"</ADCTempValue>"+eol+
    "        <ADCLM335TempValue>"+SensorTemps[i]+"</ADCLM335TempValue>"+eol+
    "        <ADCLM35TempValue>"+SensorTempsLM35[i]+"</ADCLM35TempValue>"+eol+            
    "        <ADCMCP9700TempValue>"+SensorTempsMCP9700[i]+"</ADCMCP9700TempValue>"+eol+
    "        <ADCMCP9701TempValue>"+SensorTempsMCP9701[i]+"</ADCMCP9701TempValue>"+eol+
    "        <ADCPercentValue>"+SensorPercents[i]+"</ADCPercentValue>"+eol+
    "        <ADCInvertedValue>"+SensorLights[i]+"</ADCInvertedValue>"+eol+
    "        <ADCVoltageValue>"+SensorVolts[i]+"</ADCVoltageValue>"+eol+
    "        <ADCCalibrationValue>"+Calibration[i]+"</ADCCalibrationValue>"+eol+
    
    "        <No>"+String.valueOf(i+1)+"</No>"+eol+
    "        <SensorType>"+SensorType[i]+"</SensorType>"+eol+
    "        <SensorTypeName>"+SensorTypeName[i]+"</SensorTypeName>"+eol;
    //Event=hix(tmp,10);
    //body+="        <EventOn>"+Event+"</EventOn>"+eol;
    //tmp[4]=0;Event=hix(tmp,10);
    //body+="        <EventOff>"+Event+"</EventOff>"+eol;
    //tmp[4]=2;Event=hix(tmp,10);
    //body+="        <EventToggle>"+Event+"</EventToggle>"+eol            
    /*String inversion="Normal";
    if (InputInverts[i]) inversion="Inverted";
     body+="        <Type>"+inversion+"</Type>"+eol;
     */
     body+="    </Item>"+eol+eol;
}

header+=bodyheader+body+bodyfooter+eol;



bodyheader=eol+"<Inputs>"+eol;
body=eol;
bodyfooter=eol;
maxio=INPUTS_COUNT_RM;
if ((IsERM) || (IsEHM) || (IsEEM)) maxio=12;
for (int i=0;i<maxio;i++)
{
//    int tmp[]={DevAdrH,DevAdrL,0x21,0,1,0,0,0,0,0};
  //  tmp[3]=i;
    String state="0"; String value="On";   
    if ((IsCommManager) || (IsLevelManager)) 
        {
        if (!((InputStates[i])^(InputInverts[i])))
            {state="1";value="Off";} 
        else
            {state="0";value="On";}
    
        }
    else
        {
        if ((InputStates[i])^(InputInverts[i]))
            {state="0";value="On";} 
        else
            {state="1";value="Off";}
        }
    
    body+="    <Item>"+eol+
    "        <Name>"+InputNames[i]+"</Name>"+eol+
            
    "        <No>"+String.valueOf(i+1)+"</No>"+eol+
    "        <State>"+state+"</State>"+eol+
    "        <Value>"+value+"</Value>"+eol;
    if ((IsCommManager) || (IsLevelManager)) 
        {

            
            
        if (!((AlarmSensorsActive[i])^(InputInverts[i])))
            {state="0";value="Off";} 
        else
            {state="1";value="On";}
        body+="        <ActiveState>"+state+"</ActiveState>"+eol+
        "        <ActiveValue>"+value+"</ActiveValue>"+eol;
            
            
            
        if (!((AlarmSensorsWarning[i])^(InputInverts[i])))
            {state="0";value="Off";} 
        else
            {state="1";value="On";}
        body+="        <WarningState>"+state+"</WarningState>"+eol+
        "        <WarningValue>"+value+"</WarningValue>"+eol;
        
        //MonitoringSensorsWarning
        if (!((AlarmSensorsMonitoring[i])^(InputInverts[i])))
            {state="0";value="Off";} 
        else
            {state="1";value="On";}
        body+="        <MonitoringState>"+state+"</MonitoringState>"+eol+
        "        <MonitoringValue>"+value+"</MonitoringValue>"+eol;
        
        
       if (!((AlarmSensorsAlarm[i])^(InputInverts[i])))
            {state="0";value="Off";} 
        else
            {state="1";value="On";}
        body+="        <AlarmState>"+state+"</AlarmState>"+eol+
        "        <AlarmValue>"+value+"</AlarmValue>"+eol;
        
        
        
        
        }
    //Event=hix(tmp,10);
    //body+="        <EventOn>"+Event+"</EventOn>"+eol;
    //tmp[4]=0;Event=hix(tmp,10);
    //body+="        <EventOff>"+Event+"</EventOff>"+eol;
    //tmp[4]=2;Event=hix(tmp,10);
    //body+="        <EventToggle>"+Event+"</EventToggle>"+eol            
    String inversion="Normal";
    if (InputInverts[i]) inversion="Inverted";
     body+="        <Type>"+inversion+"</Type>"+eol;
     
     body+="    </Item>"+eol+eol;
}
bodyfooter=eol+"</Inputs>"+eol;

header+=bodyheader+body+bodyfooter+eol;
footer="</Device>\r\n";
footer+="\r\n</eHouse> \r\n";

try {
    BufferedWriter out = new BufferedWriter(new FileWriter(ehousecommunication.path+DeviceName+".xml"));
    out.write(header+footer);
    out.flush();
    out.close();
} catch (Exception e) {
    //log()
}
return header+footer;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/***
 * Check ADC status changed flag
 * @return 
 */
public boolean ChkIsAdcChanged()
      {
          if (AdcChanged)
          {
              AdcChanged = false;
              return true;
          }
          return false;
      }
///////////////////////////////////////////////////////////////////////////////////////////////////////
/***
 * Check device name of current device
 * @param dname - Device name for checking index
 * @return 
 */
public boolean IsDeviceName(String dname)
      {
          if (DeviceName == null) return false;
          if (DeviceName.length() == 0) return false;
      if (dname.length() > 0)
          {
          if (dname.compareTo(DeviceName) == 0) return true;
          }
      return false;
      }
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/***
 * 
 *  Calculate temperature of LM335 sensor value from adc input
 * 
 * @param dta   --adc value 0-1024 10bit
 * @param calibration   - offset for calibration
 * @param k
 * @param VCC  - supply voltage for reference
 * @return   double value
 */
private double gettemplm(int dta, int calibration, double k, int VCC)
    {
    double temp;
    temp=(dta*VCC/(1023*k))+calibration/100;
//t=Math.Round(temp*10);
//temp=(t/10);
    temp = Math.round(temp*10)/10;
    return temp;
    }
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/***
 *  Check integer value and calculate from string
 * @param stt
 * @param defaut
 * @return 
 */
private int check_in(String stt, int defaut)
    {        
    double dd = Double.valueOf(stt);
    int ino = (int)dd;
    //ino=st.IConvertible.ToInt32();
    return (ino);
    }
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/***
 * Read alam sernsor names from file and init data
 * @param pat 
 */
public void ReadAlarmSensorsNames(String pat)
{
    int i=0;
    int z=0;
    if (ehousecommunication.FileExists(pat))
                        {
                         String[] AlarmS=ehousecommunication.getfile(pat);
                        while (AlarmS[i]!=null)
                        {
                            
                            {
                                AlarmSensorsActive[i] = false;
                                AlarmSensorsAlarm[i] = false;
                                MonitoringSensorsWarning[i]=false;
                                AlarmSensorsWarning[i] = false;
                            }
                            AlarmSensorsNames[i] = AlarmS[i];
                            
                            i++;
                            if (i == SENSORS_COUNT_ALARM) break;
                            //z++;
                            
                        }
                            while (i<SENSORS_COUNT_ALARM)
                            {
                            AlarmSensorsActive[i] = false;
                            AlarmSensorsAlarm[i] = false;
                            AlarmSensorsWarning[i] = false;
                            MonitoringSensorsWarning[i]=false;
                            AlarmSensorsNames[i] = "";
                            i++;
                            }
                            
                        }
}                  
      /******************************************************************************************************/
/**
 * Load Complete Configuration data for controller from config files
 * @param name 
 */
        public void LoadDta(String name)/*, Encoding enc)*/
        {
            String temp;
            int i;
//            try
            {
                if (ehousecommunication.FileExists(name))
                
                {
                
                    String st[]=ehousecommunication.getfile(name);
                    DeviceName = st[0];                                                         //device name
                    DevAdrH = check_in(st[1], 0);                                             //device addr h

                    DevAdrL = check_in(st[2], 0);                                             //device addr l
                    DevAdr = String.valueOf(DevAdrL); ;
                    while (DevAdr.length()<3) DevAdr='0'+DevAdr;
                    DevAdr = String.valueOf(DevAdrH) + DevAdr;
                    while (DevAdr.length() < 6) DevAdr = '0' + DevAdr;                          //combined address
                    temp = st[3];
                    if (temp.compareTo("CM") == 0) IsCommManager = true;     //communicationManager
                    if (temp.compareTo("LM") == 0) IsLevelManager = true;     //LevelManager
                    if (temp.compareTo("ERM") == 0) IsERM = true;               //EthernetRoommanager
                    if (temp.compareTo("EHM") == 0) IsEHM = true;           //EthernetHeatManager
                    if (temp.compareTo("EEM") == 0) IsEEM = true;           //indywidual heat manager
                    st=ehousecommunication.getfile(ehousecommunication.path+"mobile"+sep+DevAdr+sep+"names"+sep+"AdcNames.txt");//adc input names 
                    String senstypes[]=ehousecommunication.getfile(ehousecommunication.path+"mobile"+sep+DevAdr+sep+"names"+sep+"AdcSensorTypes.txt"); //adc sensor types list
                    String senstype[]=ehousecommunication.getfile(ehousecommunication.path+"mobile"+sep+DevAdr+sep+"names"+sep+"AdcConfig.cfg");        //adc sensors type
                    for (i = 0; i < SENSORS_COUNT_RM; i++)
                         {
                        if (st[i]==null) st[i]="";
                        SensorNames[i] = st[i];
                        int senstyp=0;
                        try
                        {
                            senstyp=Integer.parseInt(senstype[i]);
                                    }
                        catch (Exception e)
                                {
                                senstyp=0;
                                }
                        SensorType[i]=senstyp;
                        SensorTypeName[i]=senstypes[senstyp];
                        if (SensorNames[i] == null) SensorNames[i] = "";
                        SensorABSValues[i] = 0;
                        SensorTemps[i] = 0.0;      //sensor Temp value calibrated
                        SensorPercents[i] = 0.0;   //sensor percent value
                        SensorLights[i] = 0.0;
                        SensorVolts[i]=0.0;
                        Calibration[i] = -27315;
                        SensorTemps[i] = 0.0;
                        SensorTempsLM35[i] = 0.0;
                        SensorTempsMCP9700[i] = 0.0;
                        SensorTempsMCP9701[i] = 0.0;
  //                      SensorType[i] = 0;
//                        SensorTypeName[i]  = "";
                        }
                    

                    VCC = 3300;
                    // Set output names and initialize
                    if ((IsCommManager) || (IsLevelManager) ) 
                         st = ehousecommunication.getfile(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "AdditionalOutputNames.txt");    //aditional inputs for large controllers LM,CM
                    else 
                         st = ehousecommunication.getfile(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" + sep+"OutputNames.txt");      //standard output names for current controler
                    for (i = 0; i < OUTPUTS_COUNT_RM; i++)
                        {
                        if (st[i]==null) st[i]="";
                        OutputNames[i] = st[i];
                        if (OutputNames[i] == null) OutputNames[i] = "";
                        OutputStates[i] = false;
                        }
                    
                    ///Get input names 
                    if (ehousecommunication.FileExists(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "InputNames.txt"))          
                        st = ehousecommunication.getfile(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "InputNames.txt");
                    else
                        st = ehousecommunication.getfile(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "SensorNames.txt");
                    String inv[]=ehousecommunication.getfile(ehousecommunication.path + "mobile" + sep+DevAdr +sep+ "names" +sep+ "SensorsInverts.cfg");
                    for (i =0; i < INPUTS_COUNT_RM; i++)
                    
                            {
                            
                            if (st[i]==null) st[i]="";
                            AlarmSensorsNames[i] = st[i];
                            InputNames[i] = st[i];
                            InputStates[i]=false;
                            InputInverts[i]=false;
                            if (inv[i]!=null)
                                if (inv[i].trim().equalsIgnoreCase("1")) 
                                    InputInverts[i]=true;
                            //AlarmSensorsStates[i]=false;
                            AlarmSensorsActive[i] = false;
                            AlarmSensorsWarning[i] = false;
                            AlarmSensorsMonitoring[i] = false;
                            AlarmSensorsAlarm[i] = false;
        
                            }
                    
                    
                    ///Read program names
                    if  (ehousecommunication.FileExists(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "Programs.txt"))          //(!IsCommManager)
                    {
                    st = ehousecommunication.getfile(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "Programs.txt");
                    for (i =0; i < PROGRAMS_COUNT_RM; i++)
                            {
                            if (st[i]==null) st[i]="Program "+String.valueOf(i+1);
                            ProgramNames[i] = st[i];
                            }
                    }
                    
                    //read adc program names
                    if  (ehousecommunication.FileExists(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "ADCPrograms.txt"))          //(!IsCommManager)
                    {
                    st = ehousecommunication.getfile(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "ADCPrograms.txt");
                    for (i =0; i < PROGRAMS_COUNT_RM; i++)
                            {
                            if (st[i]==null) st[i]="ADC Program "+String.valueOf(i+1);
                            ADCProgramNames[i] = st[i];
                            }
                    }
                    //read security zones names
                    if (IsCommManager)
                        if  (ehousecommunication.FileExists(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "ZonesNames.txt"))          //(!IsCommManager)
                            {
                            st = ehousecommunication.getfile(ehousecommunication.path + "mobile" +sep+ DevAdr +sep+ "names" +sep+ "ZonesNames.txt");
                            for (i =0; i < ZONES_MAX; i++)
                                {
                                if (st[i]==null) st[i]="Zone "+String.valueOf(i+1);
                                ZoneNames[i] = st[i];
                                }
                            }
                    
                    changed = false;                                            //flag to set if changed value
                    //                    AdcChanged = false;
                    //LastRead = 0;
                    CurrentProgram = 0;
                    CurrentProgramName = "";
                    for (i = 0; i < STATUS_SIZE; i++)
                    {
                        CurrentStatus[i] = 0;
                        //                        PreviousStatus[i] = 0;
                    }
                    IsBatch = false;
                    IsAlarm = false;
                    IsEthernet = true;
                }
            }
            /*catch (Exception ie)
            {
                sMessageBox.Show("Error Reading File: " + name + " " + ie.getMessage());
            }*/
        }





////////////////////////////////////////////////////////////////////////////////////////////////////////////
/***
 * 
 * 
 * Calculate percent value of adc inputs
 * 
 * @param dta
 * @return 
 */        
public double calculate_percent(int dta)
            {
    
        
             double tmp = Math.round((double)((dta * 100 ) / 1023)*100)/100;  //do 2 miejsc po przecinku
                //tmp = (tmp) / 100;
            return tmp;
            }
////////////////////////////////////////////////////////////////////////////////////////////////////////////
public double getlight(int dta)
  {
 
  //double dtta=(1023-dta)*100;
      double dtta = (dta) * 100;
  dtta = ((((double)dtta) / 1023));
    return Math.round(dtta*10)/10;
  }
final static int STATUS_OFFSET                 = 1;                         //index of data in UDP & TCP complete Status 
final static int RM_STATUS_ADC                 = 1  + STATUS_OFFSET;
final static int RM_STATUS_OUT  	       = 17 + STATUS_OFFSET;
final static int HM_STATUS_OUT                 = 33 + STATUS_OFFSET;
final static int RM_STATUS_IN                  = 20 + STATUS_OFFSET;
final static int RM_STATUS_INT                 = 21 + STATUS_OFFSET;
final static int RM_STATUS_OUT25               = 22 + STATUS_OFFSET;
final static int RM_STATUS_LIGHT               = 23 + STATUS_OFFSET;
final static int RM_STATUS_ZONE_PGM            = 26 + STATUS_OFFSET;
final static int RM_STATUS_PROGRAM             = 27 + STATUS_OFFSET;
final static int RM_STATUS_INPUTEXT_A_ACTIVE   = 28 + STATUS_OFFSET;
final static int RM_STATUS_INPUTEXT_B_ACTIVE   = 32 + STATUS_OFFSET;
final static int RM_STATUS_INPUTEXT_C_ACTIVE   = 36 + STATUS_OFFSET;
final static int RM_STATUS_INPUTEXT_A          = 40 + STATUS_OFFSET;
final static int RM_STATUS_INPUTEXT_B          = 50 + STATUS_OFFSET;
final static int RM_STATUS_INPUTEXT_C          = 60 + STATUS_OFFSET;
final static int HM_STATUS_PROGRAM             = 36 + STATUS_OFFSET;
final static int HM_STATUS_KOMINEK 	       = 46 + STATUS_OFFSET;
final static int HM_STATUS_RECU 	       = 48 + STATUS_OFFSET;
final static int HM_WENT_MODE		       = 49 + STATUS_OFFSET;

////////////////////////////////////////////////////////////////////////////////////////////////////////////
/***
 *  Get value of input (bit) from bytes in status
 * 
 * @param dta - data byte which consist 8 inputs/outputs states
 * @param offset - offset in byte to get single byte for output/input
 * @return state of output/input
 */
public boolean GetInOutValue(int dta, int offset)
    {
    int temp=dta>>offset;
    if ((temp & 0x01)>0) 
            return true;
    else return false;
    }
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/***
 * 
 * @param EventName
 * @param AlarmState
 * @return 
 */
/*
public int[] GetOptsIndex(String EventName,int AlarmState)
    {
        int i;
    int[] m=new int[2];
    for (i=0;i<OUTPUTS_COUNT_RM;i++)
    {
        if (OutputNames[i].length()>0)
            if (EventName.compareTo(OutputNames[i])==0)
                {
                m[1]=i;
                m[0]=1;
                return m;// (STATUS_INDEX<<16)+(1<<8)+i;
                }
    }
    for (i=0;i<INPUTS_COUNT_RM;i++)
    {
        if (InputNames[i].length()>0)
            if (EventName.compareTo(InputNames[i])==0)
                {
                m[1]=i;
                m[0]=2;
                return m;// (STATUS_INDEX<<16)+(1<<8)+i;
                }
    }
    
    for (i = 0; i < SENSORS_COUNT_RM; i++)
    {
        if (SensorNames[i].length() > 0)
            if (EventName.compareTo(SensorNames[i]) == 0)
            {
                m[1] = i;
                m[0] = 3;
                return m;// (STATUS_INDEX<<16)+(1<<8)+i;
            }
    }
    if (IsEEM)
    for (i = 0; i < SENSORS_COUNT_ALARM;i++ )
        if (AlarmSensorsNames[i].length() > 0)
        {
            if (EventName.compareTo(AlarmSensorsNames[i]) == 0)
            {
                m[1] = i;
                m[0] = 4 + AlarmState;
                return m;
            }
        }
        
    m[1] = 255;
    m[0] = 255;
    return m;
    }*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Decode binary status from UDP broadcast or TCP status and update internal cache
 * @param dta - status data from eHouse devices
 * @param InitFromPrevious - unconditional update status
 * @param CommManager - Offset for CommManager in case of Ehouse 1 under CommManager supervision (CommManager status attached  after eHouse1 controller status)
 * @return 
 */
public boolean WriteCheckIfChangedAndCpy(byte[] dta, boolean InitFromPrevious,boolean CommManager)

        { int i,k;
        int sss=0;
        boolean tempboolean = false;
        boolean unconditional = InitFromPrevious;
        int TotalOffset=STATUS_TCP_OFFSET;
        if (CommManager) TotalOffset+=STATUS_COMMMANAGER_OFFSET;
        

        int Max_ADC = 16;
        Calendar c = Calendar.getInstance(); 
        recent=c.getTime().toLocaleString();
//            boolean changedd=false;
            if (InitFromPrevious) changed = true;
            else changed=false;
            if (!InitFromPrevious)
              //if (dta != null)
                for (i = 0; i < STATUS_SIZE; i++)
                    {
                     if (CurrentStatus[i] != dta[i])
                        {
                            CurrentStatus[i] = dta[i];
                            changed = true;
                        }
                    }
        
        if (changed) 
        {   //update data
        
        //if ((IsERM) || (IsEEM)) Max_ADC=8;
        
        {
            
            if ((IsERM) && (!InitFromPrevious))                CurrentStatus[STATUS_SIZE-1] = 0;
            
            //Update All Outputs
            for (k = 0; k < 8; k++)
                {   ///output states
                    OutputStates[k] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C], k);
                    OutputStates[k + 8]  = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 1], k); 
                    OutputStates[k + 16] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 2], k); 
                    OutputStates[k + 24] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+3], k); 
                    OutputStates[k+32] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+4], k);
                    OutputStates[k + 40]  = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 5], k); 
                    OutputStates[k + 48] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 6], k); 
                    OutputStates[k + 56] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+7], k); 
                    OutputStates[k+64] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+8], k);
                    OutputStates[k + 72]  = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 9], k);
                    OutputStates[k + 80] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 10], k);
                    OutputStates[k + 88] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+11], k); 
                    OutputStates[k + 96] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 12], k); 
                    OutputStates[k + 104] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+13], k); 
                    OutputStates[k+112] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+14], k);
                    OutputStates[k + 120]  = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 15], k); 
                    OutputStates[k + 128] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 16], k); 
                    OutputStates[k + 136] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+17], k); 
                    OutputStates[k+144] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C+18], k);
                    OutputStates[k + 152]  = GetInOutValue(CurrentStatus[TotalOffset+STATUS_OUT_I2C + 19], k); 
                    //Update all inputs
                    InputStates[k]       = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C], k);
                    InputStates[k+8]     = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+1], k);
                    InputStates[k+16]       = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+2], k);
                    InputStates[k+24]     = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+3], k);                   
                    InputStates[k+32]       = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+4], k);
                    InputStates[k+40]     = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+5], k);
                    InputStates[k+48]       = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+6], k);
                    InputStates[k+56]     = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+7], k);
                    InputStates[k+64]       = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+8], k);
                    InputStates[k+72]     = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+9], k);
                    InputStates[k+80]       = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+10], k);
                    InputStates[k+88]     = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+11], k);
                    
                    
                    //Security sensors status Alarm, Warning, Monitoring Mask violations
                if (IsCommManager)
                    {
                        ////active sensors - inputs
                    AlarmSensorsActive[k] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C], k);
                    AlarmSensorsActive[k + 8] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C + 1], k); 
                    AlarmSensorsActive[k + 16] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C + 2], k); 
                    AlarmSensorsActive[k + 24] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C + 3], k); 
                    AlarmSensorsActive[k + 32] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C + 4], k);
                    AlarmSensorsActive[k + 40] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C + 5], k); 
                    AlarmSensorsActive[k + 48] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+6], k);
                    AlarmSensorsActive[k + 56] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+7], k); 
                    AlarmSensorsActive[k + 64] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+8], k);
                    AlarmSensorsActive[k + 72] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+9], k);
                    AlarmSensorsActive[k + 80] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+10], k);
                    AlarmSensorsActive[k + 88] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_INPUTS_I2C+11], k);                    
                    AlarmSensorsAlarm[k] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C], k);
                    // active sensors violating Alarm mask
                    AlarmSensorsAlarm[k + 8] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 1], k); 
                    AlarmSensorsAlarm[k + 16] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 2], k); 
                    AlarmSensorsAlarm[k + 24] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 3], k); 
                    AlarmSensorsAlarm[k + 32] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 4], k);
                    AlarmSensorsAlarm[k + 40] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 5], k); 
                    AlarmSensorsAlarm[k + 48] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 6], k); 
                    AlarmSensorsAlarm[k + 56] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 7], k); 
                    AlarmSensorsAlarm[k + 64] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 8], k);
                    AlarmSensorsAlarm[k + 72] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 9], k);
                    AlarmSensorsAlarm[k + 80] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 10], k);
                    AlarmSensorsAlarm[k + 88] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_ALARM_I2C + 11], k);
                    //security sensors - violating Warning Mask
                     AlarmSensorsWarning[k] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C], k);
                    AlarmSensorsWarning[k + 8] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 1], k); 
                    AlarmSensorsWarning[k + 16] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 2], k); 
                    AlarmSensorsWarning[k + 24] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 3], k); 
                    AlarmSensorsWarning[k + 32] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 4], k);
                    AlarmSensorsWarning[k + 40] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 5], k); 
                    AlarmSensorsWarning[k + 48] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 6], k); 
                    AlarmSensorsWarning[k + 56] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 7], k); 
                    AlarmSensorsWarning[k + 64] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 8], k);
                    AlarmSensorsWarning[k + 72] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 9], k);
                    AlarmSensorsWarning[k + 80] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 10], k);
                    AlarmSensorsWarning[k + 88] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_WARNING_I2C + 11], k);
                    //security sensors - violating monitoring mask
                    MonitoringSensorsWarning[k] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C], k);
                    MonitoringSensorsWarning[k + 8] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 1], k); 
                    MonitoringSensorsWarning[k + 16] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 2], k);
                    MonitoringSensorsWarning[k + 24] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 3], k);
                    MonitoringSensorsWarning[k + 32] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 4], k);
                    MonitoringSensorsWarning[k + 40] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 5], k);
                    MonitoringSensorsWarning[k + 48] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 6], k);
                    MonitoringSensorsWarning[k + 56] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 7], k);
                    MonitoringSensorsWarning[k + 64] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 8], k);
                    MonitoringSensorsWarning[k + 72] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 9], k);
                    MonitoringSensorsWarning[k + 80] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 10], k);
                    MonitoringSensorsWarning[k + 88] = GetInOutValue(CurrentStatus[TotalOffset+STATUS_MONITORING_I2C + 11], k);


                    }
                }

            CurrentProgram=CurrentStatus[TotalOffset+STATUS_PROGRAM_NR];
            CurrentZone = CurrentStatus[TotalOffset+STATUS_ZONE_NR];            
            CurrentProgramName="";
            if (CurrentZone<ZONES_MAX)
                CurrentZoneName=ZoneNames[CurrentZone];
            else CurrentZoneName="-";
            ADCCurrentProgramName="";
            
            }
/*        if (IsTCPEM)
        {
            CurrentProgramName = "";
        }*/
/*        if (IsTCPHM) 
            {
            Max_ADC=16;
            CurrentProgram = CurrentStatus[HM_STATUS_PROGRAM];
            CurrentProgramName = "";//na razie
            for (k = 0; k < 8; k++)
                {
                int mm = 0;
                OutputStates[k] = GetInOutValue(CurrentStatus[HM_STATUS_OUT], k);
                OutputStates[k + 8] = GetInOutValue(CurrentStatus[HM_STATUS_OUT + 1], k); //bitoffset++; k++;
                OutputStates[k + 16] = GetInOutValue(CurrentStatus[HM_STATUS_OUT + 2], k); //bitoffset++; k++;
//                InputStates[k] = GetInOutValue(CurrentStatus[RM_STATUS_IN ], k);
  //              InputStates[k + 8] = GetInOutValue(CurrentStatus[RM_STATUS_INT ], k);
                }
            }*/
        i=0;
        while (i < Max_ADC)
                {                                               //offset od 2                       //offset od 2
                int temppp= CurrentStatus[TotalOffset+i * 2 + 1 ];
                if (temppp<0) temppp+=256;
                 temppp+=(CurrentStatus[TotalOffset+i * 2 ] << 8);
                if (SensorABSValues[i] != temppp)
                    {
                    changed = true;
                    AdcChanged = true;
                    }
                    SensorABSValues[i] = temppp;
                    SensorTemps[i] = gettemplm(SensorABSValues[i], Calibration[i], 10, VCC);
                    SensorLights[i] = getlight(SensorABSValues[i]);
                    SensorPercents[i] = calculate_percent(SensorABSValues[i]);
                    i++;
                }
        int m=0;
        }
        //if (changed) 
            MakeXml();
        return changed;
        }
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 
 * Check address for current device cache instance verification
 * 
 * @param devadrh - high address
 * @param devadrl - low address
 * @return true if address match
 */
        public  boolean isAddress(int devadrh, int devadrl)
        {
            int devadrhh,devadrll;
            devadrhh=devadrh;
            devadrll=devadrl;
       if (devadrhh<0) devadrhh=256+devadrhh;
       if (devadrll<0) devadrll=256+devadrll;
        if ((devadrhh==DevAdrH) && (devadrll==DevAdrL))             
            return true;
            
        
        
        return false;

        }
    
    }

