package kr.co.icontrols.wallpadmain;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.SQLException;
import android.graphics.Color;
import android.hardware.Camera;
import android.media.AudioManager;
import android.net.Uri;
import android.net.ethernet.EthernetDevInfo;
import android.net.ethernet.EthernetManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;

import com.artncore.WallPadDataMgr.WallpadCallHistoryData;
import com.artncore.WallPadDataMgr.WallpadDeviceSet;
import com.artncore.WallPadDataMgr.WallpadParkInfo;
import com.artncore.WallPadDataMgr.WallpadSalesSampleData;
import com.artncore.WallPadDataMgr.WallpadScheduleData;
import com.artncore.WallPadDataMgr.WallpadStatusData;
import com.artncore.WallPadDataMgr.WallpadVisitorPicData_A20;
import com.artncore.WallPadDataMgr.wallpaddbmgr;
import com.artncore.WallPadDataMgr.wallpaddbmgr.AddressSet;
import com.artncore.WallPadDataMgr.wallpaddbmgr.AddressSetBackup;
import com.artncore.commons.APIErrorCode;
import com.artncore.commons.DataClasses.CarParkingData;
import com.artncore.commons.define;
import com.artncore.deviceinterface.WallPadInterface;
import com.artncore.wallpadapi.IntLightAPI;
import com.artncore.wallpadapi.LightAPI;
import com.artncore.wallpadapi.MultiSwitchAPI;
import com.artncore.wallpadapi.SdbAPI;
import com.artncore.wallpadapi.Sdb_LivingRoomLightAPI;
import com.artncore.wallpadapi.WallPadAPI;
import com.artncore.wallpadimap.RetProci;
import com.artncore.wallpadimap.WallPadiMAPNotifyAPI;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.util.LogUtil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Pattern;

import kr.co.icontrols.v40ioctl.V40IOInterface;
import kr.co.icontrols.wallpadmain.declare.Common;
import kr.co.icontrols.wallpadmain.declare.Common.BR_MAIN_LIVE_CHECKER;
import kr.co.icontrols.wallpadmain.declare.DataClasses.IconInfoTable;
import kr.co.icontrols.wallpadmain.declare.ID;
import kr.co.icontrols.wallpadmain.declare.ID_OLD;
import kr.co.icontrols.wallpadmain.declare.LayoutDevice;
import kr.co.icontrols.wallpadmain.imap.iMAPAlarmOperation;
import kr.co.icontrols.wallpadmain.imap.iMAPCarParking;
import kr.co.icontrols.wallpadmain.imap.iMAPCarParking_UPIS;
import kr.co.icontrols.wallpadmain.imap.iMAPElecCarChargingInfo;
import kr.co.icontrols.wallpadmain.imap.iMAPEnergyServer_EnergyMeter;
import kr.co.icontrols.wallpadmain.imap.iMAPEnergyServer_EnergyModule;
import kr.co.icontrols.wallpadmain.imap.iMAPEnergyServer_Realmeter;
import kr.co.icontrols.wallpadmain.imap.iMAPRemotemeter;
import kr.co.icontrols.wallpadmain.menu.CallSubMenuScreen;
import kr.co.icontrols.wallpadmain.screen.EASYUI_MAIN;
import kr.co.icontrols.wallpadmain.screen.HYOSUNGUI_MAIN_HA;
import kr.co.icontrols.wallpadmain.screen.HYOSUNGUI_MAIN_HN;
import kr.co.icontrols.wallpadmain.screen.MAIN;
import kr.co.icontrols.wallpadmain.screen.METROUI_MAIN;
import kr.co.icontrols.wallpadmain.screen.METROUI_SUB_01;
import kr.co.icontrols.wallpadmain.screen.METROUI_SUB_02;
import kr.co.icontrols.wallpadmain.screen.METROUI_SUB_GROUP;
import kr.co.icontrols.wallpadmain.screen.SUB_01;
import kr.co.icontrols.wallpadmain.screen.SUB_02;
import kr.co.icontrols.wallpadmain.util.EnergyAlramPopupMgr;
import kr.co.icontrols.wallpadmain.util.IconManager;
import kr.co.icontrols.wallpadmain.util.MobileProcService;
import kr.co.icontrols.wallpadmain.util.StringUtil;
import kr.co.icontrols.wallpadmain.util.iMapServer;
import kr.co.icontrols.wallpadsupport.Version;
import kr.co.icontrols.wallpadsupport.Version.MODEL_TYPE;
import kr.co.icontrols.wallpadsupport.WpadActivity;
import kr.co.icontrols.wallpadsupport.WpadRelativeLayoutParams;
import kr.co.icontrols.wallpadsupport.WpadScale;
import kr.co.icontrols.wallpadsupport.WpadSound;
import kr.co.icontrols.wallpadsupport.WpadSound.SND;
import kr.co.icontrols.wallpadsupport.WpadUtil;

import kr.co.icontrols.wallpadmain.imap.iMAPAlarmOperation.EMER_STATE;
import kr.co.icontrols.wallpadmain.imap.iMAPAlarmOperation.EMER_DETAIL_INFO;

import static android.content.Intent.ACTION_TIME_TICK;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static com.artncore.commons.define.ALBUM_PICTURE_LOCATION;
import static com.artncore.commons.define.BESTIN_LOCATION;


/**
 * @description
 * 월패드 [설정기능] 메인화면 이다.<br>
 * 상단의 Top 메뉴, [홈] [돌아가기]<br>
 * 좌측의 Tab 메뉴, [조명] [난방] [가스] ... 등 선택 메뉴<br>
 * 를 여기서 처리한다.
 */
public class MainActivity extends WpadActivity {
    private final static String TAG = "MainActivity";
    
    private void DebugLogOutput(String s) { if(Common.DEBUG_LOG_ON) Log.d(TAG, s); }

    // =================================================================================================
    // [[ Declaration ]] region
    // =================================================================================================
    protected Context mContext = null;
    static Context mContext_call = null;
    public Context getContext() { return mContext; }
    private WallPadAPI mWallPadAPI = null;
    public static IOInterface mIOInterface = null;
    private int DEVICE_OPERATION_MODE = Common.MODE;
    boolean bEasyModeUsage = false;

    public static boolean bGoodDesign2020 = false;
    
    // Layout
    private RelativeLayout MainLayout;   // 메인화면
    private RelativeLayout MainScreenLayout;
    
    private RelativeLayout SubLayout_01;   // 서브 01 화면
    private RelativeLayout SubScreenLayout_01;
    
    private RelativeLayout SubLayout_02;   // 서브 02 화면
    private RelativeLayout SubScreenLayout_02;

    private RelativeLayout EasyMainLayout;   // 간편모드 메인화면
    private RelativeLayout EasyMainScreenLayout;

    private ViewFlipper mViewFlipper;
    Animation aniSlideIn, aniSlideOut;

    public static ImageView IMG_LCD_KEEPER;
   
    
    // PopupActivityRun
    private static boolean PopupActivityRun = false;
    public static boolean getPopupActivityRun() { return PopupActivityRun; }
    public static void setPopupActivityRun(boolean run) { PopupActivityRun = run; }
    
	// InfoActivityRun
	private static boolean InfoActivityRun = false;
	public static boolean getInfoActivityRun() {
		Log.d(TAG, "[getInfoActivityRun] InfoActivityRun: " + InfoActivityRun);
	    return InfoActivityRun;
	}
	public static void setInfoActivityRun(boolean run) {
		InfoActivityRun = run;
	    if (!InfoActivityRun) resetCurrentInfoScreenID();
	}
	
    // Menu & TabData
    private Menu mMenu = null;
//    private TabData mTabData = null;
    
    // CurrentScreenId
    private int mCurrentScreenId = -1;
    private int mTempCurrentScreenId = -1;
    private static int mCurrentInfoScreenId = -1;
    
    // Screen    
    private MAIN MainScreen = null;
    private SUB_01 SUB_01Screen = null;
    private SUB_02 SUB_02Screen = null;
    private METROUI_MAIN MetroUI_MainScreen = null;
    private METROUI_SUB_01 MetroUI_SUB_01Screen = null;
    private METROUI_SUB_02 MetroUI_SUB_02Screen = null;
    private METROUI_SUB_GROUP MetroUI_SUB_GroupScreen = null;
    private HYOSUNGUI_MAIN_HN Hyosung_HN_MainScreen = null;
    private HYOSUNGUI_MAIN_HA Hyosung_HA_MainScreen = null;
    private EASYUI_MAIN EasyUI_MainScreen = null;

    // 메뉴 리스트 처리 및 서브 스크린 호출
 	public CallSubMenuScreen m_CallSubMenuScreen = null;
    
    ///////////////////////////// AnC 메인어플에서 사용되는 변수 모음
	
    
	int       LastTimeSync = 0;
	boolean     	HomeCTROn = true;
	//int          	  PSTNStatus = 0;
	int         	MAINStatus = 0;
	public static final int MAIN_NORMAL        = 0;
	public static final int MAIN_WAIT_SETIP    = 1;
	static boolean Alert_App_On = false;
	
	byte    bootupretryCNT = 0;
	static final int MAX_BOOTUP_RETRY_COUNT    = 1200;
	
	ScheduleManager SCManager;
	
	
	boolean SYSTEM_TIME_SET = false;
	static boolean CALLSVCSTARTED = false;
	
	public Thread mThread_getAppsVersion = null; 
    ///////////////////////////// end 
	
	// 거실조명 제어드라이버
	private IntLightAPI mIntLightAPI = null;
	// 에너지미터 제어드라이버
	private Sdb_LivingRoomLightAPI mSdb_LivingRoomLightAPI = null;
    private SdbAPI mSdbAPI = null;
	
	// 멀티스위치 제어 드라이버 
	private MultiSwitchAPI m_MultiSwitch = null;
	// 대외향 거실 스위치 드라이버 
	private LightAPI m_LightCtrl = null;
	
	private boolean m_ModelHouseSleepModeRelease = false;
    
	//주차정보 관련 변수
	public static boolean bUseofNot_ParkingInfo = false;
	public static int nParkingSystemType = Common.PARKING_SYSTEM_ICONTROLS;
    private String ParkingServerIP = null;
    private int ParkingServerPort = 10000;
    private int cGetParkingMin = 18;
    private boolean bSetMSG_GetParkingInfo = false;
    iMAPCarParking iMAPcarParking;
    iMAPCarParking_UPIS iMapcarParking_UPIS;
    
    //일정 알림 관련 변수
    private int AlarmScheduleCount = 0;
    private String AlarmScheduleString = null;
    private boolean bAlarmScheduleString = false;
    
    //전기차 충전 관련 변수
    iMAPElecCarChargingInfo imapElecCarChargingInfo;
    
    //제로 에너지 하우스 관련 변수
    private boolean bUseofNot_ZeroEnergyHouseInfo = false;
    private int cGetZeroEnergyHouseMin = 12;
    iMAPEnergyServer_Realmeter iMAPenergyServer_Realmeter;
    iMAPEnergyServer_EnergyMeter iMAPenergyServer_EnergyMeter;
    iMAPEnergyServer_EnergyModule iMAPenergyServer_EnergyModule;
    String DayofLastSecond = "2000-01-01 00:00:00";
    boolean DayofLastBoolean = false;

    //에너지관리서버 관련 변수
    private boolean bUseofNot_EnergyServer = false;
    
    //에너지 알람 발생 관련 변수
    private boolean bUseofNot_EnergyAlarm = false;
    private boolean ResultGetIntent = false;
    
    private String elect_target = "Error";
    private String elect_used = "Error";
    private String elect_info = "Error";
    
    private String water_target = "Error";
    private String water_used = "Error";
    private String water_info = "Error";
    
    private String gas_target = "Error";
    private String gas_used = "Error";
    private String gas_info = "Error";
    
    private String hotwater_target = "Error";
    private String hotwater_used = "Error";
    private String hotwater_info = "Error";
    
    private String heating_target = "Error";
    private String heating_used = "Error";
    private String heating_info = "Error";

    /**
     * 월패드 이벤트 알림 관련 변수
     */
    // 스마트 우편, 전기차 충전 사용 여부
    public static boolean bSmartPostUsage = false, bElecVehicleUsage = false;
    // 부재중 전화, 방문객 사진, 공지사항, 택배, 스마트 우편, 전기차 충전 이벤트 개수
    public static int nMissedCallCnt = 0, nVisitorPicCnt = 0, nNoticeCnt = 0, nParcelCnt = 0, nPostCnt = 0, nElecVehicleChangingCnt = 0;

    
    // 끝

    //월패드 CallBr 관리하기 위한 List
    static public ArrayList<Intent> CallBrList;

    IconManager mIconManager;
    public IconInfoTable mIconInfoTable;
    public static int nShortcutCnt = 0;
    public static int nShortcutMax = 12;
    public static int nShortcutCnt_HS = 0;
    public static int nShortcutMax_HS = 9;
    public static int nShortcutCnt_Metro = 0;
    public static int nShortcutMax_Metro = 3;
    int nIconsOnSubScreen = 24;
    public static List<WallpadStatusData.WidgetItem> MainScreenShortcutList;
    public static List<WallpadStatusData.WidgetItem> HSScreenShortcutList;
    public static List<WallpadStatusData.WidgetItem> MetroScreenShortcutList;

    // 조명상태를 관리하기 위한 클래스
    public static class LightInfo {
        public class Preset {
            public class Lights {
                public String ONOFF = "none";
                public int DIM = 0;
                public int COLOR = 0;
                public Lights() {
                    ONOFF = "none";
                    DIM = 0;
                    COLOR = 0;
                }
            }

            public Lights[] mLights;

            public Preset() {
                mLights = new Lights[9];   // 0번지는 프리셋별 그룹제어 설정값 (조명 1~8)
                for (int i = 0; i < mLights.length; i++) {
                    mLights[i] = new Lights();
                }
            }
        }

        public Preset[] mPreset;
        public int nLightPresetNo;
        public LightInfo() {
            mPreset = new Preset[9];   // 0번지는 전체제어 설정값 (프리셋 1~8)
            for (int i = 0; i < mPreset.length; i++) {
                mPreset[i] = new Preset();
            }
            nLightPresetNo = 0;
        }
    }
    public static LightInfo mLightInfo;
    public String BR_CTRL_LIGHT_LIVINGROOM = "kr.co.icontrols.wallpadglobalscreen.BR_CTRL_LIGHT_LIVINGROOM";

    public static WpadSound mSound;

    public void getLivinglightPreset() {
        try {
            WallpadStatusData mWallpadStatusData = new WallpadStatusData(this);
            String[] strEntireValue = mWallpadStatusData.getLivinglightModeCtrlEntireValue();
            mWallpadStatusData.closeDB();

            Log.i(TAG, "[getLivinglightPreset] strEntireValue.length = " + strEntireValue.length);
            for (int i = 0; i < strEntireValue.length; i++) {
                Log.i(TAG, "[getLivinglightPreset] strEntireValue[" + i + "] = " + strEntireValue[i]);
            }

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getLivinglightPreset()");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void initLivinglightPreset() {
        WallpadStatusData mWallpadStatusData = new WallpadStatusData(this);
        try {
            if (Version.getModelType() == Version.MODEL_TYPE.IHN_D101 || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I
                    || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K_I
                    || Version.getModelType() == MODEL_TYPE.IHN_D101_I_OCF) {
                Log.i(TAG, "[initLivinglightPreset] Initialize preset for IHN-D101");
                for (int i = 1; i < 5; i++) {
                    String strPreset = mWallpadStatusData.getLivinglightModeCtrlUnitValues(i, 0);
                    Log.i(TAG, "[initLivinglightPreset] i = " + i + ", strPreset = " + strPreset);
                    String[] strParse = strPreset.split(":");
                    if (strParse[1].equalsIgnoreCase("0") || strParse[2].equalsIgnoreCase("0")) {
                        if (i == 1) {
                            mLightInfo.mPreset[i].mLights[0].ONOFF = "on";
                            mLightInfo.mPreset[i].mLights[0].DIM = 7;
                            mLightInfo.mPreset[i].mLights[0].COLOR = 5;
                        }
                        else if (i == 2) {
                            mLightInfo.mPreset[i].mLights[0].ONOFF = "on";
                            mLightInfo.mPreset[i].mLights[0].DIM = 3;
                            mLightInfo.mPreset[i].mLights[0].COLOR = 2;
                        }
                        else if (i == 3) {
                            mLightInfo.mPreset[i].mLights[0].ONOFF = "on";
                            mLightInfo.mPreset[i].mLights[0].DIM = 1;
                            mLightInfo.mPreset[i].mLights[0].COLOR = 1;
                        }
                        mWallpadStatusData.setLivinglightModeCtrlUnitValues(i, 0, mLightInfo.mPreset[i].mLights[0].ONOFF, mLightInfo.mPreset[i].mLights[0].DIM, mLightInfo.mPreset[i].mLights[0].COLOR);
                    }
                    else {
                        mLightInfo.mPreset[i].mLights[0].ONOFF = strParse[0];
                        mLightInfo.mPreset[i].mLights[0].DIM = Integer.parseInt(strParse[1]);
                        mLightInfo.mPreset[i].mLights[0].COLOR = Integer.parseInt(strParse[2]);
                    }
                }
            }
            else if (Version.getModelType() == MODEL_TYPE.IHN_1010 || Version.getModelType() == MODEL_TYPE.IHN_1010_I
            || Version.getModelType() == MODEL_TYPE.IHN_1010_I_2443
            ) {
                Log.i(TAG, "[initLivinglightPreset] Initialize preset for IHN-1010(-I)");
                if (getKCCDimmingCtrl()) {
                    for (int i = 1; i < 5; i++) {
                        String strPreset = mWallpadStatusData.getLivinglightModeCtrlUnitValues(i, 0);
                        Log.i(TAG, "[initLivinglightPreset] i = " + i + ", strPreset = " + strPreset);
                        String[] strParse = strPreset.split(":");
                        if (strParse[1].equalsIgnoreCase("0") || strParse[2].equalsIgnoreCase("0")) {
                            if (i == 1) {
                                mLightInfo.mPreset[i].mLights[0].ONOFF = "on";
                                mLightInfo.mPreset[i].mLights[0].DIM = 10;
                                mLightInfo.mPreset[i].mLights[0].COLOR = 5;
                            }
                            else if (i == 2) {
                                mLightInfo.mPreset[i].mLights[0].ONOFF = "on";
                                mLightInfo.mPreset[i].mLights[0].DIM = 7;
                                mLightInfo.mPreset[i].mLights[0].COLOR = 2;
                            }
                            else if (i == 3) {
                                mLightInfo.mPreset[i].mLights[0].ONOFF = "on";
                                mLightInfo.mPreset[i].mLights[0].DIM = 5;
                                mLightInfo.mPreset[i].mLights[0].COLOR = 1;
                            }
                            else if (i == 4) {
                                mLightInfo.mPreset[i].mLights[0].ONOFF = "on";
                                mLightInfo.mPreset[i].mLights[0].DIM = 2;
                                mLightInfo.mPreset[i].mLights[0].COLOR = 1;
                            }
                            mWallpadStatusData.setLivinglightModeCtrlUnitValues(i, 0, mLightInfo.mPreset[i].mLights[0].ONOFF, mLightInfo.mPreset[i].mLights[0].DIM, mLightInfo.mPreset[i].mLights[0].COLOR);
                        }
                        else {
                            Log.i(TAG, "[initLivinglightPreset] i = " + i + ", strPreset = " + strPreset);
                            Log.i(TAG, "[initLivinglightPreset] mLightInfo.mPreset[" + i + "].mLights[0].ONOFF = " + mLightInfo.mPreset[i].mLights[0].ONOFF);
                            Log.i(TAG, "[initLivinglightPreset] mLightInfo.mPreset[" + i + "].mLights[0].ONOFF = " + mLightInfo.mPreset[i].mLights[0].DIM);
                            Log.i(TAG, "[initLivinglightPreset] mLightInfo.mPreset[" + i + "].mLights[0].ONOFF = " + mLightInfo.mPreset[i].mLights[0].COLOR);
                        }
                    }
                }
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] initLivinglightPreset()");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
        mWallpadStatusData.closeDB();
    }

    private boolean getKCCDimmingCtrl() {
        try {
            Log.i(TAG, "[getKCCDimmingCtrl] ========== START ==========");
            WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(mContext);
            int nEnable = mWallpadDeviceSet.GetDeviceSetted("KCC디밍제어기");
            mWallpadDeviceSet.closeDB();
            Log.i(TAG, "[getKCCDimmingCtrl] nEnable [" + nEnable + "]");

            if (nEnable == WallpadDeviceSet.DEV_DATA_ENABLE) {
                Log.i(TAG, "[getKCCDimmingCtrl] Enabled");
                return true;
            }
            else {
                Log.i(TAG, "[getKCCDimmingCtrl] Disabled");
                return false;
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] setKCCDimmingCtrl()");
            
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }

    private void initEscapeLadderDownSend() {
        try {
            WallpadDeviceSet deviceSet = new WallpadDeviceSet(getContext());
            if(deviceSet!=null)
            {
                int ladderDownSend = deviceSet.getEscapeLadderDownSend();
                boolean ladderDownRecv = deviceSet.GetEscapeLadderDownRecv(); // 기존 '피난사다리입하수신' 설정정보 (더이상 사용하지 않음 2021.01.28)\
                Log.d(TAG, "[initEscapeLadderDownSend] ladderDownRecv [" + ladderDownRecv + "]");
                if (ladderDownRecv) {
                    if (ladderDownSend == WallpadDeviceSet.ESCAPELADDER_DOWN_SEND_NONE) {
                        Log.d(TAG, "[initEscapeLadderDownSend] ===== first setting =====");
                        deviceSet.setEscapeLadderDownSend(WallpadDeviceSet.ESCAPELADDER_DOWN_SEND_UPPER); // 신규 /'피난사다리전송' 설정정보 '윗집'
                    } else {
                        Log.d(TAG, "[initEscapeLadderDownSend] ladderDownSend [" + ladderDownSend + "]");
                    }
                }
                deviceSet.closeDB();
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initEscapeLadderDownSend()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

	public void CallSubMenuScreen(int screenID) {
		if (screenID >= ID.LINKEDSCREEN.SubMenuAddService.Notice && screenID <= ID.LINKEDSCREEN.SubMenuAddService.ElecCar) m_CallSubMenuScreen.callStartAddServiceAPK(screenID);
		else if (screenID >= ID.LINKEDSCREEN.SubMenuEnergy.RealTimeCheckMeter && screenID <= ID.LINKEDSCREEN.SubMenuEnergy.IEnergy) m_CallSubMenuScreen.callStartEnergyAPK(screenID);
	}
	
	private void restoreSystemVolume() {
		try {
		    String strCurrentTopPackage = getTopActivity();
            Log.i(TAG, "[restoreSystemVolume] strCurrentTopPackage = " + strCurrentTopPackage);

			WallpadStatusData wdb = new WallpadStatusData(this.getContext());
			int nSavedVolume = wdb.GetWallPadMasterVolume();
			wdb.closeDB();

			final AudioManager audioManager = (AudioManager)this.getContext().getSystemService(this.getContext().AUDIO_SERVICE);
            int nCurrentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, nSavedVolume , 0);
            Log.i(TAG, "[restoreSystemVolume] #Before# nCurrentVolume = " + nCurrentVolume + ", #After# nSavedVolume = " + nSavedVolume);

		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
			Log.e(TAG, "[Exception] restoreSystemVolume()");
			
            LogUtil.errorLogInfo("", TAG, e);
		}
	}

    // =================================================================================================
    // [[ Activity Life Cycle ]] region 
    // =================================================================================================
    /**
     * Activity Constructors
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "[onCreate] ========== START ==========");

        Log.w(TAG, "[onCreate] Start to check booting status!!!");
        Runtime mRuntime = Runtime.getRuntime();
        Process mProcess;
        int iDelayCount = 0;

        while (true) {
            try {
                String cmd = "getprop dev.bootcomplete";

                mProcess = mRuntime.exec(cmd);
                BufferedReader br = new BufferedReader(new InputStreamReader(mProcess.getInputStream()));
                String line;
                String strResult = null;

                while ((line = br.readLine()) != null) {
                    strResult = line;
                }

                if (strResult!=null && strResult.equals("1")) {

                    File sdcard = new File("/storage/emulated/0");
                    if(sdcard.exists() == true) {
                        iDelayCount = 0;
                        Thread.sleep(1000);
                        break;
                    }
                }

                {
                    iDelayCount++;
                    Thread.sleep(100);
                }

                if (iDelayCount > 400) {
                    cmd = "setprop persist.sys.reboot 1";
                    mProcess = mRuntime.exec(cmd);
                }

            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] Checking device booting status -> Unable to execute top command");
                e.fillInStackTrace();
                
                LogUtil.errorLogInfo("", TAG, e);
            }

        }
        Log.w(TAG, "[onCreate] Device booting completed!!");

        Log.i(TAG, "[onCreate] Wallpad model name [" + Version.getModelType() + "]");

        if (Common.DIAGNOSTIC_MODE) {
        	Log.i(TAG, "------------------ [START - DIAGNOSTIC_MODE] -------------------");
        	setNetworkAddr( 2, 1, 3);
        }

        // @ AutoScale 설정 - 1.
        if (WpadScale.getWidthPixels() == 800 && WpadScale.getHeightPixels() == 480) {
            // 800x480 일 경우에만 AutoScale 을 설정한다.
            Log.i(TAG, "[onCreate] Wallpad LCD resolution. -> Width [" + WpadScale.getWidthPixels() + "], Height [" + WpadScale.getHeightPixels() + "] -> setAutoScale ON !!!");
            WpadScale.setAutoScale(true);
        }
        else if (WpadScale.getWidthPixels() == 1366 && WpadScale.getHeightPixels() == 768) {
            // 800x480 일 경우에만 AutoScale 을 설정한다.
            Log.i(TAG, "[onCreate] Wallpad LCD resolution. -> Width [" + WpadScale.getWidthPixels() + "], Height [" + WpadScale.getHeightPixels() + "] -> setAutoScale ON !!!");
            WpadScale.setAutoScale(true);
            WpadScale.changeAutoScaleValue(1024, 600);
        }
        
        // @ AutoScale 설정 - 2. 에너지관리화면을 위한 구분자 설정
        if ((WpadScale.getWidthPixels() == 1024) && (WpadScale.getHeightPixels() == 600)) {
            Common.SCREEN_TYPE = Common.SCREEN_TYPE_1024x600;
        }
        else if ((WpadScale.getWidthPixels() == 1280) && (WpadScale.getHeightPixels() == 800)) {
            Common.SCREEN_TYPE = Common.SCREEN_TYPE_1280x800;
        }
        else if ((WpadScale.getWidthPixels() == 800) && (WpadScale.getHeightPixels() == 480)) {
            Common.SCREEN_TYPE = Common.SCREEN_TYPE_800x480;
        }
        else if ((WpadScale.getWidthPixels() == 1366) && (WpadScale.getHeightPixels() == 768)) {
            Common.SCREEN_TYPE = Common.SCREEN_TYPE_1024x600;
        }
        Log.d(TAG, "[onCreate] SCREEN_TYPE: " + Common.SCREEN_TYPE);
        
        
        super.setFinishBrEnable(false);
        super.AppVersionLogOut();   // [APP Version] + [WallPadSupport Lib Version] 을 로그로 출력한다.
        
        LayoutDevice.InitGetScreenSize(this.getWindowManager(), getApplicationContext() );

        try {
        	// 최초 DB 폴더가 생성되어 있지 않으면 폴더를 생성하도록 한다.
    		File dbhome = new File(wallpaddbmgr.dblocation);
            Log.d(TAG, "[Create] - Step0.3 : dbhome path [" + dbhome.getPath() + "]");
    		if (dbhome.exists() == false) {
    			dbhome.mkdir();
    			Log.d(TAG, "[Create] - Step0.3 : Make DB Folder");
    		}
    		else {
                Log.d(TAG, "[Create] - Step0.3 : DB exists");
    		}

			WallpadStatusData mWallpadStatusData = new WallpadStatusData(getApplicationContext());
			if (mWallpadStatusData != null) {
				DebugLogOutput("[Create] - Step0.3 : WallpadStatusData Open OK");
                mWallpadStatusData.closeDB();
			}
			else {
                DebugLogOutput("[Create] - Step0.3 : WallpadStatusData Open FAIL");
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
        	
            LogUtil.errorLogInfo("", TAG, e);
        }

        DebugLogOutput("[Create] - Step0.5 : WallpadStatusData end");
        
        Log.i("Version", "<><><><>  WallPadAPI     Version = [" + define.WALLPADAPI_VERSION + "] " + "<><><><>");

        checkISSEnergyType();

        runDeviceService();
        
        // 1. 변수 초기화
        DebugLogOutput("[Create] - Step1 : EMData Create");
        PopupActivityRun = false;
        InfoActivityRun = false;
        mContext = this;
        mContext_call = mContext;
        setCallAppRunning(false); // 메인앱 초기화시 통화앱 미실행값을 DB에 저장
        // 2. 자동 종료 셋팅
        DebugLogOutput("[Create] - Step2 : Auto Finish Setting");
        
        // 3. API 호출
        DebugLogOutput("[Create] - Step3 : API Call");

        //     3.1. mWallPadAPI 생성
        try {
            mWallPadAPI = new WallPadAPI(this);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[ExceptionError] - new WallPadAPI : " + e);
            
            LogUtil.errorLogInfo("", TAG, e);
        }

        initIOInterface(mWallPadAPI);
        Common.CurrentBoardType = mIOInterface.getBoardType(Version.getModelType());

        DebugLogOutput("[Create] - Step3.5 : API Call end");

        if (Common.GetDeviceSampleMode(this)) {
            Log.d(TAG, "[Create] OperationMode = MODE_BUSINESS_SAMPLE");
            DEVICE_OPERATION_MODE = Common.MODE_BUSINESS_SAMPLE;
        }
        else {
            Log.d(TAG, "[Create] OperationMode = MODE_NOMAL");
            DEVICE_OPERATION_MODE = Common.MODE_NOMAL;
        }

        // 분전반 정보 가져오기
        WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(this);
        Common.CurrentDistributionPanelType = mWallpadDeviceSet.Get_DistributionPannelType_Info();
        mWallpadDeviceSet.closeDB();
        
        // 4. Layout registration
        DebugLogOutput("[Create] - Step4 : Layout registration");

        Common.eGUIType = checkGUIType(this.getContext());
        Log.i(TAG, "[Create] eGUIType = " + Common.eGUIType);

        mIconManager = new IconManager(mContext, mWallPadAPI);
        if (mIconManager == null) {
            Log.w(TAG, "[Create] mIconManager is null!!");
        }

        mIconInfoTable = mIconManager.getAvailableIcons();
        if (mIconInfoTable == null) {
            Log.w(TAG, "[Create] mIconInfoTable is null!!");
        }
        else {
            Log.i(TAG, "[Create] mIconInfoTable.getCnt() = " + mIconInfoTable.getCnt());
        }

        WallpadDeviceSet deviceSet = new WallpadDeviceSet(mContext);
        boolean bSupport = deviceSet.Get_EasyModeUX_Support();
        deviceSet.closeDB();
        WallpadStatusData mWallpadStatusData = new WallpadStatusData(getApplicationContext());
        if (!bSupport) {
            mWallpadStatusData.SetEasyModeUxUse(false);
        }
        bEasyModeUsage = bSupport & mWallpadStatusData.GetEasyModeUxUse();
        mWallpadStatusData.closeDB();

        // Sound API 등록
        mSound = new WpadSound(this);
        
        // 메인화면 레이아웃
        MainLayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WpadScale.getWidthPixels(), WpadScale.getHeightPixels());
        MainLayout.setLayoutParams(params);
        MainLayout.setId(ID_OLD.main.layout.ALL);
        super.setAllLayoutRegistration(MainLayout);
        
        // 메인화면 스크린 레이아웃
        MainScreenLayout = new RelativeLayout(this);
        WpadUtil.LayoutRegistration(MainLayout, MainScreenLayout, WpadScale.getWidthPixels(), WpadScale.getHeightPixels(), 0, 0, ID_OLD.main.layout.SCREEN);

        if (getWallPadCameraUsage() && (Common.CurrentBoardType == Common.BOARD_TYPE.V40 || Common.CurrentBoardType == Common.BOARD_TYPE.V40_NOUGAT)) {
            Log.i(TAG, "[Create] SurfaceLayout Registration!!!");
            SurfaceLayout = new RelativeLayout(this);
            WpadUtil.LayoutRegistration(MainLayout, SurfaceLayout, WpadScale.getWidthPixels(), WpadScale.getWidthPixels(), 0, 0, ID.MAINACTIVITY.LAYOUT.SURFACE);
        }

        if (Common.eGUIType == Common.GUI_TYPE.STANDARD) nIconsOnSubScreen = 24;
//        else if (eGUIType == GUI_TYPE.METRO) nIconsOnSubScreen = 15;
        else nIconsOnSubScreen = 24;

        // 서브화면 1 레이아웃
        if (mIconInfoTable.getCnt() > 0) {
            SubLayout_01 = new RelativeLayout(this);
            params = new RelativeLayout.LayoutParams(WpadScale.getWidthPixels(), WpadScale.getHeightPixels());
            SubLayout_01.setLayoutParams(params);
            SubLayout_01.setId(ID_OLD.main.layout.ALL);
            super.setAllLayoutRegistration(SubLayout_01);

            // 서브화면 1 스크린 레이아웃
            SubScreenLayout_01 = new RelativeLayout(this);
            WpadUtil.LayoutRegistration(SubLayout_01, SubScreenLayout_01, WpadScale.getWidthPixels(), WpadScale.getHeightPixels(), 0, 0, ID_OLD.main.layout.SCREEN);
        }

        // 서브화면 2 레이아웃
        if (mIconInfoTable.getCnt() > nIconsOnSubScreen) {
            SubLayout_02 = new RelativeLayout(this);
            params = new RelativeLayout.LayoutParams(WpadScale.getWidthPixels(), WpadScale.getHeightPixels());
            SubLayout_02.setLayoutParams(params);
            SubLayout_02.setId(ID_OLD.main.layout.ALL);
            super.setAllLayoutRegistration(SubLayout_02);

            // 서브화면 2 스크린 레이아웃
            SubScreenLayout_02 = new RelativeLayout(this);
            WpadUtil.LayoutRegistration(SubLayout_02, SubScreenLayout_02, WpadScale.getWidthPixels(), WpadScale.getHeightPixels(), 0, 0, ID_OLD.main.layout.SCREEN);
        }

        // 간편모드 메인화면 레이아웃
        if (bEasyModeUsage) {
            EasyMainLayout = new RelativeLayout(this);
            params = new RelativeLayout.LayoutParams(WpadScale.getWidthPixels(), WpadScale.getHeightPixels());
            EasyMainLayout.setLayoutParams(params);
            EasyMainLayout.setId(ID_OLD.main.layout.ALL);
            super.setAllLayoutRegistration(EasyMainLayout);

            // 간편모드 메인화면 스크린 레이아웃
            EasyMainScreenLayout = new RelativeLayout(this);
            WpadUtil.LayoutRegistration(EasyMainLayout, EasyMainScreenLayout, WpadScale.getWidthPixels(), WpadScale.getHeightPixels(), 0, 0, ID_OLD.main.layout.SCREEN);
        }
        
        m_ModelHouseSleepModeRelease= Common.GetModelHouseSleepModeRelease(this);
        Log.d(TAG, "  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% =====> GetModelHouseSleepModeRelease :" + m_ModelHouseSleepModeRelease);
        if (m_ModelHouseSleepModeRelease) {
            mLCD_SleepHandler.sendEmptyMessageDelayed(0, (30 * 1000));    
        }
        
        // 5. Top Menu - ImageView registration
        DebugLogOutput("[Create] - Step5 : Top Menu - ImageView registration");
        // 6. Tab Menu - ImageView registration

        restoreSystemVolume();
        initProximitySensor();
        
       
        // 서브 스크린 호출하기 위한 메뉴 리스트 관리 클래스
        m_CallSubMenuScreen = new CallSubMenuScreen( this , mWallPadAPI);

        if (Common.eGUIType == Common.GUI_TYPE.STANDARD) {
            // 메인화면 3가지 등록으로 인해 변경
            MainScreen = new MAIN(this, MainScreenLayout, mWallPadAPI, m_CallSubMenuScreen, DEVICE_OPERATION_MODE);
//            EasyUI_MainScreen = new EASYUI_MAIN(this, MainScreenLayout, mWallPadAPI, m_CallSubMenuScreen);
        }
        else if (Common.eGUIType == Common.GUI_TYPE.METRO) {
            MetroUI_MainScreen = new METROUI_MAIN(this, MainScreenLayout, mWallPadAPI, m_CallSubMenuScreen);
        }
        else if (Common.eGUIType == Common.GUI_TYPE.HYOSUNG) {
            Hyosung_HN_MainScreen = new HYOSUNGUI_MAIN_HN(this, MainScreenLayout, mWallPadAPI, m_CallSubMenuScreen);
        }
        else {
            MainScreen = new MAIN(this, MainScreenLayout, mWallPadAPI, m_CallSubMenuScreen, DEVICE_OPERATION_MODE);
        }
        
        DebugLogOutput("[Create] - Step6 : Main Screen registration");
        // 7. Draw
        DebugLogOutput("[Create] - Step7 : setContentView");

        try {
            if (Common.eGUIType == Common.GUI_TYPE.STANDARD) {
                if (mIconInfoTable.getCnt() > nIconsOnSubScreen) setContentView(R.layout.main);
                else setContentView(R.layout.main_2);
            }
            else if (Common.eGUIType == Common.GUI_TYPE.METRO) setContentView(R.layout.main_metro);
            else if (Common.eGUIType == Common.GUI_TYPE.HYOSUNG) setContentView(R.layout.main_hyosung);
            else {
                if (mIconInfoTable.getCnt() > nIconsOnSubScreen) setContentView(R.layout.main);
                else setContentView(R.layout.main_2);
            }

            if (bEasyModeUsage) setContentView(R.layout.main_easy);

//            setContentView(R.layout.main);
            // 메인화면 3가지로 슬라이딩 방식으로 구현하기 위하여 뷰플리퍼를 사용하여 처리
            mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
            if (mViewFlipper != null) {
                if (MainLayout != null) mViewFlipper.addView(MainLayout);
                if (SubLayout_01 != null) mViewFlipper.addView(SubLayout_01);
                if (SubLayout_02 != null && Common.eGUIType == Common.GUI_TYPE.STANDARD) mViewFlipper.addView(SubLayout_02);
                if (EasyMainLayout != null && bEasyModeUsage) mViewFlipper.addView(EasyMainLayout);
                DebugLogOutput("[Create] - Step8 : Add Flipper !!! ");
            }

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            
            LogUtil.errorLogInfo("", TAG, e);
        }

        registerBroadcastReceiver();

		Check_Upgrade_File();
		
		//앱 버전정보 DB저장
		try {
			Log.d(TAG, "mThread_getAppsVersion Start!! ");
			if (mThread_getAppsVersion== null) {
			    mThread_getAppsVersion = new getInstalledPackageInfo();
			    mThread_getAppsVersion.start();
	        }
			else {
                Log.w(TAG, "mThread_getAppsVersion is null!!");
            }
			Log.d(TAG, "mThread_getAppsVersion End!! ");
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
			
            LogUtil.errorLogInfo("", TAG, e);
		}
		
		try {
			WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
			AddressSet addc = SetData.getAddressMGR();
			AddressSetBackup addc_Backup = SetData.getAddressMGR_Backup();

			overridePendingTransition(0, 0);
			
			if (!isSystemIPSet()) {
			    Log.w(TAG, "[onCreate] The IP Address of OS is not set!");
			    startManagerSettingSetAddress();
			}
			else if (addc.Dong.equals("NONE") || addc.Ho.equals("NONE")) {
			    Log.w(TAG, "[onCreate]  The info. of resi. is not set! [primary db]");
			    if (addc_Backup.Dong.equals("NONE") || addc_Backup.Ho.equals("NONE")) {
			        Log.w(TAG, "[onCreate]  The info. of resi. is not set! [secondary db]");
			        startManagerSettingSetAddress();
			    }
			    else {
			        addc.setAddress(addc_Backup.Dong, addc_Backup.Ho);
			        addc.setIPAddress(addc_Backup.IPAddress);
			        
			        m_IPActivity = true;
                    if (addc.IPAddress!=null && !addc.IPAddress.equals("NONE")) {
                        Log.w(TAG, "[onCreate] ========== start iMapServer service ========== [secondary db]");
                        Intent intent = new Intent(getApplicationContext(), iMapServer.class);
                        startService(intent);

                        Intent intentMobile = new Intent(getApplicationContext(), MobileProcService.class);
                        Log.w(TAG, "[onCreate] ========== start MobileProcServicee ========== [secondary db]");
                        startService(intentMobile);
                    }
	                MAINStatus = MAIN_NORMAL;   
			    }
			}
			else {
				m_IPActivity = true;
                if (!addc.IPAddress.equals("NONE")) {
                    Log.w(TAG, "[onCreate] ========== start iMapServer service ========== [primary db]");
                    Intent intent = new Intent(this, iMapServer.class);
                    startService(intent);

                    Intent intentMobile = new Intent(getApplicationContext(), MobileProcService.class);
                    Log.w(TAG, "[onCreate] ========== start MobileProcServicee ========== [secondary db]");
                    startService(intentMobile);
                }
				MAINStatus = MAIN_NORMAL;	
			}
			SetData.closeDB();
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
		    Log.e(TAG, "[Exception] check device addresses(ip, resi. info.)");
			
            LogUtil.errorLogInfo("", TAG, e);
		}
		
	    //주차정보 사용여부 체크
        getParkedVehicleLocationSysInfo();

        //전기차 정보 가져오기
        GetElectricCarInfo();
        
        //에너지관리서버 사용여부 가져오기
        GetEnergyServerInfo();       

        //에너지 알람 사용여부 가져오기
        GetEnergyAlarm();

        //통화타임아웃 초기화
        setCallAppTimeoutAsDefault();

        //카카오홈 사용 여부 체크(카카오홈)
        boolean isUseKakao = getKakaoHomeCheck();
        if(isUseKakao)
        {
            Handler mHandler = new Handler();
            mHandler.postDelayed(mLaunchTaskKakao, 500);
            mHandler = null;
        }


		try {
			mWallPadApiCheckHandler.sendEmptyMessage(0); 
//			Checker.sendEmptyMessageDelayed(0, 1000);
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
			
            LogUtil.errorLogInfo("", TAG, e);
		}
		
        
		// sip 서비스 실행 옮김
        Log.d(TAG, "[onCreate] startCallService start");
        try {
            runCallServices startCallService = new runCallServices();
            startCallService.start();
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            
            LogUtil.errorLogInfo("", TAG, e);
        }
        Log.d(TAG, "[onCreate] startCallService end");
		
		try {
			// 부팅하고 나서 업그레이드 상태를 false 로 해주지 않으면 통화 수신이 안됨
			// 꼭 들어가야 함
			
			// 전체 정전시험시 단지서버도 재부팅은 하나 로긴을 하지 않으면 그시간동안 세대기가 보낸 부트업 메세지를 못 받기 때문에....단말기 시간을 재 셋팅해주도록 한다. 
			Calendar cal = new GregorianCalendar();
			String timedata = String.format("%04d",cal.get(Calendar.YEAR))+"."+String.format("%02d",cal.get(Calendar.MONTH)+1)+"."+String.format("%02d",cal.get(Calendar.DAY_OF_MONTH))+"."+String.format("%02d",cal.get(Calendar.HOUR_OF_DAY))+"."+String.format("%02d",cal.get(Calendar.MINUTE))+"."+String.format("%02d",cal.get(Calendar.SECOND));
			
			WallpadStatusData wpd = new WallpadStatusData(getApplicationContext());
			wpd.SetUpgradeState(false);
			wpd.SetLastHeartbeat(timedata);
			wpd.closeDB();

		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
			
            LogUtil.errorLogInfo("", TAG, e);
		}
		
		try {
			Calendar m_CurCalendar = Calendar.getInstance();
			//CurYear , CurMonth, CurDate, CurHour, CurMin, CurSecond;
			int CurYear = m_CurCalendar.get(Calendar.YEAR);
			
			if (CurYear < 2018) {
				WallpadStatusData DBMGR = new WallpadStatusData(getApplicationContext());
				DBMGR.setSystemTime(2018, 8, 1, 13, 0, 0);
				DBMGR.closeDB();
			}
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            
            LogUtil.errorLogInfo("", TAG, e);
		}

        mLightInfo = new LightInfo();
        getLivinglightPreset();
        initLivinglightPreset();
        getLivinglightPreset();
        initEscapeLadderDownSend();

        setPageIndicator();

        mGetCallHistoryCheckHandler.sendEmptyMessageDelayed(0, 10000);

        try {
            int getSleepTime = Settings.System.getInt(this.getContext().getContentResolver(), SCREEN_OFF_TIMEOUT);
            int mSleepModeTime = (getSleepTime / 1000);
            Log.d(TAG, "[Create] mSleepModeTime [" + mSleepModeTime + "]");
            if (mSleepModeTime <= 30) {
                Log.d(TAG, "[Create] Reset mSleepModeTime ===== [" + mSleepModeTime + "] =====");
                Settings.System.putInt(this.getContext().getContentResolver(), SCREEN_OFF_TIMEOUT, 28 * 1000); // 백라이트 off와 앱 종료가 동시에 일어나면 월패드가 비정상 종료되므로 수정 (2021.04.06 메이드인랩 김수진 선임 요청)
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }

        try {
            handlerEverySecond.sendEmptyMessageDelayed(0, 1000);

            // BSP 수정으로 인하여 해당 코드 삭제 (2021.02.24, SEULKI)
//            // 월패드 카메라 녹색 노이즈 시험 코드 (월패드 부팅시 월패드 카메라 영상을 잠시 띄운후 없앤다. JEFF/2020.01.21.01)
//            /**
//             * 부팅시 카메라 서비스 정상동작 여부를 확인한다.  (Edited by jeff, 2020.09.08)
//             */
//            sendHandlerMsgDelayed(HANDLERMSG.CHECK_WALLPAD_CAMERA_CHECK, 0, 0, 0);   // 5초후 월패드 카메라를 초기화 한다. (그냥 화면밖에 영상을 잠시 띄우고 5초뒤에 없앤다.)
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            
            LogUtil.errorLogInfo("", TAG, e);
        }

        if (bKakaoiEnable) {
            Log.i(TAG, "[onCreate] ========== Kakao function enabled ==========");
            startKakaoiFloatingBTN();
        }
//        forceCtrlStrangerRecordingUserSettingDisable(false);
        getLCDKeeperUsage();
        Log.i(TAG, "[onCreate] ==================== onCreate end ====================");
    }


    /**
     * 카카오 실행 관련 핸들러
     */
    private Runnable mLaunchTaskKakao = new Runnable() {
        public void run() {
            String Packagename =  "com.kakao.i.test.real.wallpad";
            //Handler를 이용하여 Timer 사용
            Intent mainIntent  = mContext.getPackageManager().getLaunchIntentForPackage(Packagename);
            if (mainIntent != null) {
                boolean isShowKakao = getShowKakaoCheck();
                if(isShowKakao)
                    mainIntent.putExtra("ShowKakao", true);
                mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(mainIntent);
            };
        }
    };
    
    private int nLCDKeeperType = WallpadDeviceSet.LCDKEEPER_NONE;
    private String getLCDKeeperType(int nLCDKeeperType) {
        try {
            Log.i(TAG, "[getLCDKeeperUsage] nLCDKeeperType [" + nLCDKeeperType + "]");
            if (nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_NONE) return "LCDKEEPER_NONE";
            else if (nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_PROTECT) return "LCDKEEPER_PROTECT";
            else if (nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_RECOVER) return "LCDKEEPER_RECOVER";
            else if (nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_PROTECT_RECOVER) return "LCDKEEPER_PROTECT_RECOVER";
            else return "UNKNOWN";
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return "ERROR";
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getLCDKeeperType(int nLCDKeeperType)");
            
            LogUtil.errorLogInfo("", TAG, e);
            return "ERROR";
        }
    }
    private boolean bLCDKeeperUsage = false;
    private void getLCDKeeperUsage() {
        try {
            WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(getContext());
            nLCDKeeperType = mWallpadDeviceSet.getLCDKeeperUsage();
            mWallpadDeviceSet.closeDB();
            if (nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_PROTECT || nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_RECOVER || nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_PROTECT_RECOVER) {
                bLCDKeeperUsage = true;
            }
            Log.i(TAG, "[getLCDKeeperUsage] bLCDKeeperUsage [" + bLCDKeeperUsage + "], nLCDKeeperType [" + getLCDKeeperType(nLCDKeeperType) + "]");
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getLCDKeeperUsage()");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public boolean isSystemIPSet() {
        try {
            Log.i(TAG, "[isSystemIPSet] START!");

            String strResult = "";
            if (Build.VERSION.SDK_INT > 23) {
                // Android 7
                strResult = getIPAddress();
            }
            else {
                // Android 6
                if(NetworkInterface.getByName("eth0")!=null)
                {
                    String strNetInfo = NetworkInterface.getByName("eth0").toString();
                    Log.i(TAG, "[isSystemIPSet] strNetInfo : " + strNetInfo + "]");
                    strNetInfo.trim();

                    String[] Parse_01 = strNetInfo.split("\\]");
//            for (int i = 0; i < Parse_01.length; i++) {
//                LOG_DEBUG("[getDeviceIPAddress] Parse_01[" + i + "] : " + Parse_01[i]);
//            }

                    String[] Parse_02 = Parse_01[Parse_01.length - 1].split("\\/");
//            for (int i = 0; i < Parse_02.length; i++) {
//                LOG_DEBUG("[getDeviceIPAddress] Parse_02[" + i + "] : " + Parse_02[i]);
//            }

                    strResult = Parse_02[1];
                }

            }
            
            Log.i(TAG, "[isSystemIPSet] DONE! [IP Address : " + strResult + "]");
            
            Pattern mPattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
            
            return mPattern.matcher(strResult).matches();
            
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] isSystemIPSet()");
            
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }

    public static String getIPAddress() {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress();
                        //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                        boolean isIPv4 = sAddr.indexOf(':')<0;

                        if (isIPv4)
                            return sAddr;
                    }
                }
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] isSystemIPSet()");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
        return "";
    }


    public void initIOInterface(WallPadAPI wallpadapi) {
        try {
            mIOInterface = new IOInterface(getContext(), wallpadapi);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] initIOInterface(WallPadAPI wallpadapi)");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
    }
    
    public void checkDongHoSetting() {
        try {
        	Log.d(TAG, "[checkDongHoSetting] ========== START ==========");
        	boolean IP_ExpansionSettingFlag = false;
        	EthernetDevInfo info = new EthernetDevInfo();
        	
	        WallpadStatusData mWallpadStatusData = new WallpadStatusData(this.getContext());
	        AddressSet addc =  mWallpadStatusData.getAddressMGR();
            mWallpadStatusData.SetCallAPKStatus(false);
            mWallpadStatusData.closeDB();
	        
	        if (addc.Dong!=null && !addc.Dong.equals("NONE") && addc.Ho!=null&&  !addc.Ho.equals("NONE") && addc.IPAddress!=null&&  !addc.IPAddress.equals("NONE")) {
	        	if (Version.getModelType() == MODEL_TYPE.IHN_1020GL && Version.getModelType() == MODEL_TYPE.IHN_1020B_A
                        && Version.getModelType() == MODEL_TYPE.IHN_1020SA_A && Version.getModelType() == MODEL_TYPE.IHN_750) {
		        	// LH 게이트웨이 때문에 위치 옮김 제어 서비스 보다 먼저 처리
                    if(addc.IPAddress!=null)
                    {
                        String[] iptbl = addc.IPAddress.split("[.]");
                        Log.d(TAG, "[checkDongHoSetting] Mac Set -> IP : " + addc.IPAddress +", Length : " + iptbl.length);
                        // BSP에서 초기 이더넷 비활성화시 jni 맥 셋팅시 메인어플 다이~~
                        EthernetManager mEthManager = (EthernetManager) getSystemService("ethernet");
                        mEthManager.setEthernetState(EthernetManager.ETH_STATE_DISABLED);
                        Log.d(TAG, "[checkDongHoSetting] ETH_STATE_DISABLED!!!");

                        if (IP_ExpansionSettingFlag == true) {
                            mEthManager.UpdateEthDevInfo(info);
                        }
                        mEthManager.setEthernetState(EthernetManager.ETH_STATE_ENABLING);
                        Log.d(TAG, "[checkDongHoSetting] ETH_STATE_ENABLING!!!");
                        if (iptbl.length == 4) {
                            String macadd = String.format("00:%02x:%02x:%02x:%02x:00", Integer.parseInt(iptbl[0]),Integer.parseInt(iptbl[1]), Integer.parseInt(iptbl[2]), Integer.parseInt(iptbl[3]));
                            Log.d(TAG, "[checkDongHoSetting] Mac Set "+macadd);
                            try {
                                WallPadInterface wpdifc  = new WallPadInterface();
                                wpdifc.setMacAddr(macadd);
                            } catch (RuntimeException re) {
                                LogUtil.errorLogInfo("", TAG, re);
                            }
                            catch (Exception ex) {
                                //ex.printStackTrace();
                                LogUtil.errorLogInfo("", TAG, ex);
                            }
                            Log.d(TAG, "[checkDongHoSetting] -----------------------------------MacSet");
                        }
                        else {
                            Log.d(TAG,"[checkDongHoSetting] -----------------------------------Mac iptbl.length fail !!");
                        }

                        //EthernetManager mEthManager = (EthernetManager) getSystemService("ethernet");
                        //mEthManager.setEthernetState(EthernetManager.ETH_STATE_DISABLED);
                        mEthManager.setEthernetState(EthernetManager.ETH_STATE_ENABLING);
                        Log.d(TAG, "[checkDongHoSetting] ETH_STATE_ENABLING!!!");
                    }
            	}
	        }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkDongHoSetting()");
        	
            LogUtil.errorLogInfo("", TAG, e);
        }
    }
    
    public void registerSubScreen() {
    	try {
    	    if (Common.eGUIType == Common.GUI_TYPE.METRO) {
                if (MetroUI_SUB_GroupScreen == null && SubScreenLayout_01 != null ) MetroUI_SUB_GroupScreen = new METROUI_SUB_GROUP(getContext() , SubScreenLayout_01, mWallPadAPI);
            }
    	    else if (Common.eGUIType == Common.GUI_TYPE.HYOSUNG) {
                if (MetroUI_SUB_GroupScreen == null && SubScreenLayout_01 != null ) MetroUI_SUB_GroupScreen = new METROUI_SUB_GROUP(getContext() , SubScreenLayout_01, mWallPadAPI);
            }
            else {
                if (mIconInfoTable.getCnt() > 0) {
                    if (SUB_01Screen == null && SubScreenLayout_01 != null ) SUB_01Screen = new SUB_01(getContext() , SubScreenLayout_01, mWallPadAPI);
                }

                if (mIconInfoTable.getCnt() > nIconsOnSubScreen) {
                    if (SUB_02Screen == null && SubScreenLayout_02 != null ) SUB_02Screen = new SUB_02(getContext() , SubScreenLayout_02, mWallPadAPI);
                }

                if (bEasyModeUsage) {
                    if (EasyUI_MainScreen == null && EasyMainScreenLayout != null ) EasyUI_MainScreen = new EASYUI_MAIN(getContext() , EasyMainScreenLayout, mWallPadAPI, m_CallSubMenuScreen);
                }
            }

//	        restoreSystemVolume();
	        SCManager = new ScheduleManager();
    	} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
    	    Log.w(TAG, "[registerSubScreen] registerSubScreen()");
    		
            LogUtil.errorLogInfo("", TAG, e);
    	}
    }
    
    public void moveNextPage() {
    	try {
	    	Log.d(TAG, "[moveNextPage] ===== START =====");
            aniSlideIn = AnimationUtils.loadAnimation(getContext(), R.layout.appear_from_right);
            aniSlideOut = AnimationUtils.loadAnimation(getContext(), R.layout.disappear_to_left);

            mViewFlipper.setInAnimation(aniSlideIn);
            mViewFlipper.setOutAnimation(aniSlideOut);
            mViewFlipper.showNext();
    	} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
    	    Log.e(TAG, "[Exception] moveNextPage()");
    		
            LogUtil.errorLogInfo("", TAG, e);
    	}
	}

	public void movePreviousPage() {
		try {
            Log.d(TAG, "[movePreviousPage] ===== START =====");
            aniSlideIn = AnimationUtils.loadAnimation(getContext(), R.layout.appear_from_left);
            aniSlideOut = AnimationUtils.loadAnimation(getContext(), R.layout.disappear_to_right);

            mViewFlipper.setInAnimation(aniSlideIn);
            mViewFlipper.setOutAnimation(aniSlideOut);
            mViewFlipper.showPrevious();
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] moveNextPage()");
    		
            LogUtil.errorLogInfo("", TAG, e);
    	}
	}

	boolean bScreenCheck = false;
	int nSubScreenTimeout = 20, SCREENTIMEOUT = 20;
	public void checkMainPage() {
        try {

            if (!bScreenCheck) {
                nSubScreenTimeout = SCREENTIMEOUT;
                return;
            }

            int nViewFlipperIndex = mViewFlipper.getDisplayedChild();

            if (nViewFlipperIndex != 0) {
                if (nSubScreenTimeout > 0) {
                    nSubScreenTimeout--;
                }
                else {
                    nSubScreenTimeout = SCREENTIMEOUT;
                    mViewFlipper.setDisplayedChild(0);
                }
                Log.i(TAG, "[checkMainPage] nViewFlipperIndex [" + nViewFlipperIndex + "], nSubScreenTimeout [" + nSubScreenTimeout + "]");
            }
            else {
                if (nSubScreenTimeout <= 0) {
                    nSubScreenTimeout = SCREENTIMEOUT;
                    Log.i(TAG, "[checkMainPage] nViewFlipperIndex [" + nViewFlipperIndex + "], nSubScreenTimeout [" + nSubScreenTimeout + "]");
                }
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkMainPage()");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    String strWallPadMainPakageName = "kr.co.icontrols.wallpadmain";
    private boolean isPackageTop(String strPackageName) {
        try {
            ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
            Log.i(TAG, "[isPackageTop] Build.VERSION.SDK_INT  [" + Build.VERSION.SDK_INT  + "]");
            if (Build.VERSION.SDK_INT > 23) {
                // Android 7
                List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
                for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        for (String activeProcess : processInfo.pkgList) {
                            if (activeProcess.equals(strPackageName)) {
                                Log.i(TAG, "[isPackageTop] The top package is [" + strPackageName + "]");
                                return true;
                            }
                        }
                    }
                }
            }
            else {
                // Android 6
                List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                ComponentName componentInfo = taskInfo.get(0).topActivity;
                if (componentInfo.getPackageName().equals(strPackageName)) {
                    Log.i(TAG, "[isPackageTop] The top package is [" + strPackageName + "]");
                    return true;
                }
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] isPackageTop(String strPackageName)");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
        return false;
    }



	// 부팅시에는 최초 DB에서 값을 읽어와서 변경하도록 한다.
	private boolean m_SetBookMarkMainScreen = false;
	private int m_CheckBookMarkReturnCount = 0 ;
	private final int BOOKMARK_SCREEN_RETURN_CHECK_TIME = 30;
	private boolean m_thisAcitivityRusume = false;
	
	// 즐겨찾기 메인화면을 항상 고정해서 쓸것인지 설정하는 함수
	public void SetBookMarkMainScreen(boolean Set)
	{
		m_SetBookMarkMainScreen = Set;
		try
		{
			WallpadStatusData wdb = new WallpadStatusData(this.getContext());
			if( wdb != null )
			{
				if( Set == true )
				{
					wdb.SetSelectedMainScreen( WallpadStatusData.MAIN_BOOKMARK_SCREEN);
				}
				else 
				{
					wdb.SetSelectedMainScreen( WallpadStatusData.MAIN_DEFAULT_SCREEN);
				}
				wdb.closeDB();
			}
		}
		catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e )
		{
			
            LogUtil.errorLogInfo("", TAG, e);
		}
	}
	
	public boolean CheckCurrentEnergyScreen()
	{
		int currentView = mViewFlipper.getDisplayedChild();
		Log.d(TAG, "-------> currentView : " + currentView);
		if( currentView == 1)
			return true;
		else 
			return false;
	}
	
	
	private int nTouchDownPosX = 0;
    private int nTouchUpPosX = 0;
	
	
    
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
    	boolean bReturn = false;
    	//Log.d("Move" , "dispatchTouchEvent-----------1");
    	try {
			if (ev.getAction() == MotionEvent.ACTION_DOWN) {
				nTouchDownPosX = (int)ev.getX();
			}
			else if (ev.getAction() == MotionEvent.ACTION_UP) {
				nTouchUpPosX = (int)ev.getX();
				Log.d(TAG, "[dispatchTouchEvent] nTouchDownPosX [" + nTouchDownPosX + "], nTouchUpPosX [" + nTouchUpPosX + "]");
                if (nTouchUpPosX < nTouchDownPosX - 50) {
                    moveNextPage();
                    setPageIndicator();
                }
                else if (nTouchUpPosX > nTouchDownPosX + 50) {
                    movePreviousPage();
                    setPageIndicator();
                }
				nTouchDownPosX = nTouchUpPosX;
			}
    	} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
    	    Log.e(TAG, "[Exception] dispatchTouchEvent(MotionEvent ev)");
    		
            LogUtil.errorLogInfo("", TAG, e);
    	}
    	bReturn =  super.dispatchTouchEvent(ev);
		return bReturn;
	}

	private void setPageIndicator() {
	    try {
            int nViewFlipperIndex = mViewFlipper.getDisplayedChild();
            int nChildCnt = mViewFlipper.getChildCount();
            Log.d(TAG, "[setPageIndicator] nViewFlipperIndex [" + nViewFlipperIndex + "], nChildCnt [" + nChildCnt + "]");
            if (Common.eGUIType == Common.GUI_TYPE.STANDARD) {
                Log.d(TAG, "[setPageIndicator] eGUIType == GUI_TYPE.STANDARD");
                ImageView[] IMG_INDICATOR;
                if (bEasyModeUsage) IMG_INDICATOR = new ImageView[] { (ImageView) findViewById(R.id.pageindex_main), (ImageView) findViewById(R.id.pageindex_sub1), (ImageView) findViewById(R.id.pageindex_sub2), (ImageView) findViewById(R.id.pageindex_easymain) };
                else IMG_INDICATOR = new ImageView[] { (ImageView) findViewById(R.id.pageindex_main), (ImageView) findViewById(R.id.pageindex_sub1), (ImageView) findViewById(R.id.pageindex_sub2) };
                for (int i = 0; i < nChildCnt; i++) {
                    if (i == nViewFlipperIndex) {
                        if (i == 0) IMG_INDICATOR[i].setSelected(true);
                        else IMG_INDICATOR[i].setSelected(true);
                    }
                    else {
                        if (i == 0) IMG_INDICATOR[i].setSelected(false);
                        else IMG_INDICATOR[i].setSelected(false);
                    }
                }
            }
//            else if (eGUIType == GUI_TYPE.METRO) {
//                ImageView[] IMG_INDICATOR = { (ImageView) findViewById(R.id.pageindex_sub1), (ImageView) findViewById(R.id.pageindex_sub2) };
//                if (nViewFlipperIndex == 0) {
//                    for (int i = 0; i < nChildCnt; i++) {
//                        if (i != 0) IMG_INDICATOR[i - 1].setVisibility(View.INVISIBLE);
//                    }
//                }
//                else {
//                    for (int i = 0; i < nChildCnt; i++) {
//                        if (i != 0) {
//                            IMG_INDICATOR[i - 1].setVisibility(View.VISIBLE);
//                            if (i == nViewFlipperIndex) IMG_INDICATOR[i - 1].setSelected(true);
//                            else IMG_INDICATOR[i - 1].setSelected(false);
//                        }
//                    }
//                }
//            }

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] setPageIndicator()");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
    }
	
	
    /**
     * (임시코드) WallPadAPI 초기생성시 Connect 에 시간이 걸리며, <br>
     * WallPadAPI 초기화후 바로 Get_GasValveController 등을 사용하여  API 를 가져올수 없기에, <br>
     * 본 딜레이 코드를 임시로 적용한다.
     */
    @SuppressLint("HandlerLeak")
    protected Handler mWallPadApiCheckHandler = new Handler()
    {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == 0) {
                if (mWallPadAPI != null) {
                    if (mWallPadAPI.Check_Connect()) mWallPadApiCheckHandler.sendEmptyMessageDelayed(1, 10);
                    else mWallPadApiCheckHandler.sendEmptyMessageDelayed(0, 10);
                }
            }
            else if (msg.what == 1) {
            	// 현산향 
            	AutoIGALStatusReleaseSinario();
                if (Version.getModelType() == Version.MODEL_TYPE.IHN_D101 || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I
                        || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K_I
                        || Version.getModelType() == MODEL_TYPE.IHN_D101_I_OCF) {
                    mSdb_LivingRoomLightAPI = mWallPadAPI.Get_Sdb_LivingRoomLightAPI();
                    mSdbAPI = mWallPadAPI.Get_SdbController();

                    if (mSdb_LivingRoomLightAPI == null) Log.d(TAG , "[mWallPadApiCheckHandler] Get_Sdb_LivingRoomLightAPI Fail %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
                    else Log.d(TAG , "[mWallPadApiCheckHandler] Get_Sdb_LivingRoomLightAPI Success !");

                    if (mSdbAPI == null) Log.d(TAG , "[mWallPadApiCheckHandler] Get_SdbController Fail %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
                    else Log.d(TAG , "[mWallPadApiCheckHandler] Get_SdbController Success !");

//                    ChangeLEDButtonLevel();
                }
            	else if (Version.getModelType() == MODEL_TYPE.IHN_1010GL || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I
                        || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I_2443 || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I_6410) {
            		mIntLightAPI = mWallPadAPI.Get_IntLightController();
	            	if (mIntLightAPI == null) Log.d(TAG , "[mWallPadApiCheckHandler] Get_IntLightController Fail %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
	            	else Log.d(TAG , "[mWallPadApiCheckHandler] Get_IntLightController Success !");
//	            	ChangeLEDButtonLevel();
            	}
            	else {
            		// 대외향 
    				WallpadDeviceSet devDB = new WallpadDeviceSet( getApplicationContext() );
    				int[] retArray = devDB.Get_Light_info();
    				devDB.closeDB();
    				if (retArray!= null && retArray[0] == 1) {
    					if (retArray[1] == WallpadDeviceSet.LIGHT_TYPE_LIVING) {
    						// 거실 스위치
    						m_LightCtrl = mWallPadAPI.Get_LightController();
    		            	if (m_LightCtrl == null) Log.d(TAG , "Get_LightController Fail %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
    		            	else Log.d(TAG , "Get_LightController Success !");
    					}
    					else {
    						// 멀티스위치 
    						m_MultiSwitch  = mWallPadAPI.Get_MultiSwitchController();
    		            	if (m_MultiSwitch == null) Log.d(TAG , "Get_MultiSwitchController Fail %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
    		            	else Log.d(TAG , "Get_MultiSwitchController Success !");
    					}
    				}
            	}
            }
            else if (msg.what == 10) {
            	// 부트업 실패시 5초 간격으로 보내도록 수정
            	Log.d(TAG , "NOTIFY_SENDBOOTUP_FAIL Retry!!!!");
            	Intent Newintent = new Intent();
				Newintent.setAction(define.NOTIFY_ACNAME);
				Newintent.putExtra(define.NOTIBR_KIND,Common.DEVICE_BOOTUP_RETRY);
				sendBroadcast(Newintent);	
            }
        }
    };
    
    
    private void ChangeLEDButtonLevel()
    {
    	if( Version.getModelType() == Version.MODEL_TYPE.IHN_1020GL )
    	{
    		try
    		{
		    	String filename = "/sdcard/led_button_reset.txt";
		    	       
		    	File savefile = new File(filename);
		    	
		    	Log.d(TAG, "8888888888888888888888 savefile : " + savefile.exists());
		    	if(savefile.exists())
		    	{
		    		Log.d(TAG, "try file is exist... "); 
	            	if( mIntLightAPI != null)
	            	{
	            		int ret = mIntLightAPI.LedBrightCtrl((byte)0x01);
	            		
	            		if( ret >= 0 )
	            		{
							WallpadStatusData wd = new WallpadStatusData( getApplicationContext());
							wd.SetLEDButtonBrightnessLevel(1); // DB 저장이 실패하게 되면 초기값을  2로 셋팅하기 때문에 다시 한번 셋팅해준다.
							int level = wd.GetLEDButtonBrightnessLevel();
							wd.closeDB();
							Log.d(TAG, "88888888 button brightness Level 1 == " + level);
							
							WallpadStatusData wd1 = new WallpadStatusData( getApplicationContext());
							wd1.SetLEDButtonBrightnessLevel(1);
							level = wd1.GetLEDButtonBrightnessLevel();
							wd1.closeDB();
							
							
							FileDelete(savefile);//.delete();
							
							// 생산 기술팀 요청사항
							// LED 버튼 보디 교체로 레벨이 너무 밝아 디폴트값 변경을 요청함 ,, 
							Log.d(TAG, "8888888888888888888888 button brightness Level 1 == " + level);
	            		}
	            	}
		    	}
    		}
    		catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e )
    		{
    			
                LogUtil.errorLogInfo("", TAG, e);
    		}
	    	
    	}
    }
    
    private void AutoIGALStatusReleaseSinario()
    {
		// 에너지미터 설정에 따라 조명 상태 변경시 일괄소등 해제 처리 시나리오를 설정하도록 한다.
    	// 일괄소등 해제 시나리오 적용시...
    	try
    	{
	    	WallpadDeviceSet devset = new WallpadDeviceSet(getApplicationContext());
			int setIparkEnergy = devset.Get_Energy_Devices_Info();
			Log.d(TAG , "Get_IPark_Energy_Info bSet: setIparkEnergy : " + setIparkEnergy);
			if( setIparkEnergy == 1 )
			{
				mWallPadAPI.SetAutoIGALStatusClear(true);
				Log.d(TAG , "AutoIGALStatusReleaseSinario bSet: true");
			}
			devset.closeDB();	
    	}
    	catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e )
    	{
			Log.e(TAG, e.toString());
			
            LogUtil.errorLogInfo("", TAG, e);
    	}
    }
    /**
     * onDestroy
     */
    @Override
    protected void onDestroy() {
    	// 이걸 왜 넣었지?
        setChangeScreen(mCurrentScreenId, true, false);
        unregisterBroadcastReceiver();
        super.setFinishTimerDestroy();

        Log.i(TAG, "*************************************************************");
        Log.i(TAG, "****************** [END   - MainActivity] *******************");
        Log.i(TAG, "*************************************************************");
        super.onDestroy();
    }

    /**
     * onResume
     */
    @Override
    protected void onResume() {
        super.onResume();
        m_thisAcitivityRusume = true;
        if (mWallPadAPI != null) {
            if (mWallPadAPI.Check_Connect()) Log.w(TAG, "[onResume] mWallPadAPI.Check_Connect() = true!!!");
            else Log.w(TAG, "[onResume] mWallPadAPI.Check_Connect() = false!!!");
            mWallPadAPI.Resume();
        }
        
        //CallDataChecker();
        try {
	        if (m_ModelHouseSleepModeRelease) {
//                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//                pm.userActivity(1, true);
//                pm.userActivity(2, true);1qn
                // LCD 항상 ON
                ((Activity)this.getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	        }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
        	
            LogUtil.errorLogInfo("", TAG, e);
        }
        
		if (MAINStatus == MAIN_WAIT_SETIP) {
			try {
				WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
				AddressSet addc =  SetData.getAddressMGR();
				SetData.closeDB();
				Log.i("MAINSCREEN", "onResume MAIN_WAIT_SETIP "+addc.IPAddress);
                if (addc.IPAddress!=null && !addc.IPAddress.equals("NONE")) {
                    Log.i("MAINSCREEN", "onResume Start Server");
                    EthernetManager mEthManager = (EthernetManager) getSystemService("ethernet");
                    mEthManager.setEthernetState(EthernetManager.ETH_STATE_DISABLED);
                    mEthManager.setEthernetState(EthernetManager.ETH_STATE_ENABLING);
                    Intent intent = new Intent(getApplicationContext(), iMapServer.class);
                    Log.w("MAINSCREEN", "Call Start iMapServer");
                    startService(intent);
                    WallpadDeviceSet devSet = new WallpadDeviceSet(getApplicationContext());
                    String[] sitecode = devSet.GetSettingData("site_code");
                    try {
                        if (sitecode != null) {
                            Intent sipServiceLauncher = new Intent ("cm.sip.hns.SIPStun.StartService");
                            getApplicationContext().startService(sipServiceLauncher);
                        }
                    } catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
                        Common.DebugLog("SIP StartServerice Error!!!!!!!!!!!!!!");
                    }
                    devSet.closeDB();
                    MAINStatus = MAIN_NORMAL;
                }
			} catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e ) {
				
                LogUtil.errorLogInfo("", TAG, e);
			}
		}
		
		//CheckMainScreen();
		
		//refreshUserCtr();
		//reloadData();
		try {
			WallPadInterface wpdifc  = new WallPadInterface();	
			AudioManager amanager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);			
			amanager.setMode(WallPadInterface.AUDIO_MODE_NORMAL);
			wpdifc.DoControl(WallPadInterface.IOCTL_DOOR_POWERONOFF, 0);
			
			Intent intent = new Intent(Common.MAIN_SCREEN_NOW_UPDATE, null);
	        getContext().sendBroadcast(intent);

            mGetCallHistoryCheckHandler.sendEmptyMessageDelayed(0, 1000);
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
			
            LogUtil.errorLogInfo("", TAG, e);
		}
        bScreenCheck = true;
        DebugLogOutput("@@@@@@@@ [onResume] @@@@@@@@");
    }
  	
	protected String getForegroundAPK() {
		try {
			ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
			List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
			ComponentName topActivity=taskInfo.get(0).topActivity;
			String str=topActivity.getPackageName(); 
			
			return str;
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return "  ";
        }
		catch (Exception e) {
			
            LogUtil.errorLogInfo("", TAG, e);
			return "  ";
		}
	}
    
    /**
     * onPause
     */
    @Override
    protected void onPause() {
        m_thisAcitivityRusume = false;
        if(mWallPadAPI != null) mWallPadAPI.Pause();
        bScreenCheck = false;
        DebugLogOutput("@@@@@@@@ [onPause] @@@@@@@@");
        super.onPause();
    }
 
    
    /* ================================================================================================
     * [BroadcastReceiver] Section
     ================================================================================================ */
    /**
     * BroadcastReceiver.onReceive for [WpadActivity]
     */
    @Override
    protected void onBrReceive(Intent intent) {
        try {
            String strAction = intent.getAction();
            Log.i(TAG, "[onBrReceive] Action [" + strAction + "]");
            if (strAction.equals(BR_CTRL_LIGHT_LIVINGROOM)) {
                Log.d(TAG, "[onBrReceive] (BR) BR_CTRL_LIGHT_LIVINGROOM");
                mLightInfo.nLightPresetNo = 0;
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] onBrReceive(Intent intent)");
            
            LogUtil.errorLogInfo("", TAG, e);
        }
        super.onBrReceive(intent);
    }
    
    
    /* ================================================================================================
     * [Touch & Key Event] Section
     ================================================================================================ */
    /**
     * TouchEvent for [WpadActivity]
     */
    @Override
    protected void onTouchEvent(View v, MotionEvent event) {
        super.onTouchEvent(v, event);
        
        int TargetId = v.getId();
        int MoveEvent = event.getAction();
        Log.i(TAG, "[onTouchEvent] TargetId [" + TargetId + "], MoveEvent [" + MoveEvent + "]");
        if (MoveEvent == MotionEvent.ACTION_UP) {

        }
    }
    
    /**
     * H/W Key Event
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i(TAG, "[onKeyDown] keyCode : " + keyCode + ", Action : " + event.getAction());
//        sendKeyEventBR(keyCode);
        return super.onKeyDown(keyCode, event);
    }
    
    
    
    @Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
        Log.i(TAG, "[onKeyUp] keyCode : " + keyCode + ", Action : " + event.getAction());
		return super.onKeyUp(keyCode, event);
	}
	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
    	DebugLogOutput("onKeyLongPress - " + " / keyCode : " + keyCode + " / Action : " + event.getAction());
		return super.onKeyLongPress(keyCode, event);
	}
	/* ================================================================================================
     * [Popup Activity] Section
     ================================================================================================ */
    /**
     * Popup Activity 를 시작시킨다.
     * 
     * @param ScreenId - 팝업시작시 Screen ID_OLD
     * @return (boolean) true : 성공,  false : 실패
     */
    public boolean StartPopup(int ScreenId){
        try {
            if (ID.POPUPS.POPUP_INTERFLOORNOISEOCCURED <= ScreenId && ScreenId <= ID.POPUPS.POPUP_POSTRECEIVED) { // 알림 팝업에 한하여
                if (Common.bWallPadCallLive) {
                    Log.w(TAG, "[StartPopup] StartPopup denied!!! === WallPadCall is running!! ScreenId [" + ScreenId + "]");
                    return false; // 통화 앱이 실행되어 있는 경우, 팝업 출력 안함
                }

                WallpadStatusData WsDB = new WallpadStatusData(getApplicationContext());
                int AlarmStatus = WsDB.GetAlarmStatus();
                WsDB.closeDB();
                if (AlarmStatus == WallpadStatusData.ALARM_ARISE || AlarmStatus == WallpadStatusData.GUARD_OUT || AlarmStatus == WallpadStatusData.GUARD_OUT_WAIT) {
                    Log.w(TAG, "[StartPopup] StartPopup denied!!! === AlarmStatus [" + AlarmStatus + "]");
                    return false; // 방범모드 실행중인 경우, 팝업 출력 안함
                }
            }

            if (getPopupActivityRun()) {
                if (ScreenId == ID.POPUPS.POPUP_NOTICESTRANGER) return ((WpadActivity)(PopupActivity.getContext())).ChangeScreen(ScreenId);
                else return false;
            }
            else {
                setPopupActivityRun(true);
                Intent intent = new Intent(mContext, PopupActivity.class);
                intent.putExtra("ScreenId", ScreenId);
                overridePendingTransition(0, 0);
                startActivityForResult(intent, 0);
                return true;
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
        catch (Exception e) {
            Log.e(TAG, "[Exception] StartPopup(int ScreenId)");

            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }
    
    /**
     * Popup Activity 를 시작시킨다. (시작시 Intent Type 데이터를 전달한다)
     * 
     * @param ScreenId - 팝업시작시 Screen ID_OLD
     * @param data     - 전달할 데이터
     * @return (boolean) true : 성공,  false : 실패
     */
    public boolean StartPopup(int ScreenId, Intent data) {
    	try {
            if (ID.POPUPS.POPUP_INTERFLOORNOISEOCCURED <= ScreenId && ScreenId <= ID.POPUPS.POPUP_POSTRECEIVED) { // 알림 팝업에 한하여
                if (Common.bWallPadCallLive) {
                    Log.w(TAG, "[StartPopup] StartPopup denied!!! === WallPadCall is running!! ScreenId [" + ScreenId + "]");
                    return false; // 통화 앱이 실행되어 있는 경우, 팝업 출력 안함
                }

                WallpadStatusData WsDB = new WallpadStatusData(getApplicationContext());
                int AlarmStatus = WsDB.GetAlarmStatus();
                WsDB.closeDB();
                if (AlarmStatus == WallpadStatusData.ALARM_ARISE || AlarmStatus == WallpadStatusData.GUARD_OUT || AlarmStatus == WallpadStatusData.GUARD_OUT_WAIT) {
                    Log.w(TAG, "[StartPopup] StartPopup denied!!! === AlarmStatus [" + AlarmStatus + "]");
                    return false; // 방범모드 실행중인 경우, 팝업 출력 안함
                }
            }

            if (getPopupActivityRun()) {
                if (ScreenId == ID.POPUPS.POPUP_NOTICESTRANGER) return ((WpadActivity)(PopupActivity.getContext())).ChangeScreen(ScreenId);
                else return false;
	        }
	        else {
	            setPopupActivityRun(true);
	            Intent intent = new Intent(mContext, PopupActivity.class);
	            intent.putExtra("ScreenId", ScreenId);
	            intent.putExtra("PopupScreenDataIntent", data);
	            overridePendingTransition(0, 0);
	            startActivityForResult(intent, 0);
	            return true;
	        }    
    	} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
    	    Log.e(TAG, "[Exception] StartPopup(int ScreenId, Intent data)");
    		
            LogUtil.errorLogInfo("", TAG, e);
    		return false;
    	}
    }
    
    /**
     * Activity Result Reception
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        try {
        	Log.d(TAG, "@@@@@@@@ [onActivityResult] @@@@@@@@");
	        
	//        int screenId = data.getIntExtra("SCREENS", -1);
	//        Log.d(TAG, "@@@@@@@@ [onActivityResult] @@@@@@@@ screenId : " + screenId );
	        //if( mViewFlipper)
	        
            if (requestCode == UNINSTALL_REQUEST_CODE) {
                if (resultCode == RESULT_OK) {
                    Log.w(TAG, "[onActivityResult] user accepted the uninstall");
                } else if (resultCode == RESULT_CANCELED) {
                    Log.w(TAG, "[onActivityResult] user canceled the uninstall");
                } else if (resultCode == RESULT_FIRST_USER) {
                    Log.w(TAG, "[onActivityResult] failed to uninstall");
                }
            }
            else {
    	        if (data != null) {
    	        	int nSenderScreenID = data.getIntExtra(Common.BR_SENDER_SCREEN, -1);
    	        	int nReceiveScreenID = data.getIntExtra(Common.BR_RECEIVE_SCREEN, -1);
    	        	int nCallSubMenuScreen = data.getIntExtra(Common.CALL_SUBMAIN_SCREEN, -1);

    	        	if (nCallSubMenuScreen > 0) {
    	        		CallSubMenuScreen(nCallSubMenuScreen);
    	        	}
    	        	else {
    		        	Log.d(TAG, "[onActivityResult] nSenderScreenID : " + nSenderScreenID  + " , nReceiveScreenID : " + nReceiveScreenID );
                        if (nSenderScreenID == ID.POPUPS.POPUP_DELETESHORTCUT) {
                            if (nReceiveScreenID == ID.SCREENS.SCREEN_MAIN) {
                                boolean bResult = data.getBooleanExtra(Common.BR_WIDGET_DELETE, false);
                                int nDeleteShortcutID = data.getIntExtra(Common.BR_DELETE_WIDGET_ID, -1);
                                Log.d(TAG, "[onActivityResult] bResult : " + bResult + ", nDeleteShortcutID : " + nDeleteShortcutID);
                                MainScreen.procDeleteShortcutPopupResult(bResult, nDeleteShortcutID);
                                return;
                            }
                            else if (nReceiveScreenID == ID.SCREENS.SCREEN_HYOSUNGUI_MAIN_HN) {
                                boolean bResult = data.getBooleanExtra(Common.BR_WIDGET_DELETE, false);
                                int nDeleteShortcutID = data.getIntExtra(Common.BR_DELETE_WIDGET_ID, -1);
                                Log.d(TAG, "[onActivityResult] bResult : " + bResult + ", nDeleteShortcutID : " + nDeleteShortcutID);
                                Hyosung_HN_MainScreen.procDeleteShortcutPopupResult(bResult, nDeleteShortcutID);
                                return;
                            }
                            else if (nReceiveScreenID == ID.SCREENS.SCREEN_METROUI_MAIN) {
                                boolean bResult = data.getBooleanExtra(Common.BR_WIDGET_DELETE, false);
                                int nDeleteShortcutID = data.getIntExtra(Common.BR_DELETE_WIDGET_ID, -1);
                                Log.d(TAG, "[onActivityResult] bResult : " + bResult + ", nDeleteShortcutID : " + nDeleteShortcutID);
                                MetroUI_MainScreen.procDeleteShortcutPopupResult(bResult, nDeleteShortcutID);
                                return;
                            }
                        }
                        else if (nSenderScreenID == ID.POPUPS.POPUP_ADDSHORTCUT) {
                            if (nReceiveScreenID == ID.SCREENS.SCREEN_MAIN) {
                                boolean bResult = data.getBooleanExtra(Common.BR_WIDGET_INSERT, false);
                                int nAddShortcutID = data.getIntExtra(Common.BR_INSERT_WIDGET_ID, -1);
                                Log.d(TAG, "[onActivityResult] bResult : " + bResult + ", nAddShortcutID : " + nAddShortcutID);
                                MainScreen.procAddShortcutPopupResult(bResult, nAddShortcutID);
                                return;
                            }
                            else if (nReceiveScreenID == ID.SCREENS.SCREEN_HYOSUNGUI_MAIN_HN) {
                                boolean bResult = data.getBooleanExtra(Common.BR_WIDGET_INSERT, false);
                                int nAddShortcutID = data.getIntExtra(Common.BR_INSERT_WIDGET_ID, -1);
                                Log.d(TAG, "[onActivityResult] bResult : " + bResult + ", nAddShortcutID : " + nAddShortcutID);
                                Hyosung_HN_MainScreen.procAddShortcutPopupResult(bResult, nAddShortcutID);
                                return;
                            }
                            else if (nReceiveScreenID == ID.SCREENS.SCREEN_METROUI_MAIN) {
                                boolean bResult = data.getBooleanExtra(Common.BR_WIDGET_INSERT, false);
                                int nAddShortcutID = data.getIntExtra(Common.BR_INSERT_WIDGET_ID, -1);
                                Log.d(TAG, "[onActivityResult] bResult : " + bResult + ", nAddShortcutID : " + nAddShortcutID);
                                MetroUI_MainScreen.procAddShortcutPopupResult(bResult, nAddShortcutID);
                                return;
                            }
                        }
                        else if (nSenderScreenID == ID.POPUPS.POPUP_CONFIGUREPRESET && nReceiveScreenID == ID.SCREENS.SCREEN_MAIN) {
                            String strLivinglightPresetInfo = data.getStringExtra(Common.BR_LIVINGLIGHT_PRESET_INFO);
                            Log.d(TAG, "[onActivityResult] strLivinglightPresetInfo [" + strLivinglightPresetInfo  + "]");
                            savePresetValue(strLivinglightPresetInfo);
                            return;
                        }
                        else if ((ID.POPUPS.POPUP_GROUP_CTRL <= nSenderScreenID && nSenderScreenID <= ID.POPUPS.POPUP_GROUP_SETTING) && nReceiveScreenID == ID.SCREENS.SCREEN_METROUI_GROUP) {
                            boolean bRun = data.getBooleanExtra(Common.BR_RUN_WIDGET, false);
                            int nIconID = data.getIntExtra(Common.BR_RUN_WIDGET_ID, 0);
                            Log.d(TAG, "[onPopupResult] bRun [" + bRun + "], nIconID [" + nIconID + "]") ;
                            if (bRun) runIcon(nIconID);
                        }
    	        	}
    	        }


    	        if (resultCode == RESULT_OK) {
//    	        	// 팝업을 종료하고 다른 팝업을 띄울경우가 있다.
//    	        	int screenIdCode = data.getExtras().getInt("CHANGE_POPUP" );
//    	        	int popupKind = data.getExtras().getInt("POPUP_KIND");
//
//    	        	Log.d(TAG, "@@@    CHANGE_POPUP : " + screenIdCode  + " , popupKind : " +popupKind);
//    	        	if( screenIdCode > 0 )
//    	        	{
//    	        		setPopupActivityRun(false);
//    	                Intent intent = new Intent();
//    	                intent.putExtra("POPUP_KIND", popupKind );
//    	        		StartPopup(screenIdCode , intent);
//    	        	}
    	        }
            }
        }
        catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e )
        {
			Log.e(TAG, e.toString());
			
            LogUtil.errorLogInfo("", TAG, e);
        }
    }
    
    /* ================================================================================================
     * [Info Activity] Section
     ================================================================================================ */
    public static ManualActivity mManualActivity;
    
    /**
	 * Info Activity를 시작시킨다.
	 * 
	 * @param screenId - 매뉴얼 시작시 Screen ID_OLD
	 * @return (boolean) true : 성공,  false : 실패
	 */
    public boolean startManualPopup(int screenId) {
	    Log.d(TAG, "[startManualPopup] ScreenId [" + screenId +"], mCurrentInfoScreenId [" + mCurrentInfoScreenId + "]" );
		if (getInfoActivityRun() == true) {
			mCurrentInfoScreenId = screenId;
		    return ((WpadActivity)(ManualActivity.getContext())).ChangeScreen(screenId);
		} else {
		    if (mCurrentInfoScreenId == screenId) return false;
		    mCurrentInfoScreenId = screenId;
			setInfoActivityRun(true);
			Intent intent = new Intent(mContext, ManualActivity.class);
			intent.putExtra("ScreenId", screenId);
			
			overridePendingTransition(0, 0);
			startActivityForResult(intent, 0);
			return true;
		}
    }
    
    public static void resetCurrentInfoScreenID() {
        try {
            mCurrentInfoScreenId = -1;
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] resetCurrentInfoScreenID()");
            
            LogUtil.errorLogInfo("", TAG, e);
        }  	
    }
	
	/**
     * 매뉴얼 버튼 사용 유무
     * 
     * @return boolean 타입 - true:사용, false:미사용 
     */
    public boolean GetManualUse() {
        WallpadDeviceSet devSet = new WallpadDeviceSet(mContext);
        String[] DBinfo = devSet.GetSettingData("매뉴얼");
        devSet.closeDB(); 
        if (DBinfo != null) {
            if (DBinfo[1].indexOf("사용함") > 0) {
                Log.d(TAG, "[GetManualUse] Use Manual");
                return true;
            }
            else {
                // 미사용
            	Log.d(TAG, "[GetManualUse] Not Use Manual");
                return false;
            }
        }
        else {
            //미사용
            return false;
        }
    }
    
    
    /* ================================================================================================
     * [Screen] Section
     ================================================================================================ */
    /**
     * Screen 에서 Screen 변경을 요청할 경우 호출된다.<br>
     * Override 사용하여 Screen 변경을  처리한다.<br>
     * 
     * @param nScreenId - 변경할 Screen ID_OLD
     * @return (boolean) true : 성공, false : 실패
     */
    @Override
    protected boolean onChangeScreen(int nScreenId) {
        super.onChangeScreen(nScreenId);
        
        return setChangeScreen(nScreenId, false, false);
    }
    
    /**
     * Screen 등록자<br>
     * MainScreenLayout 에 현재 Screen 을 삭제하고, 새로운 Screen 을 등록시킨다.
     * 
     * @param nScreenId  - 변경할 Screen ID_OLD
     * @param OnlyRemove - 현재 Screen 을 삭제만 할 경우 (onDestroy 에서 사용)
     * @return (boolean) true : 성공,  false : 실패
     */
    private boolean setChangeScreen(int nScreenId, boolean OnlyRemove, boolean setAnimation) {
        DebugLogOutput("setChangeScreen - " + "CurrentSelectDeviceId : " + mCurrentScreenId + " / NextLayoutId : " + nScreenId + " / OnlyRemove : " + OnlyRemove);
        
        // 1. 현재 Layout 삭제
        boolean remove = false;
        if (mCurrentScreenId > 0) {
            remove = true;
            MainScreenLayout.removeAllViews();
            super.setCurrentScreen(null);
        }
        
        if (OnlyRemove) return true;
        
        mCurrentScreenId = nScreenId;
        
        // 2. 새로운 Layout 표시
        try {
            switch (nScreenId) {
	            case ID.SCREENS.SCREEN_MAIN:
	            	MainScreen = new MAIN(getContext(), MainScreenLayout, mWallPadAPI, m_CallSubMenuScreen, DEVICE_OPERATION_MODE);
	                super.setCurrentScreen(MainScreen);
	                break;

                case ID.SCREENS.SCREEN_SUB_01:
                    SUB_01Screen = new SUB_01(getContext(), MainScreenLayout, mWallPadAPI);
                    super.setCurrentScreen(SUB_01Screen);
                    break;

                case ID.SCREENS.SCREEN_SUB_02:
                    SUB_02Screen = new SUB_02(getContext(), MainScreenLayout, mWallPadAPI);
                    super.setCurrentScreen(SUB_02Screen);
                    break;

                case ID.SCREENS.SCREEN_METROUI_MAIN:
                    MetroUI_MainScreen = new METROUI_MAIN(getContext(), MainScreenLayout, mWallPadAPI, m_CallSubMenuScreen);
                    super.setCurrentScreen(MetroUI_MainScreen);
                    break;

                case ID.SCREENS.SCREEN_METROUI_SUB_01:
                    MetroUI_SUB_01Screen = new METROUI_SUB_01(getContext(), MainScreenLayout, mWallPadAPI);
                    super.setCurrentScreen(MetroUI_SUB_01Screen);
                    break;

                case ID.SCREENS.SCREEN_METROUI_SUB_02:
                    MetroUI_SUB_02Screen = new METROUI_SUB_02(getContext(), MainScreenLayout, mWallPadAPI);
                    super.setCurrentScreen(MetroUI_SUB_02Screen);
                    break;

                default:
                    Log.e(TAG, "[Error] setChangeScreen - nScreenId Not found!!! (" + mCurrentScreenId + ")");
                    mCurrentScreenId = -1;
                    return false;
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[ExceptionError] - setChangeScreen->Screen Create : " + e);
            return false;
        }
        return true;
    }
    
    /////////////////////////////////////////////////////////////////////////////////
    
    private void runDeviceService() {
    	try {
    	    Log.i(TAG, "[runDeviceService] ===== START =====");
    	    /* 2018.01.30  속초 아이파크 RF현관카메라 연동으로 인하여 수정
    		// 우선 제어기기 연동 기능이 없음
    		if( Version.getModelType() == Version.MODEL_TYPE.IHN_750 )
    			return;
    	    */
    	    if (!getIsSubWallpad()) {
                ActivityManager mActivityManager = (ActivityManager)getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
                List<ActivityManager.RunningAppProcessInfo> RunningAppList = mActivityManager.getRunningAppProcesses();

                Common.DebugLog("[runDeviceService] -----> RunningAppProcessInfo : " + RunningAppList.size() + " +++ Version : " + this.getAppVersion());
                for (int i = 0; i < RunningAppList.size(); i++) {
                    ActivityManager.RunningAppProcessInfo RunningAppListInfo = RunningAppList.get(i);
                    Common.DebugLog("[runDeviceService] -----> RunningAppListInfo.processName : " + RunningAppListInfo.processName);

                    if (RunningAppListInfo.processName.equals("com.artncore.deviceservice")) {
                        Log.w(TAG, "[runDeviceService] DevService is already running");
                        return;
                    }
                }

                Log.i(TAG, "[runDeviceService] Start DevService!!");
                Intent mIntent = new Intent("wallpaddevservice.ServiceMain");
                startService(mIntent);
            }
    	    else {
                Log.w(TAG, "[runDeviceService] This wallpad is sub-wallpad. not need DevService!!!");
            }

    	} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
			Log.e(TAG, "[Exception] runDeviceService()");
			
            LogUtil.errorLogInfo("", TAG, e);
    	}
    }
    
    // 통신으로 들어오는 비상버튼 스킵하기 위한 딜레이 체크 변수
    private long EmerCommDelayTime = 0;
    public static String WALLPAD_ALERT = "WALLPAD_ALERT";
	BroadcastReceiver mWallPadAlertBR = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(TAG, "[mWallPadAlertBR] Receive alert BR");
            String strAction = intent.getAction();
            Log.d(TAG, "[mWallPadAlertBR] strAction [" + strAction + "]");
            if (strAction.equalsIgnoreCase(WALLPAD_ALERT)) {
                int kind = intent.getIntExtra("KIND",0);
                Log.i(TAG, "[mWallPadAlertBR] " + String.format("Receive alert BR [%d][tag:%s]", kind,String.valueOf(Alert_App_On)));

                // 제주 아이파크 스위트현장의 비상발생 증상을 디버깅하기 위한 코드 (JEFF, 2019.09.26)
//                if (kind == 4) {
//                    try {
//                        byte hFrom = intent.getByteExtra("FROM", (byte) 0xFF);
//                        if (hFrom != (byte) 0xFF) {
//                            if (hFrom % 10 == 3) {
//                                Log.w(TAG, "[mWallPadAlertBR] Emergency from BathPhone!!!");
//                                int nDstPort = 10000;
//                                sendAlarmOperationToMainServer("10.0.1.1", nDstPort, EMER_STATE.FIRE, EMER_DETAIL_INFO.EMERGENCY_COMM);
//                                return;
//                            }
//                        }
//                    } catch (RuntimeException re) {
//                        LogUtil.errorLogInfo("", TAG, re);
//                    }
//                    catch (Exception e) {
//                        Log.e(TAG, "[Exception] mWallPadAlertBR - 1");
//                        e.printStackTrace();
//                    }
//                }

                if (kind == 30) Alert_App_On = true;
                else if (kind == 40) Alert_App_On = false;
                else {
                    WallpadStatusData wdb = new WallpadStatusData(getApplicationContext());
                    int alarmState = wdb.GetAlarmStatus();
                    wdb.closeDB();

                    if (alarmState == WallpadStatusData.ALARM_ARISE || alarmState == WallpadStatusData.ALARM_STOP) {
                        // 알람화면이 현재 실행중이면 스킵
                        Log.d(TAG, "Skip BR ==> Current Alarm state : "+ alarmState );
                        return;
                    }

                    if (kind == 4 && ( Math.abs(System.currentTimeMillis()-EmerCommDelayTime) < 1000)) {
                        // 통신 비상알람의 경우 중복으로 날라오는 경우가 있어서 필터링
                        Log.d(TAG, "Skip BR ==> deleayTime :" + String.valueOf( Math.abs(System.currentTimeMillis()-EmerCommDelayTime)));
                        return;
                    }

                    EmerCommDelayTime = System.currentTimeMillis();

                    SendAppFinishReqBR();
                    Log.i(TAG, "[mWallPadAlertBR] before Call Alert App");

                    int base = 7000;
                    int [] Menu_Id_List = { base+11, base+21 , base+31 , base+41, base+51};
                    int Menu_Start_Id = base+21;
                    int Menu_Start_Option = 1;
                    String Cause = "none";
                    if (kind  == 1) Cause = "gas";
                    else if (kind  == 2) Cause = "fire";
                    else if (kind == 4) Cause = "emergency_Comm";
                    else if (kind == 5) {
                        Cause = "heating_Leak";
                        Menu_Start_Id = base + 51;
                    }
                    else {
                        Cause = "unknown(" + kind + ")";
                    }

                    Intent newintent = new Intent(Intent.ACTION_MAIN);
                    newintent.putExtra("MENU_ID_LIST", Menu_Id_List);                 // KEY : MENU_ID_LIST
                    newintent.putExtra("MENU_START_ID", Menu_Start_Id);               // KEY : MENU_START_ID
                    newintent.putExtra("MENU_START_OPTION", Menu_Start_Option);       // KEY : MENU_START_OPTION
                    newintent.putExtra("MENU_DETAIL_INFO", Cause);
                    newintent.setComponent(new ComponentName("kr.co.icontrols.wallpademergency", "kr.co.icontrols.wallpademergency.MainActivity"));
                    newintent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(newintent);
                }
            }
		}
	};

    private void sendAlarmOperationToMainServer(String DstIP, int DstPort, EMER_STATE alarm_mode, EMER_DETAIL_INFO cause) {
        Log.d(TAG, "[sendAlarmOperationToMainServer] DstIP [" + DstIP + "], DstPort [" + DstPort + "], alarm_mode [" + EMER_STATE.GetXMLData(alarm_mode) + "], cause [" + EMER_DETAIL_INFO.GetXMLData(cause) + "]");
        WallpadStatusData wdb = new WallpadStatusData(this.getContext());
        AddressSet addc =  wdb.getAddressMGR(); //DB에서 동호 정보 받아옴
        wdb.closeDB();
        final iMAPAlarmOperation imapAlarmOperation = new iMAPAlarmOperation(getContext() , addc);

        imapAlarmOperation.SetServerIPcfg(DstIP, DstPort);
        imapAlarmOperation.DoWork(alarm_mode, cause);
        imapAlarmOperation.SetRetCtr(new RetProci(){
            @Override
            public void ProcSuccess() {
                // TODO Auto-generated method stub
                Log.i(TAG, "[sendAlarmOperationToMainServer] ProcSuccess()");
                String result = imapAlarmOperation.GetAttributeVal(0, "result");
                Log.i(TAG, "[sendAlarmOperationToMainServer] result [" + result +"]");
                if (result.equalsIgnoreCase("ok")) {
                    Log.i(TAG, "[sendAlarmOperationToMainServer] result [" + result +"]");
                }

            }

            @Override
            public void ProcError() {
                // TODO Auto-generated method stub
                Log.i(TAG, "[sendAlarmOperationToMainServer] ProcError() -> " + APIErrorCode.GetLogPrefix());
            }

            @Override
            public void ProcDoing() {
                // TODO Auto-generated method stub
                Log.i(TAG, "[sendAlarmOperationToMainServer] ProcDoing()");
            }
        });
    }

    private String getMainVersion() {
		return this.getAppVersion();
	}
	
	private int m_LiveImapServer = 0;
	private int m_LiveMainActivity = 0;
	private boolean m_IPActivity = false;
	
	BroadcastReceiver mWallPadNotifyBR = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			String strAction = intent.getAction();
			int item = 0;
            Log.i(TAG, "[mWallPadNotifyBR] strAction [" + strAction + "]");
            if (strAction.equals(define.NOTIFY_ACNAME)) {
                int kind = intent.getIntExtra(Common.BR_MAIN_NOTI.KIND,0);
                Log.d(TAG, "[mWallPadNotifyBR] define.NOTIFY_ACNAME -> kind : " + kind);
                switch (kind) {
                    case define.NOTIFY_GET_ELEC_CHARGE:
                        String strState = intent.getStringExtra("sCharging_Status");
                        String strCarNum = intent.getStringExtra("sCar_Num");
                        if (strState.equals("start")) {
                            try {
                                WallpadStatusData SetData = new WallpadStatusData(getContext());
                                boolean soundOut = SetData.GetSoundOutputOfEventAlarm();
                                SetData.closeDB();
                                if (soundOut) Sound().Play(SND.effect.EFFECT1);
                            } catch (RuntimeException re) {
                                LogUtil.errorLogInfo("", TAG, re);
                            }
                            catch (Exception e) {
                                
                                LogUtil.errorLogInfo("", TAG, e);
                            }

                            // 충전시작
                            Intent data = new Intent();
                            data.putExtra("CarNum", strCarNum);                 // KEY : MENU_ID_LIST
                            data.putExtra("Msg", "충전을 시작합니다.");

                            mIOInterface.ctrlLcdWakeUp();
                            StartPopup(ID.POPUPS.POPUP_CHARGINGELECTRICVEHICLE, data);
                        }
                        else if (strState.equals("stop")) {
                            try {
                                WallpadStatusData SetData = new WallpadStatusData(getContext());
                                boolean soundOut = SetData.GetSoundOutputOfEventAlarm();
                                SetData.closeDB();
                                if (soundOut) Sound().Play(SND.effect.EFFECT1);
                            } catch (RuntimeException re) {
                                LogUtil.errorLogInfo("", TAG, re);
                            }
                            catch (Exception e) {
                                
                                LogUtil.errorLogInfo("", TAG, e);
                            }
                            // 충전 종료
                            Intent data = new Intent();
                            data.putExtra("CarNum", strCarNum);                 // KEY : MENU_ID_LIST
                            data.putExtra("Msg", "충전이 종료되었습니다.");

                            mIOInterface.ctrlLcdWakeUp();
                            StartPopup(ID.POPUPS.POPUP_CHARGINGELECTRICVEHICLE, data);
                        }
                        break;

                    case define.NOTIFY_INTERLAYTER_NOISE_ALARM:
                        if (checkInterFloorNoiseFuncUsage()) {
                            mIOInterface.ctrlLcdWakeUp();
                            StartPopup(ID.POPUPS.POPUP_INTERFLOORNOISEOCCURED);
                        }
                        break;

                    case define.NOTIFY_INTERLAYTER_SENSOR_STATUS_CHANGE :
                        if (checkInterFloorNoiseFuncUsage() && checkInterFloorNoiseError()) {
                            mIOInterface.ctrlLcdWakeUp();
                            StartPopup(ID.POPUPS.POPUP_INTERFLOORNOISEERROR);
                        }
                        break;

                    case define.NOTIFY_AUTOPICTURE_FINISH:
                        Log.d(TAG, "[mWallPadNotifyBR] define.NOTIFY_AUTOPICTURE_FINISH");
                        // 전자액자 종료 BR 수신시 LCD ON Flag 제거
                        ctrlLCDOnOff(false);
                        break;

                    case define.NOTIFY_ALARM_CHANGE:
                        Log.d(TAG, "[mWallPadNotifyBR] define.NOTIFY_ALARM_CHANGE");
//                        WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
//                        int nAlarmStatus = SetData.GetAlarmStatus();
//                        SetData.closeDB();
//
//                        Log.d(TAG, "[mWallPadNotifyBR] nAlarmStatus = " + nAlarmStatus);
//                        if (nAlarmStatus == WallpadStatusData.GUARD_IN) {
//                            mSound.PlayMent(SND.mode.INMODE_SETTING);
//                        }
//                        else if (nAlarmStatus == WallpadStatusData.GUARD_OUT) {
//                            mSound.PlayMent(SND.mode.OUTMODE_SETTING);
//                        }
//                        else if (nAlarmStatus == WallpadStatusData.ALARM_NONE) {
//                            mSound.PlayMent(SND.mode.NORMALMODE_COMEBACK);
//                        }
                        break;

                    case define.NOTIFY_PLAYMENT:
                        int sndidx = intent.getIntExtra(define.NOTIBR_CONTENT,0);
                        Sound().PlayMent(sndidx);

                    case define.NOTIFY_DEVICE_INIT_COMPLETION:
                        Log.i(TAG, "[mWallPadNotifyBR] NOTIFY_DEVICE_INIT_COMPLETION: bLCDKeeperUsage [" + bLCDKeeperUsage +"]");
                        if (bLCDKeeperUsage) registerLCDKeeper();
                        break;

                    default:
                        Log.w(TAG, "[mWallPadNotifyBR] (BR.nKind) Not support!! -> " + kind);
                        break;
                }
            }
			else if (strAction.equals(Common.BR_ACK_WALLPADCALL_LIVE)) {
                Log.d(TAG, "[mWallPadNotifyBR] Common.BR_ACK_WALLPADCALL_LIVE");
				return;
			}
            else if (strAction.equals(define.DRIVER_VENTIL_BR)) {
                Log.d(TAG, "[mWallPadNotifyBR] define.DRIVER_VENTIL_BR");
                return;
            }
			else if (strAction.equals(Common.BR_MAIN_NOTI.ACNAME_MAIN_NOTI)) {
				try {
					int kind = intent.getIntExtra(Common.BR_MAIN_NOTI.KIND,0);
                    Log.d(TAG, "[mWallPadNotifyBR] ACNAME_MAIN_NOTI -> kind : " + kind);
					switch (kind) {
						case Common.BR_MAIN_NOTI.ARRIVED_CAR:
                            StartPopup(ID.POPUPS.POPUP_VEHICLEARRIVED, intent);
//							StartPopup(ID_OLD.SCREENS.ArrivedCarPopupScreen);
							break;

						case Common.BR_MAIN_NOTI.UI_UPDATE_PARCEL:
                            StartPopup(ID.POPUPS.POPUP_PARCELRECEIVED);
//							StartPopup(ID_OLD.SCREENS.DeliveryBox);
							break;

						case Common.BR_MAIN_NOTI.SMARTKEY_ALARM_BR:
                            StartPopup(ID.POPUPS.POPUP_SMARTKEYEMERGENCY, intent);
//						    StartPopup(ID_OLD.SCREENS.SmartKeyAlarmPopupScreen, intent);
						    break;

                        case Common.BR_MAIN_NOTI.UI_BANDLOCATION_ALARM:
                            ctrlLCDOnOff(true);
                            int nCardNum = intent.getIntExtra(Common.BR_MAIN_NOTI.CARD_NUM,0);
                            Intent mIntent = new Intent();
                            mIntent.putExtra(Common.BR_MAIN_NOTI.CARD_NUM, nCardNum);
                            StartPopup(ID.POPUPS.POPUP_BANDLOCATIONALARM, mIntent);
                            break;

                        case Common.BR_MAIN_NOTI.UI_UPDATE_POST:
                            ctrlLCDOnOff(true);
                            StartPopup(ID.POPUPS.POPUP_POSTRECEIVED);
                            break;

                        case Common.BR_MAIN_NOTI.NOTICE_DETECT_STRANGER:
                            // 알람 상태 확인
                            int doorCamType = intent.getIntExtra("DOORCAM_TYPE", -1);
                            Intent data = new Intent();
                            data.putExtra("DOORCAM_TYPE", doorCamType);

                            mIOInterface.ctrlLcdWakeUp();
//                            StartPopup(ID.POPUPS.POPUP_NOTICESTRANGER, data); // 시나리오 변경: 거동수상자 알림 팝업 삭제 (바로 녹화 시작)

                            WallpadStatusData SetData = new WallpadStatusData(mContext);
                            boolean soundOut = SetData.GetSoundOutputOfEventAlarm();
                            SetData.closeDB();
                            if (soundOut) Sound().Play(SND.effect.EFFECT1);

                            // 메인 앱으로 BR 전송
                            Intent notiIntent = new Intent();
                            notiIntent.setAction(define.NOTIFY_ACNAME);
                            notiIntent.putExtra(define.NOTIBR_KIND, define.NOTIFY_ACCEPT_RECORD_STRANGER);
                            mContext.sendBroadcast(notiIntent);
                            break;

                        case Common.BR_MAIN_NOTI.ACCEPT_RECORDING:
                            int nEmerState = intent.getIntExtra("EMERGENCY_STATE", -1);
                            //여기서 거동 수상자 녹화 시작 여부 확인
                            Common.bRecordStatus = true;

                            boolean bFromCall = intent.getBooleanExtra("FROMCALL", false);

                            if (!bFromCall) {
                                // yjyoon. 2443에서는 Call 앱에서 녹화 수행
                                // 여기서 해당하는 br 정보를 저장 해야 함
                                //jglee - 여기서 BR들을 관리하기 위하여
                                if(CallBrList == null)
                                    CallBrList = new ArrayList<Intent>();

                                Intent brListIntent = new Intent();
                                brListIntent.setAction(define.NOTIFY_ACNAME);
                                brListIntent.putExtra(define.NOTIBR_KIND, define.NOTIFY_SMART_DCAM_DETECT);

                                if(CallBrList.size() > 1)
                                {
                                    if(CallBrList.get(0) != brListIntent)
                                    {
                                        CallBrList.add(brListIntent);
                                        Log.d(TAG, "jglee - Call 인텐트 추가 > size : " + CallBrList.size()  + ", Action : " + CallBrList.get(0).getAction());
                                    }
                                }
                                else {
                                    CallBrList.add(brListIntent);
                                    Log.d(TAG, "jglee - Call 인텐트 추가 > size : " + CallBrList.size()  + ", Action : " + CallBrList.get(0).getAction());
                                }

                                //여기서 BrList에 남아 있는 갯수를 확인
                                if(CallBrList!=null && CallBrList.size() > 1)
                                {
                                    return;
                                }
                                Log.d(TAG, "jglee - Call Record");
                                m_CallSubMenuScreen.callStartCallAPK(ID.LINKEDSCREEN.SubCall.Door_Record, nEmerState);
                            }
                            break;

                        case Common.BR_MAIN_NOTI.STOP_RECORDING:
                            // yjyoon. 거동수상자 녹화중지 시 상태값 변경.
                            Log.v("yjyoon", "Common.BR_MAIN_NOTI.STOP_RECORDING     Common.bWallPadRecoder = false");
                            //Common.bWallPadRecoder = false;
                            Common.bRecordStatus = false;

                            mediaStopRecord();
                            break;

                        default:
                            Log.w(TAG, "[mWallPadNotifyBR] (BR.nKind) Not support!! -> " + kind);
                            break;
					}
				} catch (RuntimeException re) {
                    LogUtil.errorLogInfo("", TAG, re);
                }
                catch (Exception e) {
					e.toString();
				}
				return;
			}
			else if(strAction.equals(BR_MAIN_LIVE_CHECKER.ACNAME_MAIN_LIVE_CHECKER )) {
				int kind = intent.getIntExtra(BR_MAIN_LIVE_CHECKER.KIND,0);
                Log.d(TAG, "[mWallPadNotifyBR] BR_MAIN_LIVE_CHECKER.ACNAME_MAIN_LIVE_CHECKER -> kind : " + kind + ", m_LiveImapServer [" + m_LiveImapServer + "], m_LiveMainActivity [" + m_LiveMainActivity + "]");
				if (kind == BR_MAIN_LIVE_CHECKER.IMAP_SERVER) {
					Log.d(TAG, "[mWallPadNotifyBR] received Imap Server Live !");
					m_LiveImapServer++;
				}
				else if( kind == BR_MAIN_LIVE_CHECKER.MAIN_ACTIVITY) {
					Log.d(TAG, "[mWallPadNotifyBR] received Main Activity Live !");
					m_LiveMainActivity++;
					if (m_IPActivity == false) {
						Log.d(TAG, "[mWallPadNotifyBR] IP is not set");
						m_LiveImapServer++;
					}
				}
                Log.d(TAG, "[mWallPadNotifyBR] m_LiveImapServer [" + m_LiveImapServer + "], m_LiveMainActivity [" + m_LiveMainActivity +"]");
				return;
			}

			int kind = intent.getIntExtra("KIND",0);			
			Log.d(TAG, "MainActivity mWallPadNotifyBR Receive Notify BR "+kind+" "/*+electr.isActive()*/);		
			switch (kind) {
				case define.NOTIFY_ELE_MOVE:
//					if (electr!= null /*&& electr.isActive()*/)
//					{
//						Log.i("MAINSCREEN", "Receive NOTIFY_ELE_MOVE");	
//						electr.updateUI(intent.getStringExtra("FLOOR"), intent.getByteExtra("UPDOWN",(byte)-1));
//					}
					break;

				case define.NOTIFY_ELE_ARRIVAL_UP:
					Log.i("AIDLTEST", "Receive NOTIFY_ELE_ARRIVAL_UP");
					Sound().Play(SND.elevator.UP_ARRIVED);
					break;

				case define.NOTIFY_ELE_ARRIVAL_DOWN:
					try {
						WallpadDeviceSet devset = new WallpadDeviceSet(getApplicationContext());
						int eleinfo = devset.Get_Elevator_Info();
						devset.closeDB();

						if (WallpadDeviceSet.ELEVATOR_SIMPLE == eleinfo) Sound().Play(SND.elevator.ORG_ARRIVED);
						else if (WallpadDeviceSet.ELEVATOR_FLOOR == eleinfo) Sound().Play(SND.elevator.DN_ARRIVED);
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
					}
					break;

				case define.NOTIFY_UPDATE_START:	
					try {
						String updateFile = intent.getStringExtra("PATH");
						Log.i("WALLPADAPI","Call Update App :" + updateFile);
						if (updateFile==null) return;						
		        		ComponentName cn = new ComponentName("com.telechips.android.systemupdater","com.telechips.android.systemupdater.SystemUpdate");
		        		Intent Uintent = new Intent(Intent.ACTION_MAIN);
		        		Uintent.addCategory(Intent.CATEGORY_LAUNCHER);
		        		Uintent.putExtra("updatefile",updateFile);
		        		Uintent.setComponent(cn);
		        		startActivity(Uintent);	     
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
					}
	        		break;

				case define.NOTIFY_DEVSERVICE_START:	
					mWallPadAPI = new WallPadAPI(getApplicationContext());
					break;

				case define.NOTIFY_DEVICECONNECTED:						
					//DevLockCtr.ReleaseLock(define.DEVICE_LOCK_SVC_INIT);					
					break;

				case define.NOTIFY_SENDBOOTUP_FAIL:	
					// 부트업 실패시 5초 간격으로 다시 시도하도록 수정.
					mWallPadApiCheckHandler.sendEmptyMessageDelayed(10, 10000);
					break;

				case define.NOTIFY_IMAPSERVER_START:
				case Common.DEVICE_BOOTUP_RETRY:
					Log.i(TAG, "Try Send Boot up MSG kind : " + kind );
					bootupretryCNT++;
					if (bootupretryCNT > MAX_BOOTUP_RETRY_COUNT) break;
					try {
						WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
						if (SetData != null) {
							// AnC 기존 코드는 네트워크 연결이 안된경우 DB Close를 50회를 안 하도록 되어있어서 수정함.
							String strServerIP = SetData.GetServerIP();
							int nServerPort = SetData.GetServerPort();
                            String svrVersion = SetData.GetServerVer();
                            Log.d(TAG, "DB Server Version : " + svrVersion );
                            if (svrVersion == null) svrVersion = "1.0";
							
							//설정정보 버전 가져오기
                            StringBuilder result = new StringBuilder();
                            result.append(SetData.GetSettingVer());
                            SetData.closeDB();

                            String Setting_Version = result.toString();
                            Log.i(TAG, "Setting's Version :"+Setting_Version);

                            boolean mNewDanjiServer = false;
                            try {
                                WallpadDeviceSet wallpadDeviceSet = new WallpadDeviceSet(getApplicationContext());
                                //mNewDanjiServer =  wallpadDeviceSet.GetNewDanjiServer();
                                int danjiserverType = wallpadDeviceSet.GetNewDanjiServer();
                                if(danjiserverType == 1)
                                {
                                    mNewDanjiServer = false;
                                }
                                else if(danjiserverType == 2)
                                {
                                    mNewDanjiServer = true;
                                }
                                else
                                {
                                    mNewDanjiServer = true;
                                }

                                wallpadDeviceSet.closeDB();
                            } catch (RuntimeException re) {
                                LogUtil.errorLogInfo("", TAG, re);
                                mNewDanjiServer = false;
                            }
                            catch (Exception e) {
                                Log.e(TAG, "[iMapSverSocket] - GetNewDanjiServer ExceptionError !!!");
                                
                                LogUtil.errorLogInfo("", TAG, e);
                                mNewDanjiServer = false;
                            }

                            if (mNewDanjiServer == true) {
                                // DB 값하고 , 신형단지서버 사용 설정이 동일 하다면 DB값을 전달한다.
                                // 나중에 2.X 이상 버전이 갱신될 경우를 위해서
                            }
                            else {
                                svrVersion = "1.0";
                            }

                            //Main App 버전정보 가져오기
                            WallPadiMAPNotifyAPI notify = new WallPadiMAPNotifyAPI(getApplicationContext());
                            notify.SetSocketWaitCount(3000);
                            notify.SetServerIPcfg(strServerIP, nServerPort);
                            notify.Send_Device_BootUP(getMainVersion(), Setting_Version , svrVersion );
						}
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                        Intent Newintent = new Intent();
                        Newintent.setAction(define.NOTIFY_ACNAME);
                        Newintent.putExtra(define.NOTIBR_KIND,define.NOTIFY_SENDBOOTUP_FAIL);
                        sendBroadcast(Newintent);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
						Intent Newintent = new Intent();
						Newintent.setAction(define.NOTIFY_ACNAME);
						Newintent.putExtra(define.NOTIBR_KIND,define.NOTIFY_SENDBOOTUP_FAIL);
						sendBroadcast(Newintent);	
					}
					break;

				case define.NOTIFY_SUBDEVCALLBUSY:
					/*
					callbtn  = (Button)findViewById(R.id.Callbtn);
					callbtn.setBackgroundResource(R.drawable.but_call_on);
					MAIN_CALL_LOCK = true;
					*/
					break;
					
				case define.NOTIFY_SUBDEVCALLEND:
					/*
					callbtn  = (Button)findViewById(R.id.Callbtn);
					callbtn.setBackgroundResource(R.drawable.but_call);
					MAIN_CALL_LOCK = false;
					*/
					break;

				case define.NOTIFY_UPDATECALLDATA:
					try{
						String[] UpdateCallData = intent.getStringExtra(define.NOTIBR_CONTENT).split(define.DEVCTR_CMD_SPLITER);
						Log.i(APIErrorCode.GetLogPrefix(),"Receive NOTIFY_UPDATECALLDATA "+UpdateCallData[0]+";"+UpdateCallData[1]);
						int IncallCnt = 0;
						int VisitorCNT = 0;
						try {
							IncallCnt = Integer.parseInt(UpdateCallData[0]);
							VisitorCNT = Integer.parseInt(UpdateCallData[1]);
						} catch (RuntimeException re) {
                            LogUtil.errorLogInfo("", TAG, re);
                        }
                        catch (Exception e) {
							
                            LogUtil.errorLogInfo("", TAG, e);
						}
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
					}
					break;

				case define.NOTIFY_UPDATENOTICE:
					Common.DebugLog("Main Activity Receive Br=== . define.NOTIFY_UPDATENOTICE ");
					try {
						WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
						boolean soundOut = SetData.GetSoundOutputOfEventAlarm();
						SetData.closeDB();
						if (soundOut) {
							Sound().PlayMent(SND.effect.EFFECT1);
						}

                        mIOInterface.ctrlLcdWakeUp();
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) { LogUtil.errorLogInfo("", TAG, e);
						
					}
					break;

				case define.NOTIFY_UPDATEPARCEL:
					try {
						
						String type = intent.getStringExtra(define.NOTIBR_CONTENT);
						int itemcnt = intent.getIntExtra("ITEM",-1);
						
						WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
						boolean soundOut = SetData.GetSoundOutputOfEventAlarm();
						if (itemcnt !=-1) SetData.SetParcelCNT(itemcnt);
						SetData.closeDB();
						
						Common.DebugLog("Main Activity Receive Br=== . define.NOTIFY_UPDATEPARCEL  itemcnt : " + itemcnt);
//						if (soundOut) {
//							if (type.equals("parcel_in")) {
//								PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//								pm.userActivity(1, true);
//								Sound().PlayMent(SND.mode.BOX_ARRIVED);
//							}
//						}
						
						Log.d(TAG, "Send BR --> Common.BR_MAIN_NOTI.UI_UPDATE_PARCEL");
						Intent Newintent = new Intent();
						Newintent.setAction(Common.BR_MAIN_NOTI.ACNAME_MAIN_NOTI);
						Newintent.putExtra(Common.BR_MAIN_NOTI.KIND, Common.BR_MAIN_NOTI.UI_UPDATE_PARCEL);		
						getApplicationContext().sendBroadcast(Newintent);
						
						//NoticeIconOnoff(true);
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
					}
					
//					if (type.equals("parcel_in"))
//					{
//						PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);						
//						pm.userActivity(1, true);
//						PlayNotiSound(WpadSound.SND.mode.BOX_ARRIVED);
// 					}
//					
//					if (itemcnt!=-1){
//						if (itemcnt > 0)
//							ParcelIconOnoff(true);			
//						else
//							ParcelIconOnoff(false);
//						WallpadStatusData ParData = new WallpadStatusData(getApplicationContext());
//						ParData.SetParcelCNT(itemcnt);
//						ParData.closeDB();
//						if (ParcelMGR!=null) ParcelMGR.updateParcel();
//					}
							
					break;

                case define.NOTIFY_UPDATEPOST:
                    try {
                        int nItemCnt = intent.getIntExtra("ITEM",-1);
                        Log.d(TAG, "[UI_UPDATE_POST] nItemCnt [" + nItemCnt + "]");

                        WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
                        if (nItemCnt != -1) SetData.SetPostCNT(nItemCnt);
                        SetData.closeDB();

                        Common.DebugLog("Main Activity Receive Br=== . define.NOTIFY_UPDATEPOST  nItemCnt : " + nItemCnt);

                        Log.d(TAG, "Send BR --> Common.BR_MAIN_NOTI.UI_UPDATE_POST");
                        Intent Newintent = new Intent();
                        Newintent.setAction(Common.BR_MAIN_NOTI.ACNAME_MAIN_NOTI);
                        Newintent.putExtra(Common.BR_MAIN_NOTI.KIND, Common.BR_MAIN_NOTI.UI_UPDATE_POST);
                        getApplicationContext().sendBroadcast(Newintent);
                    } catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
                        Log.e(TAG, "[Exception] mWallPadNotifyBR.onReceive()");
                        
                        LogUtil.errorLogInfo("", TAG, e);
                    }
                    break;

				case define.NOTIFY_UPDATEPARKING:	
				    Common.DebugLog("Main Activity Receive Br=== . define.NOTIFY_UPDATEPARKING ");
				    
				    /*
				    WallpadParkInfo parkdb = new WallpadParkInfo(getApplicationContext());
				    List<String[]> parkList  = parkdb.GetParkInfo();
				    
				    if(parkList != null)
				    {   
				        for(int j= 0; j<parkList.size(); j++)
				        {
				            for(int i = 0; i<4; i++)
	                        {
	                            Common.DebugLog("parkList.get("+j+")["+i+"]:"+ parkList.get(j)[i]);                         
	                        }    
				            
				        }
				    }
				    parkdb.closeDB();
				     */
					break;

				case define.NOTIFY_DEVICEREBOOT:
					try {
					    //[Model]
//					    if (Version.getPlatformType() == Version.PLATFORM_TYPE.A20) {
//					        // A20
//					        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
//                            pm.userActivity(8, true);
//				        }
//                        else if (Version.getPlatformType() == Version.PLATFORM_TYPE.A40i) {
                        if (Version.getPlatformType() == Version.PLATFORM_TYPE.A40i) {
                            // V40
                            V40IOInterface mV40IOInterface = new V40IOInterface();
                            mV40IOInterface.setV40Reboot(5);
                        }
					    else {
					        // TCC8935
					        SendAppFinishReqBR();
	                        ComponentName cnA = new ComponentName("com.artncore.updater","com.artncore.updater.MainActivity");
	                        intent = new Intent(Intent.ACTION_MAIN);
	                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
	                        intent.putExtra("updatesystem", "no");
	                        intent.putExtra("updateapp", " no ");
	                        intent.putExtra("rebootcmd", "reboot");
	                        intent.setComponent(cnA);
	                        startActivity(intent);
					    }
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
					}
					break;

				case define.NOTIFY_DEVICEDEEPSLEEP:
					try {
						Log.d(TAG, "[mWallPadAlertBR] NOTIFY_DEVICEDEEPSLEEP");
						WallpadStatusData sdb = new WallpadStatusData(getApplicationContext());
						String[] getstate = sdb.GetSystemUpdateStatus();
						for (int i = 0; i < getstate.length; i++) {
                            Log.d(TAG, "[mWallPadAlertBR] getstate[" + i + "] = " + getstate[i]);
                        }

						if (getstate[0].equalsIgnoreCase("SET")) {
							sdb.SetSystemUpdate(null, null);
							sdb.SetUpgradeState(true);
							ComponentName cnn = new ComponentName("com.artncore.updater","com.artncore.updater.MainActivity");
			        		intent = new Intent(Intent.ACTION_MAIN);		        		
			        		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			        		intent.addCategory(Intent.CATEGORY_LAUNCHER);
			        		intent.putExtra("updatesystem", getstate[1]);
			        		intent.putExtra("updateapp", getstate[2]);		        		
			        		intent.setComponent(cnn);		        		        		
			        		Log.e("MAINSCREEN","Call Upgrade Request BSP : "+getstate[1]+" APP : "+getstate[2]);
			        		startActivity(intent);
						}
						sdb.closeDB();
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
					}
					break;

				case define.NOTIFY_SYSTEMTIMESETTED:
					try {
						Common.DebugLog("MainActivity ---------- > define.NOTIFY_SYSTEMTIMESETTED");
						Calendar caldata = new GregorianCalendar();
	//					refreshdate(caldata);
	//					refreshclock(caldata);
						if (SYSTEM_TIME_SET == false) {
							SYSTEM_TIME_SET = true;
							if (SCManager != null) {
								if (SCManager.isSetted != true) SCManager.refreshSchedule();	
							}
						}
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
					}
					break;

				case define.NOTIFY_SCHEDULEUPDATED:
//					item = intent.getIntExtra("ITEM",0);
//					if (item == ScheduleManager.SCHEDULE_TYPE_SCHEDULER && SYSTEM_TIME_SET)
//						SCManager.refreshSchedulerData();
//					else if (item == ScheduleManager.SCHEDULE_TYPE_SYSRESET && SYSTEM_TIME_SET)
//						SCManager.refreshsysreset();
//					else if (item == ScheduleManager.SCHEDULE_TYPE_MORNINGCALL && SYSTEM_TIME_SET)
//						SCManager.refreshMorningCall();
//					break;
				case define.NOTIFY_ALARMSTAUSCHANGED:
					try {
						item = intent.getIntExtra("ITEM",0);
						if (item == WallpadStatusData.GUARD_OUT) {
							int base = 8000;
							int [] Menu_Id_List = { base+11};
							int Menu_Start_Id = base+11;
							int Menu_Start_Option = -1;
							Intent iintent = new Intent(Intent.ACTION_MAIN);
							iintent.putExtra("MENU_ID_LIST", Menu_Id_List); // KEY : MENU_ID_LIST
							iintent.putExtra("MENU_START_ID", Menu_Start_Id); // KEY : MENU_START_ID
							iintent.putExtra("MENU_START_OPTION", Menu_Start_Option); // KEY : MENU_START_OPTION
							iintent.setComponent(new ComponentName("kr.co.icontrols.wallpadoutmoderun","kr.co.icontrols.wallpadoutmoderun.MainActivity"));
							startActivity(iintent);
						}
						else if (item == WallpadStatusData.GUARD_IN) {
								WallpadStatusData SettData = new WallpadStatusData(getApplicationContext());
	//							Button callBtn = (Button)findViewById(R.id.GuardBtn);												
	//							callBtn.setBackgroundResource((SettData.GetAlarmStatus() == WallpadStatusData.GUARD_IN)?R.drawable.but_guard_on:R.drawable.but_guard);
								SettData.closeDB();
						}
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
						
                        LogUtil.errorLogInfo("", TAG, e);
					}	
					break;

				case define.NOTIFY_ENERGYUPDATE:
					try
					{
						Calendar caldata = new GregorianCalendar(); 
						String[] getData =  intent.getStringExtra(define.NOTIBR_CONTENT).split(define.DEVCTR_CMD_SPLITER);
						String checkDate = String.format("%04d%02d%02d",caldata.get(Calendar.YEAR),caldata.get(Calendar.MONTH)+1,caldata.get(Calendar.DAY_OF_MONTH));
						WallpadStatusData energyData = new WallpadStatusData(getApplicationContext());
						energyData.SetEnergyData(intent.getStringExtra(define.NOTIBR_CONTENT));
						energyData.SetEnergyCheckDate(checkDate);	
						energyData.closeDB();
						//if (NeedCheckEnergy)
						//	CheckEnergyUsage(getData);
	//					if (EnergyMGR!=null)
	//						EnergyMGR.UpdateData(getData);
					}
					catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e )
					{
						
                        LogUtil.errorLogInfo("", TAG, e);
					}
					break;	
				case define.NOTIFY_STARTEFRAME:	
					try
					{
						Log.w("MAINSCREEN"," Receive NOTIFY_STARTEFRAME Start StartAutoPictureAPP ");
						WallpadStatusData SettData = new WallpadStatusData(getApplicationContext());
					
						if (SettData.DecideAutoPictureAppStartOrNot(new GregorianCalendar()))
						{
							if (!SettData.StartAutoPictureAPP())
							{
//								PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//								pm.userActivity(3, true);
							}
						}
						else
						{
//							PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//							pm.userActivity(3, true);
						}
						SettData.closeDB();						
					}
					catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e )
					{
						LogUtil.errorLogInfo("", TAG, e);
					}
					break;
				case define.NOTIFY_ADDDEVICELOCK:
					Log.w("MAINSCREEN"," Receive NOTIFY_ADDDEVICELOCK Start  ");
					//DevLockCtr.AddLock(intent.getIntExtra(define.NOTIBR_CONTENT, 0));
					break;
				case define.NOTIFY_RELEASEDEVICELOCK:
					Log.w("MAINSCREEN"," Receive NOTIFY_RELEASEDEVICELOCK Start  ");
					//DevLockCtr.ReleaseLock(intent.getIntExtra(define.NOTIBR_CONTENT, 0));
					break;
				case define.NOTIFY_PLAYMENT:
				    {
						int sndidx = intent.getIntExtra(define.NOTIBR_CONTENT,0);
						Sound().PlayMent(sndidx);
						
						if (sndidx == WpadSound.SND.elevator.CALL) {
							byte floorInfo = intent.getByteExtra(define.NOTIBR_FLOOR,(byte)0);
							Log.e("MANUAL_MAIN", " PLAY MENT Get Ele Call : "+floorInfo);
						}
					}
					break;
					
				case define.NOTIFY_ENERGY_DATA:
				{
					try
					{
					    Log.w("MAINSCREEN"," Receive NOTIFY_ENERGY DATA Start  ");
					    
					    //에너지 데이터 개수 - 3종 또는 5종
					    EnergyAlramPopupMgr.m_EnergyInfoCount = intent.getIntExtra(Common.ENERGY_INTENT_ENERGY_COUNT, -1);
					    Log.w("MAINSCREEN"," ENERGY_INTENT_ENERGY_COUNT :"+ EnergyAlramPopupMgr.m_EnergyInfoCount);
					    
					    //에너지 단지서버에서 받아온 시간
					    EnergyAlramPopupMgr.m_ReceiveYear = intent.getIntExtra(Common.ENERGY_INTENT_GETDATA_TIME_YEAR, -1);
					    Log.w("MAINSCREEN"," ENERGY_INTENT_GETDATA_TIME_YEAR :"+ EnergyAlramPopupMgr.m_ReceiveYear);
			            
					    EnergyAlramPopupMgr.m_ReceiveMonth = intent.getIntExtra(Common.ENERGY_INTENT_GETDATA_TIME_MONTH, -1);
					    Log.w("MAINSCREEN"," ENERGY_INTENT_GETDATA_TIME_MONTH :"+ EnergyAlramPopupMgr.m_ReceiveMonth);
	                    
					    EnergyAlramPopupMgr.m_ReceiveDay = intent.getIntExtra(Common.ENERGY_INTENT_GETDATA_TIME_DAY, -1);
					    Log.w("MAINSCREEN"," ENERGY_INTENT_GETDATA_TIME_DAY :"+ EnergyAlramPopupMgr.m_ReceiveDay );
	                    				    
					    Log.w("MAINSCREEN"," ENERGY_INTENT_GETDATA_TIME_HOUR :"+ intent.getIntExtra(Common.ENERGY_INTENT_GETDATA_TIME_HOUR, -1));
	                    				    
					    Log.w("MAINSCREEN"," ENERGY_INTENT_GETDATA_TIME_MINUTE :"+ intent.getIntExtra(Common.ENERGY_INTENT_GETDATA_TIME_MINUTE, -1));
	             
					    //전기 에너지 정보
					    String Vaule = "";
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_USE_ELECTRIC);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_Elec_UseValue = Double.parseDouble(Vaule);
					    
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_GOAL_ELECTRIC);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_Elec_GoalValue = Double.parseDouble(Vaule);
	                    
	                    //수도 에너지 정보
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_USE_WATER);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_Water_UseValue = Double.parseDouble(Vaule);
					    
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_GOAL_WATER);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_Water_GoalValue = Double.parseDouble(Vaule);
	                                        
	                    //가스 에너지 정보
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_USE_GAS);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_Gas_UseValue = Double.parseDouble(Vaule);
					    
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_GOAL_GAS);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_Gas_GoalValue = Double.parseDouble(Vaule);
					    
	
	                    //온수 에너지 정보
					    if( EnergyAlramPopupMgr.m_EnergyInfoCount >= 5 )
					    {
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_USE_HOTWATER);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_HotWater_UseValue = Double.parseDouble(Vaule);
					    
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_GOAL_HOTWATER);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_HotWater_GoalValue = Double.parseDouble(Vaule);
					    
	                    //난방 에너지 정보
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_USE_HEATING);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_Heating_UseValue = Double.parseDouble(Vaule);
					    
					    Vaule = intent.getStringExtra(Common.ENERGY_INTENT_GOAL_HEATING);
					    if( Vaule != null && Vaule.length() > 0 )
					    	EnergyAlramPopupMgr.m_Heating_GoalValue = Double.parseDouble(Vaule);
					    }
					}
					catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e )
					{
						LogUtil.errorLogInfo("", TAG, e);
					}

				}
				break;
				
				case define.NOTIFY_GET_CAR_PARKING:
					try
					{
					    if(bUseofNot_ParkingInfo == true)
					    {
					        bSetMSG_GetParkingInfo = true;
		                    LoadParkingDataFromServer();    
					    }
					    else
					    {
					        DebugLogOutput("bUseofNot_ParkingInfo == false");
					    }
					    
					}
					catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e )
					{
						LogUtil.errorLogInfo("", TAG, e);
					}
				break;
						
				case define.NOTIFY_ENERGY_TARGET_INFO_ALARM_FROM_SERVER:
				    
				    String tempFromWhere = intent.getStringExtra("FromWhere");
				    if(tempFromWhere == null)
				    {
				        ResultGetIntent = true;    
				    }
				    
				    String tempElect_target = intent.getStringExtra("elect_target");				     
		            if(tempElect_target != null)
		            {
		                elect_target = tempElect_target;
		            }
		            
		            String tempElect_used = intent.getStringExtra("elect_used");		            
		            if(tempElect_used != null)
		            {
		                elect_used = tempElect_used;
		            }
		            
		            String tempElect_info = intent.getStringExtra("elect_info");
		            if(tempElect_info != null)
		            {
		                elect_info = tempElect_info;
		            }
		            
		            String tempWater_target = intent.getStringExtra("water_target"); 
		            if(tempWater_target != null)
		            {
		                water_target = tempWater_target;
		            }
		            
		            String tempWater_used = intent.getStringExtra("water_used");
		            if(tempWater_used != null)
		            {
		                water_used = tempWater_used;
		            }
		            
		            String tempWater_info = intent.getStringExtra("water_info"); 
		            if(tempWater_info != null)
		            {
		                water_info = tempWater_info;
		            }
		            
		            String tempGas_target = intent.getStringExtra("gas_target");
		            if(tempGas_target != null)
		            {
		                gas_target = tempGas_target;
		            }

		            String tempGas_used = intent.getStringExtra("gas_used");
		            if(tempGas_used != null)
		            {
		                gas_used = tempGas_used;
		            }
		            
		            String tempGas_info = intent.getStringExtra("gas_info");
		            if(tempGas_info != null)
		            {
		                gas_info = tempGas_info;		                
		            }
		            
		            String tempHotwater_target = intent.getStringExtra("hotwater_target");
		            if(tempHotwater_target != null)
		            {
		                hotwater_target = tempHotwater_target;
		            }
		            
		            String tempHotwater_used = intent.getStringExtra("hotwater_used"); 
		            if(tempHotwater_used != null)
		            {
	                    hotwater_used = tempHotwater_used;	                    
		            }
		            
		            String tempHotwater_info = intent.getStringExtra("hotwater_info");
		            if(tempHotwater_info != null)
		            {
		                hotwater_info = tempHotwater_info;
		            }
		           
		            String tempHeating_target = intent.getStringExtra("heating_target");
		            if(tempHeating_target != null)
		            {
		                heating_target = tempHeating_target;
		            }

		            String tempHeating_used = intent.getStringExtra("heating_used");
		            if(tempHeating_used != null)
		            {
		                heating_used = tempHeating_used;
		            }
		            
		            String tempHeatin_info = intent.getStringExtra("heating_info");
		            if(tempHeatin_info != null)
		            {
		                heating_info = tempHeatin_info;
		            }
				    break;
			}						
		}			
	};
	
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    private void ctrlLCDOnOff(boolean bOn) {
        try {
            if (bOn) {
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                Log.d(TAG, "[ctrlLCDOnOff] Screen On: " + pm.isScreenOn());
                if (getCompareBSPVersion()) {
                    if (!checkLCDOnByCMD()) {
                        Log.d(TAG, "[ctrlLCDOnOff] V40Interface LcdWakeUp Call!!");
                        mIOInterface.ctrlLcdWakeUp(); // 절전상태일 경우, jni LcdWakeUp 먼저 호출
                    }
                }
                else {
                    if (!pm.isScreenOn()) {
                        Log.d(TAG, "[ctrlLCDOnOff] V40Interface LcdWakeUp Call!!");
                        mIOInterface.ctrlLcdWakeUp(); // 절전상태일 경우, jni LcdWakeUp 먼저 호출
                    }
                }
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            } else
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] ctrlLCDOnOff(boolean bOn)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

	protected void refreshUserCtr() {
		Intent intent = new Intent();
		intent.setAction(define.DRIVER_LIGHT_BR);
		Log.i("HIGH","StatusChanged BR Send "+define.DRIVER_LIGHT_BR);
		sendBroadcast(intent);  
		
		intent = new Intent();
		intent.setAction(define.DRIVER_BATCHLIGHT_BR);
		Log.i("HIGH","StatusChanged BR Send "+define.DRIVER_BATCHLIGHT_BR);
		sendBroadcast(intent);
		
		intent = new Intent();
		intent.setAction(define.DRIVER_VENTIL_BR);
		Log.i("HIGH","StatusChanged BR Send "+define.DRIVER_VENTIL_BR);
		sendBroadcast(intent);		
		
//		intent = new Intent();
//		intent.setAction(HEATERBR);
//		Log.i("HIGH","StatusChanged BR Send "+HEATERBR);
//		sendBroadcast(intent);
	}
	
    
	private void Check_Upgrade_File() {
		try {
			WallpadStatusData sdb = new WallpadStatusData(getApplicationContext());
			String[] getstate = sdb.GetSystemUpdateStatus();					
			if (getstate[0].equalsIgnoreCase("SET")) {
				for (int i = 1; i < 3; i++) {
					if (!getstate[i].equals("no")) {
						String filePath = "/sdcard/"+getstate[i];
						File updradef = new File(filePath);
						if (updradef.exists()) FileDelete(updradef);//.delete();
					}
				}
				sdb.SetSystemUpdate(null, null);
			}
			sdb.closeDB();
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
		    Log.e(TAG, "[Exception] Check_Upgrade_File()");
			LogUtil.errorLogInfo("", TAG, e);
		}
	}
	
    protected void SendAppFinishReqBR() {
    	try {
	    	Log.e("MANUAL_MAIN", "Send Finish BR");
//	    	PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//			pm.userActivity(1, true);
            // LCD Always ON
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			Intent notiIntent = new Intent();
			notiIntent.setAction(define.BR_APP_FINISH);						
			getApplicationContext().sendBroadcast(notiIntent);
    	} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] SendAppFinishReqBR()");
			LogUtil.errorLogInfo("", TAG, e);
		}
	}
    
	private void registerBroadcastReceiver() {
		try {
			IntentFilter mIntentFilter = new IntentFilter();
            mIntentFilter.addAction("WALLPAD_ALERT");
			registerReceiver(mWallPadAlertBR, mIntentFilter);

            mIntentFilter = new IntentFilter();
            mIntentFilter.addAction("WALLPAD_NOTIFY");
            mIntentFilter.addAction(define.DRIVER_VENTIL_BR);
            mIntentFilter.addAction(Common.BR_MAIN_NOTI.ACNAME_MAIN_NOTI); // ACC 꺼와 구분되는 Noti 추가
            mIntentFilter.addAction(BR_MAIN_LIVE_CHECKER.ACNAME_MAIN_LIVE_CHECKER);
            mIntentFilter.addAction(Common.BR_ACK_WALLPADCALL_LIVE);
			registerReceiver(mWallPadNotifyBR, mIntentFilter);

            registerMainActivityBR();

            registerStrangeRecordBR();

		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] registerBroadcastReceiver()");
			LogUtil.errorLogInfo("", TAG, e);
		}
	}

    private void unregisterBroadcastReceiver() {
        try {
            unregisterReceiver(mWallPadAlertBR);
            unregisterReceiver(mWallPadNotifyBR);
            unregisterReceiver(MainActivityBroadcastReceiver);
            //거동수상자 관련 리시버 해제
            unregisterReceiver(StrangeRecordBroadcastReceiver);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] unregisterBroadcastReceiver()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }
    
	private void MainScrLog(String msg) {
		Log.e("MAINSCREEN",APIErrorCode.GetLogPrefix()+msg);
	}

	protected void CheckEnv() {
		try {
			File dnDIC = new File(BESTIN_LOCATION);
			if (!dnDIC.exists()) dnDIC.mkdir();

			dnDIC = new File(ALBUM_PICTURE_LOCATION);
			if (!dnDIC.exists()) dnDIC.mkdir();

		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
		    Log.e(TAG, "[Exception] CheckEnv()");
            LogUtil.errorLogInfo("", TAG, e);
		}
	}

	public void FileCopy(String Target, String Source) {
        FileInputStream input = null;
        FileOutputStream output = null;
		try {
            input = new FileInputStream(Source);
			long size = input.available();
			byte buff[] = new byte[(int)size];
			input.read(buff);

            output = new FileOutputStream(Target);
			output.write(buff);
			output.flush();

		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e ) {
            Log.e(TAG, "[Exception] FileCopy(String Target, String Source)");
            LogUtil.errorLogInfo("", TAG, e);
		}
		finally {
		    if(input!=null) {
                try {
                    input.close( );
                } catch (IOException e) {
                    LogUtil.errorLogInfo("", TAG, e);
                }
            }
            input = null;

		    if(output!=null) {
                try {
                    output.close();
                } catch (IOException e) {
                    LogUtil.errorLogInfo("", TAG, e);
                }
            }
            output = null;
        }
	}

	public void checkEventNotifications() {
	    try {
            Log.d(TAG,"[checkEventNotifications] ========== START ==========)");

            // 스마트우편함, 전기차충전 연동 여부 확인
            int nRetElecVehicle = -1;
            WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(this.getContext());
            bSmartPostUsage = mWallpadDeviceSet.Get_SmartPostUse();
            nRetElecVehicle = mWallpadDeviceSet.GetDeviceSetted("전기차충전");
            mWallpadDeviceSet.closeDB();

            if (nRetElecVehicle == WallpadDeviceSet.DEV_DATA_ENABLE) bElecVehicleUsage = true;
            else bElecVehicleUsage = false;
            Log.d(TAG, "[checkEventNotifications] bSmartPostUsage [" + bSmartPostUsage + "], nRetElecVehicle [" + nRetElecVehicle + "], bElecVehicleUsage [" + bElecVehicleUsage + "]");

            // 부재중 통화
            WallpadCallHistoryData mWallpadCallHistoryData = new WallpadCallHistoryData(getContext());
            try {
                nMissedCallCnt = mWallpadCallHistoryData.RowCallHistoryCountData();
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] checkEventNotifications() -> mWallpadCallHistoryData");
                LogUtil.errorLogInfo("", TAG, e);
            }
            mWallpadCallHistoryData.closeDB();

            // 방문자 사진
            WallpadVisitorPicData_A20 mWallpadVisitorPicData_A20 = new WallpadVisitorPicData_A20(getContext());
            try {
                nVisitorPicCnt = mWallpadVisitorPicData_A20.RowVisitorPictureCountData();
            } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
                Log.e(TAG, "[Exception] checkEventNotifications() -> mWallpadVisitorPicData_A20");
                LogUtil.errorLogInfo("", TAG, e);
            }
            mWallpadVisitorPicData_A20.closeDB();

            // 공지사항, 택배, 스마트 우편
            WallpadStatusData mWallpadStatusData = new WallpadStatusData(this.getContext());
            try {
                nNoticeCnt = mWallpadStatusData.GetNoticeCNT();
                nParcelCnt = mWallpadStatusData.GetParcelCNT();
                nPostCnt = mWallpadStatusData.GetPostCNT();
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] checkEventNotifications() -> mWallpadStatusData");
                LogUtil.errorLogInfo("", TAG, e);
            }
            mWallpadStatusData.closeDB();


            if (0 > nMissedCallCnt) {
                Log.w(TAG,"[checkEventNotifications] out of range!! nMissedCallCnt [" + nMissedCallCnt + "]");
                nMissedCallCnt = 0;
            }

            if (0 > nVisitorPicCnt) {
                Log.w(TAG,"[checkEventNotifications] out of range!! nVisitorPicCnt [" + nVisitorPicCnt + "]");
                nVisitorPicCnt = 0;
            }

            if (0 > nNoticeCnt) {
                Log.w(TAG,"[checkEventNotifications] out of range!! nNoticeCnt [" + nNoticeCnt + "]");
                nNoticeCnt = 0;
            }

            if (0 > nParcelCnt) {
                Log.w(TAG,"[checkEventNotifications] out of range!! nParcelCnt [" + nParcelCnt + "]");
                nParcelCnt = 0;
            }

            if (0 > nPostCnt) {
                Log.w(TAG,"[checkEventNotifications] out of range!! nPostCnt [" + nPostCnt + "]");
                nPostCnt = 0;
            }

            if (0 > nElecVehicleChangingCnt) {
                Log.w(TAG,"[checkEventNotifications] out of range!! nElecVehicleChangingCnt [" + nElecVehicleChangingCnt + "]");
                nElecVehicleChangingCnt = 0;
            }

            if (!bSmartPostUsage) {
                Log.w(TAG,"[checkEventNotifications] bSmartPostUsage is not supported!! -> bSmartPostUsage [" + bSmartPostUsage + "]");
                nPostCnt = 0;
            }

            if (!bElecVehicleUsage) {
                Log.w(TAG,"[checkEventNotifications] bElecVehicleUsage is not supported!! -> bElecVehicleUsage [" + bElecVehicleUsage + "]");
                nElecVehicleChangingCnt = 0;
            }

            Log.d(TAG,"[checkEventNotifications] nMissedCallCnt [" + nMissedCallCnt + "], nVisitorPicCnt [" + nVisitorPicCnt + "], nNoticeCnt [" + nNoticeCnt + "], nParcelCnt [" + nParcelCnt + "], nPostCnt [" + nPostCnt + "], nElecVehicleChangingCnt [" + nElecVehicleChangingCnt + "]");

            sendEventNotiBR(nMissedCallCnt, nVisitorPicCnt, nNoticeCnt, nParcelCnt, nPostCnt, nElecVehicleChangingCnt);
            Send_NotiSmartSwitch(MainActivity.nNoticeCnt, MainActivity.nParcelCnt, MainActivity.nVisitorPicCnt);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
	        Log.e(TAG, "[Exception] checkEventNotifications()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public String getEventNotificationInfo() {
        try {
            Log.d(TAG,"[getEventNotificationInfo] ========== START ==========)");
            // 부재중 통화, 방문자 사진, 공지사항, 택배
            int nMissedCallCnt = 0, nVisitorPicCnt = 0, nNoticeCnt = 0, nParcelCnt = 0, nPostCnt = 0;

            // 부재중 통화
            WallpadCallHistoryData mWallpadCallHistoryData = new WallpadCallHistoryData(getContext());
            try {
                nMissedCallCnt = mWallpadCallHistoryData.RowCallHistoryCountData();
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] getEventNotificationInfo() -> mWallpadCallHistoryData");
                LogUtil.errorLogInfo("", TAG, e);
            }
            mWallpadCallHistoryData.closeDB();

            // 방문자 사진
            WallpadVisitorPicData_A20 mWallpadVisitorPicData_A20 = new WallpadVisitorPicData_A20(getContext());
            try {
                nVisitorPicCnt = mWallpadVisitorPicData_A20.RowVisitorPictureCountData();
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] getEventNotificationInfo() -> mWallpadVisitorPicData_A20");
                LogUtil.errorLogInfo("", TAG, e);
            }
            mWallpadVisitorPicData_A20.closeDB();

            // 공지사항, 택배
            WallpadStatusData mWallpadStatusData = new WallpadStatusData(this.getContext());
            try {
                nNoticeCnt = mWallpadStatusData.GetNoticeCNT();
                nParcelCnt = mWallpadStatusData.GetParcelCNT();
                nPostCnt = mWallpadStatusData.GetPostCNT();
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] getEventNotificationInfo() -> mWallpadStatusData");
                LogUtil.errorLogInfo("", TAG, e);
            }
            mWallpadStatusData.closeDB();

            if (0 > nMissedCallCnt) {
                Log.w(TAG,"[getEventNotificationInfo] out of range!! nMissedCallCnt [" + nMissedCallCnt + "]");
                nMissedCallCnt = 0;
            }

            if (0 > nVisitorPicCnt) {
                Log.w(TAG,"[getEventNotificationInfo] out of range!! nVisitorPicCnt [" + nVisitorPicCnt + "]");
                nVisitorPicCnt = 0;
            }

            if (0 > nNoticeCnt) {
                Log.w(TAG,"[getEventNotificationInfo] out of range!! nNoticeCnt [" + nNoticeCnt + "]");
                nNoticeCnt = 0;
            }

            if (0 > nParcelCnt) {
                Log.w(TAG,"[getEventNotificationInfo] out of range!! nParcelCnt [" + nParcelCnt + "]");
                nParcelCnt = 0;
            }

            if (0 > nPostCnt) {
                Log.w(TAG,"[getEventNotificationInfo] out of range!! nPostCnt [" + nPostCnt + "]");
                nPostCnt = 0;
            }

            Log.d(TAG,"[getEventNotificationInfo] nMissedCallCnt [" + nMissedCallCnt + "], nVisitorPicCnt [" + nVisitorPicCnt + "], nNoticeCnt [" + nNoticeCnt + "], nParcelCnt [" + nParcelCnt + "], nPostCnt [" + nPostCnt + "]");

            if (bSmartPostUsage) return nMissedCallCnt + define.DEVCTR_CMD_SPLITER + nVisitorPicCnt + define.DEVCTR_CMD_SPLITER + nNoticeCnt + define.DEVCTR_CMD_SPLITER + nParcelCnt + define.DEVCTR_CMD_SPLITER + nPostCnt;
            else return nMissedCallCnt + define.DEVCTR_CMD_SPLITER + nVisitorPicCnt + define.DEVCTR_CMD_SPLITER + nNoticeCnt + define.DEVCTR_CMD_SPLITER + nParcelCnt;
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return null;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getEventNotificationInfo()");
            LogUtil.errorLogInfo("", TAG, e);
            return null;
        }
    }

    private void sendEventNotiBR(int missedcall, int visitorpic, int notice, int parcel) {
        try {
            Log.d(TAG,"[sendEventNotiBR] missedcall [" + missedcall + "], visitorpic [" + visitorpic + "], notice [" + notice + "], parcel [" + parcel + "]");
            String strResult = String.valueOf(missedcall) + define.DEVCTR_CMD_SPLITER + String.valueOf(visitorpic) + define.DEVCTR_CMD_SPLITER + String.valueOf(notice) + define.DEVCTR_CMD_SPLITER + String.valueOf(parcel);
            Log.d(TAG,"[sendEventNotiBR] strResult [" + strResult + "]");

            Intent mIntent = new Intent();
            mIntent.setAction(define.NOTIFY_ACNAME);
            mIntent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATECALLDATA);
            mIntent.putExtra(define.NOTIBR_CONTENT, strResult);
            getApplicationContext().sendBroadcast(mIntent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendEventNotiBR(int missedcall, int visitorpic, int notice, int parcel)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private void sendEventNotiBR(int missedcall, int visitorpic, int notice, int parcel, int post) {
        try {
            Log.d(TAG,"[sendEventNotiBR] missedcall [" + missedcall + "], visitorpic [" + visitorpic + "], notice [" + notice + "], parcel [" + parcel + "], post [" + post + "]");
            String strResult = String.valueOf(missedcall) + define.DEVCTR_CMD_SPLITER + String.valueOf(visitorpic) + define.DEVCTR_CMD_SPLITER + String.valueOf(notice) + define.DEVCTR_CMD_SPLITER + String.valueOf(parcel) + define.DEVCTR_CMD_SPLITER + String.valueOf(post);
            Log.d(TAG,"[sendEventNotiBR] strResult [" + strResult + "]");

            Intent mIntent = new Intent();
            mIntent.setAction(define.NOTIFY_ACNAME);
            mIntent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATECALLDATA);
            mIntent.putExtra(define.NOTIBR_CONTENT, strResult);
            getApplicationContext().sendBroadcast(mIntent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendEventNotiBR(int missedcall, int visitorpic, int notice, int parcel, int post)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private void sendEventNotiBR(int missedcall, int visitorpic, int notice, int parcel, int post, int elecvehiclecharging) {
        try {
            Log.d(TAG,"[sendEventNotiBR] missedcall [" + missedcall + "], visitorpic [" + visitorpic + "], notice [" + notice + "], parcel [" + parcel + "], post [" + post + "], elecvehiclecharging [" + elecvehiclecharging +"]");
            String strResult = String.valueOf(missedcall) + define.DEVCTR_CMD_SPLITER + String.valueOf(visitorpic) + define.DEVCTR_CMD_SPLITER + String.valueOf(notice)
                                           + define.DEVCTR_CMD_SPLITER + String.valueOf(parcel) + define.DEVCTR_CMD_SPLITER + String.valueOf(post) + define.DEVCTR_CMD_SPLITER + String.valueOf(elecvehiclecharging);
            Log.d(TAG,"[sendEventNotiBR] strResult [" + strResult + "]");

            Intent mIntent = new Intent();
            mIntent.setAction(define.NOTIFY_ACNAME);
            mIntent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATECALLDATA);
            mIntent.putExtra(define.NOTIBR_CONTENT, strResult);
            getApplicationContext().sendBroadcast(mIntent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendEventNotiBR(int missedcall, int visitorpic, int notice, int parcel, int post, int elecvehiclecharging)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private void CheckCallData_CalledCountAndVisitorCount() {
        try {
            int Vcount = 0;
            int Ccount = 0;
            try {
                //DB정보 읽어서 처리
                Log.d(TAG,"CheckCallData_CalledCountAndVisitorCount Start");
                WallpadCallHistoryData mWallpadCallHistoryData = new WallpadCallHistoryData(getContext());
                int TempCcount = mWallpadCallHistoryData.RowCallHistoryCountData();
                mWallpadCallHistoryData.closeDB();

                Log.d(TAG,"RowCallHistoryCountData() :" + TempCcount);
                if (TempCcount != -999) {
                    Ccount = TempCcount;
                }

                WallpadVisitorPicData_A20 mWallpadVisitorPicData_A20 = new WallpadVisitorPicData_A20(getContext());
                int TempVcount = mWallpadVisitorPicData_A20.RowVisitorPictureCountData();
                mWallpadVisitorPicData_A20.closeDB();

                Log.d(TAG,"RowVisitorPictureCountData() :" + TempVcount);
                if (TempVcount != -999) {
                    Vcount = TempVcount;
                }
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                LogUtil.errorLogInfo("", TAG, e);
            }

            Log.d(TAG," Call Count Check  Receive Ccount :" + Ccount + " , Photo Count : " + Vcount );

            String Retdata = String.valueOf(Ccount)+define.DEVCTR_CMD_SPLITER+String.valueOf(Vcount);
            Intent intent = new Intent();
            intent.setAction(define.NOTIFY_ACNAME);
            intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATECALLDATA);
            intent.putExtra(define.NOTIBR_CONTENT, Retdata);
            getApplicationContext().sendBroadcast(intent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] CheckCallData_CalledCountAndVisitorCount()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    

    

	class ScheduleManager {
		public static final int SCHEDULE_TYPE_GETINFO      = 5000;
		public static final int SCHEDULE_TYPE_MORNINGCALL  = 5001;
		public static final int SCHEDULE_TYPE_SCHEDULER    = 5002;
		public static final int SCHEDULE_TYPE_SYSRESET     = 5003;
		public static final int SCHEDULE_TYPE_NONE         = 5004;
		
		public boolean isSetted = false;
		
		List<TimeScheduleUnit> SchedulerData = new ArrayList<TimeScheduleUnit>();
		List<TimeScheduleUnit> GeneralData   = new ArrayList<TimeScheduleUnit>();
		public ScheduleManager() {
		}

		public class TimeScheduleUnit {		
			int 	 type;		
			Calendar TimeSet;
			String   message;
			TimeScheduleUnit(int sctype, Calendar target) {
				type = sctype;
				TimeSet = target;
			}

			TimeScheduleUnit(int sctype, Calendar target, String msg) {
				Log.i("MAINSCREEN","TimeScheduleUnit Create "+sctype+" : MSG : "+msg);
				type = sctype;
				TimeSet = target;
				message = msg;
			}
			
			public boolean isOver() {
				Calendar cal_now = new GregorianCalendar();
				if (cal_now.after(TimeSet)) {
					return true;
				}				
				return false;
			}
		}

		private void CheckSysResetData() {
			try {
				Calendar today = new GregorianCalendar();
				Log.i("MAINSCREEN","CheckSysResetData Schedule");
				WallpadStatusData WsDB = new WallpadStatusData(getApplicationContext());
				String[] ResetData = WsDB.GetResetSchedule();
				if (!ResetData[0].equals("NONE")) {
					int type = Integer.parseInt(ResetData[0]);
					Log.i("MAINSCREEN","CheckSysResetData Schedule check typr : "+type + " Week : "+today.get(Calendar.DAY_OF_WEEK)+" Set Week : "+ResetData[1]);
					if ((type == WallpadStatusData.RESET_MONTH && today.get(Calendar.DAY_OF_MONTH)+1 == Integer.parseInt(ResetData[1])) ||
						(type == WallpadStatusData.RESET_WEEK && today.get(Calendar.DAY_OF_WEEK) == (Integer.parseInt(ResetData[1]))+1)	)
					{
						if (today.get(Calendar.HOUR_OF_DAY) == Integer.parseInt(ResetData[2]) && today.get(Calendar.MINUTE) < 2) {
							SendAppFinishReqBR();
							ComponentName cn = new ComponentName("com.artncore.updater","com.artncore.updater.MainActivity");
							Intent intent = new Intent(Intent.ACTION_MAIN);
							intent.addCategory(Intent.CATEGORY_LAUNCHER);
							intent.putExtra("updatesystem", "no");
							intent.putExtra("updateapp", " no ");
							intent.putExtra("rebootcmd", "reboot");
							intent.setComponent(cn);
							startActivity(intent);	
						}
					}				
				}
				WsDB.closeDB();
			} catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
			    Log.e(TAG, "[Exception] CheckSysResetData()");
                LogUtil.errorLogInfo("", TAG, e);
			}
		}

		private boolean checkMorningCall() {
			try {
				WallpadStatusData WsDB = new WallpadStatusData(getApplicationContext());			
				int AlarmStatus = WsDB.GetAlarmStatus();
				
				if (AlarmStatus != WallpadStatusData.ALARM_NONE && AlarmStatus != WallpadStatusData.GUARD_IN && AlarmStatus != WallpadStatusData.ALARM_STOP) {
					WsDB.closeDB();
					return false;
				}
				Calendar today = new GregorianCalendar();
				
				int MCStatus = WsDB.GetMorningCallStatus();
				Log.i(TAG,"[checkMorningCall] GetMorningCallStatus : "+MCStatus);
				if (MCStatus==WallpadStatusData.MORNINGCALL_ON) {
					int MCPer = WsDB.GetMorningCallPeriod();
					Log.i(TAG,"[checkMorningCall] GetMorningCallPeriod : "+MCPer);
					int TodatofWeek = today.get(Calendar.DAY_OF_WEEK);
					if ((MCPer == WallpadStatusData.MORNINGCALL_EWORKDAY && TodatofWeek != Calendar.SUNDAY) || 
					    (MCPer == WallpadStatusData.MORNINGCALL_WORKDAY && TodatofWeek!=Calendar.SUNDAY && TodatofWeek != Calendar.SATURDAY) ||
					    (MCPer == WallpadStatusData.MORNINGCALL_ONCE || MCPer == WallpadStatusData.MORNINGCALL_EVERYDAY )) {

						Log.i(TAG,"[checkMorningCall] "+today.get(Calendar.HOUR_OF_DAY)+";"+WsDB.MorningHour + " -- " +today.get(Calendar.MINUTE)+":"+WsDB.MorningMin);

						if (today.get(Calendar.HOUR_OF_DAY) == WsDB.MorningHour && today.get(Calendar.MINUTE) == WsDB.MorningMin) {
							SendAppFinishReqBR();

                            mIOInterface.ctrlLcdWakeUp();
							
							StartPopup(ID.POPUPS.POPUP_MORNINGCALL);
							
							int[] MC_Doing = WsDB.GetMorningCallReserve();
							if (MC_Doing != null && MC_Doing.length > 0) {
								for (int k=0;k<MC_Doing.length;k++) {
									switch (MC_Doing[k]) {
										case WallpadStatusData.MCALLR_VENTIL_ON:
											mWallPadAPI.DeviceBatchControl(WallPadAPI.DEV_BATCH_CTRL__TYPE.VENTI, true);
											break;

										case WallpadStatusData.MCALLR_LIGHT_ON:
											//에너지 미터인 경우 안방 조명을 켜도록 하고
											//에너지 미터가 안 달린 경우 거실 조명을 켜도록 한다
                                            if (Version.getModelType() == Version.MODEL_TYPE.IHN_D101 || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I
                                                    || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K_I
                                                    || Version.getModelType() == MODEL_TYPE.IHN_D101_I_OCF) {
                                                // 안방조명에 1번 조명만 제어하도록 한다
                                                // 모닝콜이 울리면 일괄소등시나리오에 의해 일괄소등이 해제가 되겠네 ? 음.....이건 아닌데
                                                // 모닝콜이 울리는 동안만 켜고 끄자 일괄소등 시나리오를 해제할까나? 그러면 팝업 화면에서 제어처리를?
                                                Log.d(TAG, "[checkMorningCall] mSdbAPI Room 2 - Lamp 1 On");
                                                if (mSdbAPI != null) {
                                                    int nResult = mSdbAPI.SetLightOnOff((byte) 0x01, (byte) 0x00, true);
                                                    Log.d(TAG, "[checkMorningCall] mSdbAPI nResult = " + nResult);
                                                }
                                            }
											else if (Version.getModelType() == MODEL_TYPE.IHN_1010GL || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I
                                                    || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I_2443 || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I_6410) {
                                                Log.d(TAG, "[checkMorningCall] mIntLightAPI Living Room  - Lamp 1 On");
                                                if (mIntLightAPI != null) {
                                                    int nResult = mIntLightAPI.LightControl((byte) 0x01, true);
                                                    Log.d(TAG, "[checkMorningCall] mIntLightAPI nResult = " + nResult);
                                                }
											}
											else {
												// 대외향 구분하여 처리
												WallpadDeviceSet devDB = new WallpadDeviceSet( getApplicationContext() );
												int[] retArray = devDB.Get_Light_info();
												devDB.closeDB();
												if (retArray!= null && retArray[0] == 1) {
													if (retArray[1] == WallpadDeviceSet.LIGHT_TYPE_LIVING) {
														// 거실 스위치 
														if (m_LightCtrl !=  null) {
															m_LightCtrl.Refresh(false);
															m_LightCtrl.SetLightOnOff((byte)0x01, true);
														}
													}
													else {
														// 멀티 스위치 
														if (m_MultiSwitch !=  null) {
															m_MultiSwitch.Refresh((byte)0x00, false);
															if (m_MultiSwitch.data.DeviceCnt > 1) {
															    m_MultiSwitch.SetLightOnOff((byte)0x01 ,(byte)0x00 , true);    
															}
															else if(m_MultiSwitch.data.DeviceCnt == 1) {
															    m_MultiSwitch.SetLightOnOff((byte)0x00 ,(byte)0x00 , true);
															}														
														}
													}
												}
											}
											break;
										case	WallpadStatusData.MCALLR_CURTAIN_OPEN:  //fill lather
											break;												
									}
								}
							}
							
							if (MCPer == WallpadStatusData.MORNINGCALL_ONCE) {
	//							Button morning = (Button)findViewById(R.id.top_alarm);
	//							morning.setVisibility(View.INVISIBLE);
								WsDB.SetMorningCall(WallpadStatusData.MORNINGCALL_OFF,  WsDB.MorningHour, WsDB.MorningMin);
							}
						}					
				    }
				}
				WsDB.closeDB();
			} catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                LogUtil.errorLogInfo("", TAG, e);
			}
			return false;
		}
		
		private void scheduleCheck()
		{
			try
			{
				Log.d("scheduleCheck", "++++++++++++++++++++++++++++++++++++++++");
				Log.d("scheduleCheck", "Enter scheduleCheck "+GeneralData.size()+" : "+SchedulerData.size());
				checkMorningCall();
				if (GeneralData.size() > 0)
				{
					for (int i = 0;i < GeneralData.size(); i++)
					{
						TimeScheduleUnit scUnit = GeneralData.get(i);
				
						
						if (scUnit.isOver())
						{						
							switch (scUnit.type)
							{
								case  	SCHEDULE_TYPE_SYSRESET:
									GeneralData.remove(scUnit);
									Log.d("scheduleCheck", "++++++++++++++++++++++++++++++++++++++++ SCHEDULE_TYPE_SYSRESET");
									SendAppFinishReqBR();
									ComponentName cn = new ComponentName("com.artncore.updater","com.artncore.updater.MainActivity");
									Intent intent = new Intent(Intent.ACTION_MAIN);
									intent.addCategory(Intent.CATEGORY_LAUNCHER);
									intent.putExtra("updatesystem", "no");
									intent.putExtra("updateapp", "no");
									intent.putExtra("rebootcmd", "reboot");
									intent.setComponent(cn);
									startActivity(intent);								
									break;							
								case	SCHEDULE_TYPE_GETINFO:
									GeneralData.remove(scUnit);
									Log.d("scheduleCheck", "++++++++++++++++++++++++++++++++++++++++ SCHEDULE_TYPE_GETINFO");
									WallPadiMAPNotifyAPI notifyAPI = new WallPadiMAPNotifyAPI(getApplicationContext()); 
									notifyAPI.ReqGetSet();								
									break;				
							}
						}
					}
					
					Log.d("scheduleCheck", "after scheduleCheck "+GeneralData.size() );
				}
			}
			catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e)
			{
                LogUtil.errorLogInfo("", TAG, e);
			}

		}
		
		public void doSchedule(String mess, int cnt)
		{			
//			SendAppFinishReqBR();
//			Intent intent = new Intent(getApplicationContext(), schedulepopup.class);
//			String SendMSG = mess;
//			if (cnt > 1) SendMSG+=(" 외 "+cnt+"건을 알려드립니다.");
//			intent.putExtra("MESSAGE", SendMSG);			
//			Log.i("MAINSCREEN","Call Schedule POPUP");					
//			startActivity(intent);
		}		
		
		public void refreshSchedulerData()
		{			
			try
			{
				SchedulerData.clear();
				WallpadScheduleData schedata = new WallpadScheduleData(getApplicationContext());
				List<WallpadScheduleData.ScheduleData> scheduledata = schedata.GetTodaySchedule();
				Log.i("MAINSCREEN","refreshSchedulerData "+scheduledata.size());
				for(int i=0;i<scheduledata.size();i++)
				{
					WallpadScheduleData.ScheduleData ScUnit = scheduledata.get(i);
					int hour;
					int min;
					Log.i("MAINSCREEN","refreshSchedulerData "+ScUnit.inqatype+" : "+ScUnit.inqhour+" : ");
					if (ScUnit.inqatype.equals("no")) continue;				
					else if (ScUnit.inqatype.equals("intime")||ScUnit.inqatype.equals("day"))
					{
						hour = ScUnit.inqhour;
						min = 0;
					}
					else if (ScUnit.inqatype.equals("hour"))
					{
						hour = ScUnit.inqhour-1;
						if (hour < 0) continue;
						min = 0;
					}
					else if (ScUnit.inqatype.equals("min"))
					{
						hour = ScUnit.inqhour-1;
						if (hour < 0) continue;
						min = 50;
					}
					else
						continue;	
					Calendar today = new GregorianCalendar();
					int MoonM = 0;
					int MoonD = 0;
					try
					{
						String Moon = schedata.GetLunarDate(String.format("%04d%02d%02d", today.get(Calendar.YEAR),today.get(Calendar.MONTH)+1,today.get(Calendar.DAY_OF_MONTH) ));
						if(Moon!=null)
                        {
                            MoonM = Integer.parseInt(Moon.substring(4, 6));
                            MoonD = Integer.parseInt(Moon.substring(6, 8));
                            Log.i("MAINSCREEN", " Get Lunar Date "+Moon+" : "+MoonM+"/"+MoonD);
                        }

					}
					catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e)
					{
                        LogUtil.errorLogInfo("", TAG, e);
						MoonM = 0;
						MoonD = 0;					
					}
					today.set(Calendar.HOUR_OF_DAY, hour);
					today.set(Calendar.MINUTE, min);
					
					
					String Mesg = String.format("%04d년 %02d월 %02d일 (음 %02d/%02d)\n",today.get(Calendar.YEAR),today.get(Calendar.MONTH)+1,today.get(Calendar.DAY_OF_MONTH), MoonM, MoonD)+ScUnit.inqmsg;
					Log.i("MAINSCREEN","refreshSchedulerData add "+ScUnit.inqatype+" : "+ScUnit.inqhour+" : "+Mesg);
					TimeScheduleUnit newUnit = new TimeScheduleUnit(SCHEDULE_TYPE_SCHEDULER, today, Mesg);
					isSetted = true;
					SchedulerData.add(newUnit);				
				}		
				schedata.closeDB();
			
			}
			catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e)
			{
                LogUtil.errorLogInfo("", TAG, e);
			}
        }
		
		public void refreshMorningCall()
		{
			try
			{
				for (int i = 0; i <  GeneralData.size(); i++)
				{
					TimeScheduleUnit scUnit = SchedulerData.get(i);
					if (scUnit.type ==  SCHEDULE_TYPE_MORNINGCALL)
					{
						SchedulerData.remove(i);
						break;
					}
				}
				SetMorningCallData();
			}
			catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e)
			{
                LogUtil.errorLogInfo("", TAG, e);
			}
		}
		private void SetMorningCallData()
		{
			try
			{
				Log.i("MAINSCREEN","SetMorningCallData Schedule");
				Calendar today = new GregorianCalendar();
				WallpadStatusData WsDB = new WallpadStatusData(getApplicationContext());
				int MCStatus = WsDB.GetMorningCallStatus();
				if (MCStatus==WallpadStatusData.MORNINGCALL_ON)
				{
					int MCPer = WsDB.GetMorningCallPeriod();
					int TodatofWeek = today.get(Calendar.DAY_OF_WEEK);
					if ((MCPer == WallpadStatusData.MORNINGCALL_EWORKDAY && TodatofWeek != Calendar.SUNDAY) && 
					    (MCPer == WallpadStatusData.MORNINGCALL_WORKDAY && TodatofWeek!=Calendar.SUNDAY && TodatofWeek != Calendar.SATURDAY) &&
					    (MCPer == WallpadStatusData.MORNINGCALL_ONCE || MCPer == WallpadStatusData.MORNINGCALL_EVERYDAY ))
				    {
						today.set(Calendar.HOUR_OF_DAY, WsDB.MorningHour);
						today.set(Calendar.MINUTE, WsDB.MorningMin);
						today.set(Calendar.SECOND, 0);
						TimeScheduleUnit scUnit = new TimeScheduleUnit(SCHEDULE_TYPE_MORNINGCALL, today);
						if (!scUnit.isOver())
						{
							isSetted = true;
	//						Button morning = (Button)findViewById(R.id.top_alarm);
	//						morning.setVisibility(View.VISIBLE);
							GeneralData.add(scUnit);
						}
						else
						{
	//						Button morning = (Button)findViewById(R.id.top_alarm);
	//						morning.setVisibility(View.INVISIBLE);
						}
				    }
				}
				WsDB.closeDB();
			}
			catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e)
			{
                LogUtil.errorLogInfo("", TAG, e);
			}
		}
		
		public void refreshsysreset()
		{
			try
			{
				Log.i("MAINSCREEN","refreshsysreset Schedule");
				for (int i = 0; i <  GeneralData.size(); i++)
				{
					TimeScheduleUnit scUnit = SchedulerData.get(i);
					if (scUnit.type ==  SCHEDULE_TYPE_SYSRESET)
					{
						SchedulerData.remove(i);
						break;
					}
				}
				SetSysResetData();	
			}
			catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
		    catch (Exception e)
			{
                LogUtil.errorLogInfo("", TAG, e);
			}
		}
		
		private void SetSysResetData()
		{
			try
			{
				Calendar today = new GregorianCalendar();
				Log.i("MAINSCREEN","SetSysResetData Schedule");
				WallpadStatusData WsDB = new WallpadStatusData(getApplicationContext());
				String[] ResetData = WsDB.GetResetSchedule();
				if (!ResetData[0].equals("NONE"))
				{
					
					int type = Integer.parseInt(ResetData[0]);
					if ((type == WallpadStatusData.RESET_MONTH && today.get(Calendar.DAY_OF_MONTH) == Integer.parseInt(ResetData[1])) ||
						(type == WallpadStatusData.RESET_WEEK && today.get(Calendar.DAY_OF_WEEK) == Integer.parseInt(ResetData[1]))	)
					{
						Log.i("MAINSCREEN","SetSysResetData Setted");
						today.set(Calendar.HOUR_OF_DAY, Integer.parseInt(ResetData[2]));
						today.set(Calendar.MINUTE, 0);
						today.set(Calendar.SECOND, 0);
						TimeScheduleUnit scUnit = new TimeScheduleUnit(SCHEDULE_TYPE_SYSRESET, today);
						if (!scUnit.isOver())
						{
							isSetted = true;
							GeneralData.add(scUnit);
						}
					}				
				}
				WsDB.closeDB();
			}
			catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e)
			{
                LogUtil.errorLogInfo("", TAG, e);
			}
		}
		public void refreshSchedule()
		{		
			try
			{
				Log.i("MAINSCREEN","Refresh Schedule");
				GeneralData.clear();			
				Calendar today = new GregorianCalendar();
				// 하루에 한번 가져오는 걸로 변경함
				//if (today.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
				{			
					WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
					AddressSet addc =  SetData.getAddressMGR();
					SetData.closeDB();
					int dong = Integer.parseInt(addc.Dong);
					
					int ho = 101;
					if(addc.UseOrNotRentHouse == true)
					{
					    ho = addc.Ho_Integer;
					}
					else
					{
					    ho = Integer.parseInt(addc.Ho); 
					}					   
					
					int interval = (dong-(dong/100)*100) * 100 + ho/100;
					int hour;
					int min;
					int sec;
					if (interval/3600 > 0)
					{
						hour = 3+interval/3600;
						interval=interval%3600;
					}
					else hour = 3;
					
					if (interval/60 > 0)
					{
						min = interval/60;
						sec = interval%60;
					}
					else
					{
						min = 0;
						sec = interval;
					}
					today.set(Calendar.HOUR_OF_DAY, hour);
					today.set(Calendar.MINUTE, min);
					today.set(Calendar.SECOND, sec);
					TimeScheduleUnit scUnit = new TimeScheduleUnit(SCHEDULE_TYPE_GETINFO, today);
					if (!scUnit.isOver())
						GeneralData.add(scUnit);				
				}
				
				SetMorningCallData();			
				SetSysResetData();	
				refreshSchedulerData();
			}
			catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e)
			{
                LogUtil.errorLogInfo("", TAG, e);
			}
		}
	}

	class runCallServices extends Thread {
		public runCallServices() {
			super();
		}
		
		public void run() {
			try {
			    if (Version.getPlatformType() == Version.PLATFORM_TYPE.A40i) {
                    if (getIsSubWallpad()) {
                        Log.w(TAG, "[runCallServices.run()] ############### This wallpad is set as a sub-wallpad ###############");
                        Intent SubWallpadServiceLauncher = new Intent ("kr.co.icontrols.callengine.subwallpad.SubWallPadSerialManager.StartService");
                        getApplicationContext().startService(SubWallpadServiceLauncher);
                    }
                    else {
                        Log.w(TAG, "[runCallServices.run()] ############### This wallpad is set as a main-wallpad ###############");
                        // SIP/Subphone 서비스 실행
                        Intent SIPServiceLauncher = new Intent ("kr.co.icontrols.callengine.sip.SIPStun.StartService");
                        getApplicationContext().startService(SIPServiceLauncher);

                        Intent SubPhoneServiceLauncher = new Intent ("kr.co.icontrols.callengine.subphone.SubPhoneSerialManager.StartService");
                        getApplicationContext().startService(SubPhoneServiceLauncher);

                        if (GetRemoteCallUseInfo()) {
                            Intent remoteCallServiceLauncher = new Intent ("kr.co.icontrols.callengine.remotecall.RemoteCallManager.StartService");
                            getApplicationContext().startService(remoteCallServiceLauncher);
                        }
                    }
                }
			    else {
                    int nModelType = Version.getModelType();
			        if (nModelType == MODEL_TYPE.IHN_750) {
                        // SIP 서비스만 실행
                        Intent sipServiceLauncher = new Intent ("kr.co.icontrols.callengine.sip.SIPStun.StartService");
                        getApplicationContext().startService(sipServiceLauncher);
                    }
			        else {
                        // SIP/PSTN/Subphone 서비스 실행
                        Intent sipServiceLauncher = new Intent ("kr.co.icontrols.callengine.sip.SIPStun.StartService");
                        getApplicationContext().startService(sipServiceLauncher);

                        Intent PSTNServiceLauncher = new Intent ("kr.co.icontrols.callengine.pstn.PSTNSerialManager.StartService");
                        getApplicationContext().startService(PSTNServiceLauncher);

                        Intent SubPhoneServiceLauncher = new Intent ("kr.co.icontrols.callengine.subphone.SubPhoneSerialManager.StartService");
                        getApplicationContext().startService(SubPhoneServiceLauncher);
                    }
                }
			} catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
				Log.e(TAG, "[Exception] runCallServices().run()");
                LogUtil.errorLogInfo("", TAG, e);
			}
		}
	}

    // 방문객원격통화 솔루션 사용여부 판별
    private boolean GetRemoteCallUseInfo() {
        try {
            WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(this);
            if (mWallpadDeviceSet != null) {
                String[] astrRemoteCall = mWallpadDeviceSet.GetSettingData("방문객원격통화");
                if (astrRemoteCall != null) {
                    if (astrRemoteCall[1].contains("사용함"))
                        return true;
                } else {
                    Log.d(TAG, "[GetRemoteCallUseInfo] astrRemoteCall is null!!");
                }
            }
            mWallpadDeviceSet.closeDB();
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] GetRemoteCallUseInfo()");
            LogUtil.errorLogInfo("", TAG, e);
        }
        return false;
    }

	int UNINSTALL_REQUEST_CODE = 1;
	private void uninstallAnCCallApp(String strAPK) {
		try {
			Log.w(TAG, "[uninstallAnCCallApp] strAPK [" + strAPK + "]");
			if (checkAppInstalled(strAPK)) {
//				Intent mIntent = new Intent(Intent.ACTION_DELETE);
				Intent mIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
				mIntent.setData(Uri.parse("package:" + strAPK));
				mIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
				startActivityForResult(mIntent, UNINSTALL_REQUEST_CODE);
			}
			else {
				Log.w(TAG, "[uninstallAnCCallApp] Not installed [" + strAPK + "]");
			}
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {;
			Log.e(TAG, "[Exception] uninstallAnCCallApp()");
            LogUtil.errorLogInfo("", TAG, e);
		}
	}

	private boolean checkAppInstalled(String strAPK) {
		try {
			PackageManager mPackageManager = getPackageManager();
			try {
				mPackageManager.getPackageInfo(strAPK, PackageManager.GET_ACTIVITIES);
				return true;
			} catch (PackageManager.NameNotFoundException pne) {
				Log.w(TAG, "[checkAppInstalled] No Package [" + strAPK + "]");
			}
			return false;
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
			Log.e(TAG, "[Exception] checkAppInstalled(String strAPK)");
            LogUtil.errorLogInfo("", TAG, e);
			return false;
		}
	}

	private boolean MainSubScreenLoadingComplite = false;
	public boolean getMainSubScreenLoadingComplite() {
		return MainSubScreenLoadingComplite;
	}

	/**
     * 설치된 모든 어플의 이름/버전정보 Version DB에 저장하는 쓰레드. <br>
     * main Activity 생성 시 최초 1회 실행 후 die
     */
    class getInstalledPackageInfo extends Thread {
        @Override 
        public void run() {
        	super.run();
        	try {
                Log.d(TAG, "[getInstalledPackageInfo] Started getting installed package infomation");
            	ArrayList<PackageVersionInfo> PackageVersionInfos = new ArrayList<PackageVersionInfo>();
                List<PackageInfo> PackageInfoList = getPackageManager().getInstalledPackages(PackageManager.PERMISSION_GRANTED);

                while (true) {
                    Log.d(TAG, "[getInstalledPackageInfo.run()] Get installed packages start!!");
                    try {
                        for (PackageInfo pack : PackageInfoList) {
                            Log.d(TAG, "# PackageName : " + pack.packageName);
                            Log.d(TAG, "# VersionName   : " + pack.versionName);
                            if ((pack.packageName.contains("icontrols")) || (pack.packageName.contains("artncore")) || (pack.packageName.contains("dadam"))) {
                                PackageVersionInfos.add(new PackageVersionInfo(pack.packageName, pack.versionName));
                            }
                        }
                    } catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                        break;
                    }
                    catch (Exception e) {
                        LogUtil.errorLogInfo("", TAG, e);
                        break;
                    }
                    Log.d(TAG, "[getInstalledPackageInfo.run()] Get installed packages end!!");
                    break; 
                }

                Log.d(TAG, "[getInstalledPackageInfo.run()] Save installed packages start!!");
                wallpaddbmgr WallpadDBMGR = new wallpaddbmgr(getApplicationContext());
                if (PackageVersionInfos != null) {
                    for (int i = 0; i < PackageVersionInfos.size(); i++) {
                        WallpadDBMGR.UpdateVersionData(PackageVersionInfos.get(i).getPackageName(), PackageVersionInfos.get(i).getPackageVersion());
                    }
                }
                WallpadDBMGR.closeDB();
                Log.d(TAG, "[getInstalledPackageInfo.run()] Save installed packages end!!");

        		try {
        		    Thread.sleep(1500);
        		} catch (RuntimeException re) {
                    LogUtil.errorLogInfo("", TAG, re);
                }
                catch (Exception e) {
                    LogUtil.errorLogInfo("", TAG, e);
        		}

        		if (Version.getModelType() == Version.MODEL_TYPE.IHN_1020B_C || Version.getModelType() == Version.MODEL_TYPE.IHN_1030_D) {
        			try {
        			    Thread.sleep(1000);
        			} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
                        LogUtil.errorLogInfo("", TAG, e);
        			}
        		}

        		runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        registerSubScreen();
                    }
                });
        		
        		try
        		{
					WallpadScheduleData schedb = new WallpadScheduleData(getApplicationContext());
					boolean bLunarTableExist = schedb.CheckLunarTable();
                    schedb.closeDB();
					
					if (!bLunarTableExist) {
					    try {
			                Log.d(TAG, "DB File Copy Start");
			                copyDataBase(wallpaddbmgr.dblocation + "/" + wallpaddbmgr.Schedule_LunaDB);
			                Log.d(TAG, "DB File Copy End");
			            } catch (IOException e) {
                            LogUtil.errorLogInfo("", TAG, e);
			            }
					}
        		} catch (RuntimeException re) {
                    LogUtil.errorLogInfo("", TAG, re);
                }
                catch (Exception e) {
                    LogUtil.errorLogInfo("", TAG, e);
        		}
        		
//                if (Version.getModelType() == Version.MODEL_TYPE.IHN_1020B_C || Version.getModelType() == Version.MODEL_TYPE.IHN_1030_D) checkDongHoSetting();
                checkDongHoSetting();
                
	            if (Common.GetElevatorSampleMode(getApplicationContext())) {
	    	        int retCount = EnergyAlramPopupMgr.get_WallPadRebootingCount( getApplicationContext()) + 1;
	    	        EnergyAlramPopupMgr.set_WallPadRebootingCount(getApplicationContext(), retCount);
	    	        Log.d(TAG, "################################# rebooting Count : " + retCount );
	            }
	            
    			// 하드웨어 키 샘플 모드 동작 여부 설정 
    			WallpadSalesSampleData sdata = new  WallpadSalesSampleData(getApplicationContext());
    	        int salsesampleHWBtn  = sdata.getSalesSampleData(WallpadSalesSampleData.SALES_SAMPLE_MODE_HW_BUTTON_OPERATION);
    	        sdata.closeDB();
    	        
    	        WallPadInterface wpdifc  = new WallPadInterface();   
    	        if (salsesampleHWBtn == WallpadSalesSampleData.SALES_SAMPLE_MODE_DO_NOT_USED)
    	    		wpdifc.DoControl(WallPadInterface.IOCTL_KEY_ONOFF_SET, 0);
    	        
    	        CheckEnv();
        	}
        	catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e)
        	{
                LogUtil.errorLogInfo("", TAG, e);
        	}
        	
        try {Thread.sleep(5000);}
        catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            MainSubScreenLoadingComplite = true;
        }
		catch (Exception e){LogUtil.errorLogInfo("", TAG, e);}
        	MainSubScreenLoadingComplite = true;
        } 
    }
    
    public static String DB_WALLPAD_WIDGET_INIT = "DB_WALLPAD_WIDGET_INIT";
    
	public void set_WallPadWidgetInit(Context context) {
		try {
			wallpaddbmgr mgr = new wallpaddbmgr(context);
			boolean bRet = mgr.UpdateWallPADData(DB_WALLPAD_WIDGET_INIT, String.valueOf(1));
			if (bRet == false ) {
				Log.d(TAG, "----- DB_WALLPAD_WIDGET_INIT insert ==> false ");
				mgr.insertWallPADDB(DB_WALLPAD_WIDGET_INIT, "1");
			}
			mgr.closeDB();
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            LogUtil.errorLogInfo("", TAG, e);
		}
	}
	
	public int get_WallPadWidgetInit(Context context) {
		int ret = 0;
		try {
			wallpaddbmgr mgr = new wallpaddbmgr(context);
			String strRet = mgr.GetWallPADData(DB_WALLPAD_WIDGET_INIT);
			if (strRet == null) {
				Log.d(TAG, "----- get_WallPadRebootingCount strRet == null && insert ==> false ");
				mgr.insertWallPADDB(DB_WALLPAD_WIDGET_INIT, "0");
				return 0;
			}
			
			ret = Integer.parseInt(strRet);
			mgr.closeDB();
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            LogUtil.errorLogInfo("", TAG, e);
		}
		return ret;	
	}
	
     
    /**
     * 스케줄 관련 처리 핸들러 추가
     * 모닝콜, 일정관리, 엘리베이터 호출상태, 에너지 사용량 확인
     * 현재는 사용하지 않음. checkTimeTasks()로 대체
     */
	private int nDay, nHour, nMin;
    Handler Checker =  new Handler() {

		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Calendar cal = new GregorianCalendar();
			if (cal.get(Calendar.DAY_OF_MONTH) != nDay) {
				// 날짜가 바뀌었을때...
				nDay = cal.get(Calendar.DAY_OF_MONTH);

				Log.d(TAG , "-----------------day change repeat");
				if (SCManager != null) {
					if (SYSTEM_TIME_SET)SCManager.refreshSchedule();
				}
				//
//				Intent intent = new Intent();
//				intent.setAction(define.NOTIFY_ACNAME);
//				intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_DAYCHANGED);
//				getApplicationContext().sendBroadcast(intent);

				//에너지사용량 알림 초기화
				ClearEnergyUsage();

				Log.d(TAG , "cal.get(Calendar.YEAR) :" + cal.get(Calendar.YEAR) );

				if ((bUseofNot_ZeroEnergyHouseInfo == true) && (cal.get(Calendar.YEAR) > 2016) && (SYSTEM_TIME_SET == true)) {
		            //어제 시간 재입력
		            Log.d(TAG , "/**********************************************/");
		            Log.d(TAG , "GetZeroEnergyHouseInfo_RandomCheckHandler(true);");
		            Log.d(TAG , "/**********************************************/");

		            DayofLastSecond = StringUtil.GetDayofLastSecondTimeString(cal); //하루전 날짜의 마지막 시간 입력
		            Log.d(TAG , "DayofLastSecond : "+ DayofLastSecond);
                }
			}

			if (cal.get(Calendar.HOUR_OF_DAY) != nHour) {
				nHour = cal.get(Calendar.HOUR_OF_DAY);
				DoScheduleHourUnit(cal);
			}

			if (cal.get(Calendar.MINUTE) != nMin) {
				nMin = cal.get(Calendar.MINUTE);

                /**
                 * A20월패드 BSP는 전자액자 실행을 시키지 않기때문에 main app에서 전자액자 실행 여부 확인하여
                 * 실행시킴
                 * **/
                if (Version.getPlatformType() == Version.PLATFORM_TYPE.A20) {
                    Log.i(TAG, "[Checker handler] ========== JEFF 1 ========== m_LiveMainActivity : " + m_LiveMainActivity);
                    if (m_LiveMainActivity > 0) {
                        String LCD_Sleep_Status = null;

                        Runtime runtime = Runtime.getRuntime();
                        Process process;

                        try {
                            String cmd = "getprop persist.sys.display.lcdoff";
                            process = runtime.exec(cmd);
                            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                            String line;
                            while ((line = br.readLine()) != null) {
                                LCD_Sleep_Status = line;
                            }
                        } catch (RuntimeException re) {
                            LogUtil.errorLogInfo("", TAG, re);
                        }
                        catch (Exception e) {
                            e.fillInStackTrace();
                            Log.e("Process Manager", "Unable to execute top command");
                        }

                        if (LCD_Sleep_Status != null) {
                            Log.d(TAG, "The LCD_Sleep_Status : " + LCD_Sleep_Status);
                            if (LCD_Sleep_Status.equals("1") == true) {
                                // LCD 꺼져있음
                                WallpadStatusData SettData = new WallpadStatusData(getApplicationContext());

                                if (SettData.DecideAutoPictureAppStartOrNot(new GregorianCalendar())) {
                                    if (SettData.StartAutoPictureAPP() == true) {
                                        Log.d(TAG, "StartAutoPictureAPP is true");
//                                        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//                                        pm.userActivity(2, true);
                                        // LCD backlight normal
                                        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                                        Log.d(TAG, "PowerManager will be set");
                                    }
                                    else {
                                        Log.d(TAG, "StartAutoPictureAPP is false");
                                    }
                                }
                                else {
                                    Log.d(TAG, "DecideAutoPictureAppStartOrNot is false");
                                }
                                SettData.closeDB();
                            }
                        }
                        else {
                            Log.e(TAG, "The LCD_Sleep_Status is null");
                        }
                    }
                }
                if (Version.getPlatformType() == Version.PLATFORM_TYPE.A40i) {
                    Log.i(TAG, "[Checker handler] ========== JEFF 2 ========== m_LiveMainActivity : " + m_LiveMainActivity);
                    if (m_LiveMainActivity > 0) {
                        boolean bisScreenOn = false;
                        if (getCompareBSPVersion()) {
                            bisScreenOn = checkLCDOnByCMD();
                        }
                        else {
                            PowerManager mPowerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
                            bisScreenOn = mPowerManager.isScreenOn();
                        }

                        Log.i(TAG, "[Checker handler] bisScreenOn : " + bisScreenOn);

                        if (!bisScreenOn) {
                            if (getBlackoutStatus()) {
                                Log.i(TAG, "[Checker handler] getBlackoutStatus is true!!!");
                                sendBlackoutScreenRunBR();
                            }
                            else {
                                WallpadStatusData SettData = new WallpadStatusData(getApplicationContext());

                                if (SettData.DecideAutoPictureAppStartOrNot(new GregorianCalendar())) {
                                    if (SettData.StartAutoPictureAPP() == true) {
                                        Log.d(TAG, "StartAutoPictureAPP is true");
                                        mIOInterface.ctrlLcdWakeUp();
                                        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                                        Log.d(TAG, "PowerManager will be set");
                                    }
                                    else {
                                        Log.d(TAG, "StartAutoPictureAPP is false");
                                    }
                                }
                                else {
                                    Log.d(TAG, "DecideAutoPictureAppStartOrNot is false");
                                }
                                SettData.closeDB();
                            }
                        }
                    }
                }


				if ((nMin == 50) || (nMin == 0)) {
					try {
						checkScheduleReminder();
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
                        LogUtil.errorLogInfo("", TAG, e);
					}

						// 스케줄 일정 알람 팝업을 띄우도록 한다.

//						Intent intent = new Intent(getApplicationContext(), schedulepopup.class);
//						String SendMSG = doSchedule.get(0).inqmsg;
//						if (doSchedule.size() > 1) SendMSG+=(" 외 "+doSchedule.size()+"건을 알려드립니다.");
//						intent.putExtra("MESSAGE", SendMSG);
//
//						startActivity(intent);
				}

				if (SCManager != null) SCManager.scheduleCheck();
				//CheckElevator();

				if (MAX_BOOTUP_RETRY_COUNT < bootupretryCNT && SYSTEM_TIME_SET == false) {
					try {
						WallPadiMAPNotifyAPI iMAPMethod = new WallPadiMAPNotifyAPI(getApplicationContext());
						iMAPMethod.ReqGetSet();
					} catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
                        LogUtil.errorLogInfo("", TAG, e);
					}
				}

				// 중복.... 이게 왜 있는겨....
//				if ( cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY && SYSTEM_TIME_SET && cal.get(Calendar.DAY_OF_MONTH)!=LastTimeSync)
//				{
//					Calendar checktime  = GetTimeSyncTime();
//					if (checktime != null)
//					{
//						if (cal.after(checktime))
//						{
//							LastTimeSync = cal.get(Calendar.DAY_OF_MONTH);
//							WallpadStatusData wpd = new WallpadStatusData(getApplicationContext());
//							wpd.SetLastTimeSyncDate(LastTimeSync);
//							wpd.closeDB();
//							WallPadiMAPNotifyAPI iMAPMethod = new WallPadiMAPNotifyAPI(getApplicationContext());
//							iMAPMethod.ReqGetSet();
//						}
//					}
//				}

				//주차정보 관련 20분 마다 얻어오기
				if (bUseofNot_ParkingInfo == true) {
                    cGetParkingMin++;
                    //테스트
                    /*
                    bSetMSG_GetParkingInfo = true;
                    LoadParkingDataFromServer();
                    */

                    if (cGetParkingMin >= 20) {
						// 20분으로 고정
                        cGetParkingMin = 0;

                        //아이콘트롤스 일때도 처리하지 않도록 수정필요
                        //넥스파인 경우는 협의후 처리
                        switch (nParkingSystemType) {
                            case Common.PARKING_SYSTEM_ICONTROLS:
                            case Common.PARKING_SYSTEM_NEXPA:
                            case Common.PARKING_SYSTEM_UPIS:
                            case Common.PARKING_SYSTEM_IES_100:
                                break;

                            case Common.PARKING_SYSTEM_BASIC:
                            case Common.PARKING_SYSTEM_ETC:
                                GetParkingInfo_RandomCheckHandler(); //주차 정보 얻어오기
                                break;

                            default:
                                break;
                        }
                    }
                }

				// 필요없는 코드 삭제 ( yskim 2015.03.31 )
//				String checkDate = String.format("%04d%02d%02d",cal.get(Calendar.YEAR),cal.get(Calendar.MONTH)+1,cal.get(Calendar.DAY_OF_MONTH));
//				WallpadStatusData energyData = new WallpadStatusData(getApplicationContext());
//				String EnergyCheckData = energyData.GetEnergyCheckDate();
//				energyData.closeDB();
//				if (SYSTEM_TIME_SET)
//				{
//					Calendar checktime  = GetEnergyDataLoadingTime();
//					if (!checkDate.equals(EnergyCheckData))
//					{
//						if (checktime != null)
//						{
//
//							if (cal.after(checktime))
//							{
//								WallPadiMAPNotifyAPI iMAPMethod = new WallPadiMAPNotifyAPI(getApplicationContext());
//								iMAPMethod.GetEnergyUsage();
//								WallPadiMAPNotifyAPI iMAPMethod2 = new WallPadiMAPNotifyAPI(getApplicationContext());
//								iMAPMethod2.GetEnergyUsageMonth();
//							}
//						}
//					}
//				}
			}

//            checkMainPage();

			Checker.sendEmptyMessageDelayed(0, 1000);
		}
	};


    /**
     * JEFF, 2019.12.25
     * 매 1초마다 실행되면서 스케쥴 확인하여 각 기능을 동작시킨다 (시간업데이트, 전자액자 등)
     */
    Handler handlerEverySecond =  new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            checkTimeTasks();
            handlerEverySecond.sendEmptyMessageDelayed(0, 1000);
        }
    };

    private void checkTimeTasks() {
        try {
//            Log.d(TAG , "[checkTimeTasks] ===== START =====");
            Calendar cal = new GregorianCalendar();
            if (cal.get(Calendar.DAY_OF_MONTH) != nDay) {
                // 날짜 변경시
                Log.d(TAG , "[checkTimeTasks] day changed!!");
                nDay = cal.get(Calendar.DAY_OF_MONTH);
                if (SCManager != null) {
                    if (SYSTEM_TIME_SET) SCManager.refreshSchedule();
                }
                else {
                    Log.w(TAG , "[checkTimeTasks] SYSTEM_TIME_SET is null!!");
                }

                // 모바일연동 서비스로 원격검침 데이터를 전송
//                getTelemeteringDataOnRandomTime();
//                // 에너지사용량 알림 초기화
//                ClearEnergyUsage();

                Log.d(TAG , "[checkTimeTasks] Calendar.YEAR = " + cal.get(Calendar.YEAR) );

                if ((bUseofNot_ZeroEnergyHouseInfo == true) && (cal.get(Calendar.YEAR) > 2016) && (SYSTEM_TIME_SET == true)) {
                    //어제 시간 재입력
                    Log.i(TAG , "[checkTimeTasks] GetZeroEnergyHouseInfo_RandomCheckHandler(true);");
                    DayofLastSecond = StringUtil.GetDayofLastSecondTimeString(cal); //하루전 날짜의 마지막 시간 입력
                    Log.d(TAG , "[checkTimeTasks] DayofLastSecond : "+ DayofLastSecond);
                }
            }

            if (cal.get(Calendar.HOUR_OF_DAY) != nHour) {
                nHour = cal.get(Calendar.HOUR_OF_DAY);
                // 원격검침 데이터를 서버로부터 가져와 관련 기능모듈에 알린다.
                getTelemeteringDataOnRandomTime();
                DoScheduleHourUnit(cal);
            }

            if (getBlackoutStatus()) {
                Log.i(TAG, "[checkTimeTasks] getBlackoutStatus is true!!!");
                sendBlackoutScreenRunBR();
            }

            if (cal.get(Calendar.MINUTE) != nMin) {
                nMin = cal.get(Calendar.MINUTE);

                /**
                 * main app에서 전자액자 실행 여부 확인하여 실행시킴
                 * **/
                if (Version.getPlatformType() == Version.PLATFORM_TYPE.A40i) {
                    Log.i(TAG, "[checkTimeTasks] m_LiveMainActivity : " + m_LiveMainActivity);
                    if (m_LiveMainActivity > 0) {
                        boolean bScreenOn = false;

                        if (getCompareBSPVersion()) {
                            bScreenOn = checkLCDOnByCMD();
                        }
                        else {
                            PowerManager mPowerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
                            bScreenOn = mPowerManager.isScreenOn();
                        }

                        Log.i(TAG, "[checkTimeTasks] bScreenOn : " + bScreenOn);

                        if (!bScreenOn && !getBlackoutStatus()) {
                            WallpadStatusData SettData = new WallpadStatusData(getApplicationContext());

                            if (SettData.DecideAutoPictureAppStartOrNot(new GregorianCalendar())) {
                                if (SettData.StartAutoPictureAPP() == true) {
                                    Log.d(TAG, "[checkTimeTasks] StartAutoPictureAPP() is true");
                                    mIOInterface.ctrlLcdWakeUp();
                                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                                    Log.d(TAG, "[checkTimeTasks] PowerManager will be set");
                                }
                                else {
                                    Log.d(TAG, "[checkTimeTasks] StartAutoPictureAPP() is false");
                                }
                            }
                            else {
                                Log.d(TAG, "[checkTimeTasks] DecideAutoPictureAppStartOrNot(...) is false");
                            }
                            SettData.closeDB();
                        }
                    }
                }


                if ((nMin == 50) || (nMin == 0)) {
                    try {
                        checkScheduleReminder();
                    } catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
                        LogUtil.errorLogInfo("", TAG, e);
                    }
                }

                if (SCManager != null) SCManager.scheduleCheck();

                if (MAX_BOOTUP_RETRY_COUNT < bootupretryCNT && SYSTEM_TIME_SET == false) {
                    try {
                        WallPadiMAPNotifyAPI iMAPMethod = new WallPadiMAPNotifyAPI(getApplicationContext());
                        iMAPMethod.ReqGetSet();
                    } catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    }
                    catch (Exception e) {
                        LogUtil.errorLogInfo("", TAG, e);
                    }
                }

                //주차정보 관련 20분 마다 얻어오기
                if (bUseofNot_ParkingInfo == true) {
                    cGetParkingMin++;
                    //테스트
                    /*
                    bSetMSG_GetParkingInfo = true;
                    LoadParkingDataFromServer();
                    */

                    if (cGetParkingMin >= 20) {
                        // 20분으로 고정
                        cGetParkingMin = 0;

                        //아이콘트롤스 일때도 처리하지 않도록 수정필요
                        //넥스파인 경우는 협의후 처리
                        switch(nParkingSystemType) {
                            case Common.PARKING_SYSTEM_ICONTROLS:
                            case Common.PARKING_SYSTEM_NEXPA:
                            case Common.PARKING_SYSTEM_UPIS:
                            case Common.PARKING_SYSTEM_IES_100:
                                break;

                            case Common.PARKING_SYSTEM_BASIC:
                            case Common.PARKING_SYSTEM_ETC:
                                GetParkingInfo_RandomCheckHandler(); //주차 정보 얻어오기
                                break;

                            default:
                                break;
                        }
                    }
                }
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkTimeTasks()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }




	/**
	 * 일정 알림 팝업창 생성하는 함수<br>
	 * 김용성 과장님 이곳에서 팝업창 생성해주시기 바랍니다.
	 * @param popup_msg 팝업창에 띄울 메시지.
	 * **/	
	private void MakePopup_Schedule(String popup_msg) {
		try {
            Log.e(TAG, "[MakePopup_Schedule] popup_msg [" + popup_msg + "]");
	        DebugLogOutput("===================================");
	        DebugLogOutput(popup_msg);
	        DebugLogOutput("===================================");
	        WallpadStatusData mWallpadStatusData = new WallpadStatusData(getApplicationContext());
	        int AlarmStatus = mWallpadStatusData.GetAlarmStatus();
	        boolean soundOut = mWallpadStatusData.GetSoundOutputOfEventAlarm();
            mWallpadStatusData.closeDB();
	        Log.e(TAG, "[MakePopup_Schedule] ========== JEFF 1 ==========");
	        if (AlarmStatus != WallpadStatusData.ALARM_ARISE && AlarmStatus != WallpadStatusData.GUARD_OUT && AlarmStatus != WallpadStatusData.GUARD_OUT_WAIT) {
                Log.e(TAG, "[MakePopup_Schedule] ========== JEFF 2 ==========");
	        	if (!Common.bWallPadCallLive) {
                    Log.e(TAG, "[MakePopup_Schedule] ========== JEFF 3 ==========");
	        		Common.SendAppFinishReqBR(getApplicationContext());
                    PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
                    Log.d(TAG, "[MakePopup_Schedule] Screen On: " + mPowerManager.isScreenOn());

                    if (getCompareBSPVersion()) {
                        if (!checkLCDOnByCMD()) {
                            mIOInterface.ctrlLcdWakeUp(); // 절전상태일 경우, jni LcdWakeUp 먼저 호출
                        }
                    }
                    else {
                        if (!mPowerManager.isScreenOn()) {
                            Log.d(TAG, "[MakePopup_Schedule] V40Interface LcdWakeUp Call!!");
                            mIOInterface.ctrlLcdWakeUp(); // 절전상태일 경우, jni LcdWakeUp 먼저 호출
                        }
                    }

                    ((MainActivity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	        		// 알람 소리를 내준다.
					if (soundOut) {
                        Log.e(TAG, "[MakePopup_Schedule] ========== JEFF 4 ==========");
						Sound().Play(SND.effect.EFFECT1);
					}
                    Log.e(TAG, "[MakePopup_Schedule] ========== JEFF 5 ==========");
	        		EnergyAlramPopupMgr.SchedulePopupMsg = popup_msg;
                    Log.e(TAG, "[MakePopup_Schedule] ========== JEFF 6 ==========");
	        		StartPopup(ID.POPUPS.POPUP_SCHEDULENOTIFICATION);
                    Log.e(TAG, "[MakePopup_Schedule] ========== JEFF 7 ==========");
	        	}
	        }
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
		    Log.e(TAG, "[Exception] MakePopup_Schedule(String popup_msg)");
            LogUtil.errorLogInfo("", TAG, e);
		}
	}

	/**
	 * 일정 알림 시간 비교!
	 * **/
	private void checkScheduleReminder() {
	    try {
	        Calendar ScheduleCal = Calendar.getInstance();
            Log.i(TAG, "[checkScheduleReminder] ScheduleCal: " + ScheduleCal.getTime());
            WallpadScheduleData SCData = new WallpadScheduleData(getApplicationContext());
//            List<WallpadScheduleData.ScheduleData> scheduleDataDB = SCData.NewGetScheduleDataForMainActivity(ScheduleCal.get(Calendar.YEAR), ScheduleCal.get(Calendar.MONTH) + 1, ScheduleCal.get(Calendar.DAY_OF_MONTH));
            List<WallpadScheduleData.ScheduleData> scheduleDataDB = SCData.getScheduledInfoforMainActivity();
            SCData.closeDB();

            if (scheduleDataDB != null) {
                Log.i(TAG, "scheduleDataDB.size() [" + scheduleDataDB.size() + "]");
                for (int i = 0; i < scheduleDataDB.size(); i++) {
                    DebugLogOutput("[checkScheduleReminder] ===================================");
                    DebugLogOutput("[checkScheduleReminder] index [" + i + "], year [" + scheduleDataDB.get(i).inqyear + "], month [" + scheduleDataDB.get(i).inqmonth + "], day [" + scheduleDataDB.get(i).inqday + "], hour [" + scheduleDataDB.get(i).inqhour + "]");
                    DebugLogOutput("[checkScheduleReminder] msg [" + scheduleDataDB.get(i).inqmsg + "], seq [" + scheduleDataDB.get(i).seqnum + "]");
                    /**
                     * inqttype: 음력여부 - {"moon", "sun"}
                     * inqctype: 주기 - no:없음 or month:매월주기 or year:매년주기
                     * inqatype: 알림 - {"no","intime","min","hour","day"} := {안울림, 정각, 10분전, 1시간전, 하루전}
                     * inqitype: 행사 - {"birth","memorial","appoint","trip","first","wedding","tax","meeting","car","ancestor"} := {생일,기념일,약속,여행,돌,결혼,공과금,차량점검,제사}
                     */
                    DebugLogOutput("[checkScheduleReminder] lunar [" + scheduleDataDB.get(i).inqttype + "], cycle [" + scheduleDataDB.get(i).inqctype + "], remindtime [" + scheduleDataDB.get(i).inqatype + "], event [" + scheduleDataDB.get(i).inqitype + "]");
                    DebugLogOutput("[checkScheduleReminder] ===================================\n");

                    Calendar alarmCalendar = Calendar.getInstance();

                    if(scheduleDataDB.get(i).inqatype.equalsIgnoreCase("no") == true) {
                        //알림 사용하지 않음.
                        Log.i(TAG, "[checkScheduleReminder] ========== alarm off ==========");
                    }
                    else {
                        Log.i(TAG, "[checkScheduleReminder] ========== alarm on ==========");
                        if (scheduleDataDB.get(i).inqctype.equalsIgnoreCase("month")) {
                            Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> month ==========");
                            if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("intime")) {
                                //정각인 경우
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> month -> intime ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);

                                if ((ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE))) {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("min")) {
                                //10분 전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> month -> 10 min before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.MINUTE, -10);

                                if ((ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE))) {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("hour")) {
                                //1시간 전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> month -> 1 hour before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.HOUR_OF_DAY, -1);

                                if ((ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE))) {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("day")) {
                                //하루전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> month -> 1 day before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.DATE, -1);

//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.YEAR): " + ScheduleCal.get(Calendar.YEAR) + ", alarmCalendar.get(Calendar.YEAR): " + alarmCalendar.get(Calendar.YEAR));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.MONTH): " + ScheduleCal.get(Calendar.MONTH) + ", alarmCalendar.get(Calendar.MONTH): " + alarmCalendar.get(Calendar.MONTH));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.DAY_OF_MONTH): " + ScheduleCal.get(Calendar.DAY_OF_MONTH) + ", alarmCalendar.get(Calendar.DAY_OF_MONTH): " + alarmCalendar.get(Calendar.DAY_OF_MONTH));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.HOUR_OF_DAY): " + ScheduleCal.get(Calendar.HOUR_OF_DAY) + ", alarmCalendar.get(Calendar.HOUR_OF_DAY): " + alarmCalendar.get(Calendar.HOUR_OF_DAY));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.MINUTE): " + ScheduleCal.get(Calendar.MINUTE) + ", alarmCalendar.get(Calendar.MINUTE): " + alarmCalendar.get(Calendar.MINUTE));

                                if ((ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE))) {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                        }
                        else if (scheduleDataDB.get(i).inqctype.equalsIgnoreCase("year")) {
                            Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> year ==========");
                            if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("intime")) {
                                //정각인 경우
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> year -> intime ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);

                                if ((ScheduleCal.get(Calendar.MONTH) == alarmCalendar.get(Calendar.MONTH))
                                        && (ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE))) {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("min")) {
                                //10분 전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> year -> 10 min before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.MINUTE, -10);

                                if ((ScheduleCal.get(Calendar.MONTH) == alarmCalendar.get(Calendar.MONTH))
                                        && (ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE)))
                                {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("hour")) {
                                //1시간 전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> year -> 1 hour before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.HOUR_OF_DAY, -1);

                                if ((ScheduleCal.get(Calendar.MONTH) == alarmCalendar.get(Calendar.MONTH))
                                        && (ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE)))
                                {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("day")) {
                                //하루전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> year -> 1 day before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.DATE, -1);

//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.YEAR): " + ScheduleCal.get(Calendar.YEAR) + ", alarmCalendar.get(Calendar.YEAR): " + alarmCalendar.get(Calendar.YEAR));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.MONTH): " + ScheduleCal.get(Calendar.MONTH) + ", alarmCalendar.get(Calendar.MONTH): " + alarmCalendar.get(Calendar.MONTH));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.DAY_OF_MONTH): " + ScheduleCal.get(Calendar.DAY_OF_MONTH) + ", alarmCalendar.get(Calendar.DAY_OF_MONTH): " + alarmCalendar.get(Calendar.DAY_OF_MONTH));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.HOUR_OF_DAY): " + ScheduleCal.get(Calendar.HOUR_OF_DAY) + ", alarmCalendar.get(Calendar.HOUR_OF_DAY): " + alarmCalendar.get(Calendar.HOUR_OF_DAY));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.MINUTE): " + ScheduleCal.get(Calendar.MINUTE) + ", alarmCalendar.get(Calendar.MINUTE): " + alarmCalendar.get(Calendar.MINUTE));

                                if ((ScheduleCal.get(Calendar.MONTH) == alarmCalendar.get(Calendar.MONTH))
                                        && (ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE)))
                                {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                        }
                        else {
                            //반복 없는경우
                            Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> no repeat ==========");
                            if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("intime")) {
                                //정각인 경우
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> no repeat -> intime ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                if ((ScheduleCal.get(Calendar.YEAR) == alarmCalendar.get(Calendar.YEAR))
                                        && (ScheduleCal.get(Calendar.MONTH) == alarmCalendar.get(Calendar.MONTH))
                                        && (ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE)))
                                {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("min")) {
                                //10분 전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> no repeat -> 10 min before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.MINUTE, -10);

                                if ((ScheduleCal.get(Calendar.YEAR) == alarmCalendar.get(Calendar.YEAR))
                                        && (ScheduleCal.get(Calendar.MONTH) == alarmCalendar.get(Calendar.MONTH))
                                        && (ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE)))
                                {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if(scheduleDataDB.get(i).inqatype.equalsIgnoreCase("hour")) {
                                //1시간 전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> no repeat -> 1 hour before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.HOUR_OF_DAY, -1);

                                if ((ScheduleCal.get(Calendar.YEAR) == alarmCalendar.get(Calendar.YEAR))
                                        && (ScheduleCal.get(Calendar.MONTH) == alarmCalendar.get(Calendar.MONTH))
                                        && (ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE)))
                                {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else if (scheduleDataDB.get(i).inqatype.equalsIgnoreCase("day")) {
                                //하루전
                                Log.i(TAG, "[checkScheduleReminder] ========== alarm on -> no repeat -> 1 day before ==========");
                                alarmCalendar.set(scheduleDataDB.get(i).inqyear, scheduleDataDB.get(i).inqmonth - 1, scheduleDataDB.get(i).inqday, scheduleDataDB.get(i).inqhour, 0);
                                alarmCalendar.add(Calendar.DATE, -1);

//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.YEAR): " + ScheduleCal.get(Calendar.YEAR) + ", alarmCalendar.get(Calendar.YEAR): " + alarmCalendar.get(Calendar.YEAR));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.MONTH): " + ScheduleCal.get(Calendar.MONTH) + ", alarmCalendar.get(Calendar.MONTH): " + alarmCalendar.get(Calendar.MONTH));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.DAY_OF_MONTH): " + ScheduleCal.get(Calendar.DAY_OF_MONTH) + ", alarmCalendar.get(Calendar.DAY_OF_MONTH): " + alarmCalendar.get(Calendar.DAY_OF_MONTH));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.HOUR_OF_DAY): " + ScheduleCal.get(Calendar.HOUR_OF_DAY) + ", alarmCalendar.get(Calendar.HOUR_OF_DAY): " + alarmCalendar.get(Calendar.HOUR_OF_DAY));
//                                Log.i(TAG, "[checkScheduleReminder] cal.get(Calendar.MINUTE): " + ScheduleCal.get(Calendar.MINUTE) + ", alarmCalendar.get(Calendar.MINUTE): " + alarmCalendar.get(Calendar.MINUTE));

                                if ((ScheduleCal.get(Calendar.YEAR) == alarmCalendar.get(Calendar.YEAR))
                                        && (ScheduleCal.get(Calendar.MONTH) == alarmCalendar.get(Calendar.MONTH))
                                        && (ScheduleCal.get(Calendar.DAY_OF_MONTH) == alarmCalendar.get(Calendar.DAY_OF_MONTH))
                                        && (ScheduleCal.get(Calendar.HOUR_OF_DAY) == alarmCalendar.get(Calendar.HOUR_OF_DAY))
                                        && (ScheduleCal.get(Calendar.MINUTE) == alarmCalendar.get(Calendar.MINUTE)))
                                {
                                    AlarmScheduleCount++;
                                    if (bAlarmScheduleString == false) {
                                        bAlarmScheduleString = true;
                                        if (scheduleDataDB.get(i).inqttype.equalsIgnoreCase("moon")) {
                                            AlarmScheduleString = "[음력] "+ getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                        else {
                                            AlarmScheduleString = getScheduleEventType(scheduleDataDB.get(i).inqitype);
                                        }
                                    }
                                }
                            }
                            else {
                                Log.w(TAG, "[checkScheduleReminder] Unsupported alarm type!! -> " + scheduleDataDB.get(i).inqatype);
                            }
                        }
                    }
                }

                Log.i(TAG, "[checkScheduleReminder] bAlarmScheduleString [" + bAlarmScheduleString + "], AlarmScheduleCount [" + AlarmScheduleCount + "]");

                if (bAlarmScheduleString == true) {
                    if(AlarmScheduleCount == 1) {
                        //일정이 1개인 경우
                        AlarmScheduleString += " 일정이 있습니다.\r\n확인 하시겠습니까?";
                    }
                    else {
                        //일정이 1개보다 많은 경우
                        AlarmScheduleString += " 일정 외 "+(AlarmScheduleCount-1)+"건이 있습니다.\r\n확인 하시겠습니까?";
                    }
                    AlarmScheduleCount = 0;
                    bAlarmScheduleString = false;

                    MakePopup_Schedule(AlarmScheduleString);
                }
            }
            else {
                Log.w(TAG, "[checkScheduleReminder] scheduleDataDB is null!!");
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkScheduleReminder(Calendar cal)");
            LogUtil.errorLogInfo("", TAG, e);
        }
	}

	// 프로토콜에 정의된 일정표 이벤트 종류를 변환하여 반환한다.
	private String getScheduleEventType(String strEvent) {
	    try {
            Log.i(TAG, "[getScheduleEventType] strEvent [" + strEvent + "]");
	        if (strEvent.equalsIgnoreCase("birth")) return "생일";
            else if (strEvent.equalsIgnoreCase("memorial")) return "기념일";
            else if (strEvent.equalsIgnoreCase("appoint")) return "약속";
            else if (strEvent.equalsIgnoreCase("trip")) return "여행";
            else if (strEvent.equalsIgnoreCase("first")) return "돌";
            else if (strEvent.equalsIgnoreCase("wedding")) return "결혼";
            else if (strEvent.equalsIgnoreCase("tax")) return "공과금";
            else if (strEvent.equalsIgnoreCase("meeting")) return "모임";
            else if (strEvent.equalsIgnoreCase("car")) return "생일";
            else if (strEvent.equalsIgnoreCase("ancestor")) return "제사";
            else return "알수없음";
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return "알수없음";
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getScheduleEventType(String strEvent)");
            LogUtil.errorLogInfo("", TAG, e);
            return "알수없음";
        }
    }
	
	private void getParkedVehicleLocationSysInfo() {
		try {
		    DebugLogOutput("getParkedVehicleLocationSysInfo Init");
		    WallpadDeviceSet devSet = new WallpadDeviceSet(getContext());
	        String[] ParkingDB = devSet.GetSettingData("주차확인");
	        devSet.closeDB();        
	        
	        if (ParkingDB!=null) {
	            try {
	                String devInfo = ParkingDB[1];
	                
	                devInfo = devInfo.replace('(', '_');
	                devInfo = devInfo.replace(':', '_');
	                devInfo = devInfo.replace(')', '_');
	                
	                String[] ParkingInfo = devInfo.split("_");
	                
	                //ParkingInfo[3] -> 사용여부 <사용함 / else>
	                //ParkingInfo[5] -> 종류 <기본 / 아이콘트롤스 / NEXPA / UPIS / ETC / 비상벨 / else>
	                //ParkingInfo[7] -> IP정보
	                //ParkingInfo[8] -> 포트번호
	                
	                if (ParkingInfo[3].equalsIgnoreCase("사용함") == true) {
	                    bUseofNot_ParkingInfo = true;
	                }

	                if (ParkingInfo[5].equalsIgnoreCase("기본") == true) {
	                    nParkingSystemType = Common.PARKING_SYSTEM_BASIC;
	                }
	                else if (ParkingInfo[5].equalsIgnoreCase("아이콘트롤스") == true) {
	                    nParkingSystemType = Common.PARKING_SYSTEM_ICONTROLS;
	                }
	                else if (ParkingInfo[5].equalsIgnoreCase("넥스파") == true) {
	                    nParkingSystemType = Common.PARKING_SYSTEM_NEXPA;
	                } 
	                else if (ParkingInfo[5].equalsIgnoreCase("NEXPA") == true) {
	                    nParkingSystemType = Common.PARKING_SYSTEM_NEXPA;
	                }
	                else if (ParkingInfo[5].equalsIgnoreCase("UPIS") == true) {
	                    nParkingSystemType = Common.PARKING_SYSTEM_UPIS;
	                } 
	                else if (ParkingInfo[5].equalsIgnoreCase("ETC") == true) {
	                    nParkingSystemType = Common.PARKING_SYSTEM_ETC;
	                }
	                else if (ParkingInfo[5].equalsIgnoreCase("비상벨") == true) {
                        nParkingSystemType = Common.PARKING_SYSTEM_IES_100;
                    }
                    else if (ParkingInfo[5].equalsIgnoreCase("다람정보") == true) {
                        nParkingSystemType = Common.PARKING_SYSTEM_DARAM;
                    }
	                
	                ParkingServerIP = ParkingInfo[7];
	                ParkingServerPort = Integer.parseInt(ParkingInfo[8]);
	               
	                DebugLogOutput("[getParkedVehicleLocationSysInfo] bUseofNot_ParkingInfo [" + bUseofNot_ParkingInfo + ", nParkingSystemType ["+ nParkingSystemType + "]");
	                DebugLogOutput("[getParkedVehicleLocationSysInfo] ParkingServerIP ["+ParkingServerIP + "], ParkingServerPort [" + ParkingServerPort + "]");
	            } catch (RuntimeException re) {
                    LogUtil.errorLogInfo("", TAG, re);
                    bUseofNot_ParkingInfo = false;
                }
                catch (Exception e) {
	                LogUtil.errorLogInfo("", TAG, e);
	                bUseofNot_ParkingInfo = false;
	            }
	        }
	        else {
	            bUseofNot_ParkingInfo = false;
	            DebugLogOutput("[getParkedVehicleLocationSysInfo] bUseofNot_ParkingInfo ["+bUseofNot_ParkingInfo + "]");
	        }
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
			LogUtil.errorLogInfo("", TAG, e);
		}
	}

	//20분 마다 한번씩 호출되는 주차관련 함수!
	private void GetParkingInfo_RandomCheckHandler() {
	    int DelayTime = StringUtil.GetDelayTimeBaseIP(getContext());
        if (DelayTime < 1) {
            return;
        }
        
        DebugLogOutput("[GetParkingInfo] DelayTime : "+ DelayTime);
        bSetMSG_GetParkingInfo = true;
        mGetParkInfoRandomCheckHandler.sendEmptyMessageDelayed(0, 1000 * DelayTime);        
    }

    private Handler mGetParkInfoRandomCheckHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == 0) {
                DebugLogOutput("[GetParkingInfo] mGetParkInfoRandomCheckHandler() will be called");
                //얻어오기 
                LoadParkingDataFromServer();
            }
        }
    };
    
    /**
     * @description 주차정보 서버로부터 얻어오기<br>
     * 호출 시에는 bSetMSG_GetParkingInfo = true 하고 호출해야함.
     * **/    
    private void LoadParkingDataFromServer() {
        try {
            WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
            final AddressSet addc =  SetData.getAddressMGR();
            SetData.closeDB();

            if (bSetMSG_GetParkingInfo == false) {
                return;
            }

            if ((nParkingSystemType == Common.PARKING_SYSTEM_BASIC)
                    || (nParkingSystemType == Common.PARKING_SYSTEM_ICONTROLS)
                    || (nParkingSystemType == Common.PARKING_SYSTEM_NEXPA)
                    || (nParkingSystemType == Common.PARKING_SYSTEM_IES_100))
            {
                iMAPcarParking = new iMAPCarParking(mContext, true);
                iMAPcarParking.SetServerIPcfg(ParkingServerIP, ParkingServerPort);
                DebugLogOutput("ParkingServerIP :"+ParkingServerIP+",  ParkingServerPort : "+ParkingServerPort);
                DebugLogOutput("iMAPcarParking.DoWork()");
                iMAPcarParking.DoWork();

                iMAPcarParking.SetRetCtr(new RetProci(){

                    @Override
                    public void ProcSuccess() {
                        DebugLogOutput("Load EMData From Server - ProcSuccess");
                        try {
                            iMAPcarParking.SetItem("home_info");
                            int home_info_count = Integer.parseInt(iMAPcarParking.GetAttributeVal(0, "count"));
                            int park_info_count = iMAPcarParking.SetItem("park_info");

                            if (home_info_count != park_info_count) {
                                DebugLogOutput("home_info_count != park_info_count -->"+ home_info_count+" != "+ park_info_count);
                                cGetParkingMin = 0;
                                bSetMSG_GetParkingInfo = false;
                                return;
                            }

                            if (park_info_count == 0) {
                                DebugLogOutput("park_info_count :" + park_info_count);
                                WallpadParkInfo parkdb = new WallpadParkInfo(getApplicationContext());
                                parkdb.DeleteAllParkInfo();
                                parkdb.closeDB();

                                cGetParkingMin = 0;
                                bSetMSG_GetParkingInfo = false;

                            /*
                            parkdb = new WallpadParkInfo(getApplicationContext());
                            int countRow = parkdb.RowCountCarParking();
                            parkdb.closeDB();
                            DebugLogOutput("countRow :" + countRow);
                            */

                                Intent intent = new Intent();
                                intent.setAction(define.NOTIFY_ACNAME);
                                intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATEPARKING);
                                getApplicationContext().sendBroadcast(intent);
                                return;
                            }

                            WallpadParkInfo parkdb = new WallpadParkInfo(getApplicationContext());
                            parkdb.DeleteAllParkInfo();
                            parkdb.closeDB();

                            for (int i = 0; i < park_info_count; i++) {
                                if ((addc.Dong.equalsIgnoreCase(iMAPcarParking.GetAttributeVal(i, "dong"))) && (addc.Ho.equalsIgnoreCase(iMAPcarParking.GetAttributeVal(i, "ho")))) {
                                    parkdb = new WallpadParkInfo(getApplicationContext());
                                    parkdb.InputParkInfo(
                                            iMAPcarParking.GetAttributeVal(i, "index"),
                                            iMAPcarParking.GetAttributeVal(i, "dong"),
                                            iMAPcarParking.GetAttributeVal(i, "ho"),
                                            iMAPcarParking.GetAttributeVal(i, "card_num"),
                                            iMAPcarParking.GetAttributeVal(i, "uid"),
                                            iMAPcarParking.GetAttributeVal(i, "sn"),
                                            iMAPcarParking.GetAttributeVal(i, "card_type"),
                                            iMAPcarParking.GetAttributeVal(i, "time"),
                                            iMAPcarParking.GetAttributeVal(i, "location_text"),
                                            iMAPcarParking.GetAttributeVal(i, "location_map"),
                                            iMAPcarParking.GetAttributeVal(i, "vehicle_info"),
                                            iMAPcarParking.GetAttributeVal(i, "ftp_path"),
                                            iMAPcarParking.GetAttributeVal(i, "ftp_info"),
                                            iMAPcarParking.GetAttributeVal(i, "message"));
                                    parkdb.closeDB();
                                }
                            }

                            //테스트
                            parkdb = new WallpadParkInfo(getApplicationContext());
                            CarParkingData carParkingData[] = parkdb.getCarParkingData();
                            parkdb.closeDB();
                            if (carParkingData != null) {
                                for (int j = 0; j < carParkingData.length; j++) {
                                    DebugLogOutput(carParkingData[j].ToDebugString());
                                }
                            }
                            //테스트

                            Intent intent = new Intent();
                            intent.setAction(define.NOTIFY_ACNAME);
                            intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATEPARKING);
                            getApplicationContext().sendBroadcast(intent);
                        } catch (RuntimeException re) {
                            LogUtil.errorLogInfo("", TAG, re);
                            cGetParkingMin = 0;
                            bSetMSG_GetParkingInfo = false;
                        }
                        catch (Exception e) {
                            cGetParkingMin = 0;
                            bSetMSG_GetParkingInfo = false;
                            Log.e(TAG, "[Exception] iMAPcarParking.ProcSuccess()");
                            LogUtil.errorLogInfo("", TAG, e);
                        }
                        cGetParkingMin = 0;
                        bSetMSG_GetParkingInfo = false;
                    }

                    @Override
                    public void ProcError() {
                        cGetParkingMin = 0;
                        bSetMSG_GetParkingInfo = false;
                        DebugLogOutput("Load EMData From Server - ProcError");
                    }

                    @Override
                    public void ProcDoing() {

                    }
                });
            }
            else if (nParkingSystemType == Common.PARKING_SYSTEM_DARAM) {
                iMAPcarParking = new iMAPCarParking(mContext, false);
                iMAPcarParking.SetServerIPcfg(ParkingServerIP, ParkingServerPort);
                DebugLogOutput("ParkingServerIP :"+ParkingServerIP+",  ParkingServerPort : "+ParkingServerPort);
                DebugLogOutput("iMAPcarParking.DoWork()");
                iMAPcarParking.DoWork();

                iMAPcarParking.SetRetCtr(new RetProci(){

                    @Override
                    public void ProcSuccess() {
                        DebugLogOutput("Load EMData From Server - ProcSuccess");
                        try {
                            iMAPcarParking.SetItem("home_info");
                            int home_info_count = Integer.parseInt(iMAPcarParking.GetAttributeVal(0, "count"));
                            int park_info_count = iMAPcarParking.SetItem("park_info");

                            if (home_info_count != park_info_count) {
                                DebugLogOutput("home_info_count != park_info_count -->"+ home_info_count+" != "+ park_info_count);
                                cGetParkingMin = 0;
                                bSetMSG_GetParkingInfo = false;
                                return;
                            }

                            if (park_info_count == 0) {
                                DebugLogOutput("park_info_count :" + park_info_count);
                                WallpadParkInfo parkdb = new WallpadParkInfo(getApplicationContext());
                                parkdb.DeleteAllParkInfo();
                                parkdb.closeDB();

                                cGetParkingMin = 0;
                                bSetMSG_GetParkingInfo = false;

                            /*
                            parkdb = new WallpadParkInfo(getApplicationContext());
                            int countRow = parkdb.RowCountCarParking();
                            parkdb.closeDB();
                            DebugLogOutput("countRow :" + countRow);
                            */

                                Intent intent = new Intent();
                                intent.setAction(define.NOTIFY_ACNAME);
                                intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATEPARKING);
                                getApplicationContext().sendBroadcast(intent);
                                return;
                            }

                            WallpadParkInfo parkdb = new WallpadParkInfo(getApplicationContext());
                            parkdb.DeleteAllParkInfo();
                            parkdb.closeDB();

                            for (int i = 0; i < park_info_count; i++) {
                                if ((addc.Dong.equalsIgnoreCase(iMAPcarParking.GetAttributeVal(i, "dong"))) && (addc.Ho.equalsIgnoreCase(iMAPcarParking.GetAttributeVal(i, "ho")))) {
                                    parkdb = new WallpadParkInfo(getApplicationContext());
                                    parkdb.InputParkInfo(
                                            iMAPcarParking.GetAttributeVal(i, "index"),
                                            iMAPcarParking.GetAttributeVal(i, "dong"),
                                            iMAPcarParking.GetAttributeVal(i, "ho"),
                                            iMAPcarParking.GetAttributeVal(i, "card_num"),
                                            iMAPcarParking.GetAttributeVal(i, "uid"),
                                            iMAPcarParking.GetAttributeVal(i, "sn"),
                                            iMAPcarParking.GetAttributeVal(i, "card_type"),
                                            iMAPcarParking.GetAttributeVal(i, "time"),
                                            iMAPcarParking.GetAttributeVal(i, "location_text"),
                                            iMAPcarParking.GetAttributeVal(i, "location_map"),
                                            iMAPcarParking.GetAttributeVal(i, "vehicle_info"),
                                            iMAPcarParking.GetAttributeVal(i, "ftp_path"),
                                            iMAPcarParking.GetAttributeVal(i, "ftp_info"),
                                            iMAPcarParking.GetAttributeVal(i, "message"));
                                    parkdb.closeDB();
                                }
                            }

                            //테스트
                            parkdb = new WallpadParkInfo(getApplicationContext());
                            CarParkingData carParkingData[] = parkdb.getCarParkingData();
                            parkdb.closeDB();
                            if (carParkingData != null) {
                                for (int j = 0; j < carParkingData.length; j++) {
                                    DebugLogOutput(carParkingData[j].ToDebugString());
                                }
                            }
                            //테스트

                            Intent intent = new Intent();
                            intent.setAction(define.NOTIFY_ACNAME);
                            intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATEPARKING);
                            getApplicationContext().sendBroadcast(intent);
                        } catch (RuntimeException re) {
                            LogUtil.errorLogInfo("", TAG, re);
                            cGetParkingMin = 0;
                            bSetMSG_GetParkingInfo = false;
                        }
                        catch (Exception e) {
                            cGetParkingMin = 0;
                            bSetMSG_GetParkingInfo = false;
                            Log.e(TAG, "[Exception] iMAPcarParking.ProcSuccess()");
                            LogUtil.errorLogInfo("", TAG, e);
                        }
                        cGetParkingMin = 0;
                        bSetMSG_GetParkingInfo = false;
                    }

                    @Override
                    public void ProcError() {
                        cGetParkingMin = 0;
                        bSetMSG_GetParkingInfo = false;
                        DebugLogOutput("Load EMData From Server - ProcError");
                    }

                    @Override
                    public void ProcDoing() {

                    }
                });
            }
            else if (nParkingSystemType == Common.PARKING_SYSTEM_UPIS) {
                iMapcarParking_UPIS = new iMAPCarParking_UPIS(mContext, false);
                iMapcarParking_UPIS.SetServerIPcfg(ParkingServerIP, ParkingServerPort);
                DebugLogOutput("ParkingServerIP :"+ParkingServerIP+",  ParkingServerPort : "+ParkingServerPort);
                DebugLogOutput("iMapcarParking_UPIS.DoWork()");
                iMapcarParking_UPIS.DoWork();

                iMapcarParking_UPIS.SetRetCtr(new RetProci(){

                    @Override
                    public void ProcSuccess() {
                        DebugLogOutput("Load EMData From Server - ProcSuccess");
                        try {
                            iMapcarParking_UPIS.SetItem("home_info");
                            int home_info_count = Integer.parseInt(iMapcarParking_UPIS.GetAttributeVal(0, "count"));
                            int park_info_count = iMapcarParking_UPIS.SetItem("park_info");
                            if (home_info_count != park_info_count) {
                                DebugLogOutput("home_info_count != park_info_count -->"+ home_info_count+" != "+ park_info_count);
                                cGetParkingMin = 0;
                                bSetMSG_GetParkingInfo = false;
                                return;
                            }

                            if (park_info_count == 0) {
                                DebugLogOutput("park_info_count :" + park_info_count);
                                WallpadParkInfo parkdb = new WallpadParkInfo(getApplicationContext());
                                parkdb.DeleteAllParkInfo();
                                parkdb.closeDB();

                                cGetParkingMin = 0;
                                bSetMSG_GetParkingInfo = false;

                            /*
                            parkdb = new WallpadParkInfo(getApplicationContext());
                            int countRow = parkdb.RowCountCarParking();
                            parkdb.closeDB();
                            DebugLogOutput("countRow :" + countRow);
                            */

                                Intent intent = new Intent();
                                intent.setAction(define.NOTIFY_ACNAME);
                                intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATEPARKING);
                                getApplicationContext().sendBroadcast(intent);
                                return;
                            }

                            WallpadParkInfo parkdb = new WallpadParkInfo(getApplicationContext());
                            parkdb.DeleteAllParkInfo();
                            parkdb.closeDB();

                            for (int i = 0; i < park_info_count; i++) {
                                if ((addc.Dong.equalsIgnoreCase(iMapcarParking_UPIS.GetAttributeVal(i, "dong"))) && (addc.Ho.equalsIgnoreCase(iMapcarParking_UPIS.GetAttributeVal(i, "ho")))) {
                                    parkdb = new WallpadParkInfo(getApplicationContext());
                                    parkdb.InputParkInfo(
                                            iMapcarParking_UPIS.GetAttributeVal(i, "index"),
                                            iMapcarParking_UPIS.GetAttributeVal(i, "dong"),
                                            iMapcarParking_UPIS.GetAttributeVal(i, "ho"),
                                            "null",
                                            iMapcarParking_UPIS.GetAttributeVal(i, "uid"),
                                            iMapcarParking_UPIS.GetAttributeVal(i, "sn"),
                                            iMapcarParking_UPIS.GetAttributeVal(i, "card_type"),
                                            iMapcarParking_UPIS.GetAttributeVal(i, "time"),
                                            iMapcarParking_UPIS.GetAttributeVal(i, "location_2"),
                                            iMapcarParking_UPIS.GetAttributeVal(i, "location_1"),
                                            iMapcarParking_UPIS.GetAttributeVal(i, "car_info"),
                                            "null",
                                            "null",
                                            iMapcarParking_UPIS.GetAttributeVal(i, "message"));
                                    parkdb.closeDB();
                                }
                            }

                            //테스트
                            parkdb = new WallpadParkInfo(getApplicationContext());
                            CarParkingData carParkingData[] = parkdb.getCarParkingData();
                            parkdb.closeDB();
                            if (carParkingData != null) {
                                for (int j = 0; j < carParkingData.length; j++) {
                                    DebugLogOutput(carParkingData[j].ToDebugString());
                                }
                            }

                            Intent intent = new Intent();
                            intent.setAction(define.NOTIFY_ACNAME);
                            intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_UPDATEPARKING);
                            getApplicationContext().sendBroadcast(intent);
                        } catch (RuntimeException re) {
                            LogUtil.errorLogInfo("", TAG, re);
                            cGetParkingMin = 0;
                            bSetMSG_GetParkingInfo = false;
                        }
                        catch (Exception e) {
                            cGetParkingMin = 0;
                            bSetMSG_GetParkingInfo = false;
                            Log.e(TAG, "[Exception] iMAPcarParking.ProcSuccess()");
                            LogUtil.errorLogInfo("", TAG, e);
                        }
                        cGetParkingMin = 0;
                        bSetMSG_GetParkingInfo = false;
                    }

                    @Override
                    public void ProcError() {
                        cGetParkingMin = 0;
                        bSetMSG_GetParkingInfo = false;
                        DebugLogOutput("Load EMData From Server - ProcError");
                    }

                    @Override
                    public void ProcDoing() {

                    }
                });
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] LoadParkingDataFromServer()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }
    
	// 한시간에 한번식 호출되는 함수임
	private void DoScheduleHourUnit(Calendar cal) {
		nHour = cal.get(Calendar.HOUR_OF_DAY);
		// 매시 7시부터 매시간 정각에 계속해서 알려준다. 사용자가 확인하기 전까지...
		// 사용자가 확인하게 되면 알림을 중지한다.
		// 목표값 팝업 알림에 필요한 DB 정보 
		// 각각의 항목에 대한 초기화, 근접알림 발생, 근접알림 확인, 초과 알림 발생 , 초과알림 확인  5단계 구분 필요
		// 달이 넘어가게 되면 초괴하 한다.

		try {
		    if (nHour == GetEnergyAlarmTime()) {
		        if (GetEnergyAlarm() == true) {
                    if (bUseofNot_EnergyServer == true) {
                        if (ResultGetIntent == true) {
                            ResultGetIntent = false;
                            Intent intent = new Intent();
                            intent.setAction(define.NOTIFY_ACNAME);
                            intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_ENERGY_TARGET_INFO_ALARM_FROM_MAIN_ACTIVIVY);
                            
                            intent.putExtra("elect_target", elect_target);
                            intent.putExtra("elect_used", elect_used);
                            intent.putExtra("elect_info", elect_info);
                            intent.putExtra("water_target", water_target);
                            intent.putExtra("water_used", water_used);
                            intent.putExtra("water_info", water_info);
                            intent.putExtra("gas_target", gas_target);
                            intent.putExtra("gas_used", gas_used);
                            intent.putExtra("gas_info", gas_info);
                            intent.putExtra("heating_target", heating_target);
                            intent.putExtra("heating_used", heating_used);
                            intent.putExtra("heating_info", heating_info);                            
                            intent.putExtra("hotwater_target", hotwater_target);
                            intent.putExtra("hotwater_used", hotwater_used);
                            intent.putExtra("hotwater_info", hotwater_info);
                            
                            sendBroadcast(intent);   
                        }
                    }
                    else {
                        CheckEnergyUsage();    
                    }   
                }
	        }    
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
		    LogUtil.errorLogInfo("", TAG, e);
		}
		
		if (SCManager != null ) SCManager.CheckSysResetData();			
	}
	static boolean NeedCheckEnergy = false;
	
	//에너지 사용량 확인	
	public void CheckEnergyUsage() {
	    Log.d(TAG, "***********************************************");
	    Log.d(TAG, "[CheckEnergyUsage] CheckEnergyUsage Function in");
	    Log.d(TAG, "***********************************************");
		try {
		    WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());		
			int alarmstate = SetData.GetAlarmStatus();
			SetData.closeDB();
			
			if (alarmstate == WallpadStatusData.ALARM_ARISE || alarmstate == WallpadStatusData.GUARD_OUT)
				return;
			
			String strNear = "";
			String strOver = "";
			
			if (EnergyAlramPopupMgr.m_Elec_UseValue > 0 && EnergyAlramPopupMgr.m_Elec_GoalValue > 0  && EnergyAlramPopupMgr.CheckAlramPopupCreate( getContext(), EnergyAlramPopupMgr.DB_ELEC_ALAM_POPUP_STEP)) {
				if (EnergyAlramPopupMgr.m_Elec_UseValue >= EnergyAlramPopupMgr.m_Elec_GoalValue) {
					strOver += "전기 ";
					EnergyAlramPopupMgr.setAlramOverStep(getContext(), EnergyAlramPopupMgr.DB_ELEC_ALAM_POPUP_STEP);
				}
				else {
					double nNearValue = EnergyAlramPopupMgr.m_Elec_GoalValue * 0.9;
					if (EnergyAlramPopupMgr.m_Elec_UseValue > nNearValue) {
						strNear += "전기 ";
						EnergyAlramPopupMgr.setAlramNearStep(getContext(), EnergyAlramPopupMgr.DB_ELEC_ALAM_POPUP_STEP);
					}
				}
			}
			
			if (EnergyAlramPopupMgr.m_Water_UseValue > 0 && EnergyAlramPopupMgr.m_Water_GoalValue > 0  && EnergyAlramPopupMgr.CheckAlramPopupCreate( getContext(), EnergyAlramPopupMgr.DB_WATER_ALAM_POPUP_STEP)) {
				if (EnergyAlramPopupMgr.m_Water_UseValue >= EnergyAlramPopupMgr.m_Water_GoalValue) {
					strOver += "수도 ";
					EnergyAlramPopupMgr.setAlramOverStep(getContext(), EnergyAlramPopupMgr.DB_WATER_ALAM_POPUP_STEP);
				}
				else {
					double nNearValue = EnergyAlramPopupMgr.m_Water_GoalValue * 0.9;
					if (EnergyAlramPopupMgr.m_Water_UseValue > nNearValue) {
						strNear += "수도 ";
						EnergyAlramPopupMgr.setAlramNearStep(getContext(), EnergyAlramPopupMgr.DB_WATER_ALAM_POPUP_STEP);
					}
				}
			}
			
			if (EnergyAlramPopupMgr.m_Gas_UseValue > 0 && EnergyAlramPopupMgr.m_Gas_GoalValue > 0 && EnergyAlramPopupMgr.CheckAlramPopupCreate( getContext(), EnergyAlramPopupMgr.DB_GAS_ALAM_POPUP_STEP)) {
				if (EnergyAlramPopupMgr.m_Gas_UseValue >= EnergyAlramPopupMgr.m_Gas_GoalValue) {
					strOver += "가스 ";
					EnergyAlramPopupMgr.setAlramOverStep(getContext(), EnergyAlramPopupMgr.DB_GAS_ALAM_POPUP_STEP);
				}
				else {
					double nNearValue = EnergyAlramPopupMgr.m_Gas_GoalValue * 0.9;
					if (EnergyAlramPopupMgr.m_Gas_UseValue > nNearValue) {
						strNear += "가스 ";
						EnergyAlramPopupMgr.setAlramNearStep(getContext(), EnergyAlramPopupMgr.DB_GAS_ALAM_POPUP_STEP);
					}
				}
			}
			
			if (EnergyAlramPopupMgr.m_HotWater_UseValue > 0 && EnergyAlramPopupMgr.m_HotWater_GoalValue > 0 && EnergyAlramPopupMgr.CheckAlramPopupCreate( getContext(), EnergyAlramPopupMgr.DB_HOTWATER_ALAM_POPUP_STEP)) {
				if (EnergyAlramPopupMgr.m_HotWater_UseValue >= EnergyAlramPopupMgr.m_HotWater_GoalValue) {
					strOver += "온수 ";
					EnergyAlramPopupMgr.setAlramOverStep(getContext(), EnergyAlramPopupMgr.DB_HOTWATER_ALAM_POPUP_STEP);
				}
				else {
					double nNearValue = EnergyAlramPopupMgr.m_HotWater_GoalValue * 0.9;
					if (EnergyAlramPopupMgr.m_HotWater_UseValue > nNearValue) {
						strNear += "온수 ";
						EnergyAlramPopupMgr.setAlramNearStep(getContext(), EnergyAlramPopupMgr.DB_HOTWATER_ALAM_POPUP_STEP);
					}
				}
			}
			
			if (EnergyAlramPopupMgr.m_Heating_UseValue > 0 && EnergyAlramPopupMgr.m_Heating_GoalValue > 0 && EnergyAlramPopupMgr.CheckAlramPopupCreate( getContext(), EnergyAlramPopupMgr.DB_HEATING_ALAM_POPUP_STEP)) {
				if (EnergyAlramPopupMgr.m_Heating_UseValue >= EnergyAlramPopupMgr.m_Heating_GoalValue) {
					strOver += "난방 ";
					EnergyAlramPopupMgr.setAlramOverStep(getContext(), EnergyAlramPopupMgr.DB_HEATING_ALAM_POPUP_STEP);
				}
				else {
					double nNearValue = EnergyAlramPopupMgr.m_Heating_GoalValue * 0.9;
					if (EnergyAlramPopupMgr.m_Heating_UseValue > nNearValue) {
						strNear += "난방 ";
						EnergyAlramPopupMgr.setAlramNearStep(getContext(), EnergyAlramPopupMgr.DB_HEATING_ALAM_POPUP_STEP);
					}  
				}
			}




            if (strNear.length() > 8) EnergyAlramPopupMgr.PopupMsg01 = strNear + "사용량이\n목표값에 가까워지고 있습니다.\n확인 하시겠습니까?";
            else if (0 < strNear.length() && strNear.length() <= 8) EnergyAlramPopupMgr.PopupMsg01 = strNear + "사용량이 목표값에 가까워지고 있습니다.\n확인 하시겠습니까?";
            else EnergyAlramPopupMgr.PopupMsg01 = "";

            if (strOver.length() > 10) {
                EnergyAlramPopupMgr.PopupMsg02 = strOver + "사용량이\n목표값을 초과하였습니다.\n확인 하시겠습니까?";
            }
            else if (0 < strOver.length() && strOver.length() <= 10) {
                EnergyAlramPopupMgr.PopupMsg02 = strOver + "사용량이 목표값을 초과하였습니다.\n확인 하시겠습니까?";
            }
            else if(strOver.length() < 0){
                EnergyAlramPopupMgr.PopupMsg02 = "";
            }



			if (EnergyAlramPopupMgr.PopupMsg01.length() > 0 || EnergyAlramPopupMgr.PopupMsg02.length() > 0) {
				mIOInterface.ctrlLcdWakeUp();
				StartPopup(ID.POPUPS.POPUP_ENERGYUSAGEALERT);
			}
		} catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
		    Log.e(TAG, "[Exception] CheckEnergyUsage()");
			LogUtil.errorLogInfo("", TAG, e);
		}
	}
	
    
	//시간 동기화를 위한 getinfo 실행 시간을 구함	
	protected Calendar GetTimeSyncTime()
	{
		Calendar retTime = new GregorianCalendar();
		
		WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
		AddressSet addc =  SetData.getAddressMGR();
		SetData.closeDB();
		try {
			int dong = Integer.parseInt(addc.Dong);
			int ho = 101;
			
			if(addc.UseOrNotRentHouse == true)
			{
			    ho = addc.Ho_Integer;
			}
			else
			{
			    ho = Integer.parseInt(addc.Ho); 
			}
					
			int interval = (dong-(dong/100)*100) * 100 + ho/100;
			int hour;
			int min;
			int sec;
			if (interval/3600 > 0)
			{
				hour = 3+interval/3600;
				interval=interval%3600;
			}
			else hour = 6;
			
			if (interval/60 > 0)
			{
				min = interval/60;
				sec = interval%60;
			}
			else
			{
				min = 0;
				sec = interval;
			}
			retTime.set(Calendar.HOUR_OF_DAY, hour);
			retTime.set(Calendar.MINUTE, min);
			retTime.set(Calendar.SECOND, sec);
		}
		catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return null;
        }
		catch (Exception e)
		{
			LogUtil.errorLogInfo("", TAG, e);
			return null;
		}
		
		return retTime;
	}
	
	//에너지 사용량 확인을 위한 데이터 로딩 시간을 가져옴	
	protected Calendar GetEnergyDataLoadingTime()
	{
		Calendar retTime = new GregorianCalendar();
		
		WallpadStatusData SetData = new WallpadStatusData(getApplicationContext());
		AddressSet addc =  SetData.getAddressMGR();
		SetData.closeDB();
		try {
			int dong = Integer.parseInt(addc.Dong);
			int ho = 201;
			
			if(addc.UseOrNotRentHouse == true)
			{
			    ho = addc.Ho_Integer; 
			}
			else
			{
			    ho = Integer.parseInt(addc.Ho); 
			}
			   
			int interval = (dong-(dong/100)*100) * 100 + ho/100;
			int hour;
			int min;
			int sec;
			if (interval/3600 > 0)
			{
				hour = 6+interval/3600;
				interval=interval%3600;
			}
			else hour = 6;
			
			if (interval/60 > 0)
			{
				min = interval/60;
				sec = interval%60;
			}
			else
			{
				min = 0;
				sec = interval;
			}
			retTime.set(Calendar.HOUR_OF_DAY, hour);
			retTime.set(Calendar.MINUTE, min);
			retTime.set(Calendar.SECOND, sec);
		}
		catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return null;
        }
		catch (Exception e)
		{
			LogUtil.errorLogInfo("", TAG, e);
			return null;
		}
		
		return retTime;
	}
	
	
    private void setNetworkAddr(int secNum, int thirdNum, int forthNum) {
    	try
    	{
	        String IPAddress = String.format("10.%d.%d.%d", secNum, thirdNum, forthNum);
	        String gateWayIPAddress = String.format("10.%d.%d.%d", secNum, Common.DEFAULT_GATEWAY_IP_THIRD, Common.DEFAULT_GATEWAY_IP_FORTH);
	        String MacAddr = String.format("00:0A:%02x:%02x:%02x:00", secNum, thirdNum, forthNum);
	
	        String serverIP = Common.DEFAULT_SERVER_IP;
	        int serverPort = Common.DEFAULT_SERVER_PORT;
	
	        String managePCIP = Common.DEFAULT_MANAGER_PC_IP;
	        int managePCPort = Common.DEFAULT_MANAGER_PC_PORT;
	
	        wallpaddbmgr dbmgr = new wallpaddbmgr(this);
	        AddressSet addc =  dbmgr.getAddressMGR();
	        String mDong = String.format("%d%02d", 1, secNum);
	        String mHo = String.format("%d%02d", thirdNum, forthNum);
	        addc.setAddress(mDong, mHo);
	        addc.setIPAddress(IPAddress);
	        dbmgr.closeDB();
	        
	        WallpadStatusData wallpadStatusData = new WallpadStatusData(this);
	        wallpadStatusData.SetServerIP(serverIP, serverPort);
	        wallpadStatusData.SetManagePC(managePCIP, managePCPort);
	        wallpadStatusData.closeDB();
	
	        EthernetDevInfo info = new EthernetDevInfo();
	
	        info.setIfName("eth0");
	        info.setConnectMode(EthernetDevInfo.ETH_CONN_MODE_MANUAL);
	        info.setIpAddress(IPAddress);
	        info.setRouteAddr(gateWayIPAddress);
	        info.setDnsAddr(Common.DNS_IP);
	        info.setNetMask(Common.SUBNET_MASK);
	
	        EthernetManager mEthManager = (EthernetManager) getSystemService("ethernet");
	        mEthManager.setEthernetState(EthernetManager.ETH_STATE_DISABLED);
	        mEthManager.UpdateEthDevInfo(info);
	        mEthManager.setEthernetState(EthernetManager.ETH_STATE_ENABLING);
	        WallPadInterface wallPadInterface = new WallPadInterface();;
	        wallPadInterface.setMacAddr(MacAddr);
	        Log.d("MANAGERSETTING", " IP : "+IPAddress+" Mac : "+ MacAddr);
	
	        writeMacAddress(MacAddr);
    	}
		catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e)
		{
			LogUtil.errorLogInfo("", TAG, e);
		}
    }
    
    private final String NETWORK_SETTING = "network_setting";
    private final String MAC_ADDRESS_FILE_PATH = Common.CONTENTS_ROOT + NETWORK_SETTING + ".inc";
    
    private boolean writeMacAddress(String MacAddr) {
        boolean ret = false;
        String read = null;

        BufferedWriter bufferWriter = null;

        try {
            FileOutputStream fos = new FileOutputStream(MAC_ADDRESS_FILE_PATH, false);
            OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
            bufferWriter = new BufferedWriter(osr, 1024);

            if ((bufferWriter != null) && (MacAddr != null)) {
                bufferWriter.write(MacAddr, 0, MacAddr.length());
                bufferWriter.newLine();
                bufferWriter.flush();

                ret = true;
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            LogUtil.errorLogInfo("", TAG, e);
        } finally {
            try {
                if (bufferWriter != null) {
                    bufferWriter.close();
                }
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                LogUtil.errorLogInfo("", TAG, e);
            }
        }


        Log.d(TAG, "writeMacAddress() path : " + MAC_ADDRESS_FILE_PATH
                                    + ", MacAddr : " + MacAddr
                                    + ", ret : " + ret
                                    );

        return ret;
    }
    private void GetElectricCarInfo() {
        try {
            Log.d(TAG, "[GetElectricCarInfo] ===== START =====");
            int retInt = -1;
            WallpadDeviceSet mWallpadDeviceSet = null;
            mWallpadDeviceSet = new WallpadDeviceSet(getApplicationContext());
            retInt = mWallpadDeviceSet.GetDeviceSetted("전기차충전");
            mWallpadDeviceSet.closeDB();
            Log.d(TAG, "[GetElectricCarInfo] retInt = " + retInt);
            if (retInt == WallpadDeviceSet.DEV_DATA_ENABLE) {
                Log.i(TAG, "[GetElectricCarInfo] Electronic car changing enabled!!");
                GetElectricCarInfo_RandomCheckHandler();
            }
            else Log.i(TAG, "[GetElectricCarInfo] Electronic car changing disabled!!");

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] GetElectricCarInfo()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }
    private void GetElectricCarInfo_RandomCheckHandler() {
        try {
            Log.d(TAG, "[GetElectricCarInfo_RandomCheckHandler] ===== START =====");
            int nDelayTime = StringUtil.GetDelayTimeBaseIP(getContext());
            Log.d(TAG, "[GetElectricCarInfo_RandomCheckHandler] nDelayTime : "+ nDelayTime);
            if (nDelayTime < 1) {
                Log.w(TAG, "[GetElectricCarInfo_RandomCheckHandler] DelayTime error!! -> nDelayTime = " + nDelayTime);
                return;
            }
            mGetElecricCarRandomCheckHandler.sendEmptyMessageDelayed(0, 1000 * nDelayTime);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] GetElectricCarInfo_RandomCheckHandler()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private Handler mGetElecricCarRandomCheckHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == 0) {
                Log.i(TAG, "[GetElectricCarInfo] mGetElecricCarRandomCheckHandler() will be called!!");
                //얻어오기 
                imapElecCarChargingInfo = new iMAPElecCarChargingInfo(getApplicationContext());
                LoadElectricCarDataFromServer();
            }
        }
    };

    void LoadElectricCarDataFromServer() {
        DebugLogOutput("LoadElectricCarDataFromServer");
        imapElecCarChargingInfo.DoWork();
        imapElecCarChargingInfo.SetRetCtr(new RetProci() {
            @Override
            public void ProcSuccess() {
                Log.i(TAG, "[LoadElectricCarDataFromServer] ProcSuccess");
                try {
                    int SetItemResult = imapElecCarChargingInfo.SetItem("charging_cnt");
                    if(SetItemResult != 1) {
                        Log.w(TAG, "[LoadElectricCarDataFromServer.ProcSuccess()] Error1 - SetItemResult : "+ SetItemResult);
                        nElecVehicleChangingCnt = 0;
                        return;
                    }

                    String sChargingCount = imapElecCarChargingInfo.GetItemVal(0);
                    int intChargingCount = Integer.parseInt(sChargingCount);
                    if (intChargingCount < 1) {
                        Log.w(TAG, "[LoadElectricCarDataFromServer.ProcSuccess()] Error1 - intChargingCount : "+ intChargingCount);
                        nElecVehicleChangingCnt = 0;
                        return;
                    }

                    SetItemResult = imapElecCarChargingInfo.SetItem("charger_info");
                    
                    if (SetItemResult != intChargingCount) {
                        Log.w(TAG, "[LoadElectricCarDataFromServer.ProcSuccess()] Error1 - SetItemResult : "+ SetItemResult);
                        nElecVehicleChangingCnt = 0;
                        return;
                    }

                    if (intChargingCount > 0) {
                        nElecVehicleChangingCnt = intChargingCount;

                        Intent intent = new Intent();
                        intent.setAction(define.NOTIFY_ACNAME);
                        intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_GET_ELEC_CHARGE);
                        
                        intent.putExtra("sCard_Num", imapElecCarChargingInfo.GetAttributeVal(0, "card_num"));
                        intent.putExtra("sCar_Num", imapElecCarChargingInfo.GetAttributeVal(0, "car_num"));
                        intent.putExtra("sCharger_Num", imapElecCarChargingInfo.GetAttributeVal(0, "charger_num"));
                        intent.putExtra("sCharger_Loc", imapElecCarChargingInfo.GetAttributeVal(0, "charger_loc"));
                        intent.putExtra("sCharging_Status", "charging");
                        intent.putExtra("sCharger_sort", imapElecCarChargingInfo.GetAttributeVal(0, "charger_sort"));
                        intent.putExtra("sCharging_Ratio", imapElecCarChargingInfo.GetAttributeVal(0, "charging_ratio"));
                        intent.putExtra("sStart_Time", imapElecCarChargingInfo.GetAttributeVal(0, "start_time"));
                        intent.putExtra("sRemain_Time", imapElecCarChargingInfo.GetAttributeVal(0, "remain_time"));
                        intent.putExtra("sMessage", imapElecCarChargingInfo.GetAttributeVal(0, "c_msg"));
                        
                        getApplicationContext().sendBroadcast(intent);             
                    }                                  
                } catch (RuntimeException re) {
                    LogUtil.errorLogInfo("", TAG, re);
                }
                catch (Exception e) {
                    Log.e(TAG, "[Exception] LoadElectricCarDataFromServer() -> ProcSuccess");
                    LogUtil.errorLogInfo("", TAG, e);
                }
            }

            @Override
            public void ProcError()
            {
                Log.i(TAG, "[LoadElectricCarDataFromServer] ProcError");
            }

            @Override
            public void ProcDoing()
            {
                Log.i(TAG, "[LoadElectricCarDataFromServer] ProcDoing");
            }
            
        });
    }


    /**
     * 대외향 Call 버튼 점멸 및 On Off 처리
     */
    @SuppressLint("HandlerLeak")
    protected Handler mLedFlickerHandler = new Handler()
    {
    	boolean Flicker = false;
    	
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg)
        {
            if(msg.what == 0) // 콜 수신시 또는 발신시  ...
            {
            	// 점멸 시작 CallButton LED On
            	Flicker = true;
            	mLedFlickerHandler.sendEmptyMessageDelayed(1, 500);
            	WallPadInterface wpdifc  = new WallPadInterface();
            	wpdifc.callLEDControll(true);
            }
            else if(msg.what == 1)
            {
            	
            	mLedFlickerHandler.sendEmptyMessageDelayed(0, 500);
            	WallPadInterface wpdifc  = new WallPadInterface();
            	wpdifc.callLEDControll(false);
            	
            }
            else if(msg.what == 2) // 통화중
            {
            	Flicker = false;
            }
            else if(msg.what == 4) // 통화종료
            {
            	Flicker = false;
            }
        }
    };



    public void GetEnergyServerInfo()
    {
        WallpadDeviceSet devSet = new WallpadDeviceSet(getContext());
        String[] MetringDB = devSet.GetSettingData("에너지관리서버");
        devSet.closeDB();

        if (MetringDB != null)
        {
            try
            {
                String devInfo = MetringDB[1];

                devInfo = devInfo.replace('(', '_');
                devInfo = devInfo.replace(':', '_');
                devInfo = devInfo.replace(')', '_');

                String[] MetringInfo = devInfo.split("_");

                // MetringInfo[1] -> 회로수
                // MetringInfo[3] -> 에너지관리서버 사용여부 사용함 or 사용안함
                // MetringInfo[4] -> IP
                // MetringInfo[5] -> IP정보
                // MetringInfo[6] -> 검침일사용자설정
                // MetringInfo[7] -> 사용함 또는 사용안함
                
                if(MetringInfo[3].equals("사용함") == true)
                {
                    bUseofNot_EnergyServer = true;
                }                
            }
            catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e)
            {
                LogUtil.errorLogInfo("", TAG, e);
            }
        }
        else
        {
            
        }
        Log.d(TAG, "[bUseofNot_EnergyServer] bUseofNot_EnergyServer :"+bUseofNot_EnergyServer);
    }


    /**
     * 카카오 사용 여부 체크
     * @return
     */
    public boolean getKakaoHomeCheck()
    {
        boolean result  = false;
        WallpadDeviceSet mWallpadDeviceSet = null;
        mWallpadDeviceSet = new WallpadDeviceSet(getContext());
        try {
            result = mWallpadDeviceSet.Get_KakaoUse();
        }
        catch (SQLException e)
        {
            LogUtil.errorLogInfo("", TAG, e);
        }

        return result;
    }

    /**
     * 사용자 설정(카카오를 볼것인지 아닌지를 설정)
     * @return
     */
    public boolean getShowKakaoCheck()
    {
        boolean result  = false;
        WallpadDeviceSet mWallpadDeviceSet = null;
        mWallpadDeviceSet = new WallpadDeviceSet(getContext());
        try {
            result = mWallpadDeviceSet.Get_KakaoShow();
        }
        catch (SQLException e)
        {
            LogUtil.errorLogInfo("", TAG, e);
        }

        return result;
    }
    
    public boolean GetEnergyAlarm()
    {
        boolean ret = false;
        
        WallpadStatusData DBMGR = null;  
        DBMGR = new WallpadStatusData(getContext());
        
        if( DBMGR != null )
        {
	        try
	        {
	            ret = DBMGR.GetRemoteMetering_Alarm();            
	        }
	        catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
                ret = false;
                DBMGR.insertWallPADDB(WallpadStatusData.REMOTE_METERING_ALARM_USE, WallpadStatusData.REMOTE_METERING_ALARM_USE_DEFAULT);
            }
            catch (Exception e)
	        {
	            LogUtil.errorLogInfo("", TAG, e);
	            ret = false;
	            DBMGR.insertWallPADDB(WallpadStatusData.REMOTE_METERING_ALARM_USE, WallpadStatusData.REMOTE_METERING_ALARM_USE_DEFAULT);
	        }
	        
	        DBMGR.closeDB();
        }
        
        bUseofNot_EnergyAlarm = ret;
        Log.d(TAG, "[bUseofNot_EnergyAlarm] bUseofNot_EnergyAlarm :"+bUseofNot_EnergyAlarm);
        return ret;
    }
    
    /**
     * @description
     * 에너지 사용량 알림 시간 얻어오기
     * @return int Hour시간 값
     */
    public int GetEnergyAlarmTime()
    {
        int ret = 12;
        
        WallpadStatusData DBMGR = null;  
        DBMGR = new WallpadStatusData(getContext());
            
        try
        {
            ret = DBMGR.GetRemoteMetering_AlarmTime();            
        }
        catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e)
        {
            LogUtil.errorLogInfo("", TAG, e);
        }
        
        DBMGR.closeDB();
        
        Log.d(TAG, "[GetEnergyAlarmTime] GetEnergyAlarmTime :"+ret);
        return ret;
    }
    
    public void ClearEnergyUsage()
    {
        ResultGetIntent = false;
        
        elect_target = "Error";
        elect_used = "Error";
        elect_info = "Error";

        water_target = "Error";
        water_used = "Error";
        water_info = "Error";

        gas_target = "Error";
        gas_used = "Error";
        gas_info = "Error";

        hotwater_target = "Error";
        hotwater_used = "Error";
        hotwater_info = "Error";

        heating_target = "Error";
        heating_used = "Error";
        heating_info = "Error";
    }
    
    // 신규 통화어플 실행을 위한 코드 (JEFF, 2016.05.23)
    // 통화주체를 다루는 enum
    public enum CALLOWNER {
        NONE,
        WALLPAD,
        MOBILE,
        SUB_WALLPAD,
        KITCHEN_TV,
        BATH_PHONE,
        BATH_TV,
        UNIVERSAL_DEVICE,
        ERROR;
    }
    public enum CALLEVENTTYPE {
        RECEIVE_CALL,   // 호출 수신 (호출 수신)
        TRYING_CALL,   // 호출 시도중 (호출 발신)
        RECEIVE_CALL_2ND,   // 멀티콜 수신 (호출 수신)
        RECEIVE_CALL_ACK,   // 호출응답 수신 (호출 발신)
        REQUEST_FRONT_MONITORING,   // 호출응답 수신 (호출 발신)
        CONNECT_CALL,   // 통화 시작
        TERMINATE_CALL,   // 통화 종료
        CANCEL_CALL,   // 호출 취소
        CANCEL_CALL_2ND,   // 멀티콜 호출 취소
        REJECT_CALL,   // 호출수신 거절
        REJECT_BUSY_CALL,   // 통화중 호출수신 거절
        FORWARD_CALL,   // 착신전환 설정
        CALLERID,   // Caller ID_OLD
        TIMEOUT_1STCALL,   // 1st Call Timeout
        TIMEOUT_2NDCALL,   // 2nd Call Timeout
        TIMEOUT_3RDCALL,   // 3rd Call Timeout
        MOIP_VIDEO_SET,   // MoIP 영상통화 설정
        DOOR_OPEN,   // 문열림 설정
        DETECT_STRANGER, // 거동수상자 발생
        NONE;
    }
    public enum CALLTYPE {
        NONE,
        FRONT,
        RESIDENCE,
        LOBBY,
        GUARD,
        PSTN,
        IHUB,
        HISTORY_CALL,
        HISTORY_VISITORPIC,
        FRONT_RECORD, // 현관_영상녹화
        FRONT_TAKEPIC, // 현관_사진촬영
        ERROR,
    }
    public static class CALLTRIGGER {
        public static String CALLOWNER = "CALLOWNER";
        public static String CALLEVENTTYPE = "CALLEVENTTYPE";
        public static String CALLTYPE = "CALLTYPE";
        public enum SOURCE {
            USER,
            CALL_RECEIVE,
            SUBPHONE
        }
        public enum TYPE {
            MENU,
            FRONT,
            LOBBY,
            GUARD,
            RESIDENCE,
            PSTN
        }
    }
    String strWallPadCallPakageName = "kr.co.icontrols.wallpadcall";
    
    public void runWallPadCallAPKByUX(int nScreen) {
        try {
	        Log.i(TAG, "[runWallPadCallAPKByUX] nScreen [" + nScreen + "]");
	        
	        CALLOWNER eCallOwner = CALLOWNER.NONE;
	        CALLEVENTTYPE eEventType = CALLEVENTTYPE.NONE;
	        CALLTYPE eCallType = CALLTYPE.GUARD;
	        
	        if (nScreen == ID.LINKEDSCREEN.SubCall.Door) {
	            if (getIsSubWallpad()) eCallOwner = CALLOWNER.SUB_WALLPAD;
	            else eCallOwner = CALLOWNER.WALLPAD;
	            eEventType = CALLEVENTTYPE.REQUEST_FRONT_MONITORING;
	            eCallType = CALLTYPE.FRONT;
	        }
            else if (nScreen == ID.LINKEDSCREEN.SubCall.Door_Record) {
                eCallType = CALLTYPE.FRONT;
                eEventType = CALLEVENTTYPE.DETECT_STRANGER;
            }
	        else if (nScreen == ID.LINKEDSCREEN.SubCall.Lobby) eCallType = CALLTYPE.LOBBY;
	        else if (nScreen == ID.LINKEDSCREEN.SubCall.Guard) eCallType = CALLTYPE.GUARD;
	        else if (nScreen == ID.LINKEDSCREEN.SubCall.Neighboor) eCallType = CALLTYPE.RESIDENCE;
	        else if (nScreen == ID.LINKEDSCREEN.SubCall.Pstn) eCallType = CALLTYPE.PSTN;
	        else if (nScreen == ID.LINKEDSCREEN.SubCall.CallList) eCallType = CALLTYPE.HISTORY_CALL;
	        else if (nScreen == ID.LINKEDSCREEN.SubCall.Visitor) eCallType = CALLTYPE.HISTORY_VISITORPIC;
	        else {
	            Log.w(TAG, "[runWallPadCallAPKByUX] NOT Supported nScreen!! [" + nScreen + "]");
	        }

            Log.i(TAG, "[runWallPadCallAPKByUX] eCallOwner [" + eCallOwner + "], eEventType [" + eEventType + "], eCallType [" + eCallType + "]");

            if (getIsSubWallpad()) {
                // 서브월패드는 국선 기능을 제공하지 않는다.
                if (eCallType != CALLTYPE.PSTN) runCallMainActivity(eCallOwner, eEventType, eCallType);
            }
            else {
                runCallMainActivity(eCallOwner, eEventType, eCallType);
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runWallPadCallAPKByUX(int nScreen)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void runWallPadCallAPKByUX(int nScreen, int nEmerState) {
        try {
            Log.i(TAG, "[runWallPadCallAPKByUX] nScreen [" + nScreen + "], nEmerState [" + nEmerState + "]");

            CALLOWNER eCallOwner = CALLOWNER.NONE;
            CALLEVENTTYPE eEventType = CALLEVENTTYPE.NONE;
            CALLTYPE eCallType = CALLTYPE.GUARD;

            if (nScreen == ID.LINKEDSCREEN.SubCall.Door) {
                if (getIsSubWallpad()) eCallOwner = CALLOWNER.SUB_WALLPAD;
                else eCallOwner = CALLOWNER.WALLPAD;
                eEventType = CALLEVENTTYPE.REQUEST_FRONT_MONITORING;
                eCallType = CALLTYPE.FRONT;
            }
            else if (nScreen == ID.LINKEDSCREEN.SubCall.Door_Record) {
                eCallType = CALLTYPE.FRONT;
                eEventType = CALLEVENTTYPE.DETECT_STRANGER;
            }
            else if (nScreen == ID.LINKEDSCREEN.SubCall.Lobby) eCallType = CALLTYPE.LOBBY;
            else if (nScreen == ID.LINKEDSCREEN.SubCall.Guard) eCallType = CALLTYPE.GUARD;
            else if (nScreen == ID.LINKEDSCREEN.SubCall.Neighboor) eCallType = CALLTYPE.RESIDENCE;
            else if (nScreen == ID.LINKEDSCREEN.SubCall.Pstn) eCallType = CALLTYPE.PSTN;
            else if (nScreen == ID.LINKEDSCREEN.SubCall.CallList) eCallType = CALLTYPE.HISTORY_CALL;
            else if (nScreen == ID.LINKEDSCREEN.SubCall.Visitor) eCallType = CALLTYPE.HISTORY_VISITORPIC;
            else {
                Log.w(TAG, "[runWallPadCallAPKByUX] NOT Supported nScreen!! [" + nScreen + "]");
            }

            Log.i(TAG, "[runWallPadCallAPKByUX] eCallOwner [" + eCallOwner + "], eEventType [" + eEventType + "], eCallType [" + eCallType + "]");



            if (getIsSubWallpad()) {
                // 서브월패드는 국선 기능을 제공하지 않는다.
                if (eCallType != CALLTYPE.PSTN) runCallMainActivity(eCallOwner, eEventType, eCallType, nEmerState);
            }
            else {
                runCallMainActivity(eCallOwner, eEventType, eCallType, nEmerState);
            }

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runWallPadCallAPKByUX(int nScreen, int nEmerState)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    static public Handler CallIntentHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            if(CallBrList!=null && CallBrList.size() > 0)
            {
                Intent intent = CallBrList.get(0);
                mContext_call.sendBroadcast(intent);
                Log.d(TAG, "jglee - Call Handler Next 호출 > Action : " + MainActivity.CallBrList.get(0).getAction() +  ", Extra : " + MainActivity.CallBrList.get(0).getIntExtra(Common.BR_MAIN_NOTI.KIND,0) );
            }

        }
    };
    
    public void runCallMainActivity(CALLOWNER eCallOwner, CALLEVENTTYPE eEventType, CALLTYPE eCallType) {
        try {
            Log.i(TAG, "[runCallMainActivity] Common.bWallPadCallLive [" + Common.bWallPadCallLive + "], eCallOwner [" + eCallOwner + "], eEventType [" + eEventType + "], eCallType [" + eCallType + "]");
            if (!Common.bWallPadCallLive) {
                // 통화어플을 실행시킨다.
                sendLCDBacklightStatus(true);

                ComponentName mComponentName = new ComponentName("kr.co.icontrols.wallpadcall", "kr.co.icontrols.wallpadcall.MainActivity");
                Intent mIntent = new Intent(Intent.ACTION_MAIN);
//                mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                mIntent.putExtra(CALLTRIGGER.CALLOWNER, eCallOwner.toString());
                mIntent.putExtra(CALLTRIGGER.CALLEVENTTYPE, eEventType.toString());
                mIntent.putExtra(CALLTRIGGER.CALLTYPE, eCallType.toString());
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mIntent.setComponent(mComponentName);
                startActivity(mIntent);
            }
            else {
                Log.w(TAG, "[runCallMainActivity] WallPadCall is already running!!");
            }
            
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runCallMainActivity()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    /**
     * Edited by jeff (2020.06.22)
     * LCD 잔상 현장 복구/보호를 위해 실행되고 있는 LCD Keeper를 종료하기 위해, 통화 App이 실행되면서
     * backlight를 On하기 전에 이를 알리는 BR를 수신하여 LCD Keeper를 종료한다.
     * @param bOn
     */
    private void sendLCDBacklightStatus(boolean bOn) {
        try {
            Log.d(TAG,"[sendLCDBacklightStatus] bOn [" + bOn + "]");
            Intent mIntent = new Intent();
            if (bOn) mIntent.setAction(define.NOTIFY_ACNAME_LCD_BACKLIGHT_ON);
            else mIntent.setAction(define.NOTIFY_ACNAME_LCD_BACKLIGHT_OFF);
            getApplicationContext().sendBroadcast(mIntent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendLCDBacklightStatus(boolean bOn)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void runCallMainActivity(CALLOWNER eCallOwner, CALLEVENTTYPE eEventType, CALLTYPE eCallType, int nEmerState) {
        try {
            Log.i(TAG, "[runCallMainActivity] Common.bWallPadCallLive [" + Common.bWallPadCallLive + "], eCallOwner [" + eCallOwner + "], eEventType [" + eEventType + "], eCallType [" + eCallType + "], nEmerState [" + nEmerState + "]");
            if (!Common.bWallPadCallLive) {
                // 통화어플을 실행시킨다.
                sendLCDBacklightStatus(true);

                if (eEventType == CALLEVENTTYPE.DETECT_STRANGER) {
                    if (nEmerState >= 0) {
                        if (nEmerState != WallpadStatusData.GUARD_OUT)
                            Common.SendAppFinishReqBR(getApplicationContext());
                    }
                }

                ComponentName mComponentName = new ComponentName("kr.co.icontrols.wallpadcall", "kr.co.icontrols.wallpadcall.MainActivity");
                Intent mIntent = new Intent(Intent.ACTION_MAIN);
//                mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                mIntent.putExtra(CALLTRIGGER.CALLOWNER, eCallOwner.toString());
                mIntent.putExtra(CALLTRIGGER.CALLEVENTTYPE, eEventType.toString());
                mIntent.putExtra(CALLTRIGGER.CALLTYPE, eCallType.toString());
                mIntent.putExtra("EMERGENCY_STATE", nEmerState);
                if (nEmerState != WallpadStatusData.GUARD_OUT) Common.SendAppFinishReqBR(getApplicationContext());
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mIntent.setComponent(mComponentName);
                startActivity(mIntent);
            }
            else {
                Log.w(TAG, "[runCallMainActivity] WallPadCall is already running!!");
            }

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runCallMainActivity(CALLOWNER eCallOwner, CALLEVENTTYPE eEventType, CALLTYPE eCallType, int nEmerState)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private String getTopActivity() {
        try {
            ActivityManager mActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> mTaskInfo = mActivityManager.getRunningTasks(1);
//            LOG_INFO("[isMainActivityTop] getClassName = " + mTaskInfo.get(0).topActivity.getClassName());
            ComponentName mComponentName = mTaskInfo.get(0).topActivity;
//            LOG_INFO("[isMainActivityTop] getPackageName = " + mComponentName.getPackageName());
            return mComponentName.getPackageName();
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return null;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getTopActivity()");
            LogUtil.errorLogInfo("", TAG, e);
            return null;
        }
    }

    /**
     * 월패드에 설치된 APP들의 패키지 명 및 버전을 저장하는 클래스
     * **/
    class PackageVersionInfo {
        protected String strPackageName;
        protected String strPackageVersion;
                
        public PackageVersionInfo(String strName, String strVersion) {
            strPackageName = strName;
            strPackageVersion = strVersion;
        }
               
        public String getPackageName() {
            return strPackageName;
        }
        public String getPackageVersion() {
            return strPackageVersion;
        }
    }   
    
    /**
     * 통화 타임아웃 DB정보 초기화 (무조건 사용함으로 변경)
     * **/
    public void setCallAppTimeoutAsDefault() {
        WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(getContext());
        try {
            mWallpadDeviceSet.Set_CallAppCallTimeout(true);
            mWallpadDeviceSet.closeDB();
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            if (mWallpadDeviceSet != null) mWallpadDeviceSet.closeDB();
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] setCallAppTimeoutAsDefault()");
            LogUtil.errorLogInfo("", TAG, e);
            if (mWallpadDeviceSet != null) mWallpadDeviceSet.closeDB();
        }
    }
    
    /**
     * 동호 설정 화면 나오게 처리
     * **/
    private void startManagerSettingSetAddress() {
        try {
            Intent mIntent = new Intent(Intent.ACTION_MAIN);
            MAINStatus = MAIN_WAIT_SETIP;
            mIntent.setComponent(new ComponentName("com.artncore.managersetting", "com.artncore.managersetting.ui.activities.SetAddress"));
            mIntent.putExtra("KIND", "SOLO");
            startActivity(mIntent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] startManagerSettingSetAddress()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private Handler mGetCallHistoryCheckHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
//                CheckCallData_CalledCountAndVisitorCount();
                checkEventNotifications();
            }
        }
    };
    
    /**
     * 음력 데이터를 raw resource에서 wallpaddata폴더 밑으로 복사한다.
     * **/
    private void copyDataBase(String OutputDBPath) throws IOException {
        // Open your local db as the input stream
        //InputStream myInput = this.getAssets().open("luna_db.db");
        InputStream myInput = getResources().openRawResource(R.raw.luna_db);
        // Path to the just created empty db
        String outFileName = OutputDBPath;
        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        try {
            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0)
            {
                myOutput.write(buffer, 0, length);
            }

            // Close the streams
            myOutput.flush();
        }
        catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e)
        {
            LogUtil.errorLogInfo("", TAG, e);
        }
        finally {
            if(myOutput!=null)
                myOutput.close();
            myOutput = null;

            if(myInput!=null)
                myInput.close();
            myInput = null;
        }




    }
    
    @SuppressLint("HandlerLeak")
    protected Handler mLCD_SleepHandler = new Handler()
    {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what == 0) {
                try {
                    if (m_ModelHouseSleepModeRelease == true) {
                        if (Version.getPlatformType() == Version.PLATFORM_TYPE.A40i) {
                            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                        }
                        else {
                            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                        }
						Log.i(TAG, "[SAMPLE SLEEP MODE] Never Sleep Run ~~~");
                    }
                } catch (RuntimeException re) {
                    LogUtil.errorLogInfo("", TAG, re);
                }
                catch (Exception e) {
                    LogUtil.errorLogInfo("", TAG, e);
                }
                
            }
        }
    };

    public void runIcon(int nIconID) {
        try {
            Log.d(TAG, "[runIcon] nIconID [" + nIconID + "]");

            if (nIconID == ID.ICONS.MENUS.MAIN_ELEVATOR.getID()) {
                // DB를 체크해서 층표시이면 팝업을 띄우고 아니면 바로 호출하도록 한다
                String  strElevShortEnabled = Common.getSubDevListItem(this.getContext() ,Common.SETTING_ITEM_SUB_DEVICE_ELEVATOR);
                if(strElevShortEnabled!=null)
                {
                    Log.d(TAG, "[runIcon] strElevShortEnabled [" + strElevShortEnabled + "]");

                    if (strElevShortEnabled.contains("사용함") && strElevShortEnabled.contains("기본")) {
                        Sound().Play(SND.effect.TOUCH_LATCHED);
                        Intent intent = new Intent(Common.BR_MAIN_NOTI.ACNAME_MAIN_NOTI, null);
                        intent.putExtra(Common.BR_MAIN_NOTI.KIND, Common.BR_MAIN_NOTI.CALL_ELEVATOR_DOWN);
                        getContext().sendBroadcast(intent);
                    }
                    else {
                        ((MainActivity)(getContext())).StartPopup(ID_OLD.SCREENS.ElevatorPopupScreen);
                    }
                }

            }
            else if (nIconID == ID.ICONS.MENUS.MAIN_LIGHTS_OUT.getID()) {
                ((MainActivity)(getContext())).StartPopup(ID.POPUPS.POPUP_COLLECTIVELIGHTCTRL);
            }
            else if (nIconID == ID.ICONS.MENUS.MAIN_CALRENDAR.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.TimeSetting);
            }
            else if (nIconID == ID.ICONS.MENUS.MAIN_WEATHER.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.Weather);
            }
            else if (nIconID == ID.ICONS.MENUS.TALK_FRONT.getID()) {
//                Common.command_iGW200( this.getContext(), Common.IGW200_DOOR_MONITERING );
                m_CallSubMenuScreen.callStartCallAPK(ID.LINKEDSCREEN.SubCall.Door);
            }
            else if (nIconID == ID.ICONS.MENUS.TALK_LOBBY.getID()) {
                // 로비는 수신시에만 출력되는 화면이므로 해당코드 없음
            }
            else if (nIconID == ID.ICONS.MENUS.TALK_NEIGHBOR.getID()) {
                m_CallSubMenuScreen.callStartCallAPK(ID.LINKEDSCREEN.SubCall.Neighboor);
            }
            else if (nIconID == ID.ICONS.MENUS.TALK_GUARD.getID()) {
                m_CallSubMenuScreen.callStartCallAPK(ID.LINKEDSCREEN.SubCall.Guard);
            }
            else if (nIconID == ID.ICONS.MENUS.TALK_PHONE.getID()) {
                m_CallSubMenuScreen.callStartCallAPK(ID.LINKEDSCREEN.SubCall.Pstn);
            }
            else if (nIconID == ID.ICONS.MENUS.TALK_CALLHISTORY.getID()) {
                m_CallSubMenuScreen.callStartCallAPK(ID.LINKEDSCREEN.SubCall.CallList);
            }
            else if (nIconID == ID.ICONS.MENUS.TALK_VISITORPIC.getID()) {
                m_CallSubMenuScreen.callStartCallAPK(ID.LINKEDSCREEN.SubCall.Visitor);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_LIGHT.getID()) {
                // 모델별 설정에 따라 구분하여 호출하는 기능 추가해야함
                WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(mContext);
                int[] naLightEnable = mWallpadDeviceSet.Get_Light_info();   // 조명설정 확인
                if (mWallpadDeviceSet != null) mWallpadDeviceSet.closeDB();

//                for (int i = 0; i < naLightEnable.length; i++) Log.i(TAG, "[runIcon] naLightEnable[" + i + "] = " + naLightEnable[i]);

                if (naLightEnable[1] == WallpadDeviceSet.LIGHT_TYPE_HDC_INTLIGHT_ADD_BATCHLIGHT_MULTISWITCH) {
                    m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.HDCLivingNEach_Lamp);
                }
                else {
                    m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.HDC_EachLamp);
                }
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_HEATING.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.Heating_V1);
            }
            //커튼 추가(전동커튼)
            else if (nIconID == ID.ICONS.MENUS.CTRL_CURTAIN.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.Curtain);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_GAS.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.Gas);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_DOORLOCK.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.DoorLockWL);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_VENT.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.ChangAir_Normal);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_OUTLET.getID()) {
                WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(mContext);
                int[] naLightEnable = mWallpadDeviceSet.Get_Light_info();   // 조명설정 확인
                if (mWallpadDeviceSet != null) mWallpadDeviceSet.closeDB();

                if (naLightEnable[1] == WallpadDeviceSet.LIGHT_TYPE_HDC_INTLIGHT_ADD_BATCHLIGHT_MULTISWITCH) {
                    m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.HDCLivingNEach_Concent);
                }
                else {
                    m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.Concent);
                }
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_LIVINGLIGHT.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.HDC_LivingLamp);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_AIRQUALTY.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.AirQualty);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_ELECCOOKTOP.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.ElecCooktop);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_COOKTOPOUTLET.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.CooktopOutlet);
            }
            else if (nIconID == ID.ICONS.MENUS.CTRL_SYSTEMAIRCON.getID()) {
                m_CallSubMenuScreen.callStartHomeCtrlAPK(ID.LINKEDSCREEN.SubMenuCtrl.SystemAircon);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_NOTICE.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.Notice);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_WEATHER.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.Weather);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_MEMO.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.Memo);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_E_FRAME.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.AutoPicture);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_SCHEDULE.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.Schedule);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_CCTV.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.Cctv);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_PARKING.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.Parking);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_PARKINGLIST.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.ParkingList);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_ELECTRICCAR.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.ElecCar);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_INTERLAYERNOISE.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.InterlayerNoiseHistory);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_VISITEDVEHICLEREGI.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.VisitedVehicleRegi);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_BANDLOCATION.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.BandLocation);
            }
            else if (nIconID == ID.ICONS.MENUS.ADD_GUARDINGSTREETLAMP.getID()) {
                m_CallSubMenuScreen.callStartAddServiceAPK(ID.LINKEDSCREEN.SubMenuAddService.GuardingStreetLamp);
            }
            else if (nIconID == ID.ICONS.MENUS.SECURITY_SETARMED.getID()) {
                runSecurityAPK(ID.LINKEDSCREEN.SubMenuSecurity.SecurityMain);
            }
            else if (nIconID == ID.ICONS.MENUS.SECURITY_DEVICELINK.getID()) {
                runSecurityAPK(ID.LINKEDSCREEN.SubMenuSecurity.LinkDeviceSet);
            }
            else if (nIconID == ID.ICONS.MENUS.SECURITY_DEVICELINKSLEEP.getID()) {
                runSecurityAPK(ID.LINKEDSCREEN.SubMenuSecurity.lnkBedDeviceSet);
            }
            else if (nIconID == ID.ICONS.MENUS.SECURITY_ACCESSHISTORY.getID()) {
                runSecurityAPK(ID.LINKEDSCREEN.SubMenuSecurity.AccessHistoryDoor);
            }
            else if (nIconID == ID.ICONS.MENUS.SECURITY_VISITORVIDEO.getID()) {
                runSecurityAPK(ID.LINKEDSCREEN.SubMenuSecurity.VisitorVideo);
            }
            else if (nIconID == ID.ICONS.MENUS.ENERGY_SMARTPANEL.getID()) {
                m_CallSubMenuScreen.callStartEnergyAPK(ID.LINKEDSCREEN.SubMenuEnergy.SmartPanel);
            }
            else if (nIconID == ID.ICONS.MENUS.ENERGY_SMARTLIGHT.getID()) {
                m_CallSubMenuScreen.callStartEnergyAPK(ID.LINKEDSCREEN.SubMenuEnergy.SmartLight);
            }
            else if (nIconID == ID.ICONS.MENUS.ENERGY_SMARTOUTLET.getID()) {
                m_CallSubMenuScreen.callStartEnergyAPK(ID.LINKEDSCREEN.SubMenuEnergy.SmartOutlet);
            }
            else if (nIconID == ID.ICONS.MENUS.ENERGY_ENERGYMETER.getID()) {
                m_CallSubMenuScreen.callStartEnergyAPK(ID.LINKEDSCREEN.SubMenuEnergy.IEnergy);
            }
            else if (nIconID == ID.ICONS.MENUS.ENERGY_REMOTEMETER.getID()) {
                m_CallSubMenuScreen.callStartEnergyAPK(ID.LINKEDSCREEN.SubMenuEnergy.RemoteMeter);
            }
            else if (nIconID == ID.ICONS.MENUS.ENERGY_ENERGYCONSUMPTION.getID()) {
                m_CallSubMenuScreen.callStartEnergyAPK(ID.LINKEDSCREEN.SubMenuEnergy.EnergyMgr);
            }
            else if (nIconID == ID.ICONS.MENUS.ENERGY_ENERGYCOSTTABLE.getID()) {
                m_CallSubMenuScreen.callStartEnergyAPK(ID.LINKEDSCREEN.SubMenuEnergy.CostTable);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_CONFIG.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.Configuration);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_CLREANSCREEN.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.CleanLcd);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_PWCHANGE.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.PassWordChange);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_MORNINGCALL.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.MoningCall);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_SMARTKEY.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.SmartKey);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_SMARTBAND.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.SmartBand);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_ACCESSCARD.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.RfCard);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_CALENDAR.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.TimeSetting);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_REMOTECALLUSER.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.RemoteCallUser);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_REMOTECTRL.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.MobileDeviceReg);
            }
            else if (nIconID == ID.ICONS.MENUS.SETTING_OCCUPANCYSENSOR.getID()) {
                m_CallSubMenuScreen.callStartConfigAPK(ID.LINKEDSCREEN.SubMenuConfig.OccupancySensorConfig);
            }
            else {
                Log.w(TAG, "[runShortcut] nIconID is not supported!! [" + nIconID + "]");
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runShortcut(int nIconID)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void runSecurityAPK(int nScreenID) {
        try {
            WallpadStatusData wdb = new WallpadStatusData(this.getContext());
            int nSecurityMode = wdb.GetAlarmStatus();
            wdb.closeDB();

            Log.w(TAG, "[runSecurityAPK] nSecurityMode [" + nSecurityMode + "]");

            if (nSecurityMode == WallpadStatusData.GUARD_IN) {
                // 팝업 띄워서 재택모드 해제 유도
                StartPopup(ID.POPUPS.POPUP_RELEASEINMODE);
//                ((MainActivity)(getContext())).StartPopup(ID_OLD.SCREENS.SecurityReleasePopupScreen);
            }
            else if (nSecurityMode == WallpadStatusData.OUT_MODE) {
                // 팝업 띄워서 외출모드 해제 유도
                StartPopup(ID.POPUPS.POPUP_RELEASEOUTMODE);
//                ((MainActivity)(getContext())).StartPopup(ID_OLD.SCREENS.OutModeReleasePopupScreen);
            }
            else if (nSecurityMode == WallpadStatusData.ALARM_STOP) {
                // 알람 화면을 띄우도록 한다.
                runEmergencyAPK(this, getAlarmType(), 2 , "모름");
            }
            else {
                m_CallSubMenuScreen.callStartSecurityAPK(nScreenID);
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runSecurityAPK(int nScreenID)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void runEmergencyAPK(Context context, int nScreenID, int startOption, String detailInfo) {
        try {
            // DB 체크 해서 띄우 도록 한다.
            int [] m_EmerMenuList = new int[4];
            m_EmerMenuList[0] = ID.LINKEDSCREEN.SubEmergency.EMER_ALARM;
            m_EmerMenuList[1] = ID.LINKEDSCREEN.SubEmergency.FIRE_ALARM;
            m_EmerMenuList[2] = ID.LINKEDSCREEN.SubEmergency.BREAKIN_ALARM;
            m_EmerMenuList[3] = ID.LINKEDSCREEN.SubEmergency.LADDER_ALARM;

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.putExtra(Common.MENU_ID_LIST, m_EmerMenuList);                   // KEY : MENU_ID_LIST
            intent.putExtra(Common.MENU_START_ID, nScreenID);              			// KEY : MENU_START_ID
            intent.putExtra(Common.MENU_START_OPTION, startOption);       	 		// KEY : MENU_START_OPTION
            intent.putExtra(Common.MENU_DETAIL_INFO, detailInfo);
            intent.setComponent(new ComponentName(Common.EMER_ALARM_APK, Common.EMER_ALARM_APK + Common.MAIN_ACTIVITY ));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runEmergencyAPK(Context context, int nScreenID, int startOption, String detailInfo)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public int getAlarmType() {
        WallpadStatusData SetData = new WallpadStatusData(this.getContext());
        int alarmtype = SetData.GetAlarmType();
        SetData.closeDB();
        int Menu_Start_Option = ID.LINKEDSCREEN.SubEmergency.EMER_ALARM;

        switch (alarmtype) {
            case WallpadStatusData.ALARM_ALERT:
                Menu_Start_Option = ID.LINKEDSCREEN.SubEmergency.FIRE_ALARM;
                break;

            case WallpadStatusData.ALARM_EMM:
                Menu_Start_Option = ID.LINKEDSCREEN.SubEmergency.EMER_ALARM;
                break;

            case WallpadStatusData.ALARM_EVAC:
                Menu_Start_Option = ID.LINKEDSCREEN.SubEmergency.LADDER_ALARM;
                break;

            case WallpadStatusData.ALARM_INVADE:
                Menu_Start_Option = ID.LINKEDSCREEN.SubEmergency.BREAKIN_ALARM;
                break;
        }
        return Menu_Start_Option;
    }

    public void runGoogleLauncher() {
        try {
            ComponentName mComponentName = new ComponentName("com.android.launcher3", "com.android.launcher3.Launcher");
            Intent mIntent = new Intent(Intent.ACTION_MAIN);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.setComponent(mComponentName);
            startActivity(mIntent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runGoogleLauncher()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void setCallAppRunning(boolean bRunning) {
        try {
            Log.i(TAG, "[setCallAppRunning] bRunning [" + bRunning + "]");
            WallpadStatusData DBMGR = new WallpadStatusData(getApplicationContext());
            DBMGR.SetCallAPKStatus(bRunning);
            DBMGR.closeDB();
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] setCallAppRunning(boolean bRunning)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private void registerMainActivityBR() {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(Common.BR_REQUEST_APK_RUN);
            filter.addAction(ACTION_TIME_TICK);
            filter.addAction(Common.BR_PLAY_SOUND);
            filter.addAction(define.NOTIFY_ACNAME_LCD_BACKLIGHT_ON);
            filter.addAction(define.NOTIFY_ACNAME_LCD_BACKLIGHT_OFF);
            mContext.registerReceiver(MainActivityBroadcastReceiver, filter);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] registerMainActivityBR()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    String strAPKType = "APKType";
    String strMenuType = "MenuType";
    String strSoundID = "SoundID";
    BroadcastReceiver MainActivityBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (((MainActivity)(getContext())).getMainSubScreenLoadingComplite() == false)
                    return;

                String strActionName = intent.getAction();

                Log.d(TAG,"[MainActivityBroadcastReceiver] strActionName [" + strActionName + "]");
                if (strActionName.equals(Common.BR_REQUEST_APK_RUN)) {
                    Log.d(TAG, "[MainActivityBroadcastReceiver] (BR.Action) BR_REQUEST_APK_RUN");
                    int nAPKType = intent.getIntExtra(strAPKType,0);
                    int nMenuType = intent.getIntExtra(strMenuType,0);
                    int nCardNum = intent.getIntExtra(Common.BR_MAIN_NOTI.CARD_NUM, 0);
                    Log.d(TAG, "[MainActivityBroadcastReceiver] nAPKType [" + nAPKType + "], nMenuType [" + nMenuType + "], nCardNum [" + nCardNum + "]");
                    if (nAPKType ==  ID.LINKEDSCREEN.SubCall.BASE) {
                        m_CallSubMenuScreen.callStartCallAPK(nMenuType);
                    }
                    else if (nAPKType ==  ID.LINKEDSCREEN.SubMenuAddService.BASE) {
                        m_CallSubMenuScreen.callStartAddServiceAPK(nMenuType, nCardNum);
                    }
                }
                else if (strActionName.equals(ACTION_TIME_TICK)) {
//                    checkTimeTasks();
                    if (bLCDKeeperUsage) ctrlLCDKeeper();
                }
                else if (strActionName.equals(Common.BR_PLAY_SOUND)) {
                    int nSoundID = intent.getIntExtra(strSoundID,0);
                    Sound().Play(nSoundID);
                }
                else if (strActionName.equals(define.NOTIFY_ACNAME_LCD_BACKLIGHT_ON)) {
                    Log.d(TAG, "[MainActivityBroadcastReceiver] (BR.Action) NOTIFY_ACNAME_LCD_BACKLIGHT_ON: bLCDKeeperUsage [" + bLCDKeeperUsage + "], nLCDKeeperType [" + getLCDKeeperType(nLCDKeeperType) + "]");
                    if (bLCDKeeperUsage) {
                        bLCDBacklightPower = true;
                        ctrlLCDKeeper();
                    }
                }
                else if (strActionName.equals(define.NOTIFY_ACNAME_LCD_BACKLIGHT_OFF)) {
                    Log.d(TAG, "[MainActivityBroadcastReceiver] (BR.Action) NOTIFY_ACNAME_LCD_BACKLIGHT_OFF: bLCDKeeperUsage [" + bLCDKeeperUsage + "], nLCDKeeperType [" + getLCDKeeperType(nLCDKeeperType) + "]");
                    if (bLCDKeeperUsage) {
                        bLCDBacklightPower = false;
                        ctrlLCDKeeper();
                    }
                }
                else {
                    Log.w(TAG,"[MainActivityBroadcastReceiver] Not supported strActionName [" + strActionName + "]");
                }
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] MainActivityBroadcastReceiver()");
                LogUtil.errorLogInfo("", TAG, e);
            }
        }
    };

    public Common.GUI_TYPE checkGUIType(Context context) {
        try {
            WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(context);
            String strGUIType = mWallpadDeviceSet.GetMainGUISelect();
            mWallpadDeviceSet.closeDB();
            if (strGUIType.equalsIgnoreCase(WallpadDeviceSet.MAIN_GUI_TYPE_DEFAULT)) return Common.GUI_TYPE.STANDARD;
            else if (strGUIType.equalsIgnoreCase(WallpadDeviceSet.MAIN_GUI_TYPE_METRO)) return Common.GUI_TYPE.METRO;
            else if (strGUIType.equalsIgnoreCase(WallpadDeviceSet.MAIN_GUI_TYPE_HYOSUNG)) return Common.GUI_TYPE.HYOSUNG;
            else if (strGUIType.equalsIgnoreCase(WallpadDeviceSet.MAIN_GUI_TYPE_HIMCHAN)) return Common.GUI_TYPE.HIMCHAN;
            else return Common.GUI_TYPE.STANDARD;
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return Common.GUI_TYPE.STANDARD;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkGUIType(Context context)");
            LogUtil.errorLogInfo("", TAG, e);
            return Common.GUI_TYPE.STANDARD;
        }
    }

    public void finishActivity() {
        try {
            Log.i(TAG, "[finishActivity]");
            super.finish();
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] finishActivity()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    // MainActivity Handler
    public final class HANDLERMSG {
        public final static int CHECK_FLIPPER_MAINSCREEN_ID = 100;
        public final static int CHECK_WALLPAD_CAMERA_INIT = 200;
        public final static int CHECK_WALLPAD_CAMERA_REMOVE = 300;
        public final static int CHECK_WALLPAD_CAMERA_RESET = 400;
        public final static int CHECK_WALLPAD_CAMERA_CHECK = 500;
        public final static int FINISH_ACTIVITY = 999;
    }

    public Handler MainHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            Log.d(TAG, "[MainHandler] MainHandler : what [" + msg.what + "], arg1 [" + msg.arg1 + "], arg2 [" + msg.arg2 + "]");
            switch (msg.what) {
                case HANDLERMSG.CHECK_FLIPPER_MAINSCREEN_ID:
//                    checkMainPage();
                    break;

                case HANDLERMSG.CHECK_WALLPAD_CAMERA_INIT:
                    if (getWallPadCameraUsage()) {
                        initMyVideoSurfaceLayout();
                        sendHandlerMsgDelayed(HANDLERMSG.CHECK_WALLPAD_CAMERA_REMOVE, 0, 0, 3000);   // 월패드 카메라 영상을 띄우고 5초뒤에 없앤다.
                    }
                    break;

                case HANDLERMSG.CHECK_WALLPAD_CAMERA_REMOVE:
                    if (getWallPadCameraUsage()) removeMyVideoSurfaceLayout();
                    break;

                case HANDLERMSG.CHECK_WALLPAD_CAMERA_RESET:
                    if (getWallPadCameraUsage()) resetCameraService();
                    break;

                case HANDLERMSG.CHECK_WALLPAD_CAMERA_CHECK:
                    checkCameraLoading();
                    break;

                case HANDLERMSG.FINISH_ACTIVITY:
                    finishActivity();
                    break;

                default:
                    Log.d(TAG, "MainHandler : " + msg.what);
                    break;
            }
        }
    };

    public void sendHandlerMsg(int what, int arg1, int arg2) {
        try {
            Log.i(TAG, "[sendHandlerMsg] what [" + what + "], arg1 [" + arg1 + "], arg2 [" + arg2 + "]");
            Message HandleMsg = MainHandler.obtainMessage();
            HandleMsg.what = what;
            HandleMsg.arg1 = arg1;
            HandleMsg.arg2 = arg2;
            MainHandler.sendMessage(HandleMsg);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendHandlerMsg(msg)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void sendHandlerMsgDelayed(int what, int arg1, int arg2, long delay) {
        try {
            Log.i(TAG, "[sendHandlerMsgDelayed] what [" + what + "], arg1 [" + arg1 + "], arg2 [" + arg2 + "], delay [" + delay + "]");
            Message HandleMsg = MainHandler.obtainMessage();
            HandleMsg.what = what;
            HandleMsg.arg1 = arg1;
            HandleMsg.arg2 = arg2;
            MainHandler.sendMessageDelayed(HandleMsg, delay);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendHandlerMsgDelayed(msg)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private boolean savePresetValue(String strPresetValues) {
        try {
            Log.i(TAG, "[savePresetValue] strPresetValues [" + strPresetValues + "]");
            String[] strParse_01 = strPresetValues.split("/");
            int presetid = Integer.parseInt(strParse_01[0]);
            String[] strParse_02 = strParse_01[1].split(":");
            String onoff = strParse_02[0];
            int dim = Integer.parseInt(strParse_02[1]);
            int color = Integer.parseInt(strParse_02[2]);

            WallpadStatusData mWallpadStatusData = new WallpadStatusData(mContext);
            boolean result = mWallpadStatusData.setLivinglightModeCtrlUnitValues(presetid, 0, "on", dim, color);
            mWallpadStatusData.closeDB();

            Log.d(TAG, "[savePresetValue] result [" + result  + "], onoff [" + onoff  + "], dim [" + dim  + "], color [" + color  + "]");
            if (result) {
                mLightInfo.mPreset[presetid].mLights[0].ONOFF = onoff;
                mLightInfo.mPreset[presetid].mLights[0].DIM = dim;
                mLightInfo.mPreset[presetid].mLights[0].COLOR = color;
                Log.d(TAG,"[savePresetValue] OnOff [" + mLightInfo.mPreset[presetid].mLights[0].ONOFF + "], Level [" + mLightInfo.mPreset[presetid].mLights[0].DIM + "], Color [" + mLightInfo.mPreset[presetid].mLights[0].COLOR + "]");
                return true;
            }
            else {
                Log.w(TAG,"[savePresetValue] Fail to save light preset values!!");
                return false;
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] savePresetValue(String strPresetValues)");
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }

    private void initProximitySensor() {
        try {
            WallpadStatusData mWallpadStatusData = new WallpadStatusData(this);
            int nProximitySensorLevel = mWallpadStatusData.GetCloseSensorValue();
            mWallpadStatusData.closeDB();

            Log.i(TAG, "[initProximitySensor] nProximitySensorLevel = " + nProximitySensorLevel);

            if (nProximitySensorLevel < 0 || 5 < nProximitySensorLevel) {
                Log.w(TAG, "[initProximitySensor] nProximitySensorLevel is out of range!!");
                nProximitySensorLevel = 5;
            }

            int nResult = mIOInterface.setProximitySensorLevel(nProximitySensorLevel * 3);
            Log.i(TAG, "[initProximitySensor] nResult = " + nResult);

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] initProximitySensor()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }



    private boolean checkInterFloorNoiseError() {
        try {
            WallpadStatusData wsd = new WallpadStatusData(getContext());
            String stSensorStatus = wsd.Get_InterlayerSensor_Status();
            wsd.closeDB();

            // 센서 정상 : false, 센서 이상 : true
            Log.i(TAG, "[checkInterFloorNoiseError] stSensorStatus : " + stSensorStatus);
            if (stSensorStatus.equalsIgnoreCase(define.INTERLAYER_NOISE_STATUS_NORMAL)) return false;
            else return true;

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkInterFloorNoiseError()");
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }

    private boolean checkInterFloorNoiseFuncUsage() {
        try {
            WallpadStatusData wsd = new WallpadStatusData(getContext());
            boolean bUsage = wsd.GetNoisePopupUse();
            wsd.closeDB();

            return bUsage;
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkInterFloorNoiseFuncUsage()");
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }
    /**
     * 현관호출 or 전화호출시 사용되는 keycode - Broadcast 을 송신한다.
     *
     * @param nKeyCode - (int) 송신할 keycode
     * @return (int) - >=0 : 성공, <0 : 실패
     */
    private int sendKeyEventBR(int nKeyCode) {
        try {
            Log.i(TAG, "[sendKeyEventBR] nKeyCode [" + nKeyCode +"] -> EVENT_DEVICE_CONTROL");
            KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP, nKeyCode);
            Intent intent = new Intent("EVENT_DEVICE_CONTROL", null);
            intent.putExtra(Intent.EXTRA_KEY_EVENT, event);
            intent.putExtra("keycode",nKeyCode);
            sendBroadcast(intent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return -100;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendKeyEventBR(int nKeyCode) [" + nKeyCode + "]");
            LogUtil.errorLogInfo("", TAG, e);
            return -100;
        }
        return 0;
    }

    // 카카오 연동 관련
    public static boolean bKakaoiEnable = false;

    /**
     * 이진규
     * kakaohome 서비스 사용 유무 판단
     */
    protected boolean bKakaoHomeEnable = false;


     // run Kakao i floating button  실행
    private void startKakaoiFloatingBTN() {
        try {
            Log.i(TAG, "[startKakaoiFloatingBTN] ========== Run Kakao i floating button ==========");
            ComponentName mComponentName = new ComponentName("kr.co.icontrols.wallpadglobalbutton", "kr.co.icontrols.wallpadglobalbutton.MainActivity");
            Intent mIntent = new Intent(Intent.ACTION_MAIN);
            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.setComponent(mComponentName);
            startActivity(mIntent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] startKakaoiFloatingBTN()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void Send_NotiSmartSwitch(int nNoticeCnt, int nParcelCnt, int nVisitorPicCnt)
	{
		try
		{
			Intent intentBR = new Intent();
			intentBR.setAction(define.DRIVER_ISD_NOTIINFO);
			//if( m_NoticeCNT > 0 || m_ParcelCNT > 0 || m_InCallCNT > 0 || m_VisitorCNT > 0  )
			{
				// 아이콘  활성화
				if( nNoticeCnt > 0 )
				{
					Log.d(TAG, "LOG : NOTICE CNT INCREASED ++");
					intentBR.putExtra(define.NOTIBR_ISD_NOTICECNT,  nNoticeCnt);
					Log.d(TAG, "NoticeCNT BroadCast Added");
				}
				else
				{
					intentBR.putExtra(define.NOTIBR_ISD_NOTICECNT,  0);
					Log.d(TAG, "NoticeCNT ZERO Added");
				}

				if( nParcelCnt > 0 )
				{
					Log.d(TAG, "LOG : Parcel CNT INCREASED ++");
					intentBR.putExtra(define.NOTIBR_ISD_PARCELCNT,  nParcelCnt);
					Log.d(TAG, "ParcelCNT BroadCast Added");
				}
				else
				{
					intentBR.putExtra(define.NOTIBR_ISD_PARCELCNT, 0);
					Log.d(TAG, "ParcelCNT ZERO Added");
				}

				if( nVisitorPicCnt > 0 )
				{
					Log.d(TAG, "LOG : VISITOR CNT INCREASED ++");
					intentBR.putExtra(define.NOTIBR_ISD_VISITORCNT,  nVisitorPicCnt);
					Log.d(TAG, "VisitorCNT BroadCast Added");
				}
				else
				{
					intentBR.putExtra(define.NOTIBR_ISD_VISITORCNT,  nVisitorPicCnt);
					Log.d(TAG, "VisitorCNT ZERO Added");
				}

				// 알림정보 intent BroadCast
				getContext().sendBroadcast(intentBR);
			}
		}
		catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e)
		{
			Log.e(TAG, e.toString());
			LogUtil.errorLogInfo("", TAG, e);
		}
	}

//    private void startKakaoiVoiceAgent() {
//        try {
//            Log.i(TAG, "[startKakaoiVoiceAgent] ========== Start Kakao i Voice Agent ==========");
//            Intent mIntent = new Intent("com.kakao.i.agent.START_SERVICE").setPackage("com.kakao.i.test.sandbox");
//            ContextCompat.startForegroundService(this, mIntent);
//        } catch (RuntimeException re) {
//            LogUtil.errorLogInfo("", TAG, re);
//        }
//		catch (Exception e) {
//            Log.e(TAG, "[Exception] startKakaoiVoiceAgent()");
//            e.printStackTrace();
//        }
//    }
//
//    private void enableKakaoiVoiceAgent() {
//        try {
//            Log.i(TAG, "[enableKakaoiVoiceAgent] ========== Enable Kakao i Voice Agent ==========");
//            Intent mIntent = new Intent("com.kakao.i.agent.ENABLE_KAKAO_I").setPackage("com.kakao.i.test.sandbox");
//            ContextCompat.startForegroundService(this, mIntent);
//        } catch (RuntimeException re) {
//           LogUtil.errorLogInfo("", TAG, re);
//        }
//		catch (Exception e) {
//            Log.e(TAG, "[Exception] enableKakaoiVoiceAgent()");
//            e.printStackTrace();
//        }
//    }
//
//    private void diableKakaoiVoiceAgent() {
//        try {
//            Log.i(TAG, "[diableKakaoiVoiceAgent] ========== Disable Kakao i Voice Agent ==========");
//            Intent mIntent = new Intent("com.kakao.i.agent.DISABLE_KAKAO_I").setPackage("com.kakao.i.test.sandbox");
//            ContextCompat.startForegroundService(this, mIntent);
//        } catch (RuntimeException re) {
//            LogUtil.errorLogInfo("", TAG, re);
//        }
//		catch (Exception e) {
//            Log.e(TAG, "[Exception] diableKakaoiVoiceAgent()");
//            e.printStackTrace();
//        }
//    }


    /**
     * JEFF, 2019.08.06
     * 동탄현장 월패드 죽는 이슈 원인 분석을 위한 월패드 App 삭제 코드
     * 메인App만 남기고 모두 삭제
     */
    UninstallAPKs mUninstallAPKs = new UninstallAPKs();
    class UninstallAPKs extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                Log.d(TAG, "[UninstallAPKs.run()] Started getting installed package infomation");
                ArrayList<PackageVersionInfo> PackageVersionInfos = new ArrayList<PackageVersionInfo>();
                List<PackageInfo> PackageInfoList = getPackageManager().getInstalledPackages(PackageManager.PERMISSION_GRANTED);

                while (true) {
                    Log.d(TAG, "[UninstallAPKs.run()] Get installed packages start!!");
                    try {
                        for (PackageInfo pack : PackageInfoList) {
//                            Log.d(TAG, "[UninstallAPKs.run()] Package Name [" + pack.packageName + "]");
//                            Log.d(TAG, "[UninstallAPKs.run()] Version Name [" + pack.versionName + "]");
                            if ((pack.packageName.contains("icontrols")) || (pack.packageName.contains("artncore"))) {
                                PackageVersionInfos.add(new PackageVersionInfo(pack.packageName, pack.versionName));
                            }
                        }

                    } catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                        break;
                    } catch (Exception e) {
                        LogUtil.errorLogInfo("", TAG, e);
                        break;
                    }
                    Log.d(TAG, "[getInstalledPackageInfo.run()] Get installed packages end!!");
                    break;
                }

                for (int i = 0; i < PackageVersionInfos.size(); i++) {
                    Log.d(TAG, "[UninstallAPKs.run()] Package Name [" + PackageVersionInfos.get(i).getPackageName() + "]");
                    Log.d(TAG, "[UninstallAPKs.run()] Version Name [" + PackageVersionInfos.get(i).strPackageVersion + "]");
                    uninstallWallPadApp(PackageVersionInfos.get(i).getPackageName());
                    try {
                        Thread.sleep(5000);
                    } catch (RuntimeException re) {
                        LogUtil.errorLogInfo("", TAG, re);
                    } catch (Exception e) {
                        LogUtil.errorLogInfo("", TAG, e);
                    }
                }

            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            } catch (Exception e) {
                Log.e(TAG, "[Exception] UninstallAPKs.run()");
                LogUtil.errorLogInfo("", TAG, e);
            }

//            try {Thread.sleep(5000);}catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re);}catch (Exception e){e.printStackTrace();}

        }
    }

    private void uninstallWallPadApp(String strAPK) {
        try {
            Log.w(TAG, "[uninstallWallPadApp] strAPK [" + strAPK + "]");
            if (checkAppInstalled(strAPK)) {
//				Intent mIntent = new Intent(Intent.ACTION_DELETE);
                Intent mIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
                mIntent.setData(Uri.parse("package:" + strAPK));
                mIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
                startActivityForResult(mIntent, UNINSTALL_REQUEST_CODE);
            }
            else {
                Log.w(TAG, "[uninstallWallPadApp] Not installed [" + strAPK + "]");
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {;
            Log.e(TAG, "[Exception] uninstallWallPadApp()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }









    iMAPRemotemeter miMAPRemotemeter;
    boolean mEMS_Enable;
    int nEnergyTypeCnt;
    private boolean mCostInfo_Enable = false;

    private Calendar nowCal, HourCal, DateCal, MonthCal, YearCal, EnergyDataGetCal;

    int CalendarYear;
    int CalendarMonth;
    int CalendarDate;

    int ShowNowEnergyIndex = 0;
    String[] ShowListEnergyType_String = {
            "전기",
            "수도",
            "가스",
            "온수",
            "난방",
            "탄소"
    };

    // 원격검침 월사용량 데이터 클래스
    MonthTableClass monthTableClass[] = new MonthTableClass[6];
    class MonthTableClass {
        private String Use;
        private String SamePyungUse;
        private String Rank;
        private String Goal;
        private String Price;


        public MonthTableClass (String Use, String SamePyungUse, String Rank, String Goal) {
            this.Use = Use;
            this.SamePyungUse = SamePyungUse;
            this.Rank = Rank;
            this.Goal = Goal;
        }

        public String getUse(){return Use;}
        public String getSamePyungUse(){return SamePyungUse;}
        public String getRank(){return Rank;}
        public String getGoal(){return Goal;}
        public String getPrice(){return Price;}
    }

    public void GetMeteringCount()
    {
        WallpadDeviceSet devSet = new WallpadDeviceSet(getContext());
        String[] MetringDB = devSet.GetSettingData("원격검침");
        devSet.closeDB();
        if (MetringDB != null)
        {
            try
            {
                String devInfo = MetringDB[1];

                devInfo = devInfo.replace('(', '_');
                devInfo = devInfo.replace(':', '_');
                devInfo = devInfo.replace(')', '_');

                String[] MetringInfo = devInfo.split("_");
                // MetringInfo[1] -> 회로수
                // MetringInfo[5] -> EMS 사용여부 사용함 or 사용안함
                if ((Integer.parseInt(MetringInfo[1]) == 2) || (Integer.parseInt(MetringInfo[1]) == 3) || (Integer.parseInt(MetringInfo[1]) == 5) || (Integer.parseInt(MetringInfo[1]) == 6))
                {
                    nEnergyTypeCnt = Integer.parseInt(MetringInfo[1]);
                }
                else
                {
                    nEnergyTypeCnt = 5;
                }

                if (MetringInfo[5].equals("사용함"))
                {
                    mEMS_Enable = true;
                }
                else
                {
                    mEMS_Enable = false;
                }
                if(MetringInfo[7].equals("사용함"))
                {
                    mCostInfo_Enable = true;
                }
                else
                {
                    mCostInfo_Enable = false;
                }
            }
            catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
                nEnergyTypeCnt = 5;
                mEMS_Enable = true;
            }
            catch (Exception e)
            {
                LogUtil.errorLogInfo("", TAG, e);
                nEnergyTypeCnt = 5;
                mEMS_Enable = true;
            }
        }
        else
        {
            nEnergyTypeCnt = 5;
            mEMS_Enable = true;
        }
    }

    /**
     * @description
     * 서버로 부터 데이터를 받아와 분석하고 표현하는 함수<br>
     * @param
     *  InputType 0 당월, 1 일별<br>
     *  @param
     *  //year - 연도<br>
     *  @param
     *  //month - 월<br>
     *  @param
     *  //energy - 0 전기, 1 수도, 2 가스, 3 온수, 4 열량, 5 탄소<br>
     */
    private void LoadRemotemeterDataFromServer(int InputType, int Year, int Month, int Energy, final boolean bSendToMobile) {
        final int inputType = InputType;
        final int year = Year;
        final int month = (Month+1);

        try {
            Log.i(TAG, "[LoadRemotemeterDataFromServer] InputType [" + InputType + "], Year [" + Year + "], Month [" + Month + "], Energy [" + Energy + "], bSendToMobile [" + bSendToMobile + "]");
            Log.i(TAG, "[LoadRemotemeterDataFromServer] inputType [" + inputType + "], year [" + year + "], month [" + month + "]");

            miMAPRemotemeter = new iMAPRemotemeter(getApplicationContext());

            switch(inputType) {
                case 0: //당월
                    miMAPRemotemeter.DoWork(true, true, true, true, true, true, true, mEMS_Enable, year, month);
                    break;

                case 1: //일별
                    miMAPRemotemeter.DoWork(false, true, true, true, true, true, false, false, year, month);
                    break;

                default:
                    break;
            }
            boolean isUseEMS = true;
            WallpadDeviceSet wds = new WallpadDeviceSet(getContext());
            isUseEMS = wds.GetEMSProtocolUse();
            wds.closeDB();

            if(isUseEMS)
            {
                miMAPRemotemeter.SetRetCtr(new RetProci() {

                    @Override
                    public void ProcSuccess() {
                        String TempString = null;

                        // DB
                        WallpadStatusData StatusDBMGR = null;
                        try {
                            StatusDBMGR = new WallpadStatusData(getApplicationContext());
                            Log.i(TAG, "[LoadRemotemeterDataFromServer.ProcSuccess] inputType [" + inputType + "]");
                            boolean result = false;
                            switch (inputType) {
                                case 0: // 당월
                                    EnergyDataGetCal = Calendar.getInstance();
                                    int NumberOfValuelist = miMAPRemotemeter.SetItem("valuelist");
                                    if (NumberOfValuelist != 0) {
                                        for (int i = 0; i < NumberOfValuelist; i++) {
                                            //DebugLogOutput("NumberOfValuelist " + Integer.toString(NumberOfValuelist));
                                            //DebugLogOutput("GetAttributeVal(i, month) " + imapRemotemeter.GetAttributeVal(i, "month"));
                                            //DebugLogOutput("CalendarMonth " + (CalendarMonth + 1));
                                            if ((Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "month")) == (CalendarMonth + 1)) && (Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "year")) == (CalendarYear))) {
                                                result = true;
                                                int Temp_mNumberOfEnergy = nEnergyTypeCnt;
                                                if (Temp_mNumberOfEnergy == 2) {
                                                    Temp_mNumberOfEnergy = 3;
                                                }

                                                for (int j = 0; j < Temp_mNumberOfEnergy; j++) {
                                                    switch (j) {
                                                        case 0:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "elect_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "elect_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "elect_used");
                                                                }
                                                            }

                                                            if (miMAPRemotemeter.GetAttributeVal(i, "elect_average_used_samesize") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "elect_average_used_samesize").equals("null") == true) {
                                                                    monthTableClass[j].SamePyungUse = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].SamePyungUse = miMAPRemotemeter.GetAttributeVal(i, "elect_average_used_samesize");
                                                                }
                                                            }

                                                            if ((miMAPRemotemeter.GetAttributeVal(i, "elect_ranking_samesize") != null) && (miMAPRemotemeter.GetAttributeVal(i, "count_samesize") != null)) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "elect_ranking_samesize").equals("null") == true) {
                                                                    TempString = "- / ";
                                                                }
                                                                else {
                                                                    TempString = miMAPRemotemeter.GetAttributeVal(i, "elect_ranking_samesize") + " / ";
                                                                }

                                                                if (miMAPRemotemeter.GetAttributeVal(i, "count_samesize").equals("null") == true) {
                                                                    TempString = TempString + "-";
                                                                }
                                                                else {
                                                                    TempString = TempString + miMAPRemotemeter.GetAttributeVal(i, "count_samesize");
                                                                }
                                                                monthTableClass[j].Rank = TempString;
                                                            }

                                                            //가격정보
                                                            if (mCostInfo_Enable == true) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "elect_price") != null) {
                                                                    if (miMAPRemotemeter.GetAttributeVal(i, "elect_price").equals("null") == true) {
                                                                        monthTableClass[j].Price = "";
                                                                    }
                                                                    else {
                                                                        monthTableClass[j].Price = miMAPRemotemeter.GetAttributeVal(i, "elect_price");
                                                                    }
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("전기");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 1:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "water_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "water_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "water_used");
                                                                }
                                                            }

                                                            if (miMAPRemotemeter.GetAttributeVal(i, "water_average_used_samesize") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "water_average_used_samesize").equals("null") == true) {
                                                                    monthTableClass[j].SamePyungUse = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].SamePyungUse = miMAPRemotemeter.GetAttributeVal(i, "water_average_used_samesize");
                                                                }
                                                            }

                                                            if ((miMAPRemotemeter.GetAttributeVal(i, "water_ranking_samesize") != null) && (miMAPRemotemeter.GetAttributeVal(i, "count_samesize") != null)) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "water_ranking_samesize").equals("null") == true) {
                                                                    TempString = "- / ";
                                                                }
                                                                else {
                                                                    TempString = miMAPRemotemeter.GetAttributeVal(i, "water_ranking_samesize") + " / ";
                                                                }

                                                                if (miMAPRemotemeter.GetAttributeVal(i, "count_samesize").equals("null") == true) {
                                                                    TempString = TempString + "-";
                                                                }
                                                                else {
                                                                    TempString = TempString + miMAPRemotemeter.GetAttributeVal(i, "count_samesize");
                                                                }
                                                                monthTableClass[j].Rank = TempString;
                                                            }

                                                            //가격정보
                                                            if (mCostInfo_Enable == true) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "water_price") != null) {
                                                                    if (miMAPRemotemeter.GetAttributeVal(i, "water_price").equals("null") == true) {
                                                                        monthTableClass[j].Price = "";
                                                                    }
                                                                    else {
                                                                        monthTableClass[j].Price = miMAPRemotemeter.GetAttributeVal(i, "water_price");
                                                                    }
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("수도");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 2:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "gas_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "gas_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "gas_used");
                                                                }
                                                            }

                                                            if (miMAPRemotemeter.GetAttributeVal(i, "gas_average_used_samesize") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "gas_average_used_samesize").equals("null") == true) {
                                                                    monthTableClass[j].SamePyungUse = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].SamePyungUse = miMAPRemotemeter.GetAttributeVal(i, "gas_average_used_samesize");
                                                                }
                                                            }

                                                            if ((miMAPRemotemeter.GetAttributeVal(i, "gas_ranking_samesize") != null) && (miMAPRemotemeter.GetAttributeVal(i, "count_samesize") != null)) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "gas_ranking_samesize").equals("null") == true) {
                                                                    TempString = "- / ";
                                                                }
                                                                else {
                                                                    TempString = miMAPRemotemeter.GetAttributeVal(i, "gas_ranking_samesize") + " / ";
                                                                }

                                                                if (miMAPRemotemeter.GetAttributeVal(i, "count_samesize").equals("null") == true) {
                                                                    TempString = TempString + "-";
                                                                }
                                                                else {
                                                                    TempString = TempString + miMAPRemotemeter.GetAttributeVal(i, "count_samesize");
                                                                }
                                                                monthTableClass[j].Rank = TempString;
                                                            }

                                                            //가격정보
                                                            if (mCostInfo_Enable == true) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "gas_price") != null) {
                                                                    if (miMAPRemotemeter.GetAttributeVal(i, "gas_price").equals("null") == true) {
                                                                        monthTableClass[j].Price = "";
                                                                    }
                                                                    else {
                                                                        monthTableClass[j].Price = miMAPRemotemeter.GetAttributeVal(i, "gas_price");
                                                                    }
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("가스");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 3:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "hotwater_used");
                                                                }
                                                            }

                                                            if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_average_used_samesize") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_average_used_samesize").equals("null") == true) {
                                                                    monthTableClass[j].SamePyungUse = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].SamePyungUse = miMAPRemotemeter.GetAttributeVal(i, "hotwater_average_used_samesize");
                                                                }
                                                            }

                                                            if ((miMAPRemotemeter.GetAttributeVal(i, "hotwater_ranking_samesize") != null) && (miMAPRemotemeter.GetAttributeVal(i, "count_samesize") != null)) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_ranking_samesize").equals("null") == true) {
                                                                    TempString = "- / ";
                                                                }
                                                                else {
                                                                    TempString = miMAPRemotemeter.GetAttributeVal(i, "hotwater_ranking_samesize") + " / ";
                                                                }

                                                                if (miMAPRemotemeter.GetAttributeVal(i, "count_samesize").equals("null") == true) {
                                                                    TempString = TempString + "-";
                                                                }
                                                                else {
                                                                    TempString = TempString + miMAPRemotemeter.GetAttributeVal(i, "count_samesize");
                                                                }
                                                                monthTableClass[j].Rank = TempString;
                                                            }

                                                            //가격정보
                                                            if (mCostInfo_Enable == true) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_price") != null) {
                                                                    if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_price").equals("null") == true) {
                                                                        monthTableClass[j].Price = "";
                                                                    }
                                                                    else {
                                                                        monthTableClass[j].Price = miMAPRemotemeter.GetAttributeVal(i, "hotwater_price");
                                                                    }
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("온수");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 4:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "energy_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "energy_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "energy_used");
                                                                }
                                                            }

                                                            if (miMAPRemotemeter.GetAttributeVal(i, "energy_average_used_samesize") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "energy_average_used_samesize").equals("null") == true) {
                                                                    monthTableClass[j].SamePyungUse = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].SamePyungUse = miMAPRemotemeter.GetAttributeVal(i, "energy_average_used_samesize");
                                                                }
                                                            }

                                                            if ((miMAPRemotemeter.GetAttributeVal(i, "energy_ranking_samesize") != null) && (miMAPRemotemeter.GetAttributeVal(i, "count_samesize") != null)) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "energy_ranking_samesize").equals("null") == true) {
                                                                    TempString = "- / ";
                                                                }
                                                                else {
                                                                    TempString = miMAPRemotemeter.GetAttributeVal(i, "energy_ranking_samesize") + " / ";
                                                                }

                                                                if (miMAPRemotemeter.GetAttributeVal(i, "count_samesize").equals("null") == true) {
                                                                    TempString = TempString + "-";
                                                                }
                                                                else {
                                                                    TempString = TempString + miMAPRemotemeter.GetAttributeVal(i, "count_samesize");
                                                                }
                                                                monthTableClass[j].Rank = TempString;
                                                            }

                                                            //가격정보
                                                            if (mCostInfo_Enable == true) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "energy_price") != null) {
                                                                    if (miMAPRemotemeter.GetAttributeVal(i, "energy_price").equals("null") == true) {
                                                                        monthTableClass[j].Price = "";
                                                                    }
                                                                    else {
                                                                        monthTableClass[j].Price = miMAPRemotemeter.GetAttributeVal(i, "energy_price");
                                                                    }
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("열량");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 5:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "carbon_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "carbon_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "carbon_used");
                                                                }
                                                            }

                                                            if (miMAPRemotemeter.GetAttributeVal(i, "carbon_average_used_samesize") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "carbon_average_used_samesize").equals("null") == true) {
                                                                    monthTableClass[j].SamePyungUse = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].SamePyungUse = miMAPRemotemeter.GetAttributeVal(i, "carbon_average_used_samesize");
                                                                }
                                                            }

                                                            if ((miMAPRemotemeter.GetAttributeVal(i, "carbon_ranking_samesize") != null) && (miMAPRemotemeter.GetAttributeVal(i, "count_samesize") != null)) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "carbon_ranking_samesize").equals("null") == true) {
                                                                    TempString = "- / ";
                                                                }
                                                                else {
                                                                    TempString = miMAPRemotemeter.GetAttributeVal(i, "carbon_ranking_samesize") + " / ";
                                                                }

                                                                if (miMAPRemotemeter.GetAttributeVal(i, "count_samesize").equals("null") == true) {
                                                                    TempString = TempString + "-";
                                                                }
                                                                else {
                                                                    TempString = TempString + miMAPRemotemeter.GetAttributeVal(i, "count_samesize");
                                                                }
                                                                monthTableClass[j].Rank = TempString;
                                                            }

                                                            //가격정보
                                                            if (mCostInfo_Enable == true) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "carbon_price") != null) {
                                                                    if (miMAPRemotemeter.GetAttributeVal(i, "carbon_price").equals("null") == true) {
                                                                        monthTableClass[j].Price = "";
                                                                    }
                                                                    else {
                                                                        monthTableClass[j].Price = miMAPRemotemeter.GetAttributeVal(i, "carbon_price");
                                                                    }
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("탄소");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        default:
                                                            break;

                                                    }
                                                }
                                            }
                                        }

                                        if (result) {
                                            if (1 < nEnergyTypeCnt && nEnergyTypeCnt < 6) {
                                                Intent intent = new Intent();
                                                intent.setAction(define.NOTIFY_ACNAME);
                                                intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_ENERGY_TARGET_INFO_ALARM_FROM_SERVER);
                                                intent.putExtra("FromWhere", "IcEnergyMgrScreen");

                                                if (nEnergyTypeCnt == 2) {
                                                    elect_target = monthTableClass[0].Goal;
                                                    elect_used = monthTableClass[0].Use;
                                                    water_target = monthTableClass[1].Goal;
                                                    water_used = monthTableClass[1].Use;
                                                }
                                                else if (nEnergyTypeCnt == 3) {
                                                    elect_target = monthTableClass[0].Goal;
                                                    elect_used = monthTableClass[0].Use;
                                                    water_target = monthTableClass[1].Goal;
                                                    water_used = monthTableClass[1].Use;
                                                    gas_target = monthTableClass[2].Goal;
                                                    gas_used = monthTableClass[2].Use;
                                                }
                                                else if (nEnergyTypeCnt == 4) {
                                                    elect_target = monthTableClass[0].Goal;
                                                    elect_used = monthTableClass[0].Use;
                                                    water_target = monthTableClass[1].Goal;
                                                    water_used = monthTableClass[1].Use;
                                                    hotwater_target = monthTableClass[2].Goal;
                                                    hotwater_used = monthTableClass[2].Use;
                                                    heating_target = monthTableClass[3].Goal;
                                                    heating_used = monthTableClass[3].Use;
                                                }
                                                else if (nEnergyTypeCnt == 5) {
                                                    elect_target = monthTableClass[0].Goal;
                                                    elect_used = monthTableClass[0].Use;
                                                    water_target = monthTableClass[1].Goal;
                                                    water_used = monthTableClass[1].Use;
                                                    gas_target = monthTableClass[2].Goal;
                                                    gas_used = monthTableClass[2].Use;
                                                    hotwater_target = monthTableClass[3].Goal;
                                                    hotwater_used = monthTableClass[3].Use;
                                                    heating_target = monthTableClass[4].Goal;
                                                    heating_used = monthTableClass[4].Use;
                                                }
                                                else {
                                                    Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcSuccess] Out of range!! =1 = mNumberOfEnergy -> " + nEnergyTypeCnt);
                                                    return;
                                                }

                                                getApplicationContext().sendBroadcast(intent);
                                                if (bSendToMobile) sendRemotemeterDataToMobile();

                                            }
                                            else {
                                                Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcSuccess] Out of range!! =2 = mNumberOfEnergy -> " + nEnergyTypeCnt);
                                            }
                                            return;
                                        }
                                        else {
                                            Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcSuccess] result [" + result + "]");
                                        }
                                    }
                                    break;

                                default:
                                    break;
                            }
                            StatusDBMGR.closeDB();
                        } catch (RuntimeException re) {
                            if (StatusDBMGR != null) {
                                StatusDBMGR.closeDB();
                            }
                            LogUtil.errorLogInfo("", TAG, re);
                        }
                        catch (Exception e) {
                            if (StatusDBMGR != null) {
                                StatusDBMGR.closeDB();
                            }
                            LogUtil.errorLogInfo("", TAG, e);
                        }
                    }

                    @Override
                    public void ProcError() {
                        Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcError] Error!!!");
                    }

                    @Override
                    public void ProcDoing() {
                        Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcDoing] Processing!!!");
                    }
                });
            }
            else {
                miMAPRemotemeter.SetRetCtr(new RetProci() {

                    @Override
                    public void ProcSuccess() {
                        String TempString = null;

                        // DB
                        WallpadStatusData StatusDBMGR = null;
                        try {
                            StatusDBMGR = new WallpadStatusData(getApplicationContext());
                            Log.i(TAG, "[LoadRemotemeterDataFromServer.ProcSuccess] inputType [" + inputType + "]");
                            boolean result = false;
                            switch (inputType) {
                                case 0: // 당월
                                    EnergyDataGetCal = Calendar.getInstance();
                                    int NumberOfValuelist = miMAPRemotemeter.SetItem("valuelist");
                                    if (NumberOfValuelist != 0) {
                                        for (int i = 0; i < NumberOfValuelist; i++) {
                                            //DebugLogOutput("NumberOfValuelist " + Integer.toString(NumberOfValuelist));
                                            //DebugLogOutput("GetAttributeVal(i, month) " + imapRemotemeter.GetAttributeVal(i, "month"));
                                            //DebugLogOutput("CalendarMonth " + (CalendarMonth + 1));
                                            if ((Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "month")) == (CalendarMonth + 1)) && (Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "year")) == (CalendarYear))) {
                                                result = true;
                                                int Temp_mNumberOfEnergy = nEnergyTypeCnt;
                                                if (Temp_mNumberOfEnergy == 2) {
                                                    Temp_mNumberOfEnergy = 3;
                                                }

                                                for (int j = 0; j < Temp_mNumberOfEnergy; j++) {
                                                    switch (j) {
                                                        case 0:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "elect_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "elect_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "elect_used");
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("전기");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 1:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "water_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "water_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "water_used");
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("수도");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 2:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "gas_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "gas_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "gas_used");
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("가스");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 3:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "hotwater_used");
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("온수");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 4:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            if (miMAPRemotemeter.GetAttributeVal(i, "energy_used") != null) {
                                                                if (miMAPRemotemeter.GetAttributeVal(i, "energy_used").equals("1000000") == true) {
                                                                    monthTableClass[j].Use = "0";
                                                                }
                                                                else {
                                                                    monthTableClass[j].Use = miMAPRemotemeter.GetAttributeVal(i, "energy_used");
                                                                }
                                                            }

                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("열량");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        case 5:
                                                            monthTableClass[j] = new MonthTableClass("", "", "", "");
                                                            monthTableClass[j].Goal = StatusDBMGR.GetRemoteMeteringTargetValue(j);
                                                            //DebugLogOutput("탄소");
                                                            //DebugLogOutput("Homeuse: " + monthTableClass[j].Use);
                                                            //DebugLogOutput("SamePyungUse: " + monthTableClass[j].SamePyungUse);
                                                            break;

                                                        default:
                                                            break;

                                                    }
                                                }
                                            }
                                        }

                                        if (result) {
                                            if (1 < nEnergyTypeCnt && nEnergyTypeCnt < 6) {
                                                Intent intent = new Intent();
                                                intent.setAction(define.NOTIFY_ACNAME);
                                                intent.putExtra(define.NOTIBR_KIND, define.NOTIFY_ENERGY_TARGET_INFO_ALARM_FROM_SERVER);
                                                intent.putExtra("FromWhere", "IcEnergyMgrScreen");

                                                if (nEnergyTypeCnt == 2) {
                                                    elect_target = monthTableClass[0].Goal;
                                                    elect_used = monthTableClass[0].Use;
                                                    water_target = monthTableClass[1].Goal;
                                                    water_used = monthTableClass[1].Use;
                                                }
                                                else if (nEnergyTypeCnt == 3) {
                                                    elect_target = monthTableClass[0].Goal;
                                                    elect_used = monthTableClass[0].Use;
                                                    water_target = monthTableClass[1].Goal;
                                                    water_used = monthTableClass[1].Use;
                                                    gas_target = monthTableClass[2].Goal;
                                                    gas_used = monthTableClass[2].Use;
                                                }
                                                else if (nEnergyTypeCnt == 4) {
                                                    elect_target = monthTableClass[0].Goal;
                                                    elect_used = monthTableClass[0].Use;
                                                    water_target = monthTableClass[1].Goal;
                                                    water_used = monthTableClass[1].Use;
                                                    hotwater_target = monthTableClass[2].Goal;
                                                    hotwater_used = monthTableClass[2].Use;
                                                    heating_target = monthTableClass[3].Goal;
                                                    heating_used = monthTableClass[3].Use;
                                                }
                                                else if (nEnergyTypeCnt == 5) {
                                                    elect_target = monthTableClass[0].Goal;
                                                    elect_used = monthTableClass[0].Use;
                                                    water_target = monthTableClass[1].Goal;
                                                    water_used = monthTableClass[1].Use;
                                                    gas_target = monthTableClass[2].Goal;
                                                    gas_used = monthTableClass[2].Use;
                                                    hotwater_target = monthTableClass[3].Goal;
                                                    hotwater_used = monthTableClass[3].Use;
                                                    heating_target = monthTableClass[4].Goal;
                                                    heating_used = monthTableClass[4].Use;
                                                }
                                                else {
                                                    Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcSuccess] Out of range!! =1 = mNumberOfEnergy -> " + nEnergyTypeCnt);
                                                    return;
                                                }

                                                getApplicationContext().sendBroadcast(intent);
                                                if (bSendToMobile) sendRemotemeterDataToMobile();

                                            }
                                            else {
                                                Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcSuccess] Out of range!! =2 = mNumberOfEnergy -> " + nEnergyTypeCnt);
                                            }
                                            return;
                                        }
                                        else {
                                            Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcSuccess] result [" + result + "]");
                                        }
                                    }
                                    break;

                                default:
                                    break;
                            }
                            StatusDBMGR.closeDB();
                        } catch (RuntimeException re) {
                            if (StatusDBMGR != null) {
                                StatusDBMGR.closeDB();
                            }
                            LogUtil.errorLogInfo("", TAG, re);
                        }
                        catch (Exception e) {
                            if (StatusDBMGR != null) {
                                StatusDBMGR.closeDB();
                            }
                            LogUtil.errorLogInfo("", TAG, e);
                        }
                    }

                    @Override
                    public void ProcError() {
                        Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcError] Error!!!");
                    }

                    @Override
                    public void ProcDoing() {
                        Log.w(TAG, "[LoadRemotemeterDataFromServer.ProcDoing] Processing!!!");
                    }
                });
            }


        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] LoadRemotemeterDataFromServer(int InputType, int Year, int Month, int Energy)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }








    /**
     * @description
     * 서버로 부터 데이터를 받아와 분석하고 표현하는 함수<br>
     *  @param
     *  //year - 연도<br>
     *  @param
     *  //month - 월<br>
     *  @param
     *  //energy - 0 전기, 1 수도, 2 가스, 3 온수, 4 열량, 5 탄소<br>
     */
    private void getTelemeringDailyUsageData(final int nYear, final int nMonth, final int nDate) {
        try {
            Log.i(TAG, "[getTelemeringDailyUsageData] nYear [" + nYear + "], nMonth [" + nMonth + "], nDate [" + nDate + "]");

            miMAPRemotemeter = new iMAPRemotemeter(getApplicationContext());
            miMAPRemotemeter.DoWork(false, true, true, true, true, true, false, false, nYear, nMonth);

            boolean isUseEMS = true;
            WallpadDeviceSet wds = new WallpadDeviceSet(getContext());
            isUseEMS = wds.GetEMSProtocolUse();
            wds.closeDB();

            if(isUseEMS)
            {
                miMAPRemotemeter.SetRetCtr(new RetProci() {
                    @Override
                    public void ProcSuccess() {
                        String strTempValue = null;
                        int nEnergyTypeCnt = 5;

                        try {
                            boolean bResult = false;
                            String strElecUsage = "", strGasUsage = "", strWaterUsage = "", strHotwaterUsage = "", strHeatingUsage = "";
                            int nDataCnt = miMAPRemotemeter.SetItem("valuelist");
                            if (nDataCnt != 0) {
                                Log.i(TAG, "[getTelemeringDailyData] nDataCnt [" + nDataCnt + "]");
                                for (int i = 0; i < nDataCnt; i++) {
                                    if ((Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "year")) == nYear)
                                            && (Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "month")) == nMonth)
                                            && (Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "day")) == nDate)) {
                                        bResult = true;
                                        Log.i(TAG, "[getTelemeringDailyUsageData] Find!!! nYear [" + nYear + "], nMonth [" + nMonth + "], nDate [" + nDate + "]");
                                        for (int j = 0; j < nEnergyTypeCnt; j++) {
                                            if (j == 0) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "elect_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "elect_used").equals("1000000")) {
                                                        strElecUsage = "0";
                                                    }
                                                    else {
                                                        strElecUsage = miMAPRemotemeter.GetAttributeVal(i, "elect_used");
                                                    }
                                                }
                                            }
                                            else if (j == 1) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "water_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "water_used").equals("1000000") == true) {
                                                        strWaterUsage = "0";
                                                    }
                                                    else {
                                                        strWaterUsage = miMAPRemotemeter.GetAttributeVal(i, "water_used");
                                                    }
                                                }
                                            }
                                            else if (j == 2) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "gas_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "gas_used").equals("1000000") == true) {
                                                        strGasUsage = "0";
                                                    }
                                                    else {
                                                        strGasUsage = miMAPRemotemeter.GetAttributeVal(i, "gas_used");
                                                    }
                                                }
                                            }
                                            else if (j == 3) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_used").equals("1000000") == true) {
                                                        strHotwaterUsage = "0";
                                                    }
                                                    else {
                                                        strHotwaterUsage = miMAPRemotemeter.GetAttributeVal(i, "hotwater_used");
                                                    }
                                                }
                                            }
                                            else if (j == 4) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "energy_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "energy_used").equals("1000000") == true) {
                                                        strHeatingUsage = "0";
                                                    }
                                                    else {
                                                        strHeatingUsage = miMAPRemotemeter.GetAttributeVal(i, "energy_used");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (bResult) {
                                    Intent mIntent = new Intent();
                                    mIntent.setAction(define.NOTIFY_ACNAME);
                                    mIntent.putExtra(define.NOTIBR_KIND, define.NOTIFY_TELEMETERING_DAILY_USAGE);
                                    mIntent.putExtra("elect_used", strElecUsage);
                                    mIntent.putExtra("water_used", strWaterUsage);
                                    mIntent.putExtra("gas_used", strGasUsage);
                                    mIntent.putExtra("hotwater_used", strHotwaterUsage);
                                    mIntent.putExtra("heating_used", strHeatingUsage);
                                    getApplicationContext().sendBroadcast(mIntent);
                                }
                                else {
                                    Log.w(TAG, "[getTelemeringDailyUsageData.ProcSuccess] bResult [" + bResult + "]");
                                }
                            }
                        } catch (RuntimeException re) {
                            LogUtil.errorLogInfo("", TAG, re);
                        }
                        catch (Exception e) {
                            Log.e(TAG, "[Exception] getTelemeringDailyData.ProcSuccess");
                            LogUtil.errorLogInfo("", TAG, e);
                        }
                    }

                    @Override
                    public void ProcError() {
                        Log.w(TAG, "[getTelemeringDailyData.ProcError] Error!!!");
                    }

                    @Override
                    public void ProcDoing() {
                        Log.w(TAG, "[getTelemeringDailyData.ProcDoing] Processing!!!");
                    }
                });
            }
            else
            {
                miMAPRemotemeter.SetRetCtr(new RetProci() {
                    @Override
                    public void ProcSuccess() {
                        String strTempValue = null;
                        int nEnergyTypeCnt = 5;

                        try {
                            boolean bResult = false;
                            String strElecUsage = "", strGasUsage = "", strWaterUsage = "", strHotwaterUsage = "", strHeatingUsage = "";
                            int nDataCnt = miMAPRemotemeter.SetItem("valuelist");
                            if (nDataCnt != 0) {
                                Log.i(TAG, "[getTelemeringDailyData] nDataCnt [" + nDataCnt + "]");
                                for (int i = 0; i < nDataCnt; i++) {
                                    if ((Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "year")) == nYear)
                                            && (Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "month")) == nMonth)
                                            && (Integer.parseInt(miMAPRemotemeter.GetAttributeVal(i, "day")) == nDate)) {
                                        bResult = true;
                                        Log.i(TAG, "[getTelemeringDailyUsageData] Find!!! nYear [" + nYear + "], nMonth [" + nMonth + "], nDate [" + nDate + "]");
                                        for (int j = 0; j < nEnergyTypeCnt; j++) {
                                            if (j == 0) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "elect_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "elect_used").equals("1000000")) {
                                                        strElecUsage = "0";
                                                    }
                                                    else {
                                                        strElecUsage = miMAPRemotemeter.GetAttributeVal(i, "elect_used");
                                                    }
                                                }
                                            }
                                            else if (j == 1) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "water_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "water_used").equals("1000000") == true) {
                                                        strWaterUsage = "0";
                                                    }
                                                    else {
                                                        strWaterUsage = miMAPRemotemeter.GetAttributeVal(i, "water_used");
                                                    }
                                                }
                                            }
                                            else if (j == 2) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "gas_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "gas_used").equals("1000000") == true) {
                                                        strGasUsage = "0";
                                                    }
                                                    else {
                                                        strGasUsage = miMAPRemotemeter.GetAttributeVal(i, "gas_used");
                                                    }
                                                }
                                            }
                                            else if (j == 3) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "hotwater_used").equals("1000000") == true) {
                                                        strHotwaterUsage = "0";
                                                    }
                                                    else {
                                                        strHotwaterUsage = miMAPRemotemeter.GetAttributeVal(i, "hotwater_used");
                                                    }
                                                }
                                            }
                                            else if (j == 4) {
                                                if (miMAPRemotemeter.GetAttributeVal(i, "energy_used") != null) {
                                                    if (miMAPRemotemeter.GetAttributeVal(i, "energy_used").equals("1000000") == true) {
                                                        strHeatingUsage = "0";
                                                    }
                                                    else {
                                                        strHeatingUsage = miMAPRemotemeter.GetAttributeVal(i, "energy_used");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (bResult) {
                                    Intent mIntent = new Intent();
                                    mIntent.setAction(define.NOTIFY_ACNAME);
                                    mIntent.putExtra(define.NOTIBR_KIND, define.NOTIFY_TELEMETERING_DAILY_USAGE);
                                    mIntent.putExtra("elect_used", strElecUsage);
                                    mIntent.putExtra("water_used", strWaterUsage);
                                    mIntent.putExtra("gas_used", strGasUsage);
                                    mIntent.putExtra("hotwater_used", strHotwaterUsage);
                                    mIntent.putExtra("heating_used", strHeatingUsage);
                                    getApplicationContext().sendBroadcast(mIntent);
                                }
                                else {
                                    Log.w(TAG, "[getTelemeringDailyUsageData.ProcSuccess] bResult [" + bResult + "]");
                                }
                            }
                        } catch (RuntimeException re) {
                            LogUtil.errorLogInfo("", TAG, re);
                        }
                        catch (Exception e) {
                            Log.e(TAG, "[Exception] getTelemeringDailyData.ProcSuccess");
                            LogUtil.errorLogInfo("", TAG, e);
                        }
                    }

                    @Override
                    public void ProcError() {
                        Log.w(TAG, "[getTelemeringDailyData.ProcError] Error!!!");
                    }

                    @Override
                    public void ProcDoing() {
                        Log.w(TAG, "[getTelemeringDailyData.ProcDoing] Processing!!!");
                    }
                });
            }


        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getTelemeringDailyData(int nYear, int nMonth)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void sendRemotemeterDataToMobile() {
        try {
            Log.i(TAG, "[sendRemotemeterDataToMobile] ========== START ==========");
            Intent intent = new Intent();
            intent.setAction(define.NOTIFY_ACNAME);
            intent.putExtra("KIND", define.NOTIFY_ENERGY_DATA);

            intent.putExtra(Common.ENERGY_INTENT_ENERGY_COUNT, nEnergyTypeCnt);
            intent.putExtra(Common.ENERGY_INTENT_GETDATA_TIME_YEAR, EnergyDataGetCal.get(Calendar.YEAR));
            intent.putExtra(Common.ENERGY_INTENT_GETDATA_TIME_MONTH, (EnergyDataGetCal.get(Calendar.MONTH)+1));
            intent.putExtra(Common.ENERGY_INTENT_GETDATA_TIME_DAY, EnergyDataGetCal.get(Calendar.DATE));
            intent.putExtra(Common.ENERGY_INTENT_GETDATA_TIME_HOUR, EnergyDataGetCal.get(Calendar.HOUR_OF_DAY));
            intent.putExtra(Common.ENERGY_INTENT_GETDATA_TIME_MINUTE, EnergyDataGetCal.get(Calendar.MINUTE));

            if (nEnergyTypeCnt == 2) {
                intent.putExtra(Common.ENERGY_INTENT_USE_ELECTRIC, elect_used);   //전기
                intent.putExtra(Common.ENERGY_INTENT_GOAL_ELECTRIC, elect_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_WATER, water_used);  //수도
                intent.putExtra(Common.ENERGY_INTENT_GOAL_WATER, water_target);
            }
            else if (nEnergyTypeCnt == 3) {
                intent.putExtra(Common.ENERGY_INTENT_USE_ELECTRIC, elect_used);   //전기
                intent.putExtra(Common.ENERGY_INTENT_GOAL_ELECTRIC, elect_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_WATER, water_used);  //수도
                intent.putExtra(Common.ENERGY_INTENT_GOAL_WATER, water_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_GAS, gas_used);  //가스
                intent.putExtra(Common.ENERGY_INTENT_GOAL_GAS, gas_target);
            }
            else if (nEnergyTypeCnt == 4) {
                intent.putExtra(Common.ENERGY_INTENT_USE_ELECTRIC, elect_used);   //전기
                intent.putExtra(Common.ENERGY_INTENT_GOAL_ELECTRIC, elect_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_WATER, water_used);  //수도
                intent.putExtra(Common.ENERGY_INTENT_GOAL_WATER, water_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_HOTWATER, hotwater_used);  //온수
                intent.putExtra(Common.ENERGY_INTENT_GOAL_HOTWATER, hotwater_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_HEATING, heating_used);  //열량
                intent.putExtra(Common.ENERGY_INTENT_GOAL_HEATING, heating_target);
            }
            else if (nEnergyTypeCnt == 5) {
                intent.putExtra(Common.ENERGY_INTENT_USE_ELECTRIC, elect_used);   //전기
                intent.putExtra(Common.ENERGY_INTENT_GOAL_ELECTRIC, elect_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_WATER, water_used);  //수도
                intent.putExtra(Common.ENERGY_INTENT_GOAL_WATER, water_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_GAS, gas_used);  //가스
                intent.putExtra(Common.ENERGY_INTENT_GOAL_GAS, gas_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_HOTWATER, hotwater_used);  //온수
                intent.putExtra(Common.ENERGY_INTENT_GOAL_HOTWATER, hotwater_target);

                intent.putExtra(Common.ENERGY_INTENT_USE_HEATING, heating_used);  //열량
                intent.putExtra(Common.ENERGY_INTENT_GOAL_HEATING, heating_target);
            }
            getContext().sendBroadcast(intent);

            Log.i(TAG, "[sendRemotemeterDataToMobile] Sent ENERGY_INTENT_ BR "+define.NOTIFY_ENERGY_DATA);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendRemotemeterDataToMobile()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private void getTelemeteringDataOnRandomTime() {
        try {
            int DelayTime = StringUtil.GetDelayTimeBaseIP(getContext());
            if (DelayTime < 1) {
                return;
            }

            Log.i(TAG, "[getTelemeteringDataOnRandomTime] DelayTime : "+ DelayTime);
            getTelemeteringDataHandler.sendEmptyMessageDelayed(0, 1000 * DelayTime);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getTelemeteringDataOnRandomTime()");
            LogUtil.errorLogInfo("", TAG, e);
            return;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler getTelemeteringDataHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                getRemoteMeterDataFromServer(true);
            }
        }
    };

    boolean bTelemeteringToISS = false;

    private void checkISSEnergyType() {
        try {
            WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(getApplication());
            int nEnergyKind = mWallpadDeviceSet.Get_SmartSwitchEnergy_Kind();
            mWallpadDeviceSet.closeDB();

            if (nEnergyKind == WallpadDeviceSet.SMARTSWITCH_ENERGY_REMOTE) bTelemeteringToISS = true;
            else bTelemeteringToISS = false;

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkISSEnergyType()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void getRemoteMeterDataFromServer(boolean bSendToMobile) {
        try {
            nowCal = Calendar.getInstance();
            CalendarYear = nowCal.get(Calendar.YEAR);
            CalendarMonth = nowCal.get(Calendar.MONTH);
            CalendarDate = nowCal.get(Calendar.DATE);
            GetMeteringCount();
            LoadRemotemeterDataFromServer(0, CalendarYear, CalendarMonth, ShowNowEnergyIndex, bSendToMobile);
            if (bTelemeteringToISS) getTelemeringDailyUsageData(CalendarYear, CalendarMonth + 1, CalendarDate);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getRemoteMeterDataFromServer()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private boolean getBlackoutStatus() {
        try {
            SharedPreferences mSharedPreferences = getSharedPreferences("BlackoutStatus", MODE_PRIVATE);
            return mSharedPreferences.getBoolean("status", false);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getBlackoutStatus()");
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }

    private void sendBlackoutScreenRunBR() {
        try {
            Log.i(TAG, "[sendBlackoutScreenRunBR] ========== START ==========");
            Intent mIntent = new Intent(Common.BR_BLACKOUT_SCREEN_RUN, null);
            mContext.sendBroadcast(mIntent);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] sendBlackoutScreenRunBR()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    /**
     * 월패드 타입 판별
     * @return bResult
     * false: 메인월패드
     * true: 서브월패드
     */
    public boolean getIsSubWallpad() {
        boolean bResult = false;
        try {
            WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(this);
            String[] DBinfo = mWallpadDeviceSet.GetSettingData("서브월패드");
            mWallpadDeviceSet.closeDB();

            if (DBinfo == null) bResult = false;
            else {
                if (DBinfo[1].indexOf("사용함") > 0) bResult = true;
                else bResult = false;
            }
            Log.d(TAG, "[getIsSubWallpad] bResult [" + bResult + "]");
            return bResult;
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getIsSubWallpad()");
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }


    /**
     * JEFF, 2020.01.14
     * 월패드 카메라의 초기화를 위한 코드 삽입
     * 월패드 카메라 preview 실행시, 최초 1회에 한하여 카메라 화면에 녹색이 보이는 증상을 해결하기 위함
     */
        /* ================================================================================================
     * 내 영상
     ================================================================================================ */
    // SurfaceLayout 구성
    RelativeLayout MyVideoLayout;            // MoIP 카메라 영상
    SurfaceHolder MyVideoHolder;
    SurfaceView MyVideoSurface;
    RelativeLayout SurfaceLayout;            // 영상표시 화면
    public Camera mMyCamera;

    public void toggleMyVideo() {
        try {
            if (MyVideoLayout == null) {
                Log.e(TAG, "[toggleMyVideo] Show My Video!!!");
                initMyVideoSurfaceLayout();
            }
            else {
                Log.e(TAG, "[toggleMyVideo] Remove My Video!!!");
                removeMyVideoSurfaceLayout();
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] toggleMyVideo()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void initMyVideoSurfaceLayout() {
        try {
//            LOG_INFO("[initMyVideoSurfaceLayout] MyVideoLayout = " + MyVideoLayout);
            if (MyVideoLayout != null) {
                MyVideoSurface.getHolder().removeCallback(MyVideoCallback);
                MyVideoLayout.removeAllViews();
                MyVideoLayout = null;
            }

            MyVideoLayout = new RelativeLayout(mContext);
            WpadUtil.LayoutRegistration(SurfaceLayout, MyVideoLayout, 1024, 600, 0, 0, ID.MAINACTIVITY.LAYOUT.MYVIDEO);
            MyVideoSurface = new SurfaceView(mContext);
            MyVideoHolder = MyVideoSurface.getHolder();
            WpadRelativeLayoutParams MyVideoParams = new WpadRelativeLayoutParams(320, 240);
//            MyVideoParams.setMargins(10, 10, 0, 0); // 보이게
            MyVideoParams.setMargins(1300, 112, 0, 0); // 안보이게
            MyVideoLayout.addView(MyVideoSurface, MyVideoParams);
            MyVideoSurface.getHolder().addCallback(MyVideoCallback);
            MyVideoSurface.setZOrderOnTop(true);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] initMyVideoSurfaceLayout()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    public void removeMyVideoSurfaceLayout() {
        try {
            Log.i(TAG, "[removeMyVideoSurfaceLayout] MyVideoLayout = " + MyVideoLayout);
            if (MyVideoLayout != null) {
                MyVideoLayout.removeAllViews();
                MyVideoLayout = null;
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] removeRemoteVideoSurfaceLayout()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private SurfaceHolder.Callback MyVideoCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                Log.i(TAG, "[MyVideoCallback] surfaceCreated!!");
                if (Common.CurrentBoardType == Common.BOARD_TYPE.V40 || Common.CurrentBoardType == Common.BOARD_TYPE.V40_NOUGAT) {
                    mIOInterface.ctrlWallPadCamPower(true);
                    mMyCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
                    Camera.Parameters params = mMyCamera.getParameters();
                    params.setPictureSize(320, 240);
                    mMyCamera.setParameters(params);
                    mMyCamera.setPreviewDisplay(holder);
                } else {
                    Log.w(TAG, "[MyVideoCallback] surfaceCreated!! -> NOT Supported Common.CurrentBoardType [" + Common.CurrentBoardType + "]");
                }
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] MyVideoCallback -> surfaceCreated(SurfaceHolder holder)");
                LogUtil.errorLogInfo("", TAG, e);
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            try {
                Log.i(TAG, "[MyVideoCallback] surfaceChanged!!");
                if (Common.CurrentBoardType == Common.BOARD_TYPE.V40 || Common.CurrentBoardType == Common.BOARD_TYPE.V40_NOUGAT) {
                    mMyCamera.startPreview();
                } else {
                    Log.w(TAG, "[MyVideoCallback] surfaceChanged!! -> NOT Supported Common.CurrentBoardType [" + Common.CurrentBoardType + "]");
                }
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] MyVideoCallback -> surfaceChanged(SurfaceHolder holder, int format, int width, int height)");
                LogUtil.errorLogInfo("", TAG, e);
//                if (getWallPadCameraUsage()) sendHandlerMsgDelayed(HANDLERMSG.CHECK_WALLPAD_CAMERA_RESET, 0, 0, 3000);   // 3초후 카메라 서비스를 재실행한다.
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            try {
                Log.i(TAG, "[MyVideoCallback] surfaceDestroyed!!");
                if (Common.CurrentBoardType == Common.BOARD_TYPE.V40 || Common.CurrentBoardType == Common.BOARD_TYPE.V40_NOUGAT) {
                    mIOInterface.ctrlWallPadCamPower(false);
                    if (mMyCamera != null) {
                        mMyCamera.stopPreview();
                        mMyCamera.release();
                        mMyCamera = null;
                    }
                } else {
                    Log.w(TAG, "[MyVideoCallback] surfaceDestroyed!! -> NOT Supported Common.CurrentBoardType [" + Common.CurrentBoardType + "]");
                }
            } catch (RuntimeException re) {
                LogUtil.errorLogInfo("", TAG, re);
            }
            catch (Exception e) {
                Log.e(TAG, "[Exception] MyVideoCallback -> surfaceDestroyed(SurfaceHolder holder)");
                LogUtil.errorLogInfo("", TAG, e);
            }
        }
    };

    private boolean getWallPadCameraUsage() {
        boolean bResult = false;
        try {
            WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(this.getContext());
            int nResult = mWallpadDeviceSet.GetDeviceSetted("월패드카메라");
            mWallpadDeviceSet.closeDB();

            if (nResult == WallpadDeviceSet.DEV_DATA_ENABLE) bResult = true;
            else bResult = false;
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getWallPadCameraUsage()");
            LogUtil.errorLogInfo("", TAG, e);
        }
        Log.i(TAG, "[getWallPadCameraUsage] bResult [" + bResult + "]");
        return bResult;
    }

    private void forceCtrlStrangerRecordingUserSettingDisable(boolean bEnable) {
        try {
            WallpadStatusData DBMGR = new WallpadStatusData(getContext());
            DBMGR.SetStrangerRecordingOnOff(bEnable);
            DBMGR.closeDB();
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] forceCtrlStrangerRecordingUserSettingDisable(boolean bEnable)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private void registerLCDKeeper() {
        try {
            Log.i(TAG, "[registerLCDKeeper] ===== START =====");

            if (!bLCDKeeperUsage) {
                Log.w(TAG, "[registerLCDKeeper] bLCDKeeperUsage is false!!!");
                return;
            }

            if (Build.VERSION.SDK_INT < 24) {
                Log.w(TAG, "[registerLCDKeeper] not support LCDKeeper!! Build.VERSION.SDK_INT -> " + Build.VERSION.SDK_INT);
                return;
            }

            IMG_LCD_KEEPER = (ImageView) findViewById(R.id.view_lcdkeeper);
            IMG_LCD_KEEPER.bringToFront();
            IMG_LCD_KEEPER.setVisibility(View.INVISIBLE);
            Log.i(TAG, "[registerLCDKeeper] ===== END =====");
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] registerLCDKeeper()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    int LCDKEEPER_MODE_NONE = 0;   // 동작중 아님
    int LCDKEEPER_MODE_RESTROE = 1;   // 복구모드
    int LCDKEEPER_MODE_PROTECT = 2;   // 보호모드
    boolean bLCDBacklightPower = true;   // LCD backlight on/off 여부 (true: on, false: off)
    int nLCDKeeperRunMode = LCDKEEPER_MODE_NONE;   // LCD Keeper 동작 모드 (0: 동작중 아님, 1: 복구모드, 2: 예방모드)
    private void runLCDKeeper(int nKeeperMode) {
        try {
            if (!bLCDKeeperUsage) {
                Log.w(TAG, "[runLCDKeeper] bLCDKeeperUsage is false!!!");
                return;
            }

            Log.i(TAG, "[runLCDKeeper] nKeeperMode [" + nKeeperMode +"], bLCDBacklightPower [" + bLCDBacklightPower +"]");
            if (Build.VERSION.SDK_INT < 24) {
                Log.w(TAG, "[runLCDKeeper] not support LCDKeeper!! Build.VERSION.SDK_INT -> " + Build.VERSION.SDK_INT);
                return;
            }

            if (IMG_LCD_KEEPER == null) {
                Log.w(TAG, "[runLCDKeeper] IMG_LCD_KEEPER is null!!");
                return;
            }

            // check run mode
            if (nLCDKeeperRunMode == nKeeperMode) {
                // already run LCDKeeper!!
                Log.w(TAG, "[runLCDKeeper] LCD Keeper mode is same -> Asis [" + nLCDKeeperRunMode + "], Tobe [" + nKeeperMode + "]");
                return;
            }

            nLCDKeeperRunMode = nKeeperMode;

            if (nKeeperMode == LCDKEEPER_MODE_NONE) {
                IMG_LCD_KEEPER.setVisibility(View.INVISIBLE);
            }
            else if (nKeeperMode == LCDKEEPER_MODE_RESTROE) {
                if (Common.SCREEN_TYPE == Common.SCREEN_TYPE_1280x800) {
                    Glide.with(this).asGif().load(R.drawable.lcd_restore_1280).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(IMG_LCD_KEEPER);
                }
                else {
                    Glide.with(this).asGif().load(R.drawable.lcd_restore_1024).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(IMG_LCD_KEEPER);
                }
                IMG_LCD_KEEPER.setVisibility(View.VISIBLE);
            }
            else if (nKeeperMode == LCDKEEPER_MODE_PROTECT) {
                IMG_LCD_KEEPER.setImageBitmap(null);
                IMG_LCD_KEEPER.setBackgroundColor(Color.BLACK);
                IMG_LCD_KEEPER.setVisibility(View.VISIBLE);
            }
            else {
                Log.w(TAG, "[runLCDKeeper] Not supported mode!! -> " + nKeeperMode);
                IMG_LCD_KEEPER.setVisibility(View.INVISIBLE);
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] runLCDKeeper(int nKeeperMode)");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private void ctrlLCDKeeper() {
        try {
            if (!bLCDKeeperUsage) {
                Log.w(TAG, "[ctrlLCDKeeper] bLCDKeeperUsage is false!!");
                return;
            }

            if (Build.VERSION.SDK_INT < 24) {
                Log.w(TAG, "[ctrlLCDKeeper] not support LCDKeeper!! Build.VERSION.SDK_INT -> " + Build.VERSION.SDK_INT);
                return;
            }

            if (IMG_LCD_KEEPER == null) {
                Log.w(TAG, "[ctrlLCDKeeper] IMG_LCD_KEEPER is null!!");
                return;
            }

            Log.i(TAG, "[ctrlLCDKeeper] bLCDBacklightPower [" + bLCDBacklightPower +"]");
            if (bLCDBacklightPower) {
                // backlight on시 lcd keeper를 비활성화 한다.
                runLCDKeeper(LCDKEEPER_MODE_NONE);
            }
            else {
                if (nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_PROTECT) {
                    // LCD backlight off시, LCD protect 화면을 구동한다.
                    runLCDKeeper(LCDKEEPER_MODE_PROTECT);
                }
                else if (nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_RECOVER) {
                    // LCD backlight off시, LCD restore 화면을 구동한다.
                    runLCDKeeper(LCDKEEPER_MODE_RESTROE);
                }
                else if (nLCDKeeperType == WallpadDeviceSet.LCDKEEPER_PROTECT_RECOVER) {
                    // 새벽 2:00 ~ 3:59까지 LCD restore 화면을 구동하고, 나머지 시간에는 LCD protect 화면을 구동한다.
                    // 화면에 스모그 또는 미러 글라스 적용이 아닌 경우에는 LCD 보호모드(블랙)만 사용을 권장한다. (LCD RGBW rolling시 컬러가 화면에 비침)
                    Calendar LCDCal = Calendar.getInstance();
                    int nYear = LCDCal.get(Calendar.YEAR);
                    int nMonth = LCDCal.get(Calendar.MONTH) + 1;
                    int nDay = LCDCal.get(Calendar.DAY_OF_MONTH);
                    int nHour = LCDCal.get(Calendar.HOUR_OF_DAY);
                    Log.i(TAG, "[ctrlLCDKeeper] nYear [" + nYear +"], nMonth [" + nMonth +"], nDay [" + nDay +"], nHour [" + nHour +"]");
                    if (3 >= nHour && nHour >= 2) {
                        // 새벽 2:00 ~ 3:59까지 LCD restore 화면을 구동한다.
                        runLCDKeeper(LCDKEEPER_MODE_RESTROE);
                    }
                    else {
                        // 새벽 2:00 ~ 3:59 이외의 시간에는 LCD protect 화면을 구동한다.
                        if (nYear == 2020 && ((nMonth < 8 && nDay < 20) || (nMonth < 7))) {
                            // 단, 이미 증상이 발생한 현장의 LCD 복구를 위해 2020년 7월 19일까지는 protection 화면 대신 restore 화면을 구동한다.
                            runLCDKeeper(LCDKEEPER_MODE_RESTROE);
                        }
                        else {
                            runLCDKeeper(LCDKEEPER_MODE_PROTECT);
                        }
                    }
                }
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] ctrlLCDKeeper()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    private boolean checkTranslucentGlassUsage() {
        try {
            if (Version.getModelType() == MODEL_TYPE.IHN_D101 || Version.getModelType() == MODEL_TYPE.IHN_D101_I
                    || Version.getModelType() == MODEL_TYPE.IHN_D101K || Version.getModelType() == MODEL_TYPE.IHN_D101K_I
                    || Version.getModelType() == MODEL_TYPE.IHN_1010 || Version.getModelType() == MODEL_TYPE.IHN_1010_I
                    || Version.getModelType() == MODEL_TYPE.IHN_1010GL || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I
                    || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I_2443 || Version.getModelType() == MODEL_TYPE.IHN_1010GL_I_6410
                    || Version.getModelType() == MODEL_TYPE.IHN_T1010 || Version.getModelType() == MODEL_TYPE.IHN_T1010_I
                    || Version.getModelType() == MODEL_TYPE.IHN_1303_I || Version.getModelType() == MODEL_TYPE.IHN_D101_I_OCF) {
                return true;
            }
            else return false;
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkTranslucentGlassUsage()");
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }

    /**
     * LCD backlight off시 센서값 keyevent가 발생하지 않는 증상 해결을 위한 임시코드
     *  우선 IHN-1020B-I에만 적용 후, 결과를 보고 다른 일체형 월패드에도 적용 예정
     *  Jeff, 2020.09.07
     * @return true: LCD backlight On, false: LCD backlight Off
     */
    public boolean checkLCDOnByCMD() {
        try {
            Runtime mRuntime = Runtime.getRuntime();
            Process mProcess;
            String cmd = "getprop persist.sys.lcdcon";

            mProcess = mRuntime.exec(cmd);
            BufferedReader br = new BufferedReader(new InputStreamReader(mProcess.getInputStream()));
            String line;
            String strResult = null;

            while ((line = br.readLine()) != null) {
                strResult = line;
            }

            if(strResult!=null)
            {
                if (strResult.equals("0")) {
                    Log.e(TAG, "[checkLCDOnByCMD] LCD On");
                    return true;
                }
                else if (strResult.equals("1")) {
                    Log.e(TAG, "[checkLCDOnByCMD] LCD Off");
                    return false;
                }
                else {
                    Log.e(TAG, "[checkLCDOnByCMD] Unknown value [" + strResult + "], return false!!!");
                    return false;
                }
            }
            else return false;

        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            return false;
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkLCDOnByCMD()");
            LogUtil.errorLogInfo("", TAG, e);
            return false;
        }
    }

    /**
     * 절전모드에서 백라이트를 키는 경우, BSP에서 PowerManager 또는 속성값으로 상태를 구분하는데
     * BSP 버전에 따라 상이하게 동작하므로 BSP 버전 구분하여 절전모드 판별 필요
     * @return true: 기준 BSP 이후 버전, false: 기준 BSP 이전 버전
     */
    public boolean getCompareBSPVersion() {
        try {
            StringBuilder strBSPVersion = new StringBuilder();
            StringBuffer sysInfoBuffer = new StringBuffer();
            sysInfoBuffer.append(Build.DISPLAY);
            strBSPVersion.append(sysInfoBuffer.toString());

            String result = strBSPVersion.toString();
            Log.d(TAG, "[getCompareBSPVersion] result [" + result + "]");

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
            Date date = simpleDateFormat.parse(result);
            Date standardDate = simpleDateFormat.parse("2020.09.18"); // 비교 기준 BSP 버전
            if (date.compareTo(standardDate) >= 0) {
                Log.d(TAG, "[getCompareBSPVersion] BSP VERSION OVER!");
                return true;
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] getCompareBSPVersion()");
            LogUtil.errorLogInfo("", TAG, e);
        }
        return false;
    }

    /**
     *  월패드 부팅시 카메라서비스 로딩이 실패하는 경우가 생겨 카메라 화면이 안나오는 경우 발생
     *  WallPadMain에서 부팅시 카메라를 확인하여 Exception이 발생하는 경우
     *  카메라 서비스를 재실행한다.
     *  (Edited by jeff, 2020.09.08)
     */
    public void resetCameraService() {
        try {
            Log.e(TAG, "[resetCameraService] start!!");
            Runtime mRuntime = Runtime.getRuntime();
            String cmd = "setprop persist.sys.fakeactivitydel 1";
            mRuntime.exec(cmd);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] resetCameraService()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    /**
     * 월패드 부팅시 카메라서비스 로딩이 실패하는 경우가 발생하여
     * 카메라서비스 정상동작 여부를 확인하기위한 함수를 정의한다.
     * 카메라서비스 정상: 정상적으로 카메라가 open되며, camera object가 null이 아니면 카메라를 release한다.
     * 카메라 서비스 비정상: 카메라 open시 Exception이 발생하며 resetCameraService() 함수를 실행하여 카메라서비스를 재실행한다.
     * (Edited by jeff, 2020.09.08)
     */
    public void checkCameraLoading() {
        try {
            Camera checkCamera = Camera.open();
            if (checkCamera != null) {
                Log.e(TAG, "[checkCameraLoading] checkCamera is not null!!");
                checkCamera.release();
            }
            else {
                Log.e(TAG, "[checkCameraLoading] checkCamera is null!!");
                resetCameraService();
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
            resetCameraService();
        }
		catch (Exception e) {
            Log.e(TAG, "[Exception] checkCameraLoading()");
            LogUtil.errorLogInfo("", TAG, e);
            resetCameraService();
        }
    }


    private synchronized void FileDelete(File file)
    {
        if(file!=null && file.exists())
        {
            file.delete();
        }
    }

    public static void ReDirectCall(String ip)
    {
        Intent Intent = new Intent();
        Intent.setAction("CERES_CALL");

        Intent.putExtra("REMOTEINFO", ip);
        mContext_call.sendBroadcast(Intent);
    }


    /**
     * 거동 수상자 녹화 중지(MainActivity -> WallPadCall)
     */
    private void stopStrangerRecord() {
        try {
            Log.d(TAG, "[stopStrangerRecord] bRecordStatus [" + Common.bRecordStatus + "]");
            if (Common.bRecordStatus) {
                Common.bRecordStatus = false;

                // yjyoon. 녹화 중지 브로드캐스트
                Intent iIntent = new Intent();
                iIntent.setAction(Common.BR_REQUEST_RECORD_STOP);
                iIntent.putExtra(define.NOTIBR_KIND, 1);
                getApplicationContext().sendBroadcast(iIntent);

                mediaStopRecord();
            }
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] stopStrangerRecord(boolean bSave)");
            //e.printStackTrace();
            LogUtil.errorLogInfo("", TAG, e);
        }
    }

    /**
     * 거동 수상자 연속 녹화 방지(10초간 막음)
     */
    private void RecordDelayOn()
    {
        try {
            Log.d(TAG, "[RecordDelay]");
            Common.bRecordDelay = true;
            Message msg = recordDelayHandler.obtainMessage();
            recordDelayHandler.sendMessageDelayed(msg, 10 * 1000); // 녹화 종료 후 10초 동안 녹화를 막는다.
        }
        catch (Exception e)
        {

        }
    }


    /**
     * 거동 수상자 녹화 중지 관련 내부 변수 처리
     */
    private void mediaStopRecord() {
        try {
            Log.d(TAG, "[mediaStopRecord]");
            RecordDelayOn();
            Common.bRecordStatus = false; // 녹화 종료
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] mediaStopRecord()");
            //e.printStackTrace();
            LogUtil.errorLogInfo("", TAG, e);
        }
    }


    /**
     * 거동 수상자 역속 녹화를 막기 위한 Handler
     */
    Handler recordDelayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Common.bRecordDelay = false;
        }
    };


    /**
     * 거동 수상자 관련 BR 등록
     */
    private void registerStrangeRecordBR() {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(Common.BR_RECORD_EXCEPTION);
            filter.addAction(Common.BR_RECORD_STOP);
            filter.addAction(Common.BR_RECORD_DELAY);
            mContext.registerReceiver(StrangeRecordBroadcastReceiver, filter);
        } catch (RuntimeException re) {
            LogUtil.errorLogInfo("", TAG, re);
        }
        catch (Exception e) {
            Log.e(TAG, "[Exception] registerMainActivityBR()");
            LogUtil.errorLogInfo("", TAG, e);
        }
    }


    /**
     * 거동 수상자 관련 BR
     */
    BroadcastReceiver StrangeRecordBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(Common.BR_RECORD_EXCEPTION))
            {
                Common.bRecordStatus = false;
            }
            else if(intent.getAction().equals(Common.BR_RECORD_STOP))
            {
                stopStrangerRecord();
            }
            else if(intent.getAction().equals(Common.BR_RECORD_DELAY))
            {
                RecordDelayOn();
            }
        }
    };
}