package kr.co.icontrols.ilp300_700;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Camera;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.artncore.WallPadDataMgr.WallpadStatusData;
import com.artncore.wallpadapi.WallPadAPI;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import kr.co.icontrols.ilp300_700.admin.inquiry.AdminSetInquiryScreen;
import kr.co.icontrols.ilp300_700.admin.inquiry.AdminSet_Inquiry_ElevDisableFloor;
import kr.co.icontrols.ilp300_700.admin.inquiry.AdminSet_Inquiry_LineInfo;
import kr.co.icontrols.ilp300_700.admin.inquiry.AdminSet_Inquiry_LobbyPhoneInfo;
import kr.co.icontrols.ilp300_700.admin.inquiry.AdminSet_Inquiry_NetworkInfo;
import kr.co.icontrols.ilp300_700.admin.inquiry.AdminSet_Inquiry_SubLobbyInfo;
import kr.co.icontrols.ilp300_700.admin.inquiry.AdminSet_Inquiry_VerInfo;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSetSettingScreen;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_ACULink;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_AdminAccessPW;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_AdminAccessPWChange;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_AdminPW;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_BLEStrength;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_BasicInfo;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_Calendar;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_CallLevel;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_CardReaderType;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_DoorOpenDuration;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_ECOMode;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_ElevDisableFloor;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_ExternalOnePassLink;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_FingerPrintLink;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_FireSensorDoorOpenDelay;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_GuardID;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_HouseDivision;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_IPExpansion;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_InsideSensorLink;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_Language;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_LineInfo;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_LobbyRole;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_LogFileSend;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_MainServerType;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_MainSub;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_Melody;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_MoviePlay;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_OnePassConfigure;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_OnePassRSSIIndex;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_ParcelLink;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_PublicAccessPW;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_RFAccessKeyIssuedCnt;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_RFAccessLevel;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_ResetSystem;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_SelectAccessPW;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_SendHeartbeat;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_SetIPManually;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_SmartAutodoorLink;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_SmartKeyConfigure;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_SyncSetupInfo;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_Volume;
import kr.co.icontrols.ilp300_700.admin.setting.AdminSet_Setting_ZigBeeSensitivity;
import kr.co.icontrols.ilp300_700.admin.test.AdminSetTestScreen;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_Camera;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_DoorOpen;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_FireSensor;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_GoogleLauncher;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_Network;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_Network_IP;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_ProximitySensor;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_RFReader;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_RFReader_Read;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_RS485;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_Sensors;
import kr.co.icontrols.ilp300_700.admin.test.AdminSet_Test_TalkTestMode;
import kr.co.icontrols.ilp300_700.call.AvcEncoder;
import kr.co.icontrols.ilp300_700.call.CallController;
import kr.co.icontrols.ilp300_700.call.CallManager.CALLPATH;
import kr.co.icontrols.ilp300_700.database.DBManager;
import kr.co.icontrols.ilp300_700.ethernet.EthernetCtrl;
import kr.co.icontrols.ilp300_700.ethernet.iMAPCommon.iMAPResult;
import kr.co.icontrols.ilp300_700.ethernet.iMAPServer;
import kr.co.icontrols.ilp300_700.ethernet.iMAPServer.runiMAPSSLsvr;
import kr.co.icontrols.ilp300_700.ethernet.iMAPServer.runiMAPsvr;
import kr.co.icontrols.ilp300_700.fingerprint.FingerprintScanService;
import kr.co.icontrols.ilp300_700.global.BestinBroadReceiver;
import kr.co.icontrols.ilp300_700.global.Configure;
import kr.co.icontrols.ilp300_700.global.Configure.ConfigValue;
import kr.co.icontrols.ilp300_700.global.Configure.SetValue;
import kr.co.icontrols.ilp300_700.global.DataClasses;
import kr.co.icontrols.ilp300_700.global.DataClasses.POSITION;
import kr.co.icontrols.ilp300_700.global.Declare;
import kr.co.icontrols.ilp300_700.global.Declare.PrivateBR;
import kr.co.icontrols.ilp300_700.global.Enumeration.TTSEVENT;
import kr.co.icontrols.ilp300_700.global.Enumeration.UPGRADESTATUS;
import kr.co.icontrols.ilp300_700.global.Global;
import kr.co.icontrols.ilp300_700.global.ID;
import kr.co.icontrols.ilp300_700.global.LobbyAccessCtrl;
import kr.co.icontrols.ilp300_700.global.SystemUpgrade;
import kr.co.icontrols.ilp300_700.ifconverter.SmartAutoDoorIFManager;
import kr.co.icontrols.ilp300_700.imap.MakeiMAPMSG;
import kr.co.icontrols.ilp300_700.imap.Notices;
import kr.co.icontrols.ilp300_700.imap.iMAPResultCtrl;
import kr.co.icontrols.ilp300_700.rfmsg.Request_MultiRF_Detection;
import kr.co.icontrols.ilp300_700.rfreader.STDAccessKeyManager;
import kr.co.icontrols.ilp300_700.rfreader.UIDAccessKeyManager;
import kr.co.icontrols.ilp300_700.screen.AccessAdminPW;
import kr.co.icontrols.ilp300_700.screen.AccessPublicPW;
import kr.co.icontrols.ilp300_700.screen.AccessResidencePW;
import kr.co.icontrols.ilp300_700.screen.AdminSetAdminPW;
import kr.co.icontrols.ilp300_700.screen.AdminSetMain;
import kr.co.icontrols.ilp300_700.screen.Init;
import kr.co.icontrols.ilp300_700.screen.Main;
import kr.co.icontrols.ilp300_700.screen.Reboot;
import kr.co.icontrols.ilp300_700.screen.TalkGuard;
import kr.co.icontrols.ilp300_700.screen.TalkResidence;
import kr.co.icontrols.ilp300_700.serialport.HDCIPARKReaderSerial;
import kr.co.icontrols.ilp300_700.serialport.HDCStandardReaderSerial;
import kr.co.icontrols.sttttsapi.SttApi;
import kr.co.icontrols.sttttsapi.SttResult;
import kr.co.icontrols.sttttsapi.TTsApi;
import kr.co.icontrols.sttttsapi.TTsResult;
import kr.co.icontrols.wallpadsupport.WpadActivity;
import kr.co.icontrols.wallpadsupport.WpadImageView;
import kr.co.icontrols.wallpadsupport.WpadSound;
import kr.co.icontrols.wallpadsupport.WpadUtil;

public class MainActivity extends WpadActivity {

    static String TAG = "MainActivity";

    //add KSJ
    static boolean m_bFaceDetect = false;
    static boolean m_bLobbyStart = false;
    //~add KSJ

    public static RelativeLayout EntireLayout;   // 전체화면 (480*272)
    public static SurfaceView RemoteVideoSurface;
    public static AudioManager mAudioManager;
    public static WpadSound mSound;
    public static DBManager ConfigDBManager = null;
    public static DBManager RFKeySTD_RESI_DBManager = null;
    public static DBManager RFKeySTD_ADMINDONG_DBManager = null;
    public static DBManager RFKeySTD_ADMINENTIRE_DBManager = null;
    public static DBManager RFKeyDBManager = null;
    public static CallController mCallController;
    public static IOInterface mIOInterface;
    public static PowerManager mPowerManager;

    public static WpadImageView Image_Emergency;
    public static WpadImageView Image_RFReaderError;
    public static int nDefaultScreenTimeout = 10;   // Sec 단위
    public static int nAdminScreenTimeout = 15;   // Sec 단위

    static boolean bLOG = true;   // true, false
    static boolean bLOG_DEBUG = false;   // true, false
    static boolean bLOG_INFO = true;   // true, false

    AvcEncoder mAvcEncoder;

    // 자동 화면종료 기능
    static Timer AutoScreenChangeTimer = null;
    private static int nAutoScreenChangeTime = 0;   // Sec 단위
    private static int nAutoScreenChangeNextID = 0;
    private static int nAutoScreenChangeTimeout = 0;   // Sec 단위
    public RelativeLayout MyVideoLayout;   // 카메라 영상
    public SurfaceHolder MyVideoHolder;
    public SurfaceView MyVideoSurface;
    public RelativeLayout RemoteVideoLayout;   // 카메라 영상
    public SurfaceHolder RemoteVideoHolder;
    public TalkResidence SCREEN_Talk_Residence;
    public TalkGuard SCREEN_Talk_Guard;
//    public TalkResidenceLoad SCREEN_Talk_ResidenceLoad;
    public SmartAutoDoorIFManager mSmartAutoDoorIFManager;

    public boolean bChatMode = false;
    protected String SharedPreferencesName = "HDC_SharedPreferences";

    RelativeLayout MainLayout;   // 메인화면 (480*272)
    Init SCREEN_Init;
    Main SCREEN_Main;
    AccessPublicPW SCREEN_Access_PublicPW;
    AccessResidencePW SCREEN_Access_ResidencePW;
    AccessAdminPW SCREEN_Access_AdminPW;
    AdminSetAdminPW SCREEN_AdminSet_AdminPW;
    AdminSetMain SCREEN_AdminSet_Main;
    AdminSetSettingScreen SCREEN_AdminSet_Setting;
    AdminSetInquiryScreen SCREEN_AdminSet_Inquiry;
    AdminSetTestScreen SCREEN_AdminSet_Test;
    AdminSet_Setting_BasicInfo SCREEN_AdminSet_Setting_BasicInfo;
    AdminSet_Setting_GuardID SCREEN_AdminSet_Setting_GuardID;
    AdminSet_Setting_LineInfo SCREEN_AdminSet_Setting_LineInfo;
    AdminSet_Setting_MainSub SCREEN_AdminSet_Setting_MainSub;
    AdminSet_Setting_SyncSetupInfo SCREEN_AdminSet_Setting_SyncSetupInfo;
    AdminSet_Setting_SelectAccessPW SCREEN_AdminSet_Setting_SelectAccessPW;
    AdminSet_Setting_PublicAccessPW SCREEN_AdminSet_Setting_PublicAccessPW;
    AdminSet_Setting_AdminAccessPW SCREEN_AdminSet_Setting_AdminAccessPW;
    AdminSet_Setting_AdminAccessPWChange SCREEN_AdminSet_Setting_AdminAccessPWChange;
    AdminSet_Setting_AdminPW SCREEN_AdminSet_Setting_AdminPW;
    AdminSet_Setting_CallLevel SCREEN_AdminSet_Setting_CallLevel;
    AdminSet_Setting_RFAccessLevel SCREEN_AdminSet_Setting_RFAccessLevel;
    AdminSet_Setting_RFAccessKeyIssuedCnt SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt;
    AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey;
    AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey;
    AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey;
    AdminSet_Setting_Melody SCREEN_AdminSet_Setting_Melody;
    AdminSet_Setting_Volume SCREEN_AdminSet_Setting_Volume;
    AdminSet_Setting_DoorOpenDuration SCREEN_AdminSet_Setting_DoorOpenDuration;
    AdminSet_Setting_FireSensorDoorOpenDelay SCREEN_AdminSet_Setting_FireSensorDoorOpenDelay;
    AdminSet_Setting_Calendar SCREEN_AdminSet_Setting_Calendar;
    AdminSet_Setting_ECOMode SCREEN_AdminSet_Setting_ECOMode;
    AdminSet_Setting_SendHeartbeat SCREEN_AdminSet_Setting_SendHeartbeat;
    AdminSet_Setting_LogFileSend SCREEN_AdminSet_Setting_LogFileSend;
    AdminSet_Setting_SetIPManually SCREEN_AdminSet_Setting_SetIPManually;
    AdminSet_Setting_ResetSystem SCREEN_AdminSet_Setting_ResetSystem;
    AdminSet_Setting_Language SCREEN_AdminSet_Setting_Language;
    AdminSet_Setting_MoviePlay SCREEN_AdminSet_Setting_MoviePlay;
    AdminSet_Setting_LobbyRole SCREEN_AdminSet_Setting_LobbyRole;
    AdminSet_Setting_ACULink SCREEN_AdminSet_Setting_ACULink;
    AdminSet_Setting_ParcelLink SCREEN_AdminSet_Setting_ParcelLink;
    AdminSet_Setting_ExternalOnePassLink SCREEN_AdminSet_Setting_ExternalOnePassLink;
    AdminSet_Setting_MainServerType SCREEN_AdminSet_Setting_MainServerType;
    AdminSet_Setting_CardReaderType SCREEN_AdminSet_Setting_CardReaderType;
    AdminSet_Setting_ElevDisableFloor SCREEN_AdminSet_Setting_ElevDisableFloor;
    AdminSet_Setting_IPExpansion SCREEN_AdminSet_Setting_IPExpansion;
    AdminSet_Setting_HouseDivision SCREEN_AdminSet_Setting_HouseDivision;
    AdminSet_Setting_SmartAutodoorLink SCREEN_AdminSet_Setting_SmartAutodoorLink;
    AdminSet_Setting_InsideSensorLink SCREEN_AdminSet_Setting_InsideSensorLink;
    AdminSet_Setting_ZigBeeSensitivity SCREEN_AdminSet_Setting_ZigBeeSensitivity;
    AdminSet_Setting_FingerPrintLink SCREEN_AdminSet_Setting_FingerPrintLink;
    AdminSet_Setting_BLEStrength SCREEN_AdminSet_Setting_BLEStrength;
    AdminSet_Setting_OnePassRSSIIndex SCREEN_AdminSet_Setting_OnePassRSSIIndex;
    AdminSet_Setting_OnePassConfigure SCREEN_AdminSet_Setting_OnePassConfigure;
    AdminSet_Setting_SmartKeyConfigure SCREEN_AdminSet_Setting_SmartKeyConfigure;
    AdminSet_Inquiry_LobbyPhoneInfo SCREEN_AdminSet_Inquiry_LobbyPhoneInfo;
    AdminSet_Inquiry_LineInfo SCREEN_AdminSet_Inquiry_LineInfo;
    AdminSet_Inquiry_SubLobbyInfo SCREEN_AdminSet_Inquiry_SubLobbyInfo;
    AdminSet_Inquiry_ElevDisableFloor SCREEN_AdminSet_Inquiry_ElevDisableFloor;
    AdminSet_Inquiry_NetworkInfo SCREEN_AdminSet_Inquiry_NetworkInfo;
    AdminSet_Inquiry_VerInfo SCREEN_AdminSet_Inquiry_VerInfo;
    AdminSet_Test_DoorOpen SCREEN_AdminSet_Test_DoorOpen;
    AdminSet_Test_FireSensor SCREEN_AdminSet_Test_FireSensor;
    AdminSet_Test_Sensors SCREEN_AdminSet_Test_Sensors;
    AdminSet_Test_Camera SCREEN_AdminSet_Test_Camera;
    AdminSet_Test_Network SCREEN_AdminSet_Test_Network;
    AdminSet_Test_Network_IP SCREEN_AdminSet_Test_Network_IP;
    AdminSet_Test_RFReader SCREEN_AdminSet_Test_RFReader;
    AdminSet_Test_RFReader_Read SCREEN_AdminSet_Test_RFReader_Read;
    AdminSet_Test_TalkTestMode SCREEN_AdminSet_Test_TalkTestMode;
    AdminSet_Test_GoogleLauncher SCREEN_AdminSet_Test_GoogleLauncher;
    AdminSet_Test_RS485 SCREEN_AdminSet_Test_RS485;
    AdminSet_Test_ProximitySensor SCREEN_AdminSet_Test_ProximitySensor;
    Reboot SCREEN_Reboot;

    public static int m_bCallType = 0;

    int[] EmergencyImages = {R.drawable.caution_emergency, R.drawable.image_emergency};
    int[] RFReaderImages = {R.drawable.caution_rfreader_error, R.drawable.image_card_error};

    Context mContext;
    public WallPadAPI mWallPadAPI = null;

    private static final int REQUEST_MODIFY_AUDIO_SETTINGS = 100;

    iMAPServer.runiMAPsvr miMAPSvrStarter;
    iMAPServer.runiMAPSSLsvr miMAPSSLServerStarter;
    HDCIPARKReaderSerial CRSerialPort_STD;
    HDCStandardReaderSerial CRSerialPort_Multi;
    BestinBroadReceiver LPReceiver;
    static RFReaderStatusChecker mRFReaderStatusChecker;
    FaceDetectActivityChecker mFaceDetectActivityChecker;

    boolean bActivate = false; // MOTION SENSOR ACTIVATE CHECK FLAG (seulki)
    TTSEventListener mTTSEventListener;
    TTsApi mTTSApi;
    SttApi mSTTApi;

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> future;
    boolean bIgnoreFlag = false; // timer check를 위한 flag (true이면 이벤트 무시)
    CountDownTimer mFinishTimer = null;
    boolean bTimerRemain = true;

    Runnable SendPacketRun = new Runnable() {
        @Override
        public void run() {
            LOG("[SendPacketRun] bActivate: " + bActivate + ", bTimerRemain: " + bTimerRemain);
            if (bActivate && bTimerRemain) {
                LOG("[SendPacketRun] isValidOutsideSensor(): " + isValidOutsideSensor());
                if (isValidOutsideSensor()) sendExternalDetectionPacket();
            } else {
                future.cancel(false);
                future = null;
                setTimerDestroy();
            }
        }
    };

    @SuppressLint("HandlerLeak")
    public Handler mTimerCheck = new Handler() {
        public void handleMessage(Message msg) {
            LOG("[mTimerCheck] msg.what: " + msg.what + ", bIgnoreFlag: " + bIgnoreFlag);
            if (msg.what == 0) {
                setTimerCreate(60);
                if (!bIgnoreFlag) {
                    future = service.scheduleAtFixedRate(SendPacketRun, 0, 500, TimeUnit.MILLISECONDS);
                    bIgnoreFlag = true;
                    mTimerCheck.sendEmptyMessageDelayed(1, 500);
                }
            } else if (msg.what == 1) {
                // 플래그 수정
                bIgnoreFlag = false;
            }
        }
    };

    Camera mCamera;

    private Callback MyVideoCallback = new Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            LOG_INFO("[MyVideoCallback] surfaceCreated!!");
            try {
                MainActivity.mIOInterface.setAnalogCameraPower(true);
                mCamera = Camera.open();
                Camera.Parameters params = mCamera.getParameters();
                params.setPictureSize(480, 272);
                mCamera.setParameters(params);
                mCamera.setPreviewDisplay(holder);
            } catch (IOException e) {
                Log.e(TAG, "[Exception] MyVideoCallback.surfaceCreated()");
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            LOG_INFO("[MyVideoCallback] surfaceChanged!!");
            mCamera.startPreview();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            LOG_INFO("[MyVideoCallback] surfaceDestroyed!!");
            try {
                if (mCamera != null) {
                    mCamera.stopPreview();
                    MainActivity.mIOInterface.setAnalogCameraPower(false);
                    mCamera.release();
                    mCamera = null;
                }

                if (MyVideoSurface != null) {
                    MyVideoSurface.getHolder().removeCallback(MyVideoCallback);
                    MyVideoSurface = null;
                }
            } catch (Exception e) {
                Log.e(TAG, "[Exception] MyVideoCallback.surfaceDestroyed()");
                e.printStackTrace();
            }
        }
    };

    public Handler MainHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            LOG("[MainHandler] MainHandler : what [" + msg.what + "], arg1 [" + msg.arg1 + "], arg2 [" + msg.arg2 + "]");
            switch (msg.what) {
                case HANDLERMSG.AUTOSCREENCHANGE:
                    setChangeScreen(msg.arg1, false);
                    break;

                case HANDLERMSG.CANCEL_AUTOSCREENCHANGE:
                    cancelAutoScreenChange();
                    break;

                case HANDLERMSG.ON_ALARM:
//              setChangeScreen(ID.SCREENS.Alarm, false);
                    break;

                case HANDLERMSG.ON_MAIN:
                    setChangeScreen(ID.SCREENS.Main, false);
                    break;

                case HANDLERMSG.REMOVE_VIDEO_COVER:
//              showVideo(true);
                    break;

                case HANDLERMSG.SHOW_VIDEO_COVER:
//              showVideo(false);
                    break;

                case HANDLERMSG.CLEAR_ALL_CALL:
                    mCallController.mCallInfo.resetCallStatus();
                    //ctrlVideoSurface(false);
                    if (Global.nCurrentScreenID != ID.SCREENS.Main)
                        setChangeScreen(ID.SCREENS.Main, false);
                    break;

                case HANDLERMSG.START_CHATMODE:
                    startChatMode();
                    break;

                case HANDLERMSG.STOP_CHATMODE:
                    stopChatMode();
                    break;

                case HANDLERMSG.START_IMAPSERVER:
                    initiMAPServer();
                    break;

                case HANDLERMSG.SEND_HEARTBEAT_NOTICE:
                    Notices.send_Heartbeat();
                    break;

                case HANDLERMSG.START_FINGERPRINTSERVICE:
                    mContext.startService(new Intent(mContext, FingerprintScanService.class));
                    break;

                case HANDLERMSG.IMG_ON_EMERGENCY:
                    showEmergencyImage(true);
                    break;

                case HANDLERMSG.IMG_OFF_EMERGENCY:
                    showEmergencyImage(false);
                    break;

                case HANDLERMSG.IMG_ON_RFREADERERROR:
                    showRFReaderErrorImage(true);
                    break;

                case HANDLERMSG.IMG_OFF_RFREADERERROR:
                    showRFReaderErrorImage(false);
                    break;

                case HANDLERMSG.CTRL_ONEPASSDOOROPEN:
                    LobbyAccessCtrl.ctrlOnePassAccess();
                    break;

                case HANDLERMSG.SHOW_TOASTMSG:
                    if (Global.bOnePassTestMode) Toast.makeText(mContext, (String) msg.obj, Toast.LENGTH_LONG).show();
                    break;

                case HANDLERMSG.RUN_GOOGLE_LAUNCHER:
                    runGoogleLauncher();
                    break;

                case HANDLERMSG.SYSTEM_REBOOT:
                    setChangeScreen(ID.SCREENS.Reboot, false);
                    break;

                default:
                    LOG("MainHandler : " + msg.what);
                    break;
            }
        }
    };
    
    private Callback RemoteVideoCallback = new Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            LOG_INFO("[RemoteVideoCallback] surfaceCreated!!");
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            LOG_INFO("[RemoteVideoCallback] surfaceChanged!!");
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            LOG_INFO("[RemoteVideoCallback] surfaceDestroyed!!");
            if (RemoteVideoSurface != null) {
                RemoteVideoSurface.getHolder().removeCallback(RemoteVideoCallback);
                RemoteVideoSurface = null;
            }
        }
    };

    private static void LOG(String log) {
        if (bLOG) Log.v(TAG, log);
    }

    private static void LOG_DEBUG(String log) {
        if (bLOG_DEBUG) Log.d(TAG, log);
    }

    private static void LOG_INFO(String log) {
        if (bLOG_INFO) Log.i(TAG, log);
    }

    public static void showEmergencyImage(boolean bShow) {
        try {
            LOG("[showEmergencyImage] bShow [" + bShow + "]");
            if (bShow) Image_Emergency.setVisibility(View.VISIBLE);
            else Image_Emergency.setVisibility(View.INVISIBLE);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] showEmergencyImage(boolean bShow)");
            e.printStackTrace();
        }
    }

    public static void showRFReaderErrorImage(boolean bShow) {
        try {
            LOG("[showRFReaderErrorImage] bShow [" + bShow + "]");
            if (bShow) Image_RFReaderError.setVisibility(View.VISIBLE);
            else Image_RFReaderError.setVisibility(View.INVISIBLE);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] showRFReaderErrorImage(boolean bShow)");
            e.printStackTrace();
        }
    }

    public final String PREFERENCE = "ilp300.setting.value";
    public static String Face_Detect_Value = "Face_Detect_Value";
    public static String Face_Thres_Value = "Face_Thres_Value";
    public static String Face_AI_Set = "Face_AI_Set";
    public static String Face_Mask_Value = "Face_Mask_Value";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LOG_INFO("------------------ [START - MainActivity] -------------------");
        int m_bStart = getIntent().getIntExtra("test", -1);
        if(m_bStart != 1) {

            mContext = this;
            m_bLobbyStart = false;
            mSound = new WpadSound(this);
            mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

            mIOInterface = new IOInterface();

            LobbyAccessCtrl.setLobbyAccessCtrlContext(mContext);
            Global.setGlobalContext(mContext);
            Global.getConfigValues();
            Global.ctrlLobbyDoorNMent(true, false, ConfigValue.nDoorOpenDuration, false, false);

            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    Global.setDelPopup();
                }
            }, 1000);

            EntireLayout = new RelativeLayout(this);
            RelativeLayout.LayoutParams EntireParams = new RelativeLayout.LayoutParams(Declare.DeviceInfo.getScreenSizeFullW(ConfigValue.DEVICE_MODELTYPE), Declare.DeviceInfo.getScreenSizeFullH(ConfigValue.DEVICE_MODELTYPE));
            EntireLayout.setLayoutParams(EntireParams);
            EntireLayout.setId(ID.ACTIVITIES.MAINACTIVITY.LAYOUTS.Entire);

            MainLayout = new RelativeLayout(this);
            WpadUtil.LayoutRegistration(EntireLayout, MainLayout, Declare.DeviceInfo.getScreenSizeFullW(ConfigValue.DEVICE_MODELTYPE), Declare.DeviceInfo.getScreenSizeFullH(ConfigValue.DEVICE_MODELTYPE), 0, 0, ID.ACTIVITIES.MAINACTIVITY.LAYOUTS.Main);

            addBrActionFilter(PrivateBR.FINGERPRINT_DETECTED);
            addBrActionFilter(PrivateBR.CERES_CALL);
            addBrActionFilter(PrivateBR.SENSETIME_ERROR);
            addBrActionFilter(PrivateBR.UPDATE_SENSOR);

            initGlobalImages();
            setChangeScreen(ID.SCREENS.Init, false);
            Global.nCurrentScreenID = ID.SCREENS.Init;

            setContentView(EntireLayout);

            WallpadStatusData wpd = new WallpadStatusData(mContext);
            wpd.SetUpgradeState(false);
            LOG("[onCreate] GetUpgradeState [" + wpd.GetUpgradeState() + "]");
            wpd.closeDB();

            //setAiConfig_first();


            //SaveBootupTime();


            super.setCurrentScreen(SCREEN_Init);
        }
        /*else
        {
            super.setCurrentScreen(SCREEN_Main);
        }*/

//        setChangeScreen(ID.SCREENS.AdminSet_Main, false);
//        Global.nCurrentScreenID = ID.SCREENS.AdminSet_Main;
//
//        setContentView(EntireLayout);
//
//        super.setCurrentScreen(SCREEN_AdminSet_Main);
    }

    //Bootup 시간
    public void SaveBootupTime()
    {
        final String PREFS_NAME = "AppPrefs";
        final String LAST_REBOOT_DATE = "LastRebootDate";

        SharedPreferences sharedPreferences = mContext.getApplicationContext().getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Calendar calendar = Calendar.getInstance();
        long currentDate = getDateAsInt(calendar);
        editor.putLong(LAST_REBOOT_DATE, currentDate);
        editor.apply();
    }

    // Calendar 객체를 YYYYMMDD 정수로 변환
    private long getDateAsInt(Calendar calendar) {
/*        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // Calendar.MONTH는 0부터 시작하므로 +1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR);
        int min = calendar.get(Calendar.MINUTE);*/
        return calendar.getTimeInMillis(); // YYYYMMDD 형식의 정수 반환
    }


    @Override
    protected void onDestroy() {
        LOG("[onDestroy] ===== START =====");
        super.onDestroy();
        if (future != null) {
            future.cancel(false);
            future = null;
        }

        mCallController.releaseCallController();

        if (mTimerCheck != null) {
            mTimerCheck.removeMessages(0);
            mTimerCheck.removeMessages(1);
            mTimerCheck = null;
        }

        if (mAppLiveSignalSender != null) mAppLiveSignalSender.stopThread();

    }

    @Override
    protected void onPause() {
        LOG("[onPause] ===== START =====");
        super.onPause();
    }

    @Override
    protected void onRestart() {
        LOG("[onRestart] ===== START =====");
        super.onRestart();
    }

    @Override
    protected void onResume() {
        LOG("[onResume] ===== START =====");
        super.onResume();
    }

    @Override
    protected void onStart() {
        LOG("[onStart] ===== START =====");
        super.onStart();
    }

    @Override
    protected void onStop() {
        LOG("[onStop] ===== START =====");
        super.onStop();
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case REQUEST_MODIFY_AUDIO_SETTINGS: {
//                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    Log.d(TAG, "[onRequestPermissionsResult] MODIFY_AUDIO_SETTINGS PERMISSION_GRANTED");
//                } else {
//                    Log.d(TAG, "[onRequestPermissionsResult] MODIFY_AUDIO_SETTINGS PERMISSION_NOT_GRANTED");
//                }
//                return;
//            }
//        }
//    }

    @Override
    protected void onBrReceive(Intent intent) {
        try {
            LOG("[onBrReceive] onBrReceive -> intent.getAction() : " + intent.getAction());
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                LOG("[onBrReceive] (BR) ACTION_TIME_TICK");
                Global.checkSyncSystemClock();
            } else if (intent.getAction().equals(PrivateBR.FINGERPRINT_DETECTED)) {
                LOG("[onBrReceive] (BR) FINGERPRINT_DETECTED");
                byte[] hFingerprintData = intent.getByteArrayExtra(PrivateBR.FINGERPRINT_DATA);
                if (hFingerprintData != null) {
//                    MainActivity.mSound.PlayMent_lobby(R.raw.resultok);
                    Log.i(TAG, "[onBrReceive] hFingerprintData : " + Global.printHexs(hFingerprintData));
                    Global.send_verify_access_authorization(Declare.AccessValues.fingerprint.toLowerCase(), "null", hFingerprintData.length, hFingerprintData, "null");
                }
                else {
                    Log.w(TAG, "[onBrReceive] hFingerprintData is null!!");
                }
            }
            else if (intent.getAction().equals(PrivateBR.CERES_CALL)) {
                LOG("[onBrReceive] (BR) CERES_CALL");

                mCallController.onCeresCallEvent(intent);

                //USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
                //ma.setData(Sock, data, type);
            }
            else if (intent.getAction().equals(PrivateBR.SENSETIME_ERROR))
            {
                Intent intent1 = new Intent(MainActivity.this, USBCameraActivity2.class);
                intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent1);
            }
            else if (intent.getAction().equals(PrivateBR.UPDATE_SENSOR))
            {
                int value = intent.getIntExtra("data", -1);
                if (value == Declare.Button.INSIDESENSOR_ACTIVE) {
                    LOG("[onKeyDown] Pressed (INSIDESENSOR_ACTIVE)");
                    if (ConfigValue.eInsideSensorLink == SetValue.FALSE) setInteriorDetectionTime();  // 내부센서 감지시간을 저장한다.
                    else Global.ctrlLobbyDoorNMent(true, false, ConfigValue.nDoorOpenDuration, false, false);
                }
                else if (value == Declare.Button.INSIDESENSOR_INACTIVE) {
                    LOG("[onKeyDown] Pressed (INSIDESENSOR_INACTIVE)");
                }
                else if (value == Declare.Button.FIRE_ACTIVE) {
                    LOG("[onKeyDown] Pressed (FIRE_ACTIVE)");
                    Global.setFireAlarmProcess(Global.FIRESENSOR_TIMEOUT);
                }
                else if (value == Declare.Button.OUTSIDESENSOR_ACTIVE) {
                    LOG("[onKeyDown] Pressed (OUTSIDESENSOR_ACTIVE)");
                    bActivate = true;
                    // 스마트키 카드리더기 연동 설정
                    mTimerCheck.sendEmptyMessage(0);
                    setExteriorDetectionTime();
                }
                else if (value == Declare.Button.OUTSIDESENSOR_INACTIVE) {
                    LOG("[onKeyDown] Pressed (OUTSIDESENSOR_INACTIVE)");
                    bActivate = false;
                    setTimerDestroy();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onBrReceive(Intent intent)");
            e.printStackTrace();
        }
        super.onBrReceive(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        LOG("[onKeyDown] keyCode [" + keyCode + "], event [" + event + "]");
        if (!Global.getEnableDeviceInput()) {
            Log.e(TAG, "[onKeyDown] Global.getEnableDeviceInput() = " + Global.getEnableDeviceInput());
            return false;
        }

        if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
            LOG("[onKeyDown] Pressed (NUMBER_0" + (keyCode - 7) + ")");
            mSound.PlayMent_lobby(R.raw.button);
            if (Global.nCurrentScreenID != ID.SCREENS.Main) extendAutoScreenChangeTime();
        }
        else if (keyCode == Declare.Button.STAR) {
            LOG("[onKeyDown] Pressed (STAR)");
            mSound.PlayMent_lobby(R.raw.button);
            if (Global.nCurrentScreenID != ID.SCREENS.Main) extendAutoScreenChangeTime();
        }
        else if (keyCode == Declare.Button.SHARP) {
            LOG("[onKeyDown] Pressed (SHARP)");
            mSound.PlayMent_lobby(R.raw.button);
            if (Global.nCurrentScreenID != ID.SCREENS.Main) extendAutoScreenChangeTime();
        }
        else if (keyCode == Declare.Button.CALL) {
            LOG("[onKeyDown] Pressed (CALL)");
            mSound.PlayMent_lobby(R.raw.button);
            if (Global.nCurrentScreenID != ID.SCREENS.Main) extendAutoScreenChangeTime();
        }
        else if (keyCode == Declare.Button.GUARD || keyCode == Declare.Button.TACT_GUARD) {
            LOG("[onKeyDown] Pressed (GUARD)");
            mSound.PlayMent_lobby(R.raw.button);
            if (Global.nCurrentScreenID != ID.SCREENS.Main) extendAutoScreenChangeTime();
        }
        else if (keyCode == Declare.Button.CANCEL || keyCode == Declare.Button.TACT_CANCEL) {
            LOG("[onKeyDown] Pressed (CANCEL)");
            mSound.PlayMent_lobby(R.raw.button);
            if (Global.nCurrentScreenID != ID.SCREENS.Main) extendAutoScreenChangeTime();
        }
        else if (keyCode == Declare.Button.INSIDESENSOR_ACTIVE) {
            LOG("[onKeyDown] Pressed (INSIDESENSOR_ACTIVE)");
            if (ConfigValue.eInsideSensorLink == SetValue.FALSE) setInteriorDetectionTime();  // 내부센서 감지시간을 저장한다.
            else Global.ctrlLobbyDoorNMent(true, false, ConfigValue.nDoorOpenDuration, false, false);
        }
        else if (keyCode == Declare.Button.INSIDESENSOR_INACTIVE) {
            LOG("[onKeyDown] Pressed (INSIDESENSOR_INACTIVE)");
        }
        else if (keyCode == Declare.Button.FIRE_ACTIVE) {
            LOG("[onKeyDown] Pressed (FIRE_ACTIVE)");
            Global.setFireAlarmProcess(Global.FIRESENSOR_TIMEOUT);
        }
        else if (keyCode == Declare.Button.OUTSIDESENSOR_ACTIVE) {
            LOG("[onKeyDown] Pressed (OUTSIDESENSOR_ACTIVE)");
            bActivate = true;
            // 스마트키 카드리더기 연동 설정
            mTimerCheck.sendEmptyMessage(0);
            setExteriorDetectionTime();
        }
        else if (keyCode == Declare.Button.OUTSIDESENSOR_INACTIVE) {
            LOG("[onKeyDown] Pressed (OUTSIDESENSOR_INACTIVE)");
            bActivate = false;
            setTimerDestroy();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected boolean onChangeScreen(int nScreenId) {
        super.onChangeScreen(nScreenId);
        return setChangeScreen(nScreenId, false);
    }

    public boolean setFaceReset()
    {
        SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putBoolean(Face_AI_Set, false);
        editor.putInt(Face_Detect_Value, 3);
        editor.putInt(Face_Thres_Value, 1);
        editor.putBoolean(Face_Mask_Value, false);

        editor.commit();

        USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
        ma.setDeleteAll();
        return true;
    }

    public boolean setChangeScreen(int nNextScreen, boolean bRemoveOnly) {
        try {
            LOG("[setChangeScreen] nCurrentScreenID [" + Global.nCurrentScreenID + "], nNextScreen [" + nNextScreen + "], bRemoveOnly [" + bRemoveOnly + "]");

            if ( Global.nCurrentScreenID != 0 && nNextScreen == ID.SCREENS.Init) {
                Log.d(TAG, "[setChangeScreen] Screen only removed!!111");
                return true;
            }
            switch (Global.nCurrentScreenID) {
                case ID.SCREENS.Init:
                    SCREEN_Init.Close();
                    break;

                case ID.SCREENS.Main:
                    SCREEN_Main.Close();
                    break;

                case ID.SCREENS.Talk_Residence:
                    SCREEN_Talk_Residence.Close();
                    //m_bFaceDetect = false;
                    USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;

                    ma.m_bCallState = false;
                    ma.m_UIRefreshSet = true;
                    break;

                case ID.SCREENS.Talk_Guard:
                    SCREEN_Talk_Guard.Close();
                    //m_bFaceDetect = false;
                    USBCameraActivity2 ma1 = (USBCameraActivity2) USBCameraActivity2.activity;
                    ma1.m_bCallGuardState = false;
                    ma1.m_UIRefreshSet = true;
                    break;

//                case ID.SCREENS.Talk_Residence_Load:
//                    SCREEN_Talk_ResidenceLoad.Close();
//                    break;

                case ID.SCREENS.Access_PublicPW:
                    SCREEN_Access_PublicPW.Close();
                    break;

                case ID.SCREENS.Access_ResidencePW:
                    SCREEN_Access_ResidencePW.Close();
                    break;

                case ID.SCREENS.Access_AdminPW:
                    SCREEN_Access_AdminPW.Close();
                    break;

                case ID.SCREENS.AdminSet_AdminPW:
                    SCREEN_AdminSet_AdminPW.Close();
                    break;

                case ID.SCREENS.AdminSet_Main:
                    SCREEN_AdminSet_Main.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting:
                    SCREEN_AdminSet_Setting.Close();
                    break;

                case ID.SCREENS.AdminSet_Inquiry:
                    SCREEN_AdminSet_Inquiry.Close();
                    break;

                case ID.SCREENS.AdminSet_Test:
                    SCREEN_AdminSet_Test.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_BasicInfo:
                    SCREEN_AdminSet_Setting_BasicInfo.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_GuardID:
                    SCREEN_AdminSet_Setting_GuardID.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_LineInfo:
                    SCREEN_AdminSet_Setting_LineInfo.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_MainSub:
                    SCREEN_AdminSet_Setting_MainSub.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_SyncSetupInfo:
                    SCREEN_AdminSet_Setting_SyncSetupInfo.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_SelectAccessPW:
                    SCREEN_AdminSet_Setting_SelectAccessPW.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_PublicAccessPW:
                    SCREEN_AdminSet_Setting_PublicAccessPW.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_AdminAccessPW:
                    SCREEN_AdminSet_Setting_AdminAccessPW.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_AdminAccessPWChange:
                    SCREEN_AdminSet_Setting_AdminAccessPWChange.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_AdminPW:
                    SCREEN_AdminSet_Setting_AdminPW.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_CallLevel:
                    SCREEN_AdminSet_Setting_CallLevel.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessLevel:
                    SCREEN_AdminSet_Setting_RFAccessLevel.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessKeyIssuedCnt:
                    SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey:
                    SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey:
                    SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey:
                    SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_Melody:
                    SCREEN_AdminSet_Setting_Melody.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_Volume:
                    SCREEN_AdminSet_Setting_Volume.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_DoorOpenDuration:
                    SCREEN_AdminSet_Setting_DoorOpenDuration.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_FireSensorDoorOpenDelay:
                    SCREEN_AdminSet_Setting_FireSensorDoorOpenDelay.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_Calendar:
                    SCREEN_AdminSet_Setting_Calendar.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_ECOMode:
                    SCREEN_AdminSet_Setting_ECOMode.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_SendHeartbeat:
                    SCREEN_AdminSet_Setting_SendHeartbeat.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_LogFileSend:
                    SCREEN_AdminSet_Setting_LogFileSend.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_SetIPManually:
                    SCREEN_AdminSet_Setting_SetIPManually.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_ResetSystem:
                    SCREEN_AdminSet_Setting_ResetSystem.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_Language:
                    SCREEN_AdminSet_Setting_Language.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_MoviePlay:
                    SCREEN_AdminSet_Setting_MoviePlay.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_LobbyRole:
                    SCREEN_AdminSet_Setting_LobbyRole.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_ACULink:
                    SCREEN_AdminSet_Setting_ACULink.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_ParcelLink:
                    SCREEN_AdminSet_Setting_ParcelLink.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_ExternalOnePassLink:
                    SCREEN_AdminSet_Setting_ExternalOnePassLink.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_MainServerType:
                    SCREEN_AdminSet_Setting_MainServerType.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_DerivedType:
                    SCREEN_AdminSet_Setting_CardReaderType.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_ElevDisableFloor:
                    SCREEN_AdminSet_Setting_ElevDisableFloor.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_IPExpansion:
                    SCREEN_AdminSet_Setting_IPExpansion.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_HouseDivision:
                    SCREEN_AdminSet_Setting_HouseDivision.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_SmartAutodoorLink:
                    SCREEN_AdminSet_Setting_SmartAutodoorLink.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_InsideSensorLink:
                    SCREEN_AdminSet_Setting_InsideSensorLink.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_ZigBeeSensitivity:
                    SCREEN_AdminSet_Setting_ZigBeeSensitivity.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_FingerPrintLink:
                    SCREEN_AdminSet_Setting_FingerPrintLink.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_BLEStrength:
                    SCREEN_AdminSet_Setting_BLEStrength.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_OnePassRSSIIndex:
                    SCREEN_AdminSet_Setting_OnePassRSSIIndex.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_OnePassConfigure:
                    SCREEN_AdminSet_Setting_OnePassConfigure.Close();
                    break;

                case ID.SCREENS.AdminSet_Setting_SmartKeyConfigure:
                    SCREEN_AdminSet_Setting_SmartKeyConfigure.Close();
                    break;

                case ID.SCREENS.AdminSet_Inquiry_LobbyPhoneInfo:
                    SCREEN_AdminSet_Inquiry_LobbyPhoneInfo.Close();
                    break;

                case ID.SCREENS.AdminSet_Inquiry_LineInfo:
                    SCREEN_AdminSet_Inquiry_LineInfo.Close();
                    break;

                case ID.SCREENS.AdminSet_Inquiry_SubLobbyInfo:
                    SCREEN_AdminSet_Inquiry_SubLobbyInfo.Close();
                    break;

                case ID.SCREENS.AdminSet_Inquiry_ElevDisableFloor:
                    SCREEN_AdminSet_Inquiry_ElevDisableFloor.Close();
                    break;

                case ID.SCREENS.AdminSet_Inquiry_NetworkInfo:
                    SCREEN_AdminSet_Inquiry_NetworkInfo.Close();
                    break;

                case ID.SCREENS.AdminSet_Inquiry_VerInfo:
                    SCREEN_AdminSet_Inquiry_VerInfo.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_DoorOpen:
                    SCREEN_AdminSet_Test_DoorOpen.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_FireSensor:
                    SCREEN_AdminSet_Test_FireSensor.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_MotionSensor:
                    SCREEN_AdminSet_Test_Sensors.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_Camera:
                    SCREEN_AdminSet_Test_Camera.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_Network:
                    SCREEN_AdminSet_Test_Network.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_Network_IP:
                    SCREEN_AdminSet_Test_Network_IP.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_RFReader:
                    SCREEN_AdminSet_Test_RFReader.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_RFReader_Read:
                    SCREEN_AdminSet_Test_RFReader_Read.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_TalkTestMode:
                    SCREEN_AdminSet_Test_TalkTestMode.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_GoogleLauncher:
                    SCREEN_AdminSet_Test_GoogleLauncher.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_RS485:
                    SCREEN_AdminSet_Test_RS485.Close();
                    break;

                case ID.SCREENS.AdminSet_Test_ProximitySensor:
                    SCREEN_AdminSet_Test_ProximitySensor.Close();
                    break;

                case ID.SCREENS.Reboot:
                    SCREEN_Reboot.Close();
                    break;

                default:
                    if (Global.nCurrentScreenID != 0) {
                        Log.d(TAG, "[setChangeScreen] (Error) nCurrentScreenID is not defined!! nCurrentScreenID [" + Global.nCurrentScreenID + "]");
                        return false;
                    }
                    break;
            }

            cancelAutoScreenChange();   // 화면 Close시 스크린 타이머를 취소한다.
            MainLayout.removeAllViews();   // Layout의 모든 View를 삭제한다.

            if (bRemoveOnly) {
                Log.d(TAG, "[setChangeScreen] Screen only removed!!");
                return true;
            }

            // Screen 생성
            switch (nNextScreen) {
                case ID.SCREENS.Init:
                    SCREEN_Init = new Init(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_Init);
                    break;

                case ID.SCREENS.Main:
                    SCREEN_Main = new Main(mContext, MainLayout);

                    //if (Global.nCurrentScreenID == ID.SCREENS.Init) {
                    //    if(m_bFaceDetect == false)

                super.setCurrentScreen(SCREEN_Main); // 전원 ON시 Camera on


                    //if((Global.nCurrentScreenID != ID.SCREENS.Access_PublicPW) && (Global.nCurrentScreenID != ID.SCREENS.Access_ResidencePW))
                    if((Global.nCurrentScreenID == ID.SCREENS.Init) || (Global.nCurrentScreenID == ID.SCREENS.AdminSet_Setting))
                    {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                {
                                    Intent intent = new Intent(MainActivity.this, USBCameraActivity2.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                }
                            }
                        }, 2000);
                    }
                    else
                    {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                {
                                    Intent intent = new Intent(MainActivity.this, USBCameraActivity2.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                    startActivity(intent);
                                }
                            }
                        }, 2000);
                    }


                //if(m_bFaceDetect == false)

                //}

                break;

                case ID.SCREENS.Talk_Residence:
                    SCREEN_Talk_Residence = new TalkResidence(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_Talk_Residence);
                    //m_bFaceDetect = true;
                    USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
                    ma.m_bCallState = true;
                    ma.m_UIRefreshSet = true;
                    break;

                case ID.SCREENS.Talk_Guard:
                    SCREEN_Talk_Guard = new TalkGuard(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_Talk_Guard);
                    //m_bFaceDetect = true;
                    USBCameraActivity2 ma1 = (USBCameraActivity2) USBCameraActivity2.activity;
                    ma1.m_bCallGuardState = true;
                    ma1.m_UIRefreshSet = true;
                    break;

//                case ID.SCREENS.Talk_Residence_Load:
//                    SCREEN_Talk_ResidenceLoad = new TalkResidenceLoad(mContext, MainLayout);
//                    super.setCurrentScreen(SCREEN_Talk_ResidenceLoad);
//                    break;

                case ID.SCREENS.Access_PublicPW:
                    SCREEN_Access_PublicPW = new AccessPublicPW(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_Access_PublicPW);
                    break;

                case ID.SCREENS.Access_ResidencePW:
                    SCREEN_Access_ResidencePW = new AccessResidencePW(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_Access_ResidencePW);
                    break;

                case ID.SCREENS.Access_AdminPW:
                    SCREEN_Access_AdminPW = new AccessAdminPW(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_Access_AdminPW);
                    break;

                case ID.SCREENS.AdminSet_AdminPW:
                    SCREEN_AdminSet_AdminPW = new AdminSetAdminPW(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_AdminPW);
                    break;

                case ID.SCREENS.AdminSet_Main:
                    SCREEN_AdminSet_Main = new AdminSetMain(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Main);
                    break;

                case ID.SCREENS.AdminSet_Setting:
                    SCREEN_AdminSet_Setting = new AdminSetSettingScreen(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting);
                    break;

                case ID.SCREENS.AdminSet_Inquiry:
                    SCREEN_AdminSet_Inquiry = new AdminSetInquiryScreen(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Inquiry);
                    break;

                case ID.SCREENS.AdminSet_Test:
                    SCREEN_AdminSet_Test = new AdminSetTestScreen(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test);
                    break;

                case ID.SCREENS.AdminSet_Setting_BasicInfo:
                    SCREEN_AdminSet_Setting_BasicInfo = new AdminSet_Setting_BasicInfo(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_BasicInfo);
                    break;

                case ID.SCREENS.AdminSet_Setting_GuardID:
                    SCREEN_AdminSet_Setting_GuardID = new AdminSet_Setting_GuardID(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_GuardID);
                    break;

                case ID.SCREENS.AdminSet_Setting_LineInfo:
                    SCREEN_AdminSet_Setting_LineInfo = new AdminSet_Setting_LineInfo(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_LineInfo);
                    break;

                case ID.SCREENS.AdminSet_Setting_MainSub:
                    SCREEN_AdminSet_Setting_MainSub = new AdminSet_Setting_MainSub(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_MainSub);
                    break;

                case ID.SCREENS.AdminSet_Setting_SyncSetupInfo:
                    SCREEN_AdminSet_Setting_SyncSetupInfo = new AdminSet_Setting_SyncSetupInfo(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_SyncSetupInfo);
                    break;

                case ID.SCREENS.AdminSet_Setting_SelectAccessPW:
                    SCREEN_AdminSet_Setting_SelectAccessPW = new AdminSet_Setting_SelectAccessPW(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_SelectAccessPW);
                    break;

                case ID.SCREENS.AdminSet_Setting_PublicAccessPW:
                    SCREEN_AdminSet_Setting_PublicAccessPW = new AdminSet_Setting_PublicAccessPW(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_PublicAccessPW);
                    break;

                case ID.SCREENS.AdminSet_Setting_AdminAccessPW:
                    SCREEN_AdminSet_Setting_AdminAccessPW = new AdminSet_Setting_AdminAccessPW(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_AdminAccessPW);
                    break;

                case ID.SCREENS.AdminSet_Setting_AdminAccessPWChange:
                    SCREEN_AdminSet_Setting_AdminAccessPWChange = new AdminSet_Setting_AdminAccessPWChange(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_AdminAccessPWChange);
                    break;

                case ID.SCREENS.AdminSet_Setting_AdminPW:
                    SCREEN_AdminSet_Setting_AdminPW = new AdminSet_Setting_AdminPW(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_AdminPW);
                    break;

                case ID.SCREENS.AdminSet_Setting_CallLevel:
                    SCREEN_AdminSet_Setting_CallLevel = new AdminSet_Setting_CallLevel(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_CallLevel);
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessLevel:
                    SCREEN_AdminSet_Setting_RFAccessLevel = new AdminSet_Setting_RFAccessLevel(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_RFAccessLevel);
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessKeyIssuedCnt:
                    SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt = new AdminSet_Setting_RFAccessKeyIssuedCnt(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt);
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey:
                    SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey = new AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_ResiKey);
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey:
                    SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey = new AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_DongAdminKey);
                    break;

                case ID.SCREENS.AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey:
                    SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey = new AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_RFAccessKeyIssuedCnt_EntireAdminKey);
                    break;

                case ID.SCREENS.AdminSet_Setting_Melody:
                    SCREEN_AdminSet_Setting_Melody = new AdminSet_Setting_Melody(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_Melody);
                    break;

                case ID.SCREENS.AdminSet_Setting_Volume:
                    SCREEN_AdminSet_Setting_Volume = new AdminSet_Setting_Volume(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_Volume);
                    break;

                case ID.SCREENS.AdminSet_Setting_DoorOpenDuration:
                    SCREEN_AdminSet_Setting_DoorOpenDuration = new AdminSet_Setting_DoorOpenDuration(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_DoorOpenDuration);
                    break;

                case ID.SCREENS.AdminSet_Setting_FireSensorDoorOpenDelay:
                    SCREEN_AdminSet_Setting_FireSensorDoorOpenDelay = new AdminSet_Setting_FireSensorDoorOpenDelay(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_FireSensorDoorOpenDelay);
                    break;

                case ID.SCREENS.AdminSet_Setting_Calendar:
                    SCREEN_AdminSet_Setting_Calendar = new AdminSet_Setting_Calendar(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_Calendar);
                    break;

                case ID.SCREENS.AdminSet_Setting_ECOMode:
                    SCREEN_AdminSet_Setting_ECOMode = new AdminSet_Setting_ECOMode(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_ECOMode);
                    break;

                case ID.SCREENS.AdminSet_Setting_SendHeartbeat:
                    SCREEN_AdminSet_Setting_SendHeartbeat = new AdminSet_Setting_SendHeartbeat(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_SendHeartbeat);
                    break;

                case ID.SCREENS.AdminSet_Setting_LogFileSend:
                    SCREEN_AdminSet_Setting_LogFileSend = new AdminSet_Setting_LogFileSend(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_LogFileSend);
                    break;

                case ID.SCREENS.AdminSet_Setting_SetIPManually:
                    SCREEN_AdminSet_Setting_SetIPManually = new AdminSet_Setting_SetIPManually(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_SetIPManually);
                    break;

                case ID.SCREENS.AdminSet_Setting_ResetSystem:
                    SCREEN_AdminSet_Setting_ResetSystem = new AdminSet_Setting_ResetSystem(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_ResetSystem);
                    break;

                case ID.SCREENS.AdminSet_Setting_Language:
                    SCREEN_AdminSet_Setting_Language = new AdminSet_Setting_Language(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_Language);
                    break;

                case ID.SCREENS.AdminSet_Setting_MoviePlay:
                    SCREEN_AdminSet_Setting_MoviePlay = new AdminSet_Setting_MoviePlay(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_MoviePlay);
                    break;

                case ID.SCREENS.AdminSet_Setting_LobbyRole:
                    SCREEN_AdminSet_Setting_LobbyRole = new AdminSet_Setting_LobbyRole(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_LobbyRole);
                    break;

                case ID.SCREENS.AdminSet_Setting_ACULink:
                    SCREEN_AdminSet_Setting_ACULink = new AdminSet_Setting_ACULink(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_ACULink);
                    break;

                case ID.SCREENS.AdminSet_Setting_ParcelLink:
                    SCREEN_AdminSet_Setting_ParcelLink = new AdminSet_Setting_ParcelLink(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_ParcelLink);
                    break;

                case ID.SCREENS.AdminSet_Setting_ExternalOnePassLink:
                        SCREEN_AdminSet_Setting_ExternalOnePassLink = new AdminSet_Setting_ExternalOnePassLink(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_ExternalOnePassLink);
                    break;

                case ID.SCREENS.AdminSet_Setting_MainServerType:
                    SCREEN_AdminSet_Setting_MainServerType = new AdminSet_Setting_MainServerType(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_MainServerType);
                    break;

                case ID.SCREENS.AdminSet_Setting_DerivedType:
                    SCREEN_AdminSet_Setting_CardReaderType = new AdminSet_Setting_CardReaderType(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_CardReaderType);
                    break;

                case ID.SCREENS.AdminSet_Setting_ElevDisableFloor:
                    SCREEN_AdminSet_Setting_ElevDisableFloor = new AdminSet_Setting_ElevDisableFloor(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_ElevDisableFloor);
                    break;

                case ID.SCREENS.AdminSet_Setting_IPExpansion:
                    SCREEN_AdminSet_Setting_IPExpansion = new AdminSet_Setting_IPExpansion(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_IPExpansion);
                    break;

                case ID.SCREENS.AdminSet_Setting_HouseDivision:
                    SCREEN_AdminSet_Setting_HouseDivision = new AdminSet_Setting_HouseDivision(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_HouseDivision);
                    break;

                case ID.SCREENS.AdminSet_Setting_SmartAutodoorLink:
                    SCREEN_AdminSet_Setting_SmartAutodoorLink = new AdminSet_Setting_SmartAutodoorLink(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_SmartAutodoorLink);
                    break;

                case ID.SCREENS.AdminSet_Setting_InsideSensorLink:
                    SCREEN_AdminSet_Setting_InsideSensorLink = new AdminSet_Setting_InsideSensorLink(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_InsideSensorLink);
                    break;

                case ID.SCREENS.AdminSet_Setting_ZigBeeSensitivity:
                    SCREEN_AdminSet_Setting_ZigBeeSensitivity = new AdminSet_Setting_ZigBeeSensitivity(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_ZigBeeSensitivity);
                    break;

                case ID.SCREENS.AdminSet_Setting_FingerPrintLink:
                    SCREEN_AdminSet_Setting_FingerPrintLink = new AdminSet_Setting_FingerPrintLink(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_FingerPrintLink);
                    break;

                case ID.SCREENS.AdminSet_Setting_BLEStrength:
                    SCREEN_AdminSet_Setting_BLEStrength = new AdminSet_Setting_BLEStrength(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_BLEStrength);
                    break;

                case ID.SCREENS.AdminSet_Setting_OnePassRSSIIndex:
                    SCREEN_AdminSet_Setting_OnePassRSSIIndex = new AdminSet_Setting_OnePassRSSIIndex(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_OnePassRSSIIndex);
                    break;

                case ID.SCREENS.AdminSet_Setting_OnePassConfigure:
                    SCREEN_AdminSet_Setting_OnePassConfigure = new AdminSet_Setting_OnePassConfigure(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_OnePassConfigure);
                    break;

                case ID.SCREENS.AdminSet_Setting_SmartKeyConfigure:
                    SCREEN_AdminSet_Setting_SmartKeyConfigure = new AdminSet_Setting_SmartKeyConfigure(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Setting_SmartKeyConfigure);
                    break;

                case ID.SCREENS.AdminSet_Inquiry_LobbyPhoneInfo:
                    SCREEN_AdminSet_Inquiry_LobbyPhoneInfo = new AdminSet_Inquiry_LobbyPhoneInfo(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Inquiry_LobbyPhoneInfo);
                    break;

                case ID.SCREENS.AdminSet_Inquiry_LineInfo:
                    SCREEN_AdminSet_Inquiry_LineInfo = new AdminSet_Inquiry_LineInfo(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Inquiry_LineInfo);
                    break;

                case ID.SCREENS.AdminSet_Inquiry_SubLobbyInfo:
                    SCREEN_AdminSet_Inquiry_SubLobbyInfo = new AdminSet_Inquiry_SubLobbyInfo(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Inquiry_SubLobbyInfo);
                    break;

                case ID.SCREENS.AdminSet_Inquiry_ElevDisableFloor:
                    SCREEN_AdminSet_Inquiry_ElevDisableFloor = new AdminSet_Inquiry_ElevDisableFloor(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Inquiry_ElevDisableFloor);
                    break;

                case ID.SCREENS.AdminSet_Inquiry_NetworkInfo:
                    SCREEN_AdminSet_Inquiry_NetworkInfo = new AdminSet_Inquiry_NetworkInfo(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Inquiry_NetworkInfo);
                    break;

                case ID.SCREENS.AdminSet_Inquiry_VerInfo:
                    SCREEN_AdminSet_Inquiry_VerInfo = new AdminSet_Inquiry_VerInfo(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Inquiry_VerInfo);
                    break;

                case ID.SCREENS.AdminSet_Test_DoorOpen:
                    SCREEN_AdminSet_Test_DoorOpen = new AdminSet_Test_DoorOpen(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_DoorOpen);
                    break;

                case ID.SCREENS.AdminSet_Test_FireSensor:
                    SCREEN_AdminSet_Test_FireSensor = new AdminSet_Test_FireSensor(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_FireSensor);
                    break;

                case ID.SCREENS.AdminSet_Test_MotionSensor:
                    SCREEN_AdminSet_Test_Sensors = new AdminSet_Test_Sensors(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_Sensors);
                    break;

                case ID.SCREENS.AdminSet_Test_Camera:
                    SCREEN_AdminSet_Test_Camera = new AdminSet_Test_Camera(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_Camera);
                    break;

                case ID.SCREENS.AdminSet_Test_Network:
                    SCREEN_AdminSet_Test_Network = new AdminSet_Test_Network(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_Network);
                    break;

                case ID.SCREENS.AdminSet_Test_Network_IP:
                    SCREEN_AdminSet_Test_Network_IP = new AdminSet_Test_Network_IP(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_Network_IP);
                    break;

                case ID.SCREENS.AdminSet_Test_RFReader:
                    SCREEN_AdminSet_Test_RFReader = new AdminSet_Test_RFReader(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_RFReader);
                    break;

                case ID.SCREENS.AdminSet_Test_RFReader_Read:
                    SCREEN_AdminSet_Test_RFReader_Read = new AdminSet_Test_RFReader_Read(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_RFReader_Read);
                    break;

                case ID.SCREENS.AdminSet_Test_TalkTestMode:
                    SCREEN_AdminSet_Test_TalkTestMode = new AdminSet_Test_TalkTestMode(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_TalkTestMode);
                    break;

                case ID.SCREENS.AdminSet_Test_GoogleLauncher:
                    SCREEN_AdminSet_Test_GoogleLauncher = new AdminSet_Test_GoogleLauncher(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_GoogleLauncher);
                    break;

                case ID.SCREENS.AdminSet_Test_RS485:
                    SCREEN_AdminSet_Test_RS485 = new AdminSet_Test_RS485(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_RS485);
                    break;

                case ID.SCREENS.AdminSet_Test_ProximitySensor:
                    SCREEN_AdminSet_Test_ProximitySensor = new AdminSet_Test_ProximitySensor(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_AdminSet_Test_ProximitySensor);
                    break;

                case ID.SCREENS.Reboot:
                    SCREEN_Reboot = new Reboot(mContext, MainLayout);
                    super.setCurrentScreen(SCREEN_Reboot);
                    break;

                default:
                    Log.d(TAG, "[setChangeScreen] (Error) nNextScreen is not defined!! nNextScreen [" + nNextScreen + "]");
                    return false;
            }

            Global.nCurrentScreenID = nNextScreen;   // 변경된 ScreenID를 저장한다.
            return true;
        } catch (Exception e) {
            Log.d(TAG, "[Exception] setChangeScreen(...) : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initJNI() {
        try {
            Log.d(TAG, "[initJNI] = START =");
            // I/O 제어를 위한 라이브러리 사용
            mIOInterface.ctrlKeypadPower(true);
            mIOInterface.ctrlDoorOpen(false);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initJNI() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initConfigDB() {
        try {
            Log.d(TAG, "[initConfigDB] = START =");
            return Configure.initConfigValues(mContext);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initConfigDB() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initNetworkInterface() {
        try {
            Log.d(TAG, "[initNetworkInterface] === START ===");
            LOG("[initNetworkInterface] strDeviceIPAddress [" + ConfigValue.strDeviceIPAddress + "], strSubnetmask [" + ConfigValue.strSubnetmask + "], " +
                    "strGatewayIPAddress [" + ConfigValue.strGatewayIPAddress + "], strDNSIPAddress [" + ConfigValue.strDNSIPAddress + "]");
            String strSystemIPAddress = EthernetCtrl.getDeviceIPAddress();
            Log.d(TAG, "[initNetworkInterface] strSystemIPAddress [" + strSystemIPAddress + "], strDeviceIPAddress [" + ConfigValue.strDeviceIPAddress + "]");
            if (strSystemIPAddress.equals(ConfigValue.strDeviceIPAddress)) {
                // OS에 설정된 IP와 DB에 저장된 IP가 일치하는 경우
                return true;
            }
            else {
                // OS에 설정된 IP와 DB에 저장된 IP가 일치하지 않는 경우
                Log.w(TAG, "[initNetworkInterface] IP address is not correct!!! Network interface is reconfigured!!");
                return EthernetCtrl.setDeviceNetInterface(mContext, ConfigValue.strDeviceIPAddress, ConfigValue.strSubnetmask, ConfigValue.strGatewayIPAddress,
                        ConfigValue.strDNSIPAddress, EthernetCtrl.makeMACAddress(ConfigValue.strDeviceIPAddress));
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initNetworkInterface()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean initSIPModule() {
        try {
            LOG("[initSIPModule] ===== START =====");
            // SIP Module Start!
            mCallController = new CallController(mContext);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initSIPModule() : " + e);
            e.printStackTrace();
            return false;
        }
    }

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

            if (ConfigValue.eMainServerType == SetValue.Server2dot0_Integrated) {
                miMAPSSLServerStarter = new runiMAPSSLsvr(mContext, true);
                miMAPSSLServerStarter.start();
                //Mix 인 경우에만, 1.0 단지 서버와 동시 통신하도록 한다.
                if(ConfigValue.eSubServerType == SetValue.ServerMixed_Integrated) {
                    miMAPSvrStarter = new iMAPServer.runiMAPsvr(mContext, true);
                    miMAPSvrStarter.start();
                }
            }
            else {
                miMAPSvrStarter = new runiMAPsvr(mContext, true);
                miMAPSvrStarter.start();
            }

            return setDeviceName();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initiMAPServer()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean restartiMAPServer() {
        try {
            Log.d(TAG, "[restartiMAPServer] ========== START ==========");
            if (miMAPSvrStarter != null) miMAPSvrStarter.stopiMAPsvr();
            if (miMAPSSLServerStarter != null) miMAPSSLServerStarter.stopiMAPsvr();
            sendHandlerMsgDelayed(HANDLERMSG.START_IMAPSERVER, 0, 0, 0);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] restartiMAPServer()");
            e.printStackTrace();
            return false;
        }
    }

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

            if (ConfigValue.eDeviceType == SetValue.Wallpad) {
                MakeiMAPMSG.strSender = ConfigValue.strDevice_Dong + "동 " + ConfigValue.strDevice_ID + "호";
                Log.d(TAG, "[setDeviceName] MakeiMAPMSG.strSender = " + MakeiMAPMSG.strSender);
                return true;
            } else if (ConfigValue.eDeviceType == SetValue.Lobby) {
                MakeiMAPMSG.strSender = ConfigValue.strDevice_Dong + "동 " + ConfigValue.strDevice_ID + "번 로비";
                Log.d(TAG, "[setDeviceName] MakeiMAPMSG.strSender = " + MakeiMAPMSG.strSender);
                return true;
            } else if (ConfigValue.eDeviceType == SetValue.Guard) {
                MakeiMAPMSG.strSender = ConfigValue.strDevice_Dong + "동 " + ConfigValue.strDevice_ID + "번 경비";
                Log.d(TAG, "[setDeviceName] MakeiMAPMSG.strSender = " + MakeiMAPMSG.strSender);
                return true;
            } else {
                MakeiMAPMSG.strSender = "ERROR";
                Log.d(TAG, "[setDeviceName] MakeiMAPMSG.strSender = " + MakeiMAPMSG.strSender);
                return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setDeviceName()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean initRFPassModule() {
        try {
            Log.d(TAG, "[initRFPassModule] ConfigValue.eCardReaderType = " + ConfigValue.eCardReaderType.toString());

            if (ConfigValue.eCardReaderType == SetValue.CardReaderType_Standard) {
                return initRFPassMultiReader();
            } else {
                return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initRFPassModule() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initRFPassStandard() {
        try {
            Log.d(TAG, "[initRFPassStandard] ===== START =====");
            CRSerialPort_STD = new HDCIPARKReaderSerial(mContext);
            if (!CRSerialPort_STD.startSerialPort()) return false;
            return STDAccessKeyManager.initRFKeySTD(mContext);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initRFPassStandard() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initRFPassMultiReader() {
        try {
            Log.d(TAG, "[initRFPassMultiReader] ===== START =====");
            mIOInterface.ctrlCardreaderPower(true);
            CRSerialPort_Multi = new HDCStandardReaderSerial(mContext);
            if (!CRSerialPort_Multi.startSerialPort()) return false;
            if (!STDAccessKeyManager.initRFKeySTD(mContext)) return false;
            return UIDAccessKeyManager.initRFKey(mContext);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initRFPassMultiReader() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initRFPassHDEC() {
        try {
            Log.d(TAG, "[initRFPassHDEC] ===== START =====");
            mIOInterface.ctrlCardreaderPower(true);
            CRSerialPort_Multi = new HDCStandardReaderSerial(mContext);
            if (!CRSerialPort_Multi.startSerialPort()) return false;
            if (!STDAccessKeyManager.initRFKeySTD(mContext)) return false;
            return UIDAccessKeyManager.initRFKey(mContext);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initRFPassHDEC() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initRFPassAPEX() {
        try {
            Log.d(TAG, "[initRFPassAPEX] ===== START =====");
            CRSerialPort_Multi = new HDCStandardReaderSerial(mContext);
            if (!CRSerialPort_Multi.startSerialPort()) return false;
            if (!STDAccessKeyManager.initRFKeySTD(mContext)) return false;
            return UIDAccessKeyManager.initRFKey(mContext);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initRFPassAPEX()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean initRFPassSmartPhoneOnePass() {
        try {
            Log.d(TAG, "[initRFPassSmartPhoneOnePass] ===== START =====");
            CRSerialPort_Multi = new HDCStandardReaderSerial(mContext);
            if (!CRSerialPort_Multi.startSerialPort()) return false;
            if (!STDAccessKeyManager.initRFKeySTD(mContext)) return false;
            return UIDAccessKeyManager.initRFKey(mContext);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initRFPassSmartPhoneOnePass()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean initIFConverter() {
        try {
            Log.d(TAG, "[initIFConverter] ===== START =====");
            mSmartAutoDoorIFManager = new SmartAutoDoorIFManager(mContext);
            if (mSmartAutoDoorIFManager.startSmartAutoDoorManager()) return true;
            else return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initIFConverter()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean initFingerprintService() {
        try {
            Log.d(TAG, "[initFingerprintService] ===== START =====");
            mIOInterface.ctrlFingerprintModulePower(true);
            sendHandlerMsgDelayed(HANDLERMSG.START_FINGERPRINTSERVICE, 0, 0, 500);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initFingerprintService()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean initLCD() {
        try {
            return Global.setLCDECOMode(ConfigValue.nECOTime);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initLCD() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initBestinDirectory() {
        try {
            LOG_INFO("[initBestinDirectory] = START =");
            File BestinDirectory = new File("/sdcard/BESTIN/");
            if (BestinDirectory.isDirectory()) {
                LOG_INFO("[initBestinDirectory] BestinDirectory is already exist!!");
                return true;
            } else {
                LOG_INFO("[initBestinDirectory] BestinDirectory is not exist!!");
                return BestinDirectory.mkdir();
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initBestinDirectory() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initSystemVolume() {
        try {
            LOG_INFO("[initSystemVolume] ===== START =====");
            Global.setMusicStreamVolume(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
            Global.setSystemStreamVolume(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM));
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initBestinDirectory() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public void startSystemUpgrade(String strApp, String strBSP, boolean bReboot) {
        try {
            LOG_INFO("[startSystemUpgrade] strApp [" + strApp + "]");
            LOG_INFO("[startSystemUpgrade] strBSP [" + strBSP + "]");
            Log.d(TAG, "[startSystemUpgrade] bReboot [" + bReboot + "]");
            if (Global.getUpgradeStatus() != UPGRADESTATUS.READY) {
                Log.d(TAG, "[startSystemUpgrade] UPGRADESTATUS = " + Global.getUpgradeStatus());
                return;
            }

//            mIOInterface.Reboot(5);

            WallpadStatusData sdb = new WallpadStatusData(mContext);
            sdb.SetSystemUpdate(strBSP, strApp);
            sdb.SetUpgradeState(true);
            LOG("[startSystemUpgrade] GetUpgradeState [" + sdb.GetUpgradeState() + "]");
            sdb.closeDB();

            LOG_INFO("[startSystemUpgrade] ========== LiveUpdate ==========");
            MainActivity.mIOInterface.LiveUpdate();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startSystemUpgrade(strApp, strBSP, bReboot)");
            e.printStackTrace();
            Global.cancelSystemUpgrade(SystemUpgrade.FinalSystemUpgradeInfo.aModule_Path);
        }
    }

    public void startSystemReboot() {
        try {
            Log.d(TAG, "[startSystemReboot] ===== START =====");
            mIOInterface.Reboot(5);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startSystemReboot() : " + e);
            iMAPServer.ProcSysUp = null;
            e.printStackTrace();
        }
    }

    public boolean setVersions() {
        try {
            setAPPVersion();
            setBSPVersion();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setAPPVersion() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public void setAPPVersion() {
        try {
            Log.d(TAG, "[setAPPVersion] ====== START ======");
            ConfigValue.strVer_APP = ((WpadActivity) mContext).getAppVersion();
            Log.d(TAG, "[setAPPVersion] ConfigValue.strVer_APP = " + ConfigValue.strVer_APP);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setAPPVersion() : " + e);
            e.printStackTrace();
        }
    }

    public void setBSPVersion() {
        try {
            Log.d(TAG, "[setBSPVersion] ====== START ======");
            ConfigValue.strVer_BSP = Build.DISPLAY;
            Log.d(TAG, "[setBSPVersion] ConfigValue.strVer_BSP = " + ConfigValue.strVer_BSP);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setBSPVersion() : " + e);
            e.printStackTrace();
        }
    }

    // Surface manager
    public boolean ctrlVideoSurface(boolean bSet) {
        try {
            LOG("[ctrlVideoSurface] bSet = " + bSet);
            if (bSet) {
                //initMyVideoSurface();
                //initUSBCameraView();
                setCallState(true, DataClasses.RemoteIDInfo.strIP);
            } else {
                //removeMyVideoLayout();
                //removeUSBCameraView();
                setCallState(false, "");
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] ctrlVideoSurface() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    private boolean initMyVideoSurface() {
        try {
            LOG("[initMyVideoSurface] ====== START ======");
            if (MyVideoLayout != null) {
                MyVideoSurface.getHolder().removeCallback(MyVideoCallback);
                MyVideoLayout.removeAllViews();
                MyVideoLayout = null;
            }

            MyVideoLayout = new RelativeLayout(mContext);
            WpadUtil.LayoutRegistration(EntireLayout, MyVideoLayout, 480, 272, 0, 0, ID.ACTIVITIES.MAINACTIVITY.LAYOUTS.MyVideo);

            MyVideoSurface = new SurfaceView(mContext);
            MyVideoHolder = MyVideoSurface.getHolder();
            RelativeLayout.LayoutParams Params = new RelativeLayout.LayoutParams(40, 30);
            Params.setMargins(500, 0, 0, 0);
            MyVideoLayout.addView(MyVideoSurface, Params);
            MyVideoSurface.getHolder().addCallback(MyVideoCallback);
            MyVideoLayout.setVisibility(View.VISIBLE);
            mCallController.mVideoJNI.setCheckIFrame(true);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initMyVideoSurface() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    private boolean removeMyVideoLayout() {
        try {
            LOG("[removeMyVideoLayout] ===== START =====");
            if (MyVideoCallback != null) {
                MyVideoCallback.surfaceDestroyed(MyVideoHolder);
            }

            if (MyVideoLayout != null) {
                MyVideoLayout.setVisibility(View.GONE);
                MyVideoLayout.removeAllViews();
                MyVideoLayout = null;
            }

//            if (mAvcEncoder != null) {
//                mAvcEncoder.close();
//                mAvcEncoder = null;
//            }

            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] removeMyVideoLayout() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    private boolean initRemoteVideoSurface() {
        try {
            LOG("[initRemoteVideoSurface] ====== START ======");
            RemoteVideoLayout = new RelativeLayout(mContext);
            WpadUtil.LayoutRegistration(EntireLayout, RemoteVideoLayout, 480, 272, 0, 0, ID.ACTIVITIES.MAINACTIVITY.LAYOUTS.RemoteVideo);

            RemoteVideoSurface = new SurfaceView(mContext);
            RemoteVideoHolder = RemoteVideoSurface.getHolder();
            RelativeLayout.LayoutParams Params = new RelativeLayout.LayoutParams(40, 30);
            Params.setMargins(500, 0, 0, 0);
            RemoteVideoLayout.addView(RemoteVideoSurface, Params);
            RemoteVideoSurface.getHolder().addCallback(RemoteVideoCallback);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initRemoteVideoSurface() : " + e);
            return false;
        }
    }

    private boolean removeRemoteVideoSurface() {
        try {
            LOG("[removeRemoteVideoSurface] ===== START =====");
            if (RemoteVideoSurface != null) {
                RemoteVideoSurface.getHolder().removeCallback(RemoteVideoCallback);
                RemoteVideoSurface = null;
            }
            RemoteVideoLayout.setVisibility(View.GONE);
            if (RemoteVideoLayout != null) {
                RemoteVideoLayout.removeAllViews();
                RemoteVideoLayout = null;
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] removeRemoteVideoSurface() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public void sendHandlerMsg(int what, int arg1, int arg2) {
        try {
            LOG("[sendHandlerMsg] what [" + what + "], arg1 [" + arg1 + "], arg2 [" + arg2 + "]");
            Message HandleMsg = MainHandler.obtainMessage();
            HandleMsg.what = what;
            HandleMsg.arg1 = arg1;
            HandleMsg.arg2 = arg2;
            MainHandler.sendMessage(HandleMsg);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] sendHandlerMsg(int what, int arg1, int arg2)");
            e.printStackTrace();
        }
    }

    public void sendHandlerMsg(int what, int arg1, int arg2, Object obj) {
        try {
            LOG("[sendHandlerMsg] what [" + what + "], arg1 [" + arg1 + "], arg2 [" + arg2 + "]");
            Message HandleMsg = MainHandler.obtainMessage();
            HandleMsg.what = what;
            HandleMsg.arg1 = arg1;
            HandleMsg.arg2 = arg2;
            HandleMsg.obj = obj;
            MainHandler.sendMessage(HandleMsg);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] sendHandlerMsg(int what, int arg1, int arg2, Object obj)");
            e.printStackTrace();
        }
    }

    public void sendHandlerMsgDelayed(int what, int arg1, int arg2, long delay) {
        try {
            LOG("[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 (Exception e) {
            Log.e(TAG, "[Exception] sendHandlerMsgDelayed(int what, int arg1, int arg2, long delay)");
            e.printStackTrace();
        }
    }

    public boolean setAutoScreenChange(int nScreenID, int nTimeout) {
        try {
            LOG("[setAutoScreenChange] nScreenID [" + nScreenID + "], nTimeout [" + nTimeout + "]");
            nAutoScreenChangeNextID = nScreenID;
            nAutoScreenChangeTimeout = nTimeout;

            if (nAutoScreenChangeTime > 0) {
                // 타이머가 이미 동작중이므로, 시간을 새로 설정한다.
                nAutoScreenChangeTime = nAutoScreenChangeTimeout;
            } else {
                // 타이머가 돌아가고 있지 않으므로, 새로 구동한다.
                if (AutoScreenChangeTimer == null) {
                    Log.i(TAG, "[setAutoScreenChange] AutoScreenChangeTimer is null!!");
                    AutoScreenChangeTimer = new Timer();
                    AutoScreenChangeTimer.schedule(new AutoScreenChangeCntDN(), 1000, 1000);
                }
                nAutoScreenChangeTime = nAutoScreenChangeTimeout;
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setAutoScreenChange(nScreenID, nTimeout) : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean extendAutoScreenChangeTime() {
        try {
//            Log.d(TAG, "[extendAutoScreenChangeTime] nAutoScreenChangeTime [" + nAutoScreenChangeTime + "], nAutoScreenChangeTimeout [" + nAutoScreenChangeTimeout + "]");
            // 타이머가 동작중일때만 연장한다.
            if (nAutoScreenChangeTime > 0) nAutoScreenChangeTime = nAutoScreenChangeTimeout;
            Log.d(TAG, "[extendAutoScreenChangeTime] nAutoScreenChangeTime [" + nAutoScreenChangeTime + "], nAutoScreenChangeTimeout [" + nAutoScreenChangeTimeout + "]");
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] extendAutoScreenChangeTime() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean cancelAutoScreenChange() {
        try {
            Log.i(TAG, "[cancelAutoScreenChange] ===== START =====");
            Log.i(TAG, "[cancelAutoScreenChange] AutoScreenChangeTimer = " + AutoScreenChangeTimer);
            nAutoScreenChangeTime = 0;
            if (AutoScreenChangeTimer != null) {
                Log.i(TAG, "[cancelAutoScreenChange] AutoScreenChangeTimer != null");
                AutoScreenChangeTimer.cancel();
                AutoScreenChangeTimer = null;
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] cancelAutoScreenChange() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public boolean initGlobalImages() {
        try {
            Image_Emergency = new WpadImageView(mContext, 0, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_EMERGENCY).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_EMERGENCY).H, EmergencyImages[ConfigValue.DEVICE_MODELTYPE], 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_TENS);
            ViewRegistration(EntireLayout, Image_Emergency, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_EMERGENCY).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_EMERGENCY).Y);
            Image_Emergency.setVisibility(View.INVISIBLE);
            Image_RFReaderError = new WpadImageView(mContext, 0, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_RFREADER).W, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_RFREADER).H, RFReaderImages[ConfigValue.DEVICE_MODELTYPE], 0, ID.SCREENS.MAIN.ELEMENTS.IMAGES.TIME_MIN_UNITS);
            ViewRegistration(EntireLayout, Image_RFReaderError, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_RFREADER).X, getPosition(ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_RFREADER).Y);
            Image_RFReaderError.setVisibility(View.INVISIBLE);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initGlobalImages() : " + e);
            e.printStackTrace();
            return false;
        }
    }

    public POSITION getPosition(int nID) {
//      Log.d(TAG, "[getPosition] Start!!");

        POSITION position = new POSITION();
        position.SetPosition(0, 0, 480, 272);

        try {
            switch (nID) {
                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_EMERGENCY:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 148, 800, 130);
                    else position.SetPosition(52, 81, 376, 84);
                    return position;

                case ID.SCREENS.MAIN.ELEMENTS.IMAGES.NOTICE_RFREADER:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(3, 3, 117, 95);
                    else position.SetPosition(17, 3, 65, 51);
                    return position;
                default:
                    return position;
            }
        } catch (Exception e) {
            Log.d(TAG, "[Exception] getPosition(int nID)");
            return position;
        }
    }

    private 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 (Exception e) {
            Log.e(TAG, "[Exception] runGoogleLauncher() : " + e);
            e.printStackTrace();
        }
    }

    public boolean setSharedPreferencesValues(String strKey, String strValue) {
        try {
            Log.i(TAG, "[setSharedPreferencesValues] strKey [" + strKey + "], strValue [" + strValue + "]");
            SharedPreferences mSharedPreferences = getSharedPreferences(SharedPreferencesName, MODE_PRIVATE);
            return mSharedPreferences.edit().putString(strKey, strValue).commit();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setSharedPreferencesValues(String strKey, String strValue)");
            e.printStackTrace();
            return false;
        }
    }

    public String getSharedPreferencesValues(String strKey) {
        try {
            Log.i(TAG, "[getSharedPreferencesValues] strKey [" + strKey + "]");
            SharedPreferences mSharedPreferences = getSharedPreferences(SharedPreferencesName, MODE_PRIVATE);
            String strResult = mSharedPreferences.getString(strKey, "none");
            Log.i(TAG, "[getSharedPreferencesValues] strResult [" + strResult + "]");
            return strResult;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] getSharedPreferencesValues(String strKey)");
            e.printStackTrace();
            return "error";
        }
    }

    public void setTTSEventListener(TTSEventListener TTSEV) {
        mTTSEventListener = TTSEV;
    }

    public void releaseTTSEventListener() {
        mTTSEventListener = null;
    }

    private void sendTTSEvent(TTSEVENT eTTSEvent, String strMessage) {
        try {
            LOG("[sendTTSEvent] eTTSEvent [" + eTTSEvent + "], strMessage [" + strMessage + "]");
            if (mTTSEventListener != null) {
                mTTSEventListener.onTTSEvent(eTTSEvent, strMessage);
            } else {
                LOG_INFO("[sendTTSEvent] mTTSEventListener is null!!");
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] sendTTSEvent(TTSEVENT sTTSEvent, String strMessage)");
            e.printStackTrace();
        }
    }

    public void startChatMode() {
        try {
            bChatMode = true;
            mCallController.setVoiceDisable(true);
            ((MainActivity) mContext).initTTS();
            ((MainActivity) mContext).initSTT();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initChatModule()");
            e.printStackTrace();
        }
    }

    public void stopChatMode() {
        try {
            if (bChatMode) {
                mCallController.setVoiceDisable(false);
                ((MainActivity) mContext).releaseTTS();
                ((MainActivity) mContext).releaseSTT();
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] stopChatMode()");
            e.printStackTrace();
        }
    }

    public void initTTS() {
        try {
            LOG("[initTTS] ===== START =====");
            mTTSApi = new TTsApi(this, new TTsResult() {

                @Override
                public void onFinished() {
                    LOG("[initTTS.onFinished()] FINISH!!");
                    sendTTSEvent(TTSEVENT.TTS_SPEECH_END, "null");
                }

                @Override
                public void onError(int errorCode, String errorMsg) {
                    LOG("[initTTS.onError()] ERROR!!");
                    LOG("[initTTS.onError()] errorCode [" + errorCode + "], errorMsg [" + errorMsg + "]");
                    sendTTSEvent(TTSEVENT.TTS_ERROR, "null");
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initTTS()");
            e.printStackTrace();
        }
    }

    public void releaseTTS() {
        try {
            LOG("[releaseTTS] ===== START =====");
            mTTSApi.Release();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] releaseTTS()");
            e.printStackTrace();
        }
    }

    public void playTTS(String strText) {
        try {
            LOG("[playTTS] strText [" + strText + "]");
            if (mTTSApi.isPlaying()) mTTSApi.Stop();
            mTTSApi.Play(strText);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] playTTS(String strText)");
            e.printStackTrace();
        }
    }

    public boolean isTTSPlay() {
        try {
            return mTTSApi.isPlaying();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] isTTSPlay()");
            e.printStackTrace();
            return false;
        }
    }

    public void initSTT() {
        try {
            LOG("[initSTT] ===== START =====");
            mSTTApi = new SttApi(this, new SttResult() {

                @Override
                public void onReady() {
                    LOG("[initSTT.onReady()] READY!!");
                    sendTTSEvent(TTSEVENT.STT_READY, "null");
                }

                @Override
                public void onSuccess(String result) {
                    LOG("[initSTT.onSuccess()] SUCCESS!!");
                    LOG("[initSTT.onSuccess()] result [" + result + "]");
                    stopSTT();
                    sendTTSEvent(TTSEVENT.STT_SUCCESS, result);
                }

                @Override
                public void onError(int errorCode, String errorMsg) {
                    LOG("[initSTT.onError()] ERROR!!");
                    LOG("[initSTT.onError()] errorCode [" + errorCode + "], errorMsg [" + errorMsg + "]");
                    sendTTSEvent(TTSEVENT.STT_ERROR, "null");
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initSTT()");
            e.printStackTrace();
        }
    }

    public void releaseSTT() {
        try {
            LOG("[releaseSTT] ===== START =====");
            mSTTApi.Release();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] releaseSTT()");
            e.printStackTrace();
        }
    }
    public boolean startSTT() {
        try {
            LOG("[startSTT] ========== START ==========");
            if (mSTTApi == null) return false;
            mCallController.setTalkPath(CALLPATH.MOIP);
            return mSTTApi.Start();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startSTT()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean stopSTT() {
        try {
            LOG("[stopSTT] ========== START ==========");
            if (mSTTApi == null) return false;
            mCallController.setTalkPath(CALLPATH.NORMAL);
            mSTTApi.Stop();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] stopSTT()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean cancelSTT() {
        try {
            LOG("[cancelSTT] ========== START ==========");
            if (mSTTApi == null) return false;
            mCallController.setTalkPath(CALLPATH.NORMAL);
            mSTTApi.Cancel();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] cancelSTT()");
            e.printStackTrace();
            return false;
        }
    }

    public boolean isSTTRun() {
        try {
            LOG("[isSTTRun] ========== START ==========");
            if (mSTTApi == null) return false;
            if (mSTTApi.getStatus() == SttApi.STATUS.IDLE) return false;
            else return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] isSTTRun()");
            e.printStackTrace();
            return false;
        }
    }

    // 스마트키 리더기로 센서 감지 패킷 송신(X'7B)
    private void sendExternalDetectionPacket() {
        try {
            LOG("================ [sendExternalDetectionPacket] ================");
            final Request_MultiRF_Detection multiRF_detection = new Request_MultiRF_Detection(mContext);
            if (multiRF_detection.send_smartkeycr_detection()) {
                multiRF_detection.setResultCtrl(new iMAPResultCtrl() {
                    @Override
                    public void onResult(iMAPResult eResult) {
                        LOG_INFO("[sendExternalDetectionPacket] eResult = " + eResult);
                    }
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] sendExternalDetectionPacket");
            e.printStackTrace();
        }
    }

    private boolean setTimerCreate(int nTime) {
        try {
            bTimerRemain = true;
            if (nTime > 0) {
                if (mFinishTimer != null)
                    mFinishTimer.cancel();

                mFinishTimer = new CountDownTimer((long) (nTime * 1000), 1000L) {
                    @Override
                    public void onTick(long arg0) {
                        long nRemainTime = arg0 / 1000L;
                        if (nRemainTime <= 10L) {
                            Log.d(TAG, "[setTimerCreate] onTick (" + nRemainTime + " sec)");
                        }
                    }

                    @Override
                    public void onFinish() {
                        bTimerRemain = false;
                        Log.d(TAG, "[setTimerCreate] bTimerRemain: " + bTimerRemain);
                    }
                };
                mFinishTimer.cancel();
                mFinishTimer.start();
                return true;
            } else {
                bTimerRemain = false;
                return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setTimerCreate");
            e.printStackTrace();
            bTimerRemain = false;
            return false;
        }
    }

    private boolean setTimerDestroy() {
        bTimerRemain = false;
        try {
            if (mFinishTimer != null) {
                mFinishTimer.cancel();
                mFinishTimer = null;
                return true;
            } else return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setTimerDestroy");
            e.printStackTrace();
            return false;
        }
    }
    public interface TTSEventListener {
        public void onTTSEvent(TTSEVENT eTTSEvent, String strMessage);
    }

    // MainActivity Handler
    public final class HANDLERMSG {
        public final static int AUTOSCREENCHANGE = 110;
        public final static int CANCEL_AUTOSCREENCHANGE = 120;
        public final static int ON_ALARM = 130;
        public final static int ON_MAIN = 140;
        public final static int REMOVE_VIDEO_COVER = 150;
        public final static int SHOW_VIDEO_COVER = 160;
        public final static int CLEAR_ALL_CALL = 170;
        public final static int START_CHATMODE = 180;
        public final static int STOP_CHATMODE = 190;
        public final static int START_IMAPSERVER = 200;
        public final static int SEND_HEARTBEAT_NOTICE = 210;
        public final static int START_FINGERPRINTSERVICE = 220;
        public final static int IMG_ON_EMERGENCY = 230;
        public final static int IMG_OFF_EMERGENCY = 240;
        public final static int IMG_ON_RFREADERERROR = 250;
        public final static int IMG_OFF_RFREADERERROR = 260;
        public final static int CTRL_ONEPASSDOOROPEN = 270;
        public final static int SHOW_TOASTMSG = 280;
        public final static int SHOW_FACEDETECT = 300;
        public final static int RUN_GOOGLE_LAUNCHER = 900;
        public final static int SYSTEM_REBOOT = 1000;
    }

    public class AutoScreenChangeCntDN extends TimerTask {
        @Override
        public void run() {
//            DEBUG("[AutoScreenChangeCntDN().run()] Start!!");
            try {
                nAutoScreenChangeTime--;
                LOG("[AutoScreenChangeCntDN.run()] nAutoScreenChangeTime = " + nAutoScreenChangeTime);
                if (nAutoScreenChangeTime <= 0) {
                    LOG("[AutoScreenChangeCntDN.run()] Screen Change!!");
                    AutoScreenChangeTimer.cancel();
                    AutoScreenChangeTimer = null;
                    sendHandlerMsg(HANDLERMSG.AUTOSCREENCHANGE, nAutoScreenChangeNextID, 0);
                }
            } catch (Exception e) {
                Log.d(TAG, "[Exception] AutoScreenChangeCntDN().run() : " + e);
            }
        }
    }

    static long lInteriorSensorDetectTime = 0;   // 내부센서 감지시간, 내부센서가 먼저 감지되면, Configure.nOnePassInOutBlockTime 시간동안 원패스에 의한 문열림을 하지 않는다.
    long lExteriorSensorDetectTime = 0;   // 외부센서 감지시간, 외부센서 감지시간과 원패스 문열림 요청 수신 시간의 차가 ConfigValue.nOnePassAvailableTime보다 작으면 문을 연다.
    static long lOnePassRequestedTime = 0;   // 원패스 문열림 요청을 수신한 시간

    public void setInteriorDetectionTime() {
        try {
            lInteriorSensorDetectTime = System.currentTimeMillis();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setInteriorDetectionTime()");
            e.printStackTrace();
        }
    }

    public void setExteriorDetectionTime() {
        try {
            lExteriorSensorDetectTime = System.currentTimeMillis();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setExteriorDetectionTime()");
            e.printStackTrace();
        }
    }

    public static void setOnePassRequestedTime() {
        try {
            lOnePassRequestedTime = System.currentTimeMillis();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setOnePassRequestedTime()");
            e.printStackTrace();
        }
    }

    public static boolean isValidOutsideSensor() {
        try {
            if (lInteriorSensorDetectTime <= 0) return true;
            else {
                long lTimeDifference = System.currentTimeMillis() - lInteriorSensorDetectTime;
                Log.i(TAG, "[isValidOutsideSensor] lTimeDifference [" + lTimeDifference + "]");
                if (lTimeDifference > (ConfigValue.nSmartKeyInOutBlockTime * 1000)) return true;
                else return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] isValidOutsideSensor()");
            e.printStackTrace();
            return false;
        }
    }

    public void resetTimeStamp() {
        try {
            lInteriorSensorDetectTime = 0;
            lExteriorSensorDetectTime = 0;
            lOnePassRequestedTime = 0;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setOnePassRequestedTime()");
            e.printStackTrace();
        }
    }

    public class OnePassChecker extends Thread {
        boolean bRun = false;
        Context mContext;
        public OnePassChecker(Context context) {
            Log.i(TAG, "[OnePassChecker] Init OnePassChecker()");
            mContext = context;
            bRun = true;
        }

        @Override
        public void run() {
            super.run();
            Log.i(TAG, "[OnePassChecker.run()] Start OnePassChecker!!");

            while (bRun) {
                if (lExteriorSensorDetectTime != 0 && lOnePassRequestedTime != 0) {
                    if ((ConfigValue.nOnePassAvailableTime * 1000) > Math.abs(lExteriorSensorDetectTime - lOnePassRequestedTime)) {
                        // 외부센서 감지시간과 원패스 요청 수신 시간의 차가 ConfigValue.nOnePassAvailableTime보다 작으면 문을 연다.
                        // 단, 현재시간이 내부센서감지시간 + 내부차단시간의 합보다 작으면 원패스 출입 가능
                        if (System.currentTimeMillis() > (lInteriorSensorDetectTime + (ConfigValue.nOnePassInOutBlockTime * 1000))) {
                            Log.w(TAG, "[OnePassChecker.run()] Door open request by OnePass!!");
                            sendHandlerMsg(HANDLERMSG.CTRL_ONEPASSDOOROPEN, 0, 0);
                            Global.sendElevCallRequest("null", "null", true);
                            if (Global.bOnePassTestMode) sendHandlerMsg(HANDLERMSG.SHOW_TOASTMSG, 0, 0, "Door opened by OnePass");
                            resetTimeStamp();
                        }
                        else {
                            // 내부센서 감지로 인해, 원패스 문열림 차단
                            Log.w(TAG, "[OnePassChecker.run()] Ignore door open request by OnePass!! -> Interior sensor detected");
                            if (Global.bOnePassTestMode) sendHandlerMsg(HANDLERMSG.SHOW_TOASTMSG, 0, 0, "Request ignored (In -> Out)");
                            resetTimeStamp();
                        }
                    }
                    else {
                        // 타임오버
                        Log.w(TAG, "[OnePassChecker.run()] OnePass time over!!");
                        if (Global.bOnePassTestMode) sendHandlerMsg(HANDLERMSG.SHOW_TOASTMSG, 0, 0, "OnePass Time over");
                        resetTimeStamp();
                    }
                }
                else {
                    if (lExteriorSensorDetectTime != 0 && ((lExteriorSensorDetectTime + (ConfigValue.nOnePassAvailableTime * 1000)) < System.currentTimeMillis())) {
                        // 센서감지 5초후, 센서값을 초기화 한다.
                        lExteriorSensorDetectTime = 0;
                        Log.w(TAG, "[OnePassChecker.run()] Out sensor timestamp reset!!");
                        if (Global.bOnePassTestMode) sendHandlerMsg(HANDLERMSG.SHOW_TOASTMSG, 0, 0, "Time over (out sensor)");
                    }

                    if (lOnePassRequestedTime != 0 && ((lOnePassRequestedTime + (ConfigValue.nOnePassAvailableTime * 1000)) < System.currentTimeMillis())) {
                        // 센서감지 5초후, 센서값을 초기화 한다.
                        lOnePassRequestedTime = 0;
                        Log.w(TAG, "[OnePassChecker.run()] OnePass timestamp reset!!");
                        if (Global.bOnePassTestMode) sendHandlerMsg(HANDLERMSG.SHOW_TOASTMSG, 0, 0, "Time over (OnePass)");
                    }
                }

                try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }
            }
            Log.w(TAG, "[OnePassChecker.run()] ===== END =====");
        }

        public void stopOnePassChecker() {
            bRun = false;
        }
    }

    static OnePassChecker mOnePassChecker;
    public void startOnePassProc() {
        try {
            mOnePassChecker = new OnePassChecker(mContext);
            mOnePassChecker.start();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startOnePassProc()");
            e.printStackTrace();
        }
    }

    public static int nFRReaderErrorCnt = 0;
    public static void displayRFReaderStatus() {
        try {
            Log.i(TAG, "[displayRFReaderStatus] nFRReaderErrorCnt = " + nFRReaderErrorCnt);
            if (nFRReaderErrorCnt >= 3) {
                MainActivity.showRFReaderErrorImage(true);
            }
            else {
                MainActivity.showRFReaderErrorImage(false);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] displayRFReaderStatus()");
            e.printStackTrace();
        }
    }

    public static void startRFReaderChecker() {
        try {
            mRFReaderStatusChecker = new RFReaderStatusChecker();
            mRFReaderStatusChecker.start();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startRFReaderChecker()");
            e.printStackTrace();
        }
    }

    public static class RFReaderStatusChecker extends Thread {
        int nSecCheckInterval = 1000 * 30;   // 30초에 한번씩 확인한다.

        public RFReaderStatusChecker() {
        }

        public void run() {
            try {
                Thread.sleep(nSecCheckInterval);
                while (true) {
                    Global.checkRFReaderErrorMode();
                    Thread.sleep(nSecCheckInterval);
                }
            } catch (Exception e) {
                Log.e(TAG, "[Exception] RFReaderStatusChecker().run()");
                e.printStackTrace();
            }
            Log.i(TAG, "[RFReaderStatusChecker().run()] ========== END ==========");
        }
    }

    public void startFaceDetectActivityChecker() {
        try {
            mFaceDetectActivityChecker = new FaceDetectActivityChecker();
            mFaceDetectActivityChecker.start();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startRFReaderChecker()");
            e.printStackTrace();
        }
    }

    public class FaceDetectActivityChecker extends Thread {
        int nSecCheckInterval = 1000 * 60;   // 30초에 한번씩 확인한다.

        public FaceDetectActivityChecker() {

        }

        public void run() {
            try {
                Thread.sleep(nSecCheckInterval);
                while (true) {
                    
                    if(!m_bFaceDetect && Global.nCurrentScreenID == ID.SCREENS.Main)
                    {
                        Intent intent = new Intent(MainActivity.this, USBCameraActivity2.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                    }

                    Thread.sleep(nSecCheckInterval);
                }
            } catch (Exception e) {
                Log.e(TAG, "[Exception] RFReaderStatusChecker().run()");
                e.printStackTrace();
            }
            Log.i(TAG, "[RFReaderStatusChecker().run()] ========== END ==========");
        }
    }

    // 메모리 체크
    public void checkMemoryUsage() {
        try {
            Runtime.getRuntime().gc();
            long totalMem = Runtime.getRuntime().totalMemory();
            long freeMem = Runtime.getRuntime().freeMemory();
            long usedMem = totalMem - freeMem;

            Log.e(TAG, "**************** [checkMemoryUsage] *************");
            Log.e(TAG, "************ TOTAL MEM : " + totalMem + " bytes ***********");
            Log.e(TAG, "************ FREE MEM : " + freeMem + " bytes ***********");
            Log.e(TAG, "************ USED MEM : " + usedMem + " bytes ***********");
            Log.e(TAG, "*************************************************");
        } catch (Exception e) {
            Log.e(TAG, "[Exception] checkMemoryUsage()");
            e.printStackTrace();
        }
    }

    /**
     * 어플리케이션 Live 상태를 JNI를 통해 BSP에 알린다
     * 1초에 한 번씩 실행한다. (JEFF, 2019.10.08)
     */
    public AppLiveSignalSender mAppLiveSignalSender;
    public void startAppLiveSignalSender() {
        try {
            Log.w(TAG, "[startAppLiveSignalSender] ===== START =====");
            mAppLiveSignalSender = new AppLiveSignalSender();
            mAppLiveSignalSender.start();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startAppLiveSignalSender()");
            e.printStackTrace();
        }
    }
    public class AppLiveSignalSender extends Thread {

        boolean bRun = true;

        public AppLiveSignalSender() {
            Log.i(TAG, "[AppLiveSignalSender] init AppLiveSignalSender!!");
        }

        public void stopThread() {
            try {
                bRun = false;
            } catch (Exception e) {
                Log.e(TAG, "[Exception] AppLiveSignalSender.stopThread()");
                e.printStackTrace();
            }
        }

        public void run() {
            try {
                while (bRun) {
//                    mIOInterface.sendAppLiveSignal();
                    sendAppLiveSignalBR();
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                Log.e(TAG, "[Exception] AppLiveSignalSender().run()");
                e.printStackTrace();
            }
            Log.i(TAG, "[AppLiveSignalSender().run()] ========== END ==========");
        }
    }

    private void sendAppLiveSignalBR() {
        try {
            Intent intent = new Intent();
            intent.setAction(PrivateBR.APPLIVESIGNAL);
            sendBroadcast(intent);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] sendAppLiveSignalBR()");
            e.printStackTrace();
        }
    }
    //jslee start
    public void setFirmwareUpgrade(Socket Sock, String data){
        LOG("[MainActivity] setData : " + data);
        USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
        ma.setFirmwareUpgrade(Sock, data);
    }

    public void setData(Socket Sock, String data, int type){
        LOG("[MainActivity] setData : " + data);
        USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
        ma.setData(Sock, data, type);
    }
    public void setdownload(Socket Sock, String data, int type){
        LOG("[MainActivity] setData : " + data);
        USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
        ma.setdownload(Sock, data, type);
    }
    //jslee end
    public void delData(Socket Sock, String data, int type){
        LOG("[MainActivity] delData : " + data);
        USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
        ma.delData(Sock, data, type);
    }

    public int[] getDataInfo()
    {
        USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
        return ma.getDataInfo();
    }

    public void setDataInfo(int type, String value)
    {
        USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
        ma.setDataInfo(type, value);
    }

    public void setCallState(boolean onoff, String strIP)
    {
        USBCameraActivity2 ma = (USBCameraActivity2) USBCameraActivity2.activity;
        ma.setCallState(onoff, strIP);
    }



}
