package kr.co.icontrols.ilp300_700;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.graphics.Typeface;
import android.graphics.YuvImage;
import android.hardware.usb.UsbDevice;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import kr.co.icontrols.ilp300_700.call.CallManager;
import kr.co.icontrols.ilp300_700.call.YuvUtil;
import kr.co.icontrols.ilp300_700.ethernet.EthernetCtrl;
import kr.co.icontrols.ilp300_700.ethernet.iMAPCommon;
import kr.co.icontrols.ilp300_700.ethernet.iMAPServer;
import kr.co.icontrols.ilp300_700.ftp.AES;
import kr.co.icontrols.ilp300_700.ftp.HDCSFTPManager;
import kr.co.icontrols.ilp300_700.ftp.ftp_FileDownload;
import kr.co.icontrols.ilp300_700.ftp.ftps_FileDownload;
import kr.co.icontrols.ilp300_700.global.Configure;
import kr.co.icontrols.ilp300_700.global.DataClasses;
import kr.co.icontrols.ilp300_700.global.Enumeration;
import kr.co.icontrols.ilp300_700.global.ID;
import kr.co.icontrols.ilp300_700.global.LobbyAccessCtrl;
import kr.co.icontrols.ilp300_700.imap.MakeiMAPMSG;
import kr.co.icontrols.ilp300_700.imap.Request_check_lobby_passwd;
import kr.co.icontrols.ilp300_700.imap.Request_elevator_call;
import kr.co.icontrols.ilp300_700.imap.iMAPResultCtrl;
import kr.co.icontrols.ilp300_700.imap.reply_add_facepic;
import kr.co.icontrols.ilp300_700.screen.AccessResidencePW;
import kr.co.icontrols.ilp300_700.screen.Main;
import kr.co.icontrols.ilp300_700.screen.SettingActivity;
import kr.co.icontrols.ilp300_700.screen.TalkGuard;
import kr.co.icontrols.wallpadsupport.WpadTextView;
import kr.co.icontrols.ilp300_700.global.Global;
import kr.co.icontrols.ilp300_700.global.Declare;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.orhanobut.logger.Logger;
import com.sensetime.demo.SenseTimeApp;
import com.sensetime.demo.SenseTimeMtc;
import com.sensetime.demo.UsbDeviceHelper;
import com.sensetime.demo.UsbStateCallBack;
import com.sensetime.demo.bean.FaceStatus;
import com.sensetime.demo.bean.TrackingResult;
import com.sensetime.demo.bean.VerifyResult;
import com.sensetime.demo.ui.BaseActivity;
import kr.co.icontrols.ilp300_700.call.AvcEncoder;
import com.sensetime.demo.util.FileUtils;
import com.sensetime.demo.util.MaterialDialogUtils;
import com.sensetime.demo.util.Util;
import com.sensetime.demo.view.UVCCameraSurfaceView;
import com.sensetime.demo.view.UVCCameraTextureView;
import com.sensetime.mtc.AiConfig;
import com.sensetime.mtc.IReceiveCallback;
import com.sensetime.mtc.MClient;
import com.sensetime.mtc.MtcCallback;
import com.sensetime.mtc.MtcCode;
import com.serenegiant.usb.DeviceFilter;
import com.serenegiant.usb.IFrameCallback;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.UVCCamera;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static cm.sip.hns.SIPSound.mHandler;
import static com.sensetime.demo.bean.FaceStatus.AI_STATUS_ALREADY;
import static com.sensetime.demo.bean.FaceStatus.AI_STATUS_NONLIVENESS;
import static com.sensetime.demo.bean.FaceStatus.AI_STATUS_STRANGER;
import static com.sensetime.demo.bean.FaceStatus.AI_STATUS_UNKNOWN;
import static com.sensetime.demo.bean.FaceStatus.AI_STATUS_USER;
import static kr.co.icontrols.ilp300_700.global.DataClasses.RemoteIDInfo.strIP;
import static kr.co.icontrols.ilp300_700.global.Declare.DeviceInfo.ILP_300_SCREEN_SIZE_FULL_H;
import static kr.co.icontrols.ilp300_700.global.Declare.DeviceInfo.ILP_300_SCREEN_SIZE_FULL_W;

public class USBCameraActivity2 extends BaseActivity {
    private final Object mSyncUVCCamera = new Object();
    private final Object mSyncUSBMonitor = new Object();
    // for accessing USB and USB camera
    private USBMonitor mUSBMonitor;
    private UVCCamera mUVCCamera;

    public final String PREFERENCE = "ilp300.setting.value";
    public static String Face_Detect_Value = "Face_Detect_Value";
    public static String Face_Recog_Value = "Face_Recog_Value";
    public static String Face_Threshold_Value = "Face_Threshold_Value";
    public static String Face_AI_Set = "Face_AI_Set";
    public static String Face_Show_Video = "Face_Show_Video";
    public static String Face_Mask_Value = "Face_Mask_Value";
    public static String Face_AEMode_Value = "Face_AEMode_Value";
    public static String Face_IRLed_Value = "Face_IRLed_Value";

    boolean m_bSettingAI = false;
    boolean m_bSettingIRLED = false;
    boolean m_bSettingShowVideo = false;
    public String DEVICE_VERSION="";
    boolean bFUNCBlock = false;

    boolean m_bIRLEDState = false;

    private Matrix mScaleMatrix = new Matrix();
    private Paint mTextPaint, mTextAreaPaint, mTextPaintResult;
    private UVCCameraTextureView mUVCCameraView;
    private UVCCameraSurfaceView mTrackView;
    //private FrameLayout mResultView;
    private TextView mResultText;
    private TextView takeOffTipsTv;
    //////

    private FrameLayout layout_guard_view;
    private FrameLayout lobby_view;
    private FrameLayout Residence_view;
    private FrameLayout sensepw_view;
    private FrameLayout userpw_view;
    private FrameLayout sensemain_view; //
    private FrameLayout sensedistance_view;
    private FrameLayout senseadd_view;
    private FrameLayout sensesettingall_view;
    private ImageView m_Img_lobby, m_Img_ampm, m_Img_hour_ten, m_Img_hour_units, m_Img_min_tens, m_Img_min_units, m_Img_split;
    private ImageView m_guard_img;
    private TextView lobby_up;
    private TextView lobby_down;
    private TextView guard_text;
    private TextView pw_ment;
    private TextView pw_ment_user;
    boolean bLOG = true;   // true, false
    //////
    private static final int mDelayCleanCanva = 1000; //Customizable.
    private long lastTime = System.currentTimeMillis(); // ms
    private SenseTimeMtc senseTimeMtc = SenseTimeMtc.getInstance();
    private Button btnDisregard;
    private View controlContentView;
    private ImageView hdcImageView;
    private ImageView hdcResultView;
    private Switch switchUvc;
    private Handler myHandler = new Handler();
    private void LOG(String log) {
        if (bLOG) Log.v(TAG, log);
    }
    private MClient mClient = MClient.getInstance();
    private static Gson mGson = new Gson();

    //add KSJ
    Animation mAnimation;
    reply_add_facepic replyAddFacepic;
    boolean m_UIRefreshSet = true;
    boolean m_bSenseSettingState = false;
    boolean m_bCallState = false;
    boolean m_bCallGuardState = false;
    boolean m_isSwitchState = false;
    boolean m_isSwitchState_check = false;
    boolean m_isResultView = false;
    boolean m_isResult = false;
    boolean m_isResultActivity = false;
    boolean m_isResultActivity_check = false;
    String m_strRecognitionId="";
    private boolean m_bLauncherStart = false;
    private int DETECTLEN = 150;
    private int m_iDetectLen = 150;
    private int m_iDetectLen_1 = 10;
    private float m_fThreshValue = 0.8f;
    private boolean m_bAEMode = false;
    int MAXLENGTH_HO = 4;
    int MAXLENGTH_DONG = 4;
    int m_iKeyValue = 0;
    int m_iSenseSettingPage = 0;
    int m_iSenseSettingPage_sub = 0;
    int m_iSenseSettingCount = 0;
    int m_iAccessPW_type = 0;
    int m_bFaceCatch = -1;
    boolean m_bm_bFaceCatchCheck = false;


    String m_strSettingPW = "";
    int[] nFontSize_DONGHO = {73, 140};
    int[] nFontSize_DONGHO_Rent = {50, 105};
    //int[] m_DetectCase = {20, 40, 60, 80, 100, 120, 140, 160, 180, 200};
    //int[] m_DetectCase = {160, 120, 100, 85, 60, 0, 80, 60, 40, 20};
    int[][] m_DetectCase = {
            {160, 120, 100, 85, 0, 0, 80, 60, 40, 20},
            {160, 120, 100, 85, 0, 0, 80, 60, 40, 20},
            {155, 115, 95, 80, 0, 0, 75, 55, 35, 15},
    };
    float[] m_ThresCase = {0.7f, 0.75f, 0.8f, 0.85f, 0.9f};
    int m_iThrescase = 0;
    private int recog_thres_m20 = 2;
    private int recog_thres_m30 = 3;
    boolean m_bHaveMaskOrHat = false;
    String residence_ho="";

    WpadTextView Text_Instruction;   // 안내문구
    WpadTextView Text_ResidenceInfo_Dong; // 동정보
    WpadTextView Text_ResidenceInfo_Ho;   // 호정보
    String strText_Instruction = "";
    String strText_DeviceName = "";
    static String TAG = "USBCameraActivity2";
    WpadTextView lobby_info;
    MediaPlayer mMediaPlayer, mMediaPlayer1;// = MediaPlayer.create(this, R.raw.opendoor);
    TextView mTxtView_ho;
    TextView mTxtView_dong;
    TextView mTxtView_ho_pwd;
    TextView mTxtView_dong_pwd;
    TextView mTxtView_ment;
    TextView tv_time;
    CountDownTimer KeyTimer, KeyTimer_setting, KeyTimer_door;
    public static CountDownTimer KeyTimer_reboot;
    private AvcEncoder mAVcEncoder;
    boolean m_bEncoderState = false;
    boolean bPressedSTAR = false;


//
//    int year = cal.get(Calendar.YEAR);
//    int month = cal.get(Calendar.MONTH) +1 ;
//    int day = cal.get(Calendar.DAY_OF_MONTH);
//    int hour = cal.get(Calendar.HOUR_OF_DAY);
//    int min = cal.get(Calendar.MINUTE);
//    int sec = cal.get(Calendar.SECOND);

    ImageView m_imageViewPW1, m_imageViewPW2, m_imageViewPW3, m_imageViewPW4;
    ImageView m_imageViewPW1_user, m_imageViewPW2_user, m_imageViewPW3_user, m_imageViewPW4_user;

    TextView m_txtDistance, m_txtAdd_dong, m_txtAdd_ho, m_txtAdd_num, m_txtAdd_result;
    TextView m_txtAISet, m_txtVideoSet, m_txtDeviceVersion, m_txtVideoDelete, m_txtVideoRecog, m_txtVideoMenu;

    int m_iDistanceValue = 5;
    int m_iDistanceValue_old = 5;
    int m_iRecogValue = 10;


    public static Activity activity;
    boolean m_bCall = false;

    String SAVEPICTURE_PATH = "/sdcard/BESTIN/ADDPIC";
    AES m_aes;
    //~add KSJ
    /**
     * RGB 摄像头是否打开
     */
    private boolean isSwitchRGBCamera = true;

    /**
     * 判断是MainActivity运行状态
     */
    private boolean isRunning = false;


    /**
     * 判断是否与模组连接上
     */
    private boolean isConnect = false;

    /**
     * 上一次拿到数据回调的时间
     */
    private volatile long lastUpdatePreviewDataMillis;

    /**
     * 是否有带口罩或安全帽，会影响识别，得提示用户摘下来
     */
    private volatile boolean isHaveMaskOrHat = false;

    private volatile long lastTakeOffMaskTime;

    private CheckCameraStatusRunnable mCheckCameraStatusRunnable = new CheckCameraStatusRunnable(this);

    private static class CheckCameraStatusRunnable implements Runnable {
        private WeakReference<USBCameraActivity2> activityWeakReference;

        public CheckCameraStatusRunnable(USBCameraActivity2 mainActivity) {
            activityWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void run() {
            USBCameraActivity2 mainActivity = activityWeakReference.get();
            if (mainActivity == null) {
                return;
            }
            Log.e("jglee", "CheckCameraStatusRunnable");
            mainActivity.checkCameraStatus();
        }
    }

    private ClearCanvasRunable clearCanvasRunable = new ClearCanvasRunable(this);

    private static class ClearCanvasRunable implements Runnable {

        private final WeakReference<USBCameraActivity2> mActivity;

        public ClearCanvasRunable(USBCameraActivity2 mActivity) {
            this.mActivity = new WeakReference<USBCameraActivity2>(mActivity);
        }

        @Override
        public void run() {
            USBCameraActivity2 activity = mActivity.get();
            if (activity != null) {
                if (System.currentTimeMillis() - activity.lastTime > mDelayCleanCanva)
                    activity.clearCanvas();
            }
        }
    }


    private MyIReceiveCallback myIReceiveCallback = new MyIReceiveCallback(this);

    private static class MyIReceiveCallback implements IReceiveCallback {

        private final WeakReference<USBCameraActivity2> mActivity;

        public MyIReceiveCallback(USBCameraActivity2 mainActivity) {
            this.mActivity = new WeakReference<>(mainActivity);
        }

        @Override
        public void onTracking(String data) {
//            Logger.d("data: " + data); // only for DEBUG, it is easy to cause memory leak
            USBCameraActivity2 mainActivity = mActivity.get();
            //if (data != null && mainActivity != null && mainActivity.m_bLauncherStart) {
            if (data != null && mainActivity != null ) {
                mainActivity.drawFaces(data);
            }
        }

        @Override
        public void onVerify(String data) {
//            Log.e(TAG, "onVerify(String data):" + data); // only for DEBUG, it is easy to cause memory leak
            USBCameraActivity2 mainActivity = mActivity.get();

            if (data != null && mainActivity != null) {
                mainActivity.verifyResult(data);
            }
        }

        @Override
        public void onQrCodeData(String s) {

        }

        @Override
        public void onPhotoData(int trackId, String recognizeId, ByteBuffer rgbHeadpose, ByteBuffer rgbBackground, ByteBuffer irBackgroud) {
            long ts = System.currentTimeMillis();
            Logger.e(recognizeId + "_headpose_" + ts + ".jpg");
            if (rgbHeadpose != null) {
                byte[] data = new byte[rgbHeadpose.capacity()];
                rgbHeadpose.get(data);
                FileUtils.writeDataToDisk(data, "/sdcard/Pictures/" + recognizeId + "_headpose_" + ts + ".jpg");
//                Logger.d("rgb headpose size: " + rgbHeadpose.capacity() + ",ts:" + ts);  // only for DEBUG, it is easy to cause memory leak
                rgbHeadpose.clear();
                rgbHeadpose = null;
                data = null;
            }
            if (rgbBackground != null) {
//                Logger.d("rgb bg size: " + rgbBackground.capacity()); //only for DEBUG, it is easy to cause memory leak
                rgbBackground.clear();
                rgbBackground = null;
            }
            if (irBackgroud != null) {
                byte[] data = new byte[irBackgroud.capacity()];
                irBackgroud.get(data);
                FileUtils.writeDataToDisk(data, "/sdcard/Pictures/" + recognizeId + "_ir_" + ts + ".jpg");
//                Logger.d("ir size: " + irBackgroud.capacity() + ",ts:" + ts);  only for DEBUG, it is easy to cause memory leak
                irBackgroud.clear();
                irBackgroud = null;
                data = null;
            }
            System.gc();
        }

        @Override
        public void onFeatureData(String traceId, ByteBuffer feature) {
//            Logger.d("traceId length: " + traceId.length() + " ,id: " + traceId);  //only for DEBUG, it is easy to cause memory leak
            //Log.e(TAG, "feature length:" + feature.capacity());  //only for DEBUG, it is easy to cause memory leak
            if (feature != null) {
                byte[] data = new byte[feature.capacity()];
                feature.get(data);
                String fileName = traceId + "_feature_" + System.currentTimeMillis() + ".txt";
                FileUtils.writeDataToDisk(data, "/sdcard/Pictures/" + fileName);
                feature.clear();
                feature = null;
            }
            System.gc();
        }

        @Override
        public void onDisconnect(ByteBuffer notUseNow) {
            if (notUseNow != null) {
                //cb data Not Use Now
            }
            USBCameraActivity2 mainActivity = mActivity.get();
            if (mainActivity == null) {
                return;
            }
//            mainActivity.mClient.mtcDestroy(); // if you have used checkConnectThread, then you don't need to call mtcDestroy().
            Logger.d("disconnect,destroy mtc!!!!!");
        }
    }


    private MyDeviceConnectListener myDeviceConnectListener = new MyDeviceConnectListener(this);

    private static class MyDeviceConnectListener implements USBMonitor.OnDeviceConnectListener {

        private final WeakReference<USBCameraActivity2> activityWeakReference;
        boolean m_bInitCameraState = false;
        int m_initCameraErrorCount = 0;
        public MyDeviceConnectListener(USBCameraActivity2 mainActivity) {
            this.activityWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void onAttach(final UsbDevice device) {
            /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Logger.d("OnDeviceConnectListener onAttach:" + device.getProductName());
            } else {
                Logger.d("OnDeviceConnectListener onAttach:" + device.getDeviceName());
            }*/
            Log.e("jglee", "onAttach ");
            USBCameraActivity2 mainActivity = activityWeakReference.get();
            if (mainActivity != null &&
                    ((UsbDeviceHelper.DEVICE_PRODUCT_VID_4817 == device.getVendorId() && UsbDeviceHelper.DEVICE_PRODUCT_PID_17185 == device.getProductId()) ||
                            (UsbDeviceHelper.DEVICE_PRODUCT_VID_8711 == device.getVendorId() && UsbDeviceHelper.DEVICE_PRODUCT_PID_22 == device.getProductId()))) {

                mainActivity.checkCameraStatus();
            }
        }

        @Override
        @SuppressLint("CheckResult")
        public void onConnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, final boolean createNew) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Logger.v("OnDeviceConnectListener onConnect:" + device.getProductName());
            }
            Log.e("jglee", "onConnect ctrlBlock: " + ctrlBlock + " m_bInitCameraState : " + m_bInitCameraState);
            USBCameraActivity2 mainActivity = activityWeakReference.get();
            if (mainActivity != null) {

                if(m_bInitCameraState == false)
                {

                    m_bInitCameraState = mainActivity.initCamera(ctrlBlock);

                }

                // check camera init state
                if(!m_bInitCameraState) {
                    m_initCameraErrorCount++;
                    Log.e(TAG, "[MyDeviceConnectListener] onConnect m_initCameraErrorCount: " + m_initCameraErrorCount);
                    if(m_initCameraErrorCount > 1) {
                        Log.e(TAG, "[MyDeviceConnectListener] onConnect : Reboot Device  - Camera Init Error");
                        kr.co.icontrols.ilp300_700.MainActivity.mIOInterface.Reboot(0);
                    }
                } else {
                    m_initCameraErrorCount = 0;
                }

            }
        }

        @Override
        public void onDisconnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Logger.v("OnDeviceConnectListener onDisconnect:" + device.getProductName());
            }
            Log.e("jglee", "onDisconnect device: " + device);
            USBCameraActivity2 mainActivity = activityWeakReference.get();
            if (mainActivity != null) {

                Log.e("jglee", "onDisconnect");
                mainActivity.isConnect = false;
                mainActivity.releaseAndRequestCamera(null);
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Todo
                        mainActivity.checkCameraStatus();
                    }
                }, 2000);
            }
        }

        @Override
        public void onDettach(final UsbDevice device) {

        }

        @Override
        public void onCancel(final UsbDevice device) {
        }
    }

    private MyIFrameCallback myIFrameCallback = new MyIFrameCallback(this);

    private static class MyIFrameCallback implements IFrameCallback {

        private WeakReference<USBCameraActivity2> activityWeakReference;

        public MyIFrameCallback(USBCameraActivity2 mainActivity) {
            activityWeakReference = new WeakReference<>(mainActivity);
            //Log.d("KSJ", "MyIFrameCallback");


        }

        @Override
        public void onVerifyFrame(int frame_type, ByteBuffer frame, ByteBuffer verifyResultBuffer) {
            USBCameraActivity2 mainActivity = activityWeakReference.get();
            //Log.d("KSJ", "MyIFrameCallback onVerifyFrame" + frame.capacity());
            if (KeyTimer_reboot != null) {
                KeyTimer_reboot.cancel();
                KeyTimer_reboot = null;
            }
            try {

                if(mainActivity.m_bEncoderState)
                {
                    byte[] arr = new byte[frame.capacity()];
                    frame.get(arr);


                    //ver 1
//                    ByteArrayOutputStream out = new ByteArrayOutputStream();
//                    YuvImage yuv = new YuvImage(arr, ImageFormat.NV21, 360, 640, null);
//
//                    //yuv.compressToJpeg(new Rect(0, 0, 360, 640), 100, out);
//                    //yuv.compressToJpeg(new Rect(20, 200, 340, 440), 100, out);
//                    //yuv.compressToJpeg(new Rect(0, 140, 360, 500), 100, out);
//                    yuv.compressToJpeg(new Rect(0, 0, 360, 360), 100, out);
//                    Bitmap image = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.toByteArray().length);
//                    Bitmap resizedImage = Bitmap.createScaledBitmap(image, 320, 240, true);
//
//                    byte[] arr1 = mainActivity.getNV21(320,240,resizedImage);
//                    mainActivity.mAVcEncoder.offerEncoder1(arr1);
                    byte[] arr_nv21 = new byte[frame.capacity()];
                    YuvUtil.yuvNV21ToI420(arr, 360, 640,arr_nv21);
                    byte[] arr_360 = new byte[360*360*3/2];
                    byte[] arr_320 = new byte[320*240*3/2];
                    byte[] arr_320_nv21 = new byte[320*240*3/2];
                    //YuvUtil.yuvScaleI420(arr_nv21, 360, 640, arr_320, 320, 240, 0);
                    YuvUtil.yuvCropI420(arr_nv21, 360, 640, arr_360, 360, 360,0,160);
                    YuvUtil.yuvScaleI420(arr_360, 360, 360, arr_320, 320, 240, 0);
                    YuvUtil.yuvI420ToNV12(arr_320, 320,240, arr_320_nv21);
                    mainActivity.mAVcEncoder.offerEncoder1(arr_320_nv21);

                    Thread.sleep(10);

                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }

            if (mainActivity == null) {
                return;
            }





            mainActivity.verifyFrame(frame, verifyResultBuffer);
        }
    }

    static public void decodeYUV420P(int[] rgb, byte[] yuv420sp, int width, int height) {

        final int frameSize = width * height;

        int rotateYp = 0;
        int up, vp;

        for (int j = 0, yp = 0; j < height; j++) {

            int u = 0, v = 0;
            up = frameSize + ( (j >> 2) * width );
            vp = ( frameSize / 4 * 5 ) + ( (j >> 2) * width );

            for (int i = 0; i < width; i++, yp++) {
                int y = (0xff & ((int) yuv420sp[yp])) - 16;
                if (y < 0) y = 0;
                if ((i & 1) == 0) {
                    v = (0xff & yuv420sp[vp++]) - 128;
                    u = (0xff & yuv420sp[up++]) - 128;
                }


                int y1192 = 1192 * y;
                int r = (y1192 + 1634 * v);
                int g = (y1192 - 833 * v - 400 * u);
                int b = (y1192 + 2066 * u);

                if (r < 0) r = 0; else if (r > 262143) r = 262143;
                if (g < 0) g = 0; else if (g > 262143) g = 262143;
                if (b < 0) b = 0; else if (b > 262143) b = 262143;

//    			if( CameraID == 1 )
//    				rotateYp = ( ( width - i - 1 ) * height ) + j;
//    			else
//    				rotateYp = ( i * height ) + ( height - j - 1 );
                //rotateYp = ( ( width - i - 1 ) * height ) + j;
                //rotateYp = ( i * height ) + ( height - j - 1 );
                //rotateYp = ( ( height - i - 1 ) * width ) + j;
                rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff);
                //rgb[yp] = 0xFF000000+(y<<16) | (u<<8) | v;

            }
        }
    }

    // untested function
    private byte[] getNV21(int inputWidth, int inputHeight, Bitmap scaled) {

        int [] argb = new int[inputWidth * inputHeight];

        scaled.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight);

        byte [] yuv = new byte[inputWidth*inputHeight*3/2];
        encodeYUV420SP(yuv, argb, inputWidth, inputHeight);

        scaled.recycle();

        return yuv;
    }

    private void encodeYUV420SP(byte[] yuv420sp, int[] argb, int width, int height) {
        final int frameSize = width * height;

        int yIndex = 0;
        int uvIndex = frameSize;

        int a, R, G, B, Y, U, V;
        int index = 0;
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {

                a = (argb[index] & 0xff000000) >> 24; // a is not used obviously
                R = (argb[index] & 0xff0000) >> 16;
                G = (argb[index] & 0xff00) >> 8;
                B = (argb[index] & 0xff) >> 0;

                // well known RGB to YUV algorithm
                Y = ( (  66 * R + 129 * G +  25 * B + 128) >> 8) +  16;
                U = ( ( -38 * R -  74 * G + 112 * B + 128) >> 8) + 128;
                V = ( ( 112 * R -  94 * G -  18 * B + 128) >> 8) + 128;

                // NV21 has a plane of Y and interleaved planes of VU each sampled by a factor of 2
                //    meaning for every 4 Y pixels there are 1 V and 1 U.  Note the sampling is every other
                //    pixel AND every other scanline.
                yuv420sp[yIndex++] = (byte) ((Y < 0) ? 0 : ((Y > 255) ? 255 : Y));
                if (j % 2 == 0 && index % 2 == 0) {
                    yuv420sp[uvIndex++] = (byte)((V<0) ? 0 : ((V > 255) ? 255 : V));
                    yuv420sp[uvIndex++] = (byte)((U<0) ? 0 : ((U > 255) ? 255 : U));
                }

                index ++;
            }
        }
    }

    private void checkCameraStatus() {

        long timeInterval = SystemClock.elapsedRealtime() - lastUpdatePreviewDataMillis;
        kr.co.icontrols.ilp300_700.MainActivity.m_bLobbyStart = true;
        Log.e(TAG, "isRunning:" + isRunning + ",  isConnect:" + isConnect + ",  timeInterval:" + timeInterval + ",  lastUpdatePreviewDataMillis: " + lastUpdatePreviewDataMillis);
        if (!isRunning || isConnect || timeInterval < 10000 ) {//|| kr.co.icontrols.ilp300_700.MainActivity.m_bLobbyStart) {
            // 这个activity不在顶层运行或者已经连接上了，就不执行了,或者上次请求时间小于10秒
            //RGB摄像头未打卡或者从未来过数据的话，不执行。
            return;
        }




        Log.e(TAG, "preview stop, prepare restart");
        lastUpdatePreviewDataMillis = SystemClock.elapsedRealtime();
        requestPermissionDevice();
        myHandler.postDelayed(mCheckCameraStatusRunnable, 10000);
    }

    //private static final int DEVICE_PRODUCT_VIP = 4817;
    //private static final int DEVICE_PRODUCT_PID = 17185;
//12d1:4321
    private static final int DEVICE_PRODUCT_VIP = 4817;
    private static final int DEVICE_PRODUCT_PID = 17185;
    private void requestPermissionDevice() {
        final List<DeviceFilter> filter = DeviceFilter.getDeviceFilters(this, com.serenegiant.uvccamera.R.xml.device_filter);
/*        if (filter.size() > 0 && mUSBMonitor != null) {
            List<UsbDevice> usbDeviceList = mUSBMonitor.getDeviceList(filter.get(0));
            for (UsbDevice device : usbDeviceList) {
                if (DEVICE_PRODUCT_VIP == device.getVendorId() && DEVICE_PRODUCT_PID == device.getProductId()) {
                    Logger.d("requestPermission");
                    releaseAndRequestCamera(device);
                }
            }
        }*/

        if (filter.size() > 0 && mUSBMonitor != null) {
            for (int i = 0; i < filter.size(); i++) {
                List<UsbDevice> usbDeviceList = mUSBMonitor.getDeviceList(filter.get(i));
                for (UsbDevice device : usbDeviceList) {
                    if ((UsbDeviceHelper.DEVICE_PRODUCT_VID_4817 == device.getVendorId() && UsbDeviceHelper.DEVICE_PRODUCT_PID_17185 == device.getProductId()) ||
                            (UsbDeviceHelper.DEVICE_PRODUCT_VID_8711 == device.getVendorId() && UsbDeviceHelper.DEVICE_PRODUCT_PID_22 == device.getProductId())) {
                        //Logger.e("[MyDeviceConnectListener] requestPermissionDevice - releaseAndRequestCamera");
                        releaseAndRequestCamera(device);
                    }
                }
            }
        }
    }


    private boolean CameraRelease() {

        try {
            mUVCCamera.destroy();
        } catch (UnsupportedOperationException e) {
            Log.d(TAG, "initCamera Error:" + e.toString());
            return false;
        }
        return true;
    }

    UVCCamera camera = null;
    private boolean initCamera(final USBMonitor.UsbControlBlock ctrlBlock) {

        if (!mUVCCameraView.isAvailable()) {
            //return;
        }
        camera = new UVCCamera();

        try {
            camera.open(ctrlBlock);
        } catch (UnsupportedOperationException e) {
            Log.d(TAG, "initCamera Error:" + e.toString());
            return false;
        }

        Log.d(TAG, "supportedSize:" + camera.getSupportedSize());
        SenseTimeMtc senseTimeMtc = SenseTimeMtc.getInstance();
        senseTimeMtc.setPreviewWidth(640);
        senseTimeMtc.setPreviewHeight(360);
        senseTimeMtc.setCameraWidth(640);
        senseTimeMtc.setCameraHeight(360);
        senseTimeMtc.setScreenSize(0x01);

        int PREVIEW_W, PREVIEW_H;
        if (senseTimeMtc.getmM10_L_P() == SenseTimeMtc.LANDSCAPE_0 || senseTimeMtc.getmM10_L_P() == SenseTimeMtc.LANDSCAPE_180) {
            PREVIEW_W = senseTimeMtc.getPreviewWidth();
            PREVIEW_H = senseTimeMtc.getPreviewHeight();
        } else {//竖屏状态
            PREVIEW_W = senseTimeMtc.getPreviewHeight();
            PREVIEW_H = senseTimeMtc.getPreviewWidth();
        }

        Log.d(TAG, "jglee - Carmera W : " + PREVIEW_W + ", H : " + PREVIEW_H);

        try {
            camera.setPreviewSize(PREVIEW_W, PREVIEW_H, UVCCamera.FRAME_FORMAT_MJPEG); //可以指定帧格式
            Log.d(TAG, "PREVIEW_W:" + PREVIEW_W + ",  PREVIEW_H:" + PREVIEW_H);
        } catch (final IllegalArgumentException e) {
            Log.d(TAG, "e: " + e.getMessage());
            // fallback to YUV mode
            try {
                camera.setPreviewSize(PREVIEW_W, PREVIEW_H, UVCCamera.DEFAULT_PREVIEW_MODE);
            } catch (final IllegalArgumentException e1) {
                camera.destroy();
                return false;
            }
        }

        myHandler.postDelayed(() -> {
            final SurfaceTexture st = mUVCCameraView.getSurfaceTexture();
            if (st != null) {
                camera.setPreviewTexture(st);
                camera.setFrameCallback(myIFrameCallback, UVCCamera.PIXEL_FORMAT_NV21, true);
                int status = camera.startPreview();
                Log.d(TAG, "initCamera() -> start preview: " + status);
            }

            synchronized (mSyncUVCCamera) {
                mUVCCamera = camera;
            }
        }, 500);

        if (senseTimeMtc.getPreviewHeight() == 360) {
            myHandler.postDelayed(() -> {
                mClient.mtcDeviceScreenSizeSet(0x01, (mtcCode, result) -> {
                    Logger.e(" 360p mtcCode:" + mtcCode);
                    if (mtcCode != MtcCode.SUCCESS) {
                        isConnect = false;
                    } else {
                        isConnect = true;
                    }
                });//360p
            }, 500);
        } else {
            myHandler.postDelayed(() -> {
                mClient.mtcDeviceScreenSizeSet(0x00, (mtcCode, result) -> {
                    Logger.e("720p mtcCode:" + mtcCode);
                    if (mtcCode != MtcCode.SUCCESS) {
                        isConnect = false;
                    } else {
                        isConnect = true;
                    }
                });//720p
            }, 500);
        }
        return true;
    }

    public Context mContext;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("KSJ","USBCameraActivity2 onCreate");
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        //m_iDetectLen = DETECTLEN;
        activity = this;
        mContext = this;
        MClient.getInstance().mtcDestroy();

   /*     replyAddFacepic = new reply_add_facepic(this);

        File dir = new File(
                SAVEPICTURE_PATH);
        if(!dir.exists())
        {
            dir.mkdirs();
        }*/

    /*    SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);

        m_bSettingAI = pref.getBoolean(Face_AI_Set, false);
        m_bSettingShowVideo = pref.getBoolean(Face_Show_Video, false);
        m_iDistanceValue_old = pref.getInt(Face_Detect_Value, 3);
        m_iThrescase = pref.getInt(Face_Thres_Value, 5);
        m_iRecogValue = pref.getInt(Face_Recog_Value, 10);

        m_bSettingIRLED = pref.getBoolean(Face_IRLed_Value, true);

        m_bHaveMaskOrHat = pref.getBoolean(Face_Mask_Value, false);
        m_bAEMode = pref.getBoolean(Face_AEMode_Value, false);*/


      /*  try {

            m_iDetectLen = m_DetectCase[m_iDistanceValue_old-1];
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            m_iDistanceValue_old = 3;
            m_iDetectLen = m_DetectCase[m_iDistanceValue_old-1];
        }

        try {

            m_fThreshValue = m_ThresCase[m_iThrescase-1];
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            m_fThreshValue = 0.9f;
            m_iThrescase = 5;
        }
*/



        //getmDeviceInfo
        //mClient.mtcSystemVersionInfoGet((mtcCode, result) ->
        //showBasicDialogNoCancel(R.string.setting_btn_device_info, "" + result));
        //add KSJ
        //if (senseTimeMtc.getmPreviewHeight() != 360) {

/* 카메라 출력이 안되는 현상 수정 위해 주성 20240809
        DeviceVersion();

        setAiConfig_first();
        setAiConfig();

        setDeviceAntiFlickerset(m_bAEMode);


        setDeviceIRLedON();
        m_bIRLEDState = false;

        if(m_bSettingAI)
            setTemplateUpdate(1);
        else
            setTemplateUpdate(0);

        m_aes = new AES();

        kr.co.icontrols.ilp300_700.MainActivity.m_bFaceDetect = true;
*/

     /*   new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                Log.d("KSJ_INIT", "onCreate");
                //딜레이 후 시작할 코드 작성
                DeviceVersion();

                setAiConfig_first();
                setAiConfig();

                setDeviceAntiFlickerset(m_bAEMode);


                setDeviceIRLedON();
                m_bIRLEDState = false;

                if(m_bSettingAI)
                    setTemplateUpdate(1);
                else
                    setTemplateUpdate(0);
                kr.co.icontrols.ilp300_700.MainActivity.m_bFaceDetect = true;

            }
        }, 1000);// 0초 정도 딜레이를 준 후 시작*/
        m_aes = new AES();


//        String[] strName = {"814_201_범101801", "814_201_범101802", "814_201_범101803대외", "814_201_범101804대외", "814_201_범101805아이폰",
//        "814_201_범101806아이폰", "814_201_범101807아대외", "814_201_범101808아대외"};
//
//        for(int i = 0; i < strName.length; i++)
//        {
//            File file_source = new File( "/sdcard/20211018/" + strName[i] + ".jpg");
//            File file_dest = new File("/sdcard/20211018/" + strName[i] + "_dest.jpg");
//            m_aes.decryptPictureFile(file_source, file_dest);
//        }

        //recognitionCount(1);

        //NewThread nt = new NewThread() ;
        //nt.start() ;



        //ftps_FileDownload test = new ftps_FileDownload();
        //test.start();
        //ftp_FileDownload ftp_fileDownload = new ftp_FileDownload("", "id", "pwd", "path", "fileName", "");
        //boolean bRet = ftp_fileDownload.run();
        //}
        //senseTimeMtc.setmM10_L_P(SenseTimeMtc.PORTRAIT_90);
        //senseTimeMtc.setmPreviewWidth(1280);
        //senseTimeMtc.setmPreviewHeight(720);
        //Logger.d("onCreate " + senseTimeMtc.getmPreviewHeight());
        //Log.d("KSJ", "devices : " + senseTimeMtc.getmDeviceInfo());

/*
        mClient.mtcAiClearAllImage((mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS) {
                showToast(R.string.notice_success);
            } else {
                showToast(getMtcErrorMsg(mtcCode));
            }
        });
*/
        mMediaPlayer = MediaPlayer.create(this, R.raw.dooropen);
        //mMediaPlayer1 = MediaPlayer.create(this, R.raw.lobby_look);


        //MaterialDialog progressDialog = MaterialDialogUtils.showIndeterminateProgressDialog(this, "", false).show();
/*        mClient.mtcAllIdListGet((mtcCode, result) -> {

            if (mtcCode == MtcCode.SUCCESS) {
                Log.d(TAG, " KSJ result:" + result);
                //MaterialDialogUtils.showBasicDialogNoCancel(this, getString(R.string.get_all_ids), result).show();
            }
            //progressDialog.dismiss();
        });*/

        checkUserPermission();
        initView();
    }



    public void DeviceVersion()
    {
        mClient.mtcSystemVersionInfoGet((mtcCode, result) ->
                DEVICE_VERSION = result);
        //showBasicDialogNoCancel(R.string.setting_btn_device_info, "" + result));
    }

    private boolean send_check_lobby_passwd_request(final String strDong, final String strHo, final String strPW, final boolean bRentHouse) {
        try {
            Request_check_lobby_passwd check_lobby_passwd = new Request_check_lobby_passwd(this);
            if (check_lobby_passwd.send_check_lobby_passwd_request(strDong, strHo, strPW, bRentHouse)) {
                bFUNCBlock = true;
                check_lobby_passwd.setResultCtrl(new iMAPResultCtrl() {

                    @Override
                    public void onResult(iMAPCommon.iMAPResult eResult) {
                        Log.d(TAG, "[send_check_lobby_passwd_request] (onResult) eResult =" + eResult);
                        if (eResult == iMAPCommon.iMAPResult.OK) {
                            if (Configure.ConfigValue.eParcelLink == Configure.SetValue.TRUE) {
                                Global.ctrlLobbyDoorNMent(true, false, Configure.ConfigValue.nDoorOpenDuration, false, false);
                                if (bRentHouse)
                                    LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.pass, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RENTRESIDENCE, strDong, strHo), "null", 0, 0, 0, 0, "null");
                                else
                                    LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.pass, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RESIDENCE, strDong, strHo), "null", 0, 0, 0, 0, "null");
                            } else {
                                Global.ctrlLobbyDoorNMent(true, true, Configure.ConfigValue.nDoorOpenDuration, false, false);
                                if (bRentHouse)
                                    LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.pass, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RENTRESIDENCE, strDong, strHo), "null", 0, 0, 0, 0, "null");
                                else
                                    LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.pass, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RESIDENCE, strDong, strHo), "null", 0, 0, 0, 0, "null");
                            }
                            Global.sendElevCallRequest(strDong, strHo, true);
                            bFUNCBlock = false;
                        } else if (eResult == iMAPCommon.iMAPResult.ResultFail) {
                            Global.ctrlLobbyDoorNMent(false, true, 0, false, false);
                            if (bRentHouse)
                                LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RENTRESIDENCE, strDong, strHo), "null", 0, 0, 0, 0, strPW);
                            else
                                LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RESIDENCE, strDong, strHo), "null", 0, 0, 0, 0, strPW);
                            bFUNCBlock = false;
                        } else {
                            kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.trylater);
                            bFUNCBlock = false;
                        }
                        m_bSenseSettingState = false;
                        m_UIRefreshSet = true;
                        m_iSenseSettingCount = 0;
                        setSensePW_all();
                        m_strSettingPW="";
                        m_iAccessPW_type = 0;
                        m_iSenseSettingPage = 0;
                    }
                });
                return true;
            }
            bFUNCBlock = false;
            return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] send_check_lobby_passwd_request(strDong, strHo, strPW)");
            e.printStackTrace();
            bFUNCBlock = false;
            return false;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        //if(!m_bLauncherStart)
        //return super.onKeyDown(keyCode, event);

        boolean bSettingMent = false;
        if (m_bCallState || m_bCallGuardState) //세대 및 경비 호출 시
        {
            Log.d(TAG, "[Call View] onKeyDown " + keyCode);
            if (Declare.Button.CALL == keyCode ) {
                if (m_bCallState || m_bCallGuardState)  {
                    m_iSenseSettingCount = 0;
                    Intent intent = new Intent();
                    intent.setAction("UPDATE_KEYDATA_TALK");
                    intent.putExtra("data", keyCode);
                    sendBroadcast(intent);

                    if(m_bCallGuardState)
                        guard_text.setText("경비실을 호출합니다.");

                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // Todo
                            //m_bLauncherStart = true;
                            m_bCall = false;

                        }
                    }, 1000);
                }
                kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.button);
            }
            else if (Declare.Button.CANCEL == keyCode || keyCode == Declare.Button.TACT_CANCEL) {

                if (m_bCallState || m_bCallGuardState) {
                    Intent intent = new Intent();
                    intent.setAction("UPDATE_KEYDATA_TALK");
                    intent.putExtra("data", keyCode);
                    sendBroadcast(intent);
                }
                kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.button);
            }
            else if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09)  {
                Intent intent = new Intent();
                intent.setAction("UPDATE_KEYDATA_TALK");
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);

                if(Declare.Button.NUMBER_00 != keyCode)
                    m_iSenseSettingCount = 0;

                updateScreen();
                kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.button);
            }
            else if (Declare.Button.STAR == keyCode) {
                Intent intent = new Intent();
                intent.setAction("UPDATE_KEYDATA_TALK");
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);
                kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.button);
            }
            else if (keyCode == Declare.Button.FIRE_ACTIVE) {
                LOG("[onKeyDown] Pressed (FIRE_ACTIVE)");
                //Global.setFireAlarmProcess(Global.FIRESENSOR_TIMEOUT);
                showToast_fire();
                Intent intent = new Intent();
                intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);
            }
            else if (keyCode == Declare.Button.INSIDESENSOR_ACTIVE) {
                LOG("[onKeyDown] Pressed (INSIDESENSOR_ACTIVE)");
                Intent intent = new Intent();
                intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);
            }
            else if (keyCode == Declare.Button.INSIDESENSOR_INACTIVE) {
                LOG("[onKeyDown] Pressed (INSIDESENSOR_INACTIVE)");
                Intent intent = new Intent();
                intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);
            }
//            else if (keyCode == Declare.Button.FIRE_ACTIVE) {
//                LOG("[onKeyDown] Pressed (FIRE_ACTIVE)");
//                Global.setFireAlarmProcess(Global.FIRESENSOR_TIMEOUT);
//                Intent intent = new Intent();
//                intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
//                intent.putExtra("data", keyCode);
//                sendBroadcast(intent);
//            }
            else if (keyCode == Declare.Button.OUTSIDESENSOR_ACTIVE) {
                LOG("[onKeyDown] Pressed (OUTSIDESENSOR_ACTIVE)");
                Intent intent = new Intent();
                intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);
            }
            else if (keyCode == Declare.Button.OUTSIDESENSOR_INACTIVE) {
                LOG("[onKeyDown] Pressed (OUTSIDESENSOR_INACTIVE)");
                Intent intent = new Intent();
                intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);

            }


            m_UIRefreshSet = true;

            return super.onKeyDown(keyCode, event);
        }

        if(!m_bSenseSettingState) {
            Log.d(TAG, "[Call View] onKeyDown " + keyCode);
            if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09)  {
                Intent intent = new Intent();
                intent.setAction("UPDATE_KEYDATA");
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);

                if(Declare.Button.NUMBER_00 != keyCode)
                    m_iSenseSettingCount = 0;
                updateScreen();
            }

            if (Declare.Button.CANCEL == keyCode || keyCode == Declare.Button.TACT_CANCEL) {
                m_iSenseSettingCount = 0;
            }

            if (Declare.Button.STAR == keyCode) {

                if ((m_iKeyValue == Declare.Button.NUMBER_00) && (m_iSenseSettingCount == 0)) {
                    m_iSenseSettingCount++;

                    if (m_iSenseSettingCount == 3) {
                        m_bSenseSettingState = true;
                        m_UIRefreshSet = true;
                        m_iSenseSettingCount = 0;
                        m_iSenseSettingPage = 1;
                        m_iAccessPW_type = 0;
                        Log.d("onKeyDown", "******** 1111111");
                        pw_ment.setText("얼굴인식 설정 비밀번호를 입력하세요.");

                        if (KeyTimer != null) {
                            KeyTimer.cancel();
                            KeyTimer = null;
                        }
                        KeyPressTimer();
                        KeyTimer.start();
                        bPressedSTAR = true;

                    }

                }
                else if ((m_iKeyValue != Declare.Button.NUMBER_00) || (m_iSenseSettingCount == 1 ))
                {
                    m_iSenseSettingCount++;

                }
                else if ((m_iKeyValue == Declare.Button.NUMBER_00) && (m_iSenseSettingCount == 2)) {
                    m_iSenseSettingCount++;


                    if (m_iSenseSettingCount == 3) {
                        m_bSenseSettingState = true;
                        m_UIRefreshSet = true;
                        m_iSenseSettingCount = 0;
                        m_iSenseSettingPage = 1;
                        m_iAccessPW_type = 0;
                        Log.d("onKeyDown", "******** 1111111");
                        pw_ment.setText("얼굴인식 설정 비밀번호를 입력하세요.");

                        if (KeyTimer != null) {
                            KeyTimer.cancel();
                            KeyTimer = null;
                        }
                        KeyPressTimer();
                        KeyTimer.start();
                        bPressedSTAR = true;
                    }

                }
                else if ((m_iKeyValue != Declare.Button.NUMBER_00) || (m_iSenseSettingCount == 3 ))
                {
                    m_iSenseSettingCount++;


                    if (m_iSenseSettingCount == 4) {
                        m_bSenseSettingState = true;
                        m_UIRefreshSet = true;
                        m_iSenseSettingCount = 0;
                        m_iSenseSettingPage = 1;
                        m_iAccessPW_type = 0;
                        Log.d("onKeyDown", "******** 1111111");
                        pw_ment.setText("얼굴인식 설정 비밀번호를 입력하세요.");

                        if (KeyTimer_setting != null) {
                            KeyTimer_setting.cancel();
                            KeyTimer_setting = null;
                        }
                        KeyPressTimer_setting();
                        KeyTimer_setting.start();
                        //bPressedSTAR = true;

                    }
                }
                else
                {
                    m_iSenseSettingCount = 0;
                }

                if ((bPressedSTAR) && (m_iKeyValue == Declare.Button.STAR)) {
                    Log.d("onKeyDown", "********");
                    if (Configure.ConfigValue.eLPRole == Configure.SetValue.LPRole_CarGate) return super.onKeyDown(keyCode, event);;
                    if (Configure.ConfigValue.eAdminAccessPWEnable == Configure.SetValue.FALSE) return super.onKeyDown(keyCode, event);;
                    m_bSenseSettingState = true;
                    m_iAccessPW_type = 1;
                    m_iSenseSettingPage = 1;
                    m_iSenseSettingCount = 0;

                    pw_ment.setText("관리자출입 비밀번호를 입력 하세요.");

                    if (KeyTimer_setting != null) {
                        KeyTimer_setting.cancel();
                        KeyTimer_setting = null;
                    }
                    KeyPressTimer_setting();
                    KeyTimer_setting.start();
                    //bPressedSTAR = true;
                } else {
                    if (KeyTimer != null) {
                        KeyTimer.cancel();
                        KeyTimer = null;
                    }
                    KeyPressTimer();
                    KeyTimer.start();
                    bPressedSTAR = true;
                }

                Intent intent = new Intent();

                if (!m_bCallState) {
                    intent.setAction("UPDATE_KEYDATA");

                    Log.d("KSJ", "onKeyDown1 " + m_bCallState);
                } else {
                    intent.setAction("UPDATE_KEYDATA_TALK");

                }
                //intent.setAction("UPDATE_KEYDATA");
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);


            }
            else if (Declare.Button.SHARP == keyCode) {
                m_iSenseSettingCount = 0;
                Intent intent = new Intent(this, kr.co.icontrols.ilp300_700.MainActivity.class);
                if ((bPressedSTAR) && (m_iKeyValue == Declare.Button.STAR)) {
                    Log.d(TAG, "Declare.Button.SHARP");

                    Intent intent1 = new Intent();
                    intent1.setAction("UPDATE_KEYDATA");
                    intent1.putExtra("data", keyCode);
                    sendBroadcast(intent1);


                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                }
                else
                {
                    if (Configure.ConfigValue.eLPRole == Configure.SetValue.LPRole_CarGate) return super.onKeyDown(keyCode, event);

                    Log.d(TAG, "[onKeyDown] eAccessPWSelected = " + Configure.ConfigValue.eAccessPWSelected);

                    if (Configure.ConfigValue.eAccessPWSelected == Configure.SetValue.PublicAccessPW_Selected) {
                        m_bSenseSettingState = true;
                        m_iAccessPW_type = 2;
                        m_iSenseSettingPage = 1;
                        m_iSenseSettingCount = 0;
                        pw_ment.setText("공용출입 비밀번호를 입력 하세요.");
                        Global.strInputPW = "";

                    } else if (Configure.ConfigValue.eAccessPWSelected == Configure.SetValue.ResiAccessPW_Selected) {

                        m_bSenseSettingState = true;
                        m_iAccessPW_type = 3;
                        m_iSenseSettingPage = 99;
                        m_iSenseSettingCount = 0;
                        initCallVariables();
                        Global.strInputPW = "";
                        setUserPW();

                    } else if (Configure.ConfigValue.eAccessPWSelected == Configure.SetValue.PW_Unselected) {

                    } else {
                        Log.d(TAG, "[onKeyDown] eAccessPWSelected is wrong!!");
                    }
                }
            }
            else if (Declare.Button.GUARD == keyCode || keyCode == Declare.Button.TACT_GUARD) {
                Intent intent = new Intent();
                intent.setAction("UPDATE_KEYDATA");
                intent.putExtra("data", keyCode);
                sendBroadcast(intent);
                m_iSenseSettingCount = 0;
            }

        }
        else if((m_bSenseSettingState) && (m_iAccessPW_type == 0))
        {

            if(m_iSenseSettingPage == 1)
            {
                if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
                    int inputKey = keyCode - 7;
                    m_strSettingPW += "" + inputKey;
                    m_iSenseSettingCount++;
                    setSensePW_view(m_iSenseSettingCount);

                }

                if (KeyTimer_setting != null) {
                    KeyTimer_setting.cancel();
                    KeyTimer_setting = null;
                }
                KeyPressTimer_setting();
                KeyTimer_setting.start();
                //bPressedSTAR = true;
            }
            else if(m_iSenseSettingPage == 2)
            {

                if(Declare.Button.NUMBER_01 == keyCode)
                {
                    m_iSenseSettingPage = 3;
                    m_txtDistance.setText(String.valueOf(m_iDistanceValue_old));
                }
                else if(Declare.Button.NUMBER_02 == keyCode)
                {
                    m_iSenseSettingPage = 4;
                }
                else if(Declare.Button.NUMBER_03 == keyCode)
                {
                    if(m_bSettingAI)
                        m_txtAISet.setText("1] AI 설정 [1]");
                    else
                        m_txtAISet.setText("1] AI 설정 [0]");

                    if(m_bSettingShowVideo)
                        m_txtVideoSet.setText("2] 영상 표시 [1]");
                    else
                        m_txtVideoSet.setText("2] 영상 표시 [0]");

                    m_txtVideoRecog.setText("4] 인증률 ["+m_iRecogValue +"]");

                    m_txtDeviceVersion.setText("" + DEVICE_VERSION);

                    m_iSenseSettingPage = 5;
                    m_iSenseSettingPage_sub = 0;

                }
                m_UIRefreshSet = true;

            }
            else if(m_iSenseSettingPage == 3)
            {
                if(Declare.Button.NUMBER_01 == keyCode)
                {
                    m_iDistanceValue_old--;
                    if(m_iDistanceValue_old < 1)
                        m_iDistanceValue_old = 1;

                }
                else if(Declare.Button.NUMBER_03 == keyCode)
                {
                    m_iDistanceValue_old++;
                    if(m_iDistanceValue_old > 5)
                        m_iDistanceValue_old = 6;
                }


                m_txtDistance.setText(String.valueOf(m_iDistanceValue_old));
                m_UIRefreshSet = true;

            }
            else if(m_iSenseSettingPage == 4)
            {
                //m_txtAdd_dong.setText(DataClasses.RemoteIDInfo.nDong);
                if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
                    int inputKey = keyCode - 7;

                    setSenseADD_text(m_iSenseSettingCount, inputKey);
                }

                if(Declare.Button.STAR == keyCode)
                {
                    if(m_iSenseSettingCount == 3)
                        m_iSenseSettingCount = 0;
                    m_iSenseSettingCount++;
                    setSenseADD_view(m_iSenseSettingCount);
                }
                m_UIRefreshSet = true;
            }
            else if(m_iSenseSettingPage == 5)
            {
                SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
                SharedPreferences.Editor editor = pref.edit();

                if(m_iSenseSettingPage_sub == 0)
                {
                    if(Declare.Button.NUMBER_01 == keyCode)
                    {
                        if(m_bSettingAI) {
                            m_txtAISet.setText("1] AI 설정 [0]");
                            m_bSettingAI = false;
                            setTemplateUpdate(0);
                        }
                        else
                        {
                            m_txtAISet.setText("1] AI 설정 [1]");
                            m_bSettingAI = true;
                            setTemplateUpdate(1);
                        }
                        editor.putBoolean(Face_AI_Set, m_bSettingAI);
                        editor.commit();
                        //senstime_FWUdate();

                    }
                    else if(Declare.Button.NUMBER_02 == keyCode)
                    {
                        if(m_bSettingShowVideo) {
                            m_txtVideoSet.setText("2] 영상 표시 [0]");
                            m_bSettingShowVideo = false;
                        }
                        else
                        {
                            m_txtVideoSet.setText("2] 영상 표시 [1]");
                            m_bSettingShowVideo = true;
                        }

                        editor.putBoolean(Face_Show_Video, m_bSettingShowVideo);
                        editor.commit();
                    }
                    else if(Declare.Button.NUMBER_03 == keyCode)
                    {
                        setDeleteAll();

                    }
                    else if(Declare.Button.NUMBER_04 == keyCode)
                    {

                        if(m_iRecogValue == 10)
                            m_iRecogValue = 1;
                        else
                            m_iRecogValue++;

                        recognitionCount(m_iRecogValue);
                        editor.putInt(Face_Recog_Value, m_iRecogValue);
                        m_txtVideoRecog.setText("4] 인증률 ["+m_iRecogValue +"]");
                        editor.commit();

                    }
                    else if(Declare.Button.STAR == keyCode)
                    {
                        m_iSenseSettingPage_sub = 1;

                        if(m_bSettingIRLED == true)
                            m_txtAISet.setText("5] IR LED 설정 [1]");
                        else
                            m_txtAISet.setText("5] IR LED 설정 [0]");

                        if(m_bAEMode == true)
                            m_txtVideoSet.setText("6] AE Mode 설정 [1]");
                        else
                            m_txtVideoSet.setText("6] AE Mode 설정 [0]");

                        //m_txtVideoSet.setText("");

                        m_txtVideoRecog.setText("");
                        m_txtVideoDelete.setText("");

                    }
                    else if(Declare.Button.SHARP == keyCode)
                    {
                        m_iSenseSettingPage_sub = 1;

                        if(m_bSettingIRLED == true)
                            m_txtAISet.setText("5] IR LED 설정 [1]");
                        else
                            m_txtAISet.setText("5] IR LED 설정 [0]");

                        if(m_bAEMode == true)
                            m_txtVideoSet.setText("6] AE Mode 설정 [1]");
                        else
                            m_txtVideoSet.setText("6] AE Mode 설정 [0]");

                        m_txtVideoRecog.setText("");
                        m_txtVideoDelete.setText("");
                    }

                }
                else if(m_iSenseSettingPage_sub == 1)
                {
                    if(Declare.Button.STAR == keyCode)
                    {
                        m_iSenseSettingPage_sub = 0;
                        if(m_bSettingAI)
                            m_txtAISet.setText("1] AI 설정 [1]");
                        else
                            m_txtAISet.setText("1] AI 설정 [0]");

                        if(m_bSettingShowVideo)
                            m_txtVideoSet.setText("2] 영상 표시 [1]");
                        else
                            m_txtVideoSet.setText("2] 영상 표시 [0]");

                        m_txtVideoRecog.setText("4] 인증률 ["+m_iRecogValue +"]");
                        m_txtVideoDelete.setText("3] 전체 삭제");
                    }
                    else if(Declare.Button.SHARP == keyCode)
                    {
                        m_iSenseSettingPage_sub = 0;
                        if(m_bSettingAI)
                            m_txtAISet.setText("1] AI 설정 [1]");
                        else
                            m_txtAISet.setText("1] AI 설정 [0]");

                        if(m_bSettingShowVideo)
                            m_txtVideoSet.setText("2] 영상 표시 [1]");
                        else
                            m_txtVideoSet.setText("2] 영상 표시 [0]");

                        m_txtVideoRecog.setText("4] 인증률 ["+m_iRecogValue +"]");

                        m_txtVideoDelete.setText("3] 전체 삭제");
                    }
                    else if(Declare.Button.NUMBER_05 == keyCode)
                    {
                        if(m_bSettingIRLED == true) {
                            m_txtAISet.setText("5] IR LED 설정 [0]");
                            m_bSettingIRLED = false;
                            //if(m_bIRLEDState)
                            {
                                setDeviceIRLedON();
                                m_bIRLEDState = true;
                            }

                        }
                        else {
                            m_txtAISet.setText("5] IR LED 설정 [1]");
                            m_bSettingIRLED = true;
                        }

                        Log.d("KSJ", "m_bSettingIRLED " + m_bSettingIRLED);

                        editor.putBoolean(Face_IRLed_Value, m_bSettingIRLED);
                        editor.commit();
                    }
                    else if(Declare.Button.NUMBER_06 == keyCode)
                    {

                        if(m_bAEMode == true) {
                            m_txtVideoSet.setText("6] AE Mode 설정 [0]");
                            m_bAEMode = false;
                        }
                        else {
                            m_txtVideoSet.setText("6] AE Mode 설정 [1]");
                            m_bAEMode = true;
                        }

                        Log.d("KSJ", "m_bAEMode " + m_bAEMode);
                        setDeviceAntiFlickerset(m_bAEMode);

                        editor.putBoolean(Face_AEMode_Value, m_bAEMode);
                        editor.commit();
                    }


                }




                m_UIRefreshSet = true;


            }

            if (Declare.Button.CANCEL == keyCode || keyCode == Declare.Button.TACT_CANCEL) {

                Log.d("KSJ",  " KEYCODE_E m_iSenseSettingPage " + m_iSenseSettingPage);
                if(m_iSenseSettingPage < 3) {
                    m_bSenseSettingState = false;
                    m_UIRefreshSet = true;
                    m_iSenseSettingCount = 0;
                    setSensePW_all();
                    m_strSettingPW="";

                }
                else {
                    m_iSenseSettingPage = 2;
                    m_txtVideoDelete.setText("3] 전체 삭제");
                    m_txtAdd_result.setText("결과 : ");
                }

            }


            if (Declare.Button.GUARD == keyCode) {

                if(m_iSenseSettingPage == 1)
                {
                    if(m_iSenseSettingCount > 3)
                    {
                        if (Global.ComparePW(Enumeration.PWTYPE.ADMINSETPW, m_strSettingPW)) {
                            LOG("[onKeyDown] Password OK!!");
                            // 관리자 설정화면으로 진입
                            kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.resultok);
                            setSensePW_all();
                            m_iSenseSettingPage = 2;
                            m_iSenseSettingCount = 0;
                            m_strSettingPW="";
                        } else {
                            LOG("[onKeyDown] Password different!!");
                            m_bSenseSettingState = false;
                            m_UIRefreshSet = true;
                            m_iSenseSettingCount = 0;
                            setSensePW_all();
                            m_strSettingPW="";
                            kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.retryinput);
                        }
                    }
                }
                else if(m_iSenseSettingPage == 3)
                {
                    m_iDistanceValue = m_iDistanceValue_old;
                    m_iDetectLen = m_DetectCase[Configure.ConfigValue.DEVICE_MODELTYPE][m_iDistanceValue-1];
                    SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
                    SharedPreferences.Editor editor = pref.edit();

                    editor.putInt(Face_Detect_Value, m_iDistanceValue);

                    editor.commit();

                    bSettingMent = true;
                    m_iSenseSettingPage = 2;
                    kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.setting);
                }
                else if(m_iSenseSettingPage == 4)
                {
                    //jglee 20250609 정상동작안함
                    setCaptureAdd(m_txtAdd_dong.getText().toString(),
                            m_txtAdd_ho.getText().toString(),
                            m_txtAdd_num.getText().toString()
                    );



                    bSettingMent = true;
                    kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.setting);
                }
            }

            if(m_iSenseSettingPage != 1) {
                if (KeyTimer != null) {
                    KeyTimer.cancel();
                    KeyTimer = null;
                }
            }
            m_UIRefreshSet = true;
        }
        else if((m_bSenseSettingState) && (m_iAccessPW_type > 0))
        {

            LOG("[password] key " + keyCode + " type : " + m_iAccessPW_type);
            if(m_iAccessPW_type == 1)
            {
                if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
                    int inputKey = keyCode - 7;
                    m_strSettingPW += "" + inputKey;
                    m_iSenseSettingCount++;
                    setSensePW_view(m_iSenseSettingCount);

                }
                else if (Declare.Button.SHARP == keyCode) {
                    if (Global.ComparePW(Enumeration.PWTYPE.ACCESS_ADMINPW, m_strSettingPW)) {
                        LOG("[onKeyDown] Password OK!!");
                        // 비밀번호 동일함
                        // 로비폰 문을 연다.
                        Global.ctrlLobbyDoorNMent(true, true, Configure.ConfigValue.nDoorOpenDuration, false, false);
                        LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.pass, Declare.AccessValues.adminpw, Configure.ConfigValue.strDeviceIPAddress, "null", 0, 0, 0, 0, "null");
                        Global.sendElevCallRequest("null", "null", true);
                    } else {
                        LOG("[onKeyDown] Password different!!");
                        Global.ctrlLobbyDoorNMent(false, true, 0, false, false);
                        LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.adminpw, Configure.ConfigValue.strDeviceIPAddress, "null", 0, 0, 0, 0, Global.strInputPW);
                        kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.retryinput);
                    }
                    bSettingMent = true;
                    m_bSenseSettingState = false;
                    m_UIRefreshSet = true;
                    m_iSenseSettingCount = 0;
                    setSensePW_all();
                    initCallVariables();
                    m_strSettingPW="";
                    m_iAccessPW_type = 0;
                    m_iSenseSettingPage = 0;
                }
            }
            else if(m_iAccessPW_type == 2)
            {
                if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
                    int inputKey = keyCode - 7;
                    m_strSettingPW += "" + inputKey;
                    m_iSenseSettingCount++;
                    setSensePW_view(m_iSenseSettingCount);

                }
                else if (Declare.Button.SHARP == keyCode) {
                    if (Global.ComparePW(Enumeration.PWTYPE.ACCESS_PUBLICPW, m_strSettingPW)) {
                        Log.d(TAG, "[onKeyDown] Password OK!!");
                        // 비밀번호 동일함
                        // 로비폰 문을 연다.
                        Global.ctrlLobbyDoorNMent(true, true, Configure.ConfigValue.nDoorOpenDuration, false, false);
                        LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.pass, Declare.AccessValues.mpasswd, Configure.ConfigValue.strDeviceIPAddress, "null", 0, 0, 0, 0, "null");
                        Global.sendElevCallRequest("null", "null", true);

                    } else {
                        Log.d(TAG, "[onKeyDown] Password different!!");
                        Global.ctrlLobbyDoorNMent(false, true, 0, false, false);
                        LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.mpasswd, Configure.ConfigValue.strDeviceIPAddress, "null", 0, 0, 0, 0, Global.strInputPW);
                    }
                    bSettingMent = true;
                    m_bSenseSettingState = false;
                    m_UIRefreshSet = true;
                    m_iSenseSettingCount = 0;
                    setSensePW_all();
                    initCallVariables();
                    m_strSettingPW="";
                    m_iAccessPW_type = 0;
                    m_iSenseSettingPage = 0;
                }
            }
            else if(m_iAccessPW_type == 3)
            {
                if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
                    int inputKey = keyCode - 7;

                    if (m_iSenseSettingCount == 0) {
                        DataClasses.RemoteIDInfo.strDong += Integer.toString(keyCode - 7);

                        if (DataClasses.RemoteIDInfo.strDong.length() > MAXLENGTH_DONG) {
                            DataClasses.RemoteIDInfo.strDong = DataClasses.RemoteIDInfo.strDong.substring(1, 5);
                        }
                    } else if (m_iSenseSettingCount == 1) {
                        DataClasses.RemoteIDInfo.strHo += Integer.toString(keyCode - 7);

                        if (DataClasses.RemoteIDInfo.strHo.length() > MAXLENGTH_HO) {
                            DataClasses.RemoteIDInfo.strHo = DataClasses.RemoteIDInfo.strHo.substring(1, 5);
                        }
                    } else if (m_iSenseSettingCount == 2) {
                        if (Integer.valueOf(Global.strInputPW.length()) < 4) {
                            Global.strInputPW += Integer.toString(keyCode - 7);
                        }
                    }

                    setUserPW();

                }
                else if (Declare.Button.STAR == keyCode) {
                    if (m_iSenseSettingCount == 0) {
                        if (DataClasses.RemoteIDInfo.strDong.length() > 2) {
                            m_iSenseSettingCount = 1;
                            Global.TargetInputStep = Enumeration.TARGETINFOINPUTSTEP.HO;
                        } else {
                            kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.retryinput);
//                            m_bSenseSettingState = false;
//                            m_UIRefreshSet = true;
//                            m_iSenseSettingCount = 0;
//                            setSensePW_all();
//                            m_strSettingPW="";
//                            m_iAccessPW_type = 0;
//                            m_iSenseSettingPage = 0;
                            DataClasses.RemoteIDInfo.InitVariables();
                            setCallLevel();
                        }
                    } else if (m_iSenseSettingCount == 1) {
                        if (DataClasses.RemoteIDInfo.strHo.length() > 2) {
                            m_iSenseSettingCount = 2;
                            Global.TargetInputStep = Enumeration.TARGETINFOINPUTSTEP.DONE;
                        } else {

                            kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.retryinput);
//                            m_bSenseSettingState = false;
//                            m_UIRefreshSet = true;
//                            m_iSenseSettingCount = 0;
//                            setSensePW_all();
//                            m_strSettingPW="";
//                            m_iAccessPW_type = 0;
//                            m_iSenseSettingPage = 0;
                            DataClasses.RemoteIDInfo.InitVariables();
                            setCallLevel();
                        }
                    }
                    setUserPW();
                }
                else if (Declare.Button.SHARP == keyCode) {
                    LOG("[password] bFUNCBlock " + bFUNCBlock);
                    if (bFUNCBlock) return super.onKeyDown(keyCode, event);
                    LOG("[password] m_iSenseSettingCount " + m_iSenseSettingCount);
                    if (m_iSenseSettingCount == 1) {
                        if (Configure.ConfigValue.eHouseDivision == Configure.SetValue.TRUE) {
                            DataClasses.RemoteIDInfo.bRentRoomSelected = true;
                            DataClasses.RemoteIDInfo.nHo_Extension = 1;
                            Global.TargetInputStep = Enumeration.TARGETINFOINPUTSTEP.DONE;
                        }
                    } else if (m_iSenseSettingCount == 2) {
                        if (Global.strInputPW.length() != 4) {
                            Log.d(TAG, "[onKeyDown] The length of Global.strInputPW is not 4!!!");
                            kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.retryinput);
                            updateScreen();
                            Global.ctrlLobbyDoorNMent(false, false, 0, false, false);
                            if (DataClasses.RemoteIDInfo.bRentRoomSelected)
                                LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RENTRESIDENCE, DataClasses.RemoteIDInfo.strDong, DataClasses.RemoteIDInfo.strHo), "null", 0, 0, 0, 0, Global.strInputPW);
                            else
                                LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RESIDENCE, DataClasses.RemoteIDInfo.strDong, DataClasses.RemoteIDInfo.strHo), "null", 0, 0, 0, 0, Global.strInputPW);
                            Global.strInputPW = "";
                            return super.onKeyDown(keyCode, event);
                        }

                        if (Global.strInputPW.equals(Global.ZeroPadding_Head(4, DataClasses.RemoteIDInfo.strHo))) {
                            Log.d(TAG,"[onKeyDown] Global.strInputPW and RemoteIDInfo.strHo are same!!!");
                            kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.retryinput);
                            updateScreen();
                            Global.ctrlLobbyDoorNMent(false, false, 0, false, false);
                            if (DataClasses.RemoteIDInfo.bRentRoomSelected)
                                LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RENTRESIDENCE, DataClasses.RemoteIDInfo.strDong, DataClasses.RemoteIDInfo.strHo), "null", 0, 0, 0, 0, Global.strInputPW);
                            else
                                LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RESIDENCE, DataClasses.RemoteIDInfo.strDong, DataClasses.RemoteIDInfo.strHo), "null", 0, 0, 0, 0, Global.strInputPW);
                            Global.strInputPW = "";
                            return super.onKeyDown(keyCode, event);
                        }

                        for (int i = 0; i < Global.astrBlockedPW.length; i++) {
                            if (Global.astrBlockedPW[i].equals(Global.strInputPW)) {
                                Log.d(TAG,"[onKeyDown] Global.strInputPW is prohibited!!!");
                                kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.retryinput);
                                updateScreen();
                                Global.ctrlLobbyDoorNMent(false, false, 0, false, false);
                                if (DataClasses.RemoteIDInfo.bRentRoomSelected)
                                    LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RENTRESIDENCE, DataClasses.RemoteIDInfo.strDong, DataClasses.RemoteIDInfo.strHo), "null", 0, 0, 0, 0, Global.strInputPW);
                                else
                                    LobbyAccessCtrl.sendLobbyAccessLog(Declare.AccessValues.fail, Declare.AccessValues.passwd, EthernetCtrl.makeIPAddress(Declare.DeviceType.RESIDENCE, DataClasses.RemoteIDInfo.strDong, DataClasses.RemoteIDInfo.strHo), "null", 0, 0, 0, 0, Global.strInputPW);
                                Global.strInputPW = "";
                                return super.onKeyDown(keyCode, event);
                            }
                        }

                        if (Configure.ConfigValue.eCallLevel == Configure.SetValue.Level_Line) {

                            if (Global.isExistResi(Integer.parseInt(DataClasses.RemoteIDInfo.strHo))) {

                                if (!send_check_lobby_passwd_request(DataClasses.RemoteIDInfo.strDong, DataClasses.RemoteIDInfo.strHo, Global.strInputPW, DataClasses.RemoteIDInfo.bRentRoomSelected)) {
                                    kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.trylater);
                                    bSettingMent = true;
                                    m_bSenseSettingState = false;
                                    m_UIRefreshSet = true;
                                    m_iSenseSettingCount = 0;
                                    setSensePW_all();
                                    initCallVariables();
                                    m_strSettingPW="";
                                    m_iAccessPW_type = 0;
                                    m_iSenseSettingPage = 0;
                                    Global.strInputPW = "";
                                    //super.setChangeScreen(ID.SCREENS.Main);
                                }
                            } else {

                                kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.confirmsetting);
                                bSettingMent = true;
                                m_bSenseSettingState = false;
                                m_UIRefreshSet = true;
                                m_iSenseSettingCount = 0;
                                setSensePW_all();
                                initCallVariables();
                                m_strSettingPW="";
                                m_iAccessPW_type = 0;
                                m_iSenseSettingPage = 0;
                                Global.strInputPW = "";
                                //super.setChangeScreen(ID.SCREENS.Main);
                            }
                        } else {
                            if (!send_check_lobby_passwd_request(DataClasses.RemoteIDInfo.strDong, DataClasses.RemoteIDInfo.strHo, Global.strInputPW, DataClasses.RemoteIDInfo.bRentRoomSelected)) {
                                kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.trylater);
                                bSettingMent = true;
                                m_bSenseSettingState = false;
                                m_UIRefreshSet = true;
                                m_iSenseSettingCount = 0;
                                setSensePW_all();
                                initCallVariables();
                                m_strSettingPW="";
                                m_iAccessPW_type = 0;
                                m_iSenseSettingPage = 0;
                                Global.strInputPW = "";
                                //super.setChangeScreen(ID.SCREENS.Main);
                            }
                        }
                    } else {

                        kr.co.icontrols.ilp300_700.MainActivity.mSound.Play_lobby(R.raw.retryinput);
                        bSettingMent = true;
                        m_bSenseSettingState = false;
                        m_UIRefreshSet = true;
                        m_iSenseSettingCount = 0;
                        setSensePW_all();
                        initCallVariables();
                        m_strSettingPW="";
                        m_iAccessPW_type = 0;
                        m_iSenseSettingPage = 0;
                        Global.strInputPW = "";
                        //super.setChangeScreen(ID.SCREENS.Main);
                    }
//                    bSettingMent = true;
//                    m_bSenseSettingState = false;
//                    m_UIRefreshSet = true;
//                    m_iSenseSettingCount = 0;
//                    setSensePW_all();
//                    initCallVariables();
//                    m_strSettingPW="";
//                    m_iAccessPW_type = 0;
//                    m_iSenseSettingPage = 0;
//                    Global.strInputPW = "";

                }
            }

            if (Declare.Button.CANCEL == keyCode || keyCode == Declare.Button.TACT_CANCEL) {

                Log.d("KSJ",  " CANCEL m_iSenseSettingPage " + m_iSenseSettingPage);

                m_bSenseSettingState = false;
                m_UIRefreshSet = true;
                m_iSenseSettingCount = 0;
                setSensePW_all();
                initCallVariables();
                m_strSettingPW="";
                m_iAccessPW_type = 0;
                m_iSenseSettingPage = 0;
                Global.strInputPW = "";

            }

            if (KeyTimer_setting != null) {
                KeyTimer_setting.cancel();
                KeyTimer_setting = null;
            }
            KeyPressTimer_setting();
            KeyTimer_setting.start();
            //bPressedSTAR = true;

        }

        if (keyCode == Declare.Button.FIRE_ACTIVE) {
            LOG("[onKeyDown] Pressed (FIRE_ACTIVE)");
            Global.setFireAlarmProcess(Global.FIRESENSOR_TIMEOUT);
            showToast_fire();

        }
        else if (keyCode == Declare.Button.INSIDESENSOR_ACTIVE) {
            LOG("[onKeyDown] Pressed (INSIDESENSOR_ACTIVE)");
            Intent intent = new Intent();
            intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
            intent.putExtra("data", keyCode);
            sendBroadcast(intent);
        }
        else if (keyCode == Declare.Button.INSIDESENSOR_INACTIVE) {
            LOG("[onKeyDown] Pressed (INSIDESENSOR_INACTIVE)");
            Intent intent = new Intent();
            intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
            intent.putExtra("data", keyCode);
            sendBroadcast(intent);
        }
        else if (keyCode == Declare.Button.FIRE_ACTIVE) {
            LOG("[onKeyDown] Pressed (FIRE_ACTIVE)");
            Global.setFireAlarmProcess(Global.FIRESENSOR_TIMEOUT);
            Intent intent = new Intent();
            intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
            intent.putExtra("data", keyCode);
            sendBroadcast(intent);
        }
        else if (keyCode == Declare.Button.OUTSIDESENSOR_ACTIVE) {
            LOG("[onKeyDown] Pressed (OUTSIDESENSOR_ACTIVE)");
            Intent intent = new Intent();
            intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
            intent.putExtra("data", keyCode);
            sendBroadcast(intent);
        }
        else if (keyCode == Declare.Button.OUTSIDESENSOR_INACTIVE) {
            LOG("[onKeyDown] Pressed (OUTSIDESENSOR_INACTIVE)");
            Intent intent = new Intent();
            intent.setAction(Declare.PrivateBR.UPDATE_SENSOR);
            intent.putExtra("data", keyCode);
            sendBroadcast(intent);

        }
        else
        {
            if(!bSettingMent)
                kr.co.icontrols.ilp300_700.MainActivity.mSound.PlayMent_lobby(R.raw.button);

            if (KeyTimer_setting != null) {
                KeyTimer_setting.cancel();
                KeyTimer_setting = null;
            }
            KeyPressTimer_setting();
            KeyTimer_setting.start();
        }

        m_iKeyValue = keyCode;

        m_UIRefreshSet = true;

        return super.onKeyDown(keyCode, event);
    }

    private void initCallVariables() {
        try {
            DataClasses.RemoteIDInfo.InitVariables();
            setCallLevel();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initCallVariables()");
            e.printStackTrace();
        }
    }

    private void setCallLevel() {
        try {
            if (Configure.ConfigValue.eCallLevel == Configure.SetValue.Level_Line || Configure.ConfigValue.eCallLevel == Configure.SetValue.Level_Dong) {
                m_iSenseSettingCount = 1;
                DataClasses.RemoteIDInfo.strDong = Configure.ConfigValue.strDevice_Dong;
            } else if (Configure.ConfigValue.eCallLevel == Configure.SetValue.Level_Entire) {
                Global.TargetInputStep = Enumeration.TARGETINFOINPUTSTEP.DONG;
                m_iSenseSettingCount = 0;
            } else {
                m_iSenseSettingCount = 1;
                DataClasses.RemoteIDInfo.strDong = Configure.ConfigValue.strDevice_Dong;
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setCallLevel()");
            e.printStackTrace();
        }
    }

    public void setUserPW()
    {
        try {
//            LOG("[updateScreen] Start!!");
            if (DataClasses.RemoteIDInfo.strDong != "") {
                // 첫자리에 "0"이 출력되지 않도록 숫자로 변경하면서 "0"을 제거하고, 다시 String으로 변환한다.
                DataClasses.RemoteIDInfo.nDong = Integer.parseInt(DataClasses.RemoteIDInfo.strDong);
                DataClasses.RemoteIDInfo.strDong = Integer.toString(DataClasses.RemoteIDInfo.nDong);
            }

            if (DataClasses.RemoteIDInfo.strHo != "") {
                // 첫자리에 "0"이 출력되지 않도록 숫자로 변경하면서 "0"을 제거하고, 다시 String으로 변환한다.
                DataClasses.RemoteIDInfo.nHo = Integer.parseInt(DataClasses.RemoteIDInfo.strHo);
                DataClasses.RemoteIDInfo.strHo = Integer.toString(DataClasses.RemoteIDInfo.nHo);
            }

            String strTXT_INSTRUCTION = "";
            if (m_iSenseSettingCount == 0)
                strTXT_INSTRUCTION = "세대정보를 입력하세요.";
            else if (m_iSenseSettingCount == 1)
                strTXT_INSTRUCTION = "세대정보를 입력하세요.";
            else if (m_iSenseSettingCount == 2)
                strTXT_INSTRUCTION = "세대출입 비밀번호를 입력하세요.";

            mTxtView_dong_pwd.setText(DataClasses.RemoteIDInfo.strDong);

            String strDisplayHo = "";
            if (DataClasses.RemoteIDInfo.bRentRoomSelected) strDisplayHo = DataClasses.RemoteIDInfo.strHo + "-" + DataClasses.RemoteIDInfo.nHo_Extension;
            else strDisplayHo = DataClasses.RemoteIDInfo.strHo;
            Log.w(TAG, "[updateScreen] strDisplayHo [" + strDisplayHo + "], strDisplayHo.length() [" + strDisplayHo.length() + "]");
//

            mTxtView_ho_pwd.setText(strDisplayHo);
            pw_ment_user.setText(strTXT_INSTRUCTION);

            int nPWLength = 0;
            if (Global.strInputPW != "") {
                Log.d(TAG, "[updateScreen] Global.strInputPW = " + Global.strInputPW);
                nPWLength = Global.strInputPW.length();
            }

            if (nPWLength == 0) {
                m_imageViewPW1_user.setImageResource(R.drawable.box_blank);
                m_imageViewPW2_user.setImageResource(R.drawable.box_blank);
                m_imageViewPW3_user.setImageResource(R.drawable.box_blank);
                m_imageViewPW4_user.setImageResource(R.drawable.box_blank);
            } else if (nPWLength == 1) {
                m_imageViewPW1_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW2_user.setImageResource(R.drawable.box_blank);
                m_imageViewPW3_user.setImageResource(R.drawable.box_blank);
                m_imageViewPW4_user.setImageResource(R.drawable.box_blank);
            } else if (nPWLength == 2) {
                m_imageViewPW1_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW2_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW3_user.setImageResource(R.drawable.box_blank);
                m_imageViewPW4_user.setImageResource(R.drawable.box_blank);
            } else if (nPWLength == 3) {
                m_imageViewPW1_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW2_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW3_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW4_user.setImageResource(R.drawable.box_blank);
            } else if (nPWLength == 4) {
                m_imageViewPW1_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW2_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW3_user.setImageResource(R.drawable.box_pw);
                m_imageViewPW4_user.setImageResource(R.drawable.box_pw);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] updateScreen()");
            e.printStackTrace();
        }
    }


    public void setDeleteAll()
    {
        mClient.mtcAiClearAllImage((mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS) {
                m_txtVideoDelete.setText("3] 전체 삭제 성공");
                //showToast("등록된 유저 정보를 삭제 하였습니다.");
            } else {
                m_txtVideoDelete.setText("3] 전체 삭제 실패");
                //showToast_rotate("X");
            }
        });
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        mClient.mtcAiClearAllImage((mtcCode, result) -> {

        });
    }

    public void setTemplateUpdate(int iVal)
    {
        mClient.mtcTemplateUpdateSet(iVal,(mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS) {

                //showToast("등록된 유저 정보를 삭제 하였습니다.");
            } else {

                //showToast_rotate("X");
            }
        });
    }

    public void setCaptureAdd(String strdong, String strho, String strNum)
    {
        String id = strdong + "," + strho + "," + strNum;
        int mode = 0x02;
        MaterialDialog progressDialog = MaterialDialogUtils.showIndeterminateProgressDialog(this, "", false).show();
        MClient.getInstance().mtcAiAddImageByCamera(mode, id, SenseTimeMtc.getInstance().getmDeviceModule(), new MtcCallback() {
            @Override
            public void onResult(MtcCode mtcCode, String s) {

            }

            @Override
            public void onResult(MtcCode mtcCode, String result, String extraInfo) {
                MtcCallback.super.onResult(mtcCode, result, extraInfo);

                if (progressDialog != null) {
                    progressDialog.dismiss();
                }

                Log.d(TAG, "setCaptureAdd - mtcCode:" + mtcCode);

                if (mode == 0x02 && mtcCode != MtcCode.ERR_TIME_OUT && !TextUtils.isEmpty(result)) {
                    if (mtcCode == MtcCode.SUCCESS) {
                        //this.showToast(R.string.notice_success);
                        m_txtAdd_result.setText("결과 : 얼굴등록이 성공하였습니다.");
                    } else {
                        //showToast(getMtcErrorMsg(mtcCode));
                        m_txtAdd_result.setText("결과 : 얼굴등록이 실패 하였습니다.");
                    }
                    byte[] data = Base64.decode(result, Base64.DEFAULT);
                    long ts = System.currentTimeMillis();
                    FileUtils.writeDataToDisk(data, "/sdcard/pictures_add_user/" + id + "_" + ts + ".jpg");
                } else if (mode == 0x01 && mtcCode == MtcCode.SUCCESS) {
                    //showToast(R.string.notice_success);
                    m_txtAdd_result.setText("결과 : 얼굴등록이 성공하였습니다.");
                } else {
                    m_txtAdd_result.setText("결과 : 얼굴등록이 실패 하였습니다.");
                    //showToast(this.getMtcErrorMsg(mtcCode));
                }
            }
        });
    }

    public void setSensePW_view(int iNum)
    {
        Log.d("KSJ","setSensePW_view " + iNum);
        if(iNum == 1)
            m_imageViewPW1.setImageResource(R.drawable.box_pw);
        else if(iNum == 2)
            m_imageViewPW2.setImageResource(R.drawable.box_pw);
        else if(iNum == 3)
            m_imageViewPW3.setImageResource(R.drawable.box_pw);
        else if(iNum == 4)
            m_imageViewPW4.setImageResource(R.drawable.box_pw);

    }

    public void setSensePW_all()
    {
        m_iSenseSettingCount = 0;
        m_imageViewPW1.setImageResource(R.drawable.box_blank);
        m_imageViewPW2.setImageResource(R.drawable.box_blank);
        m_imageViewPW3.setImageResource(R.drawable.box_blank);
        m_imageViewPW4.setImageResource(R.drawable.box_blank);

    }

    public void clearResidence_PW()
    {
        Global.strInputPW = "";
        if (DataClasses.RemoteIDInfo.bRentRoomSelected)
            DataClasses.RemoteIDInfo.strDong = "";

        DataClasses.RemoteIDInfo.strHo = "";
    }

    boolean m_bSettingKeyinput = false;

    public void setSenseADD_view(int iNum)
    {
//        m_txtAdd_dong = findViewById(R.id.input_01_add);
//        m_txtAdd_ho = findViewById(R.id.input_02_add);
//        m_txtAdd_num = findViewById(R.id.input_03_add);
//        m_txtAdd_result = findViewById(R.id.item_02_add);

        m_txtAdd_dong.setTextColor(Color.WHITE);
        m_txtAdd_ho.setTextColor(Color.WHITE);
        m_txtAdd_num.setTextColor(Color.WHITE);

        if(iNum == 1) {
            m_txtAdd_dong.setTextColor(Color.RED);
            m_bSettingKeyinput = true;
            //m_txtAdd_dong.setText("");
        }
        else if(iNum == 2) {
            m_txtAdd_ho.setTextColor(Color.RED);
            m_bSettingKeyinput = true;
            //m_txtAdd_ho.setText("");
        }
        else if(iNum == 3) {
            m_txtAdd_num.setTextColor(Color.RED);
            m_bSettingKeyinput = true;
            //m_txtAdd_num.setText("");
            //m_iSenseSettingCount = 0;
        }

    }

    public void setSenseADD_text(int iNum, int key)
    {
//        m_txtAdd_dong = findViewById(R.id.input_01_add);
//        m_txtAdd_ho = findViewById(R.id.input_02_add);
//        m_txtAdd_num = findViewById(R.id.input_03_add);
//        m_txtAdd_result = findViewById(R.id.item_02_add);
        String strText = "";


        Log.d("KSJ", "setSenseADD_text iNum " + iNum + " key " + key);
        if(iNum == 1) {
            if(m_bSettingKeyinput)
            {
                m_txtAdd_dong.setText("");
                m_bSettingKeyinput =false;
            }
            strText = m_txtAdd_dong.getText().toString();
            strText += String.valueOf(key);
            m_txtAdd_dong.setText(strText);
        }
        else if(iNum == 2) {
            if(m_bSettingKeyinput)
            {
                m_txtAdd_ho.setText("");
                m_bSettingKeyinput =false;
            }
            strText = m_txtAdd_ho.getText().toString();
            strText += String.valueOf(key);
            m_txtAdd_ho.setText(strText);
        }
        else if(iNum == 3) {
            if(m_bSettingKeyinput)
            {
                m_txtAdd_num.setText("");
                m_bSettingKeyinput =false;
            }
            strText = m_txtAdd_num.getText().toString();
            strText += String.valueOf(key);
            m_txtAdd_num.setText(strText);
        }

    }


    public void setAiConfig_first()
    {

//        AiConfig aiConfig = AiConfig.getInstance();
//        Gson gson = new Gson();
//        String aiConfigString = gson.toJson(aiConfig);

        AiConfig aiConfig = AiConfig.getInstance();

        Gson gson1 = new Gson();
        String aiConfigString1 = gson1.toJson(aiConfig);

        Log.d("KSJ111", aiConfigString1);

        aiConfig.setRecognitionThresh(0.7f); //-> 설정된 레벨에 따라 달라짐 (모듈 디폴트: 0.9)
        aiConfig.setVerifyThresh(0.7f);//-> 설정된 레벨에 따라 달라짐 (모듈 디폴트: 0.9)
        aiConfig.setLivenessThresh(0.98f); //-> 설정된 레벨에 따라 달라짐 (모듈 디폴트: 0.98)
        aiConfig.setRecognitionInterval(5); //-> 동일 Track에 대해 Tracking을 지속하는 시간
        aiConfig.setReportInterval(1); //-> 인식결과 전송간격
        //aiConfig.setFaceSize(30);// -> 인식 가능한 최소 얼굴픽셀사이즈
        //(테스트 결과 이 값을 변경할 경우 tracking정보가 안 오는 경우가 있어서[매우 간헐적으로 발생] 얼굴 사이즈 제한이 필요한 경우에는 이 값을 변경하기보다는 앱에서 부가적으로 체크하는 것을 권장)
        aiConfig.setFaceMode(1);// -> 다중얼굴인식여부 설정 (0=single / 1=multi)
        aiConfig.setMaxFaceCnt(4);
        //aiConfig.setEnableEnhancedSafetyMode(0);
        //aiConfig.setAeFlickerFreq(0);
        // (0=전체화면, 1=전체 얼굴, 2=상반 얼굴)
        //역광이나 옥외에선 반드시 1이상으로 설정해야 함
        //aiConfig.setEnableMaskSign(true);// -> 마스크정보를 사용할 경우
        aiConfig.setAeMode(0); //-> Auto Exposure의 기준 이미지     ---> M30 에서는 Face AE 모드를 지원하지 않음 (SDK 4.5.3)   ---> SDK 4.6.1 부터 지원가능해짐

        Log.d("KSJ111", "jglee - setAiConfig_first");

        try {
            Gson gson = new Gson();
            String aiConfigString = gson.toJson(aiConfig);
            AiConfig aiConfigNew = gson.fromJson(Util.stringToJSON(aiConfigString), AiConfig.class);
            if (aiConfigNew == null || !aiConfigNew.isValueValid()) {
                Log.d(TAG, "jglee - Configue Error");
                //showToast(R.string.check_ai_config);
            } else {
                mClient.mtcAiConfigSet(gson.toJson(aiConfigNew), (mtcCode, result) -> {
                    if (mtcCode == MtcCode.SUCCESS) {
                        Log.d(TAG, "jglee - Configue SUCCESS");
                        //showToast(R.string.notice_success);
                        //Log.d("KSJ111", "mtcAiConfigSet suc" );
                        AiConfig.setInstance(aiConfigNew);
                    } else {
                        Log.d(TAG, "jglee - Configue Error , " + getMtcErrorMsg(mtcCode));
                        //Log.d("KSJ111", "mtcAiConfigSet fail" );
                        showToast(getMtcErrorMsg(mtcCode));
                    }
                });
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            Log.d(TAG, "jglee - JsonSyntaxException e Configue Error");
            //showToast(R.string.check_ai_config);
        }

//        Gson gson = new Gson();
//        String aiConfigString = gson.toJson(aiConfig);
//        //EditText configEt = (EditText) setAiConfigDialog.getCustomView().findViewById(R.id.config_et);
//        //configEt.setText(Util.stringToJSON(aiConfigString));
//
//        AiConfig aiConfigNew = gson.fromJson(Util.stringToJSON(aiConfigString), AiConfig.class);
//
//        if (aiConfigNew == null || !aiConfigNew.isValueValid()) {
//            showToast(R.string.check_ai_config);
//        } else {
//            mClient.mtcAiConfigSet(gson.toJson(aiConfigNew), (mtcCode, result) -> {
//                if (mtcCode == MtcCode.SUCCESS) {
//                    Log.d("KSJ111", "mtcAiConfigSet suc" );
//                    //showToast("set thresh : " + m_fThreshValue);
//                    AiConfig.setInstance(aiConfigNew);
//                } else {
//                    Log.d("KSJ111", "mtcAiConfigSet fail" );
//                    showToast(getMtcErrorMsg(mtcCode));
//                }
//            });
//        }


    }

    public void setDeviceIRLedON()
    {
        //if(m_bSettingIRLED == true)
        {
            byte autoClose = (byte) 0x00;
            if (senseTimeMtc.getmDeviceModule() == SenseTimeMtc.M30) autoClose = 0x03;
            mClient.mtcDeviceIRSet(0xC8, autoClose, (mtcCode, result) -> {
                if (mtcCode != MtcCode.SUCCESS) {
                    Logger.e("setDeviceIRLedON - error message of mtcDeviceIRSet " + getMtcErrorMsg(mtcCode));
                }
            });
        }

    }

    public void setDeviceIRLedOFF()
    {
        //if(m_bSettingIRLED == true)
        {
            //Log.d("KSJ", "setDeviceIRLedOFF " + m_bSettingIRLED);
            mClient.mtcDeviceIRSet(0x00, 0x00, (mtcCode, result) -> {
                if (mtcCode != MtcCode.SUCCESS) {
                    Log.e(TAG, "error message of mtcDeviceIRSet" + getMtcErrorMsg(mtcCode));
                }
            });
        }
    }

    public void setDeviceAntiFlickerset(boolean bRet)
    {
//        mClient.mtcDeviceAntiFlickerSet(0x00, 0x01, 0x01, (mtcCode, result) -> {
//            if (mtcCode != MtcCode.SUCCESS) {
//                Log.e(TAG, "error message of mtcDeviceAntiFlickerSet" + getMtcErrorMsg(mtcCode));
//            }
//        });
        Log.d(TAG, "[setDeviceAntiFlickerset] bRet [" + bRet + "]");
        AiConfig aiConfig = AiConfig.getInstance();

        if(bRet == false)
        {
            aiConfig.setAeMode(0);
        }
        else if(bRet == true)
        {
            aiConfig.setAeMode(1);
        }

        Gson gson = new Gson();
        String aiConfigString = gson.toJson(aiConfig);

        AiConfig aiConfigNew = gson.fromJson(Util.stringToJSON(aiConfigString), AiConfig.class);

        if (aiConfigNew == null || !aiConfigNew.isValueValid()) {
            Log.d(TAG, "jglee - setDeviceAntiFlickerset aiConfigNew.isValueValid() Configue Error");
            //showToast(R.string.check_ai_config);
        } else {
            mClient.mtcAiConfigSet(gson.toJson(aiConfigNew), (mtcCode, result) -> {
                if (mtcCode == MtcCode.SUCCESS) {
                    Log.d(TAG, "jglee - setDeviceAntiFlickerset aiConfigNew.setDeviceAntiFlickerset success");
                    //showToast("set thresh : " + m_fThreshValue);
                    AiConfig.setInstance(aiConfigNew);
                } else {
                    showToast(getMtcErrorMsg(mtcCode));
                }
            });
        }
    }

    public void setAiConfig() {
        Log.d("KSJ111", "jglee - setAiConfig");
        AiConfig aiConfig = AiConfig.getInstance();
        Log.d(TAG, "[setAiConfig] m_fThreshValue [" + m_fThreshValue + "]");
        aiConfig.setRecognitionThresh(m_fThreshValue);
        aiConfig.setVerifyThresh(m_fThreshValue);
        Gson gson = new Gson();
        String aiConfigString = gson.toJson(aiConfig);
        AiConfig aiConfigNew = gson.fromJson(Util.stringToJSON(aiConfigString), AiConfig.class);

        if (aiConfigNew == null || !aiConfigNew.isValueValid()) {
            Log.d(TAG, "jglee - setAiConfig aiConfigNew.isValueValid() Configue Error");
            //showToast(R.string.check_ai_config);
        } else {
            mClient.mtcAiConfigSet(gson.toJson(aiConfigNew), (mtcCode, result) -> {
                if (mtcCode == MtcCode.SUCCESS) {
                    //showToast("set thresh : " + m_fThreshValue);
                    Log.d("KSJ111", "jglee - mtcAiConfigSet Set Success");
                    AiConfig.setInstance(aiConfigNew);
                } else {
                    Log.d("KSJ111", "jglee - mtcAiConfigSet Set Error, " + getMtcErrorMsg(mtcCode));
                    showToast(getMtcErrorMsg(mtcCode));
                }
            });
        }
        //Log.d("KSJ", Util.stringToJSON(aiConfigString));
        //setAiConfigDialog.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e(TAG, "onStart");

       /* if(!m_bLauncherStart)
        {
            if (senseTimeMtc.getmDeviceModule() == SenseTimeMtc.M10) {
                if (senseTimeMtc.getmM10_L_P() == SenseTimeMtc.PORTRAIT_90 || senseTimeMtc.getmM10_L_P() == SenseTimeMtc.PORTRAIT_270) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //force portrait if you wish.
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            } else { //M20
                //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }

            String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            permissionGranted(permissions, 0);
            synchronized (mSyncUSBMonitor) {
                mUSBMonitor.register();
            }
        }*/
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.e(TAG, "onResume,  mUVCCameraView.isAvailable():" + mUVCCameraView.isAvailable() + ",   isRunning:" + isRunning);
        //MClient.getInstance().setReceiveCallback(myIReceiveCallback);


       /* if (!isRunning) {
            isRunning = true;
            MClient.getInstance().setReceiveCallback(myIReceiveCallback);
            requestPermissionDevice();

            if (senseTimeMtc.isPauseAI()) {//Camera Tracking view On/Off 하는 부분
                mClient.mtcAiPause((mtcCode, result) -> {
                    Logger.d("mtcAiPause's result:" + getMtcErrorMsg(mtcCode));
                });
            } else {//用户手动去恢复了AI识别算法，默认模式
                mClient.mtcAiResume((mtcCode, result) -> {
                    Logger.d("mtcAiResume's result:" + getMtcErrorMsg(mtcCode));
                });
            }
            if (senseTimeMtc.getIsIRRGBMode() == SenseTimeMtc.IR_RGB_NONE && SenseTimeMtc.M20 == senseTimeMtc.getmDeviceModule()) {
                //不知道是IR还是RGB模式下，默认换成RGB模式
                irRGBSwitch(0);
            }
        }*/
    }

    @Override
    protected void onPause() {
        Log.e(TAG, "onPause");

        super.onPause();
        //this.finish();

    }

    @Override
    protected void onStop() {
        Log.d(TAG, "jglee --- onStop");

        m_bLauncherStart = false;
        m_isResultView = false;
        m_isSwitchState = false;

        MClient.getInstance().setReceiveCallback(null);
        super.onStop();

        Logger.d("onStop2");
        clearCanvas();
        isRunning = false;
        releaseAndRequestCamera(null);
        lastUpdatePreviewDataMillis = 0;
        //m_bLauncherStart = false;


        //Note 为了防止摄像头过烫，和节省能源，在onStop里自动关闭camera，在onResume里自动打开camera。
       /* // 关闭RGB摄像头，节省能量，防止模组过热
        mClient.mtcDeviceCameraStatusSet(0x01, 0x00, (mtcCode, result) -> {
            if (mtcCode != MtcCode.SUCCESS) {
                Logger.e("error message of close RGB camera:" + getMtcErrorMsg(mtcCode));
            }
        });

        // 关闭IR摄像头，节省能量，防止模组过热
        mClient.mtcDeviceCameraStatusSet(0x01, 0x01, (mtcCode, result) -> {
            if (mtcCode != MtcCode.SUCCESS) {
                Logger.e("error message of close IR camera:" + getMtcErrorMsg(mtcCode));
            }
        });*/

        //离开视频页面时，最好关闭人脸识别功能，因为人脸识别的数据有可能包含图片数据，
        // 同时做其他动作比如升级固件、添加底库就容易导致串口通信承载不了那么大数据
        mClient.mtcAiPause((mtcCode, result) -> {
            if (mtcCode != MtcCode.SUCCESS) {
                Logger.e("mtcAiPause error message:" + getMtcErrorMsg(mtcCode));
            }
        });



    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "jglee --- onDestroy");
        removeview();
        if (KeyTimer_reboot != null) {
            KeyTimer_reboot.cancel();
            KeyTimer_reboot = null;
        }

        try {
            //mAVcEncoder.close();
            kr.co.icontrols.ilp300_700.MainActivity.m_bFaceDetect = false;
        }
        catch (Exception ex) {
            Log.e(TAG, "AvcEncoder init error1");
        }
        super.onDestroy();
        synchronized (mSyncUSBMonitor) {
            if (mUSBMonitor != null) {
                mUSBMonitor.unregister();
                mUSBMonitor.destroy();
                mUSBMonitor = null;
            }
        }
    }

    private void updateScreen() {

        try {
            LOG("[updateScreen] MainActivity.mCallController.mCallInfo.getRESI() = " + kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI());
            if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.IDLE) {
                if (DataClasses.RemoteIDInfo.strDong != "") {
                    // 첫자리에 "0"이 출력되지 않도록 숫자로 변경하면서 "0"을 제거하고, 다시 String으로 변환한다.
                    DataClasses.RemoteIDInfo.nDong = Integer.parseInt(DataClasses.RemoteIDInfo.strDong);
                    DataClasses.RemoteIDInfo.strDong = Integer.toString(DataClasses.RemoteIDInfo.nDong);
                }

                if (DataClasses.RemoteIDInfo.strHo != "") {
                    // 첫자리에 "0"이 출력되지 않도록 숫자로 변경하면서 "0"을 제거하고, 다시 String으로 변환한다.
                    DataClasses.RemoteIDInfo.nHo = Integer.parseInt(DataClasses.RemoteIDInfo.strHo);
                    DataClasses.RemoteIDInfo.strHo = Integer.toString(DataClasses.RemoteIDInfo.nHo);
                }
                strText_Instruction = TextResources.strInputResidenceInfo;
            } else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.TRYING_CALL) {
                strText_Instruction = TextResources.strTryingResidence;
                //mUSBCamera = new USBCamera();
            } else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.WAITNG_INVITE_ACK || kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.CALLED) {
//                setAnimation(true);
                strText_Instruction = TextResources.strCallingResidence;
            } else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.TALKING) {
                strText_Instruction = TextResources.strTalkingResidence;
                displayTalkVolume();
            } else {
//                setAnimation(false);
                strText_Instruction = "";
            }


            mTxtView_dong.setText(DataClasses.RemoteIDInfo.strDong); // 동 표시
            //String strDisplayDong = "";

            String strDisplayHo = "";
            if (DataClasses.RemoteIDInfo.bRentRoomSelected) strDisplayHo = DataClasses.RemoteIDInfo.strHo + "-" + DataClasses.RemoteIDInfo.nHo_Extension;
            else strDisplayHo = DataClasses.RemoteIDInfo.strHo;

            Log.w(TAG, "[updateScreen] strDisplayHo [" + strDisplayHo + "], strDisplayHo.length() [" + strDisplayHo.length() + "]");
            if (strDisplayHo.length() > MAXLENGTH_HO) {
                Log.w(TAG, "[updateScreen] ========== JEFF 1 ==========");
                mTxtView_ho.setTextSize(0, (float) nFontSize_DONGHO_Rent[Configure.ConfigValue.DEVICE_MODELTYPE]);
            }
            else {
                Log.w(TAG, "[updateScreen] ========== JEFF 2 ==========");
                mTxtView_ho.setTextSize(0, (float) nFontSize_DONGHO[Configure.ConfigValue.DEVICE_MODELTYPE]);
            }

            mTxtView_ho.setText(strDisplayHo); // 호 표시
            mTxtView_ment.setText(strText_Instruction); // 하단 안내 문구
        } catch (Exception e) {
            Log.e(TAG, "[Exception] updateScreen()");
            e.printStackTrace();
        }
    }

    int nTalkVolume = Global.getMoIPoVolume();
    private void displayTalkVolume() {
        try {
            if (!kr.co.icontrols.ilp300_700.MainActivity.mCallController.bTalkTestModeEnable) return;
            strText_Instruction = strText_Instruction + " [음량 " + nTalkVolume + "]";
        } catch (Exception e) {
            Log.e(TAG, "[Exception] displayTalkVolume() : " + e);
            e.printStackTrace();
        }
    }

    protected void displayDeviceName() {

        try {
            if (Declare.DeviceInfo.Type == Declare.DeviceType.RESIDENCE) {
                strText_DeviceName = Configure.ConfigValue.strDevice_Dong + "동 " + Configure.ConfigValue.strDevice_ID + "호 세대";
            } else if (Declare.DeviceInfo.Type == Declare.DeviceType.LOBBY) {
                if ((Integer.parseInt(Configure.ConfigValue.strDevice_Dong) % 100) == 0)
                    strText_DeviceName = "관리동 " + Configure.ConfigValue.strDevice_ID + "번 로비";
                else
                    strText_DeviceName = Configure.ConfigValue.strDevice_Dong + "동 " + Configure.ConfigValue.strDevice_ID + "번 로비";
            } else if (Declare.DeviceInfo.Type == Declare.DeviceType.GUARD) {
                if ((Integer.parseInt(Configure.ConfigValue.strDevice_Dong) % 100) == 0)
                    strText_DeviceName = "관리동 " + Configure.ConfigValue.strDevice_ID + "번 경비";
                else
                    strText_DeviceName = Configure.ConfigValue.strDevice_Dong + "동 " + Configure.ConfigValue.strDevice_ID + "번 경비";
            }
            Log.d(TAG, "[displayDeviceName] strText_DeviceName [" + strText_DeviceName + "]");
            mTxtView_dong.setText(Configure.ConfigValue.strDevice_Dong);
            lobby_up.setText(strText_DeviceName);
            lobby_up.setSingleLine();
            lobby_up.setEllipsize(TextUtils.TruncateAt.END);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] displayDeviceName() : " + e);
            e.printStackTrace();
        }
    }

    protected void infoResidence(){
        lobby_up = findViewById(R.id.lobby_up); // 로비 text view
        lobby_down = findViewById(R.id.lobby_down); // 하단 안내 text view

        if(Global.bDevicebootup)
            lobby_down.setText("   세대 호출 : 호수 + 호출");
        else
            lobby_down.setText("경비실 호출 : 경비실 + 호출");
        //if (Global.bDevicebootup) lobby_down.setText("세대 호출 : 호수 + 호출");
        //else lobby_down.setText("경비실 호출 : 경비실 + 호출");

        displayDeviceName(); // 로비 info
    }

    public void removeview()
    {
        RelativeLayout container = findViewById(R.id.precam);
        container.removeAllViews();
    }

    protected void initView() {
        Logger.d("initView");
        setContentView(R.layout.activity_u_s_b_camera2);


        lobby_view = findViewById(R.id.lobby);
        Residence_view = findViewById(R.id.Residence);
        layout_guard_view = findViewById(R.id.layout_guard);

        sensepw_view = findViewById(R.id.sensepw);
        sensemain_view = findViewById(R.id.sensemain);
        senseadd_view = findViewById(R.id.senseadd);
        sensedistance_view = findViewById(R.id.sensedistance);
        sensesettingall_view = findViewById(R.id.sensesettingall);
        userpw_view = findViewById(R.id.userpw);

        tv_time = findViewById(R.id.tv_time);
        mTxtView_ho = (TextView)findViewById(R.id.tv_ho);
        mTxtView_dong = (TextView)findViewById(R.id.tv_dong);
        mTxtView_ho_pwd = (TextView)findViewById(R.id.tv_ho_user);
        mTxtView_dong_pwd = (TextView)findViewById(R.id.tv_dong_user);
        mTxtView_ment = (TextView)findViewById(R.id.tv_ment);
        m_guard_img = (ImageView) findViewById(R.id.guard_img);
        guard_text = (TextView)findViewById(R.id.lobby_guard);
        pw_ment = (TextView)findViewById(R.id.pw_ment);
        pw_ment_user = (TextView)findViewById(R.id.pw_ment_user);

        guard_text.setText("호출버튼을 누르세요.");
        ////////////////////////////////////////////////////////////////////////////////////////

        infoResidence(); // 로비 정보 호출

        ///////////////////////////////////////////////////////////////////////////////////////


        layout_guard_view.setVisibility(View.GONE);
        Residence_view.setVisibility(View.GONE);
        sensepw_view.setVisibility(View.GONE);
        userpw_view.setVisibility(View.GONE);
        sensemain_view.setVisibility(View.GONE);
        senseadd_view.setVisibility(View.GONE);
        sensesettingall_view.setVisibility(View.GONE);
        sensedistance_view.setVisibility(View.GONE);



        int layout_w = ILP_300_SCREEN_SIZE_FULL_W;
        int layout_h = ILP_300_SCREEN_SIZE_FULL_H;


        RelativeLayout.LayoutParams Params = new RelativeLayout.LayoutParams(layout_w, layout_h);
        Params.setMargins(0, 0, 0, 0);

        RelativeLayout container = findViewById(R.id.precam);

        mTrackView = new UVCCameraSurfaceView(mContext);//(UVCCameraSurfaceView) findViewById(R.id.camera_face_sv);
        container.addView(mTrackView, Params);
        mTrackView.setZOrderOnTop(true);
        mTrackView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        //mTrackView.wid
        //mTrackView.setAspectRatio(22, 17);
        mTrackView.setAspectRatio(30, 17);
        //mTrackView.setScaleX(2f); //NOTE mirror image
        //mTrackView.setScaleY(-1f); // only for debug
        mUVCCameraView = new UVCCameraTextureView(mContext);
        container.addView(mUVCCameraView, Params);

        //mUVCCameraView.setRotation(90);
        //mTrackView.setRotation(90);
        mUVCCameraView.setSurfaceTextureListener(mSurfaceTextureListener);
        //mUVCCameraView.setAspectRatio(8, 17);
        mUVCCameraView.setAspectRatio(9, 16);
        mUVCCameraView.setScaleX(-1); //NOTE mirror image
        mUVCCameraView.setScaleY(2.2f); // 2.2 only for debug

        mTrackView.setKeepScreenOn(true);
        //mUVCCameraView.set

        initSensePW();

        mAnimation = AnimationUtils.loadAnimation(this, R.anim.rotate_call);
        mAnimation.setInterpolator(AnimationUtils.loadInterpolator(this, android.R.anim.linear_interpolator));
        ///////////////////////////////////////////////////////////////////////////////////////

//        if (mUVCCameraView.getVisibility() == View.VISIBLE || mTrackView.getVisibility() == View.VISIBLE) {
//            mTrackView.setZOrderOnTop(true);
//            lobby_img.setVisibility(View.GONE);
//            lobby_up.setVisibility(View.GONE);
//            lobby_down.setVisibility(View.GONE);
//        }else{
//            mUVCCameraView.setVisibility(View.INVISIBLE);
//            lobby_img.setVisibility(View.VISIBLE);
//            lobby_up.setVisibility(View.VISIBLE);
//            lobby_down.setVisibility(View.VISIBLE);
//        }

        ///////////////////////////////////////////////////////////////////////////////////////

        Logger.d("mUVCCameraView's width:" + mUVCCameraView.getWidth() + ",  mUVCCameraView's height:" + mUVCCameraView.getHeight());

        initTextPaint();
        mTrackView.setOnClickListener(view ->
        {
            /*
            if (controlContentView.getVisibility() == View.VISIBLE) {
                controlContentView.setVisibility(View.GONE);
            } else {
                controlContentView.setVisibility(View.VISIBLE);
            }*/
            //controlContentView.setVisibility(View.GONE);
        });
        mTrackView.setKeepScreenOn(true);

        NewRunnable nr = new NewRunnable() ;
        Thread t = new Thread(nr) ;
        t.start() ;

    }


    protected void initView_old() {
        Logger.d("initView");
        setContentView(R.layout.activity_u_s_b_camera2);

        mTrackView = (UVCCameraSurfaceView) findViewById(R.id.camera_face_sv);
        lobby_view = findViewById(R.id.lobby);
        Residence_view = findViewById(R.id.Residence);
        layout_guard_view = findViewById(R.id.layout_guard);

        sensepw_view = findViewById(R.id.sensepw);
        sensemain_view = findViewById(R.id.sensemain);
        senseadd_view = findViewById(R.id.senseadd);
        sensedistance_view = findViewById(R.id.sensedistance);
        sensesettingall_view = findViewById(R.id.sensesettingall);
        userpw_view = findViewById(R.id.userpw);

        tv_time = findViewById(R.id.tv_time);
        mTxtView_ho = (TextView)findViewById(R.id.tv_ho);
        mTxtView_dong = (TextView)findViewById(R.id.tv_dong);
        mTxtView_ho_pwd = (TextView)findViewById(R.id.tv_ho_user);
        mTxtView_dong_pwd = (TextView)findViewById(R.id.tv_dong_user);
        mTxtView_ment = (TextView)findViewById(R.id.tv_ment);
        m_guard_img = (ImageView) findViewById(R.id.guard_img);
        guard_text = (TextView)findViewById(R.id.lobby_guard);
        pw_ment = (TextView)findViewById(R.id.pw_ment);
        pw_ment_user = (TextView)findViewById(R.id.pw_ment_user);

        guard_text.setText("호출버튼을 누르세요.");
        ////////////////////////////////////////////////////////////////////////////////////////

        infoResidence(); // 로비 정보 호출

        ///////////////////////////////////////////////////////////////////////////////////////


        layout_guard_view.setVisibility(View.GONE);
        Residence_view.setVisibility(View.GONE);
        sensepw_view.setVisibility(View.GONE);
        userpw_view.setVisibility(View.GONE);
        sensemain_view.setVisibility(View.GONE);
        senseadd_view.setVisibility(View.GONE);
        sensesettingall_view.setVisibility(View.GONE);
        sensedistance_view.setVisibility(View.GONE);
        mTrackView.setZOrderOnTop(true);
        mTrackView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        //mTrackView.wid
        //mTrackView.setAspectRatio(22, 17);
        mTrackView.setAspectRatio(30, 17);
        //mTrackView.setScaleX(2f); //NOTE mirror image
        //mTrackView.setScaleY(-1f); // only for debug
        mUVCCameraView = (UVCCameraTextureView) findViewById(R.id.camera_texture_view);

        //mUVCCameraView.setRotation(90);
        //mTrackView.setRotation(90);
        mUVCCameraView.setSurfaceTextureListener(mSurfaceTextureListener);
        //mUVCCameraView.setAspectRatio(8, 17);
        mUVCCameraView.setAspectRatio(9, 16);
        mUVCCameraView.setScaleX(-3f); //-2.2 NOTE mirror image
        mUVCCameraView.setScaleY(2.2f); // 2.2 only for debug
        //mUVCCameraView.set

        initSensePW();

        mAnimation = AnimationUtils.loadAnimation(this, R.anim.rotate_call);
        mAnimation.setInterpolator(AnimationUtils.loadInterpolator(this, android.R.anim.linear_interpolator));
        ///////////////////////////////////////////////////////////////////////////////////////

//        if (mUVCCameraView.getVisibility() == View.VISIBLE || mTrackView.getVisibility() == View.VISIBLE) {
//            mTrackView.setZOrderOnTop(true);
//            lobby_img.setVisibility(View.GONE);
//            lobby_up.setVisibility(View.GONE);
//            lobby_down.setVisibility(View.GONE);
//        }else{
//            mUVCCameraView.setVisibility(View.INVISIBLE);
//            lobby_img.setVisibility(View.VISIBLE);
//            lobby_up.setVisibility(View.VISIBLE);
//            lobby_down.setVisibility(View.VISIBLE);
//        }

        ///////////////////////////////////////////////////////////////////////////////////////

        Logger.d("mUVCCameraView's width:" + mUVCCameraView.getWidth() + ",  mUVCCameraView's height:" + mUVCCameraView.getHeight());

        initTextPaint();
        mTrackView.setOnClickListener(view ->
        {
            /*
            if (controlContentView.getVisibility() == View.VISIBLE) {
                controlContentView.setVisibility(View.GONE);
            } else {
                controlContentView.setVisibility(View.VISIBLE);
            }*/
            //controlContentView.setVisibility(View.GONE);
        });
        mTrackView.setKeepScreenOn(true);

        NewRunnable nr = new NewRunnable() ;
        Thread t = new Thread(nr) ;
        t.start() ;

    }

    private void initSensePW()
    {
        m_imageViewPW1 = findViewById(R.id.img_blank_pw1);
        m_imageViewPW2 = findViewById(R.id.img_blank_pw2);
        m_imageViewPW3 = findViewById(R.id.img_blank_pw3);
        m_imageViewPW4 = findViewById(R.id.img_blank_pw4);

        m_imageViewPW1_user = findViewById(R.id.img_blank_pw1_user);
        m_imageViewPW2_user = findViewById(R.id.img_blank_pw2_user);
        m_imageViewPW3_user = findViewById(R.id.img_blank_pw3_user);
        m_imageViewPW4_user = findViewById(R.id.img_blank_pw4_user);

        m_txtDistance = findViewById(R.id.item_01_distance);

        m_txtAdd_dong = findViewById(R.id.input_01_add);
        m_txtAdd_ho = findViewById(R.id.input_02_add);
        m_txtAdd_num = findViewById(R.id.input_03_add);
        m_txtAdd_result = findViewById(R.id.item_02_add);

        m_txtAISet = findViewById(R.id.tv_ai_setting);
        m_txtVideoSet = findViewById(R.id.tv_show_video);
        m_txtVideoDelete = findViewById(R.id.tv_video_del);
        m_txtVideoRecog = findViewById(R.id.tv_video_recog);
        m_txtVideoMenu = findViewById(R.id.tv_video_menu);

        //m_txtVideoMenu.setText("* : 이전 페이지 이동 \n # : 다음 페이지 이동");
        m_txtDeviceVersion = findViewById(R.id.tv_device_version);

        m_Img_ampm = findViewById(R.id.img_ampm);
        m_Img_hour_ten = findViewById(R.id.img_hour_ten);
        m_Img_hour_units = findViewById(R.id.img_hour_units);
        m_Img_min_tens = findViewById(R.id.img_min_tens);
        m_Img_min_units = findViewById(R.id.img_min_units);
        m_Img_lobby = findViewById(R.id.lobby_img);
        m_Img_split = findViewById(R.id.img_time_split);

        if(Global.bDevicebootup)
        {
            //m_Img_lobby.setImageResource(R.drawable.bg_time_new);
            m_Img_lobby.setVisibility(View.GONE);
            m_Img_ampm.setVisibility(View.VISIBLE);
            m_Img_hour_ten.setVisibility(View.VISIBLE);
            m_Img_hour_units.setVisibility(View.VISIBLE);
            m_Img_min_tens.setVisibility(View.VISIBLE);
            m_Img_min_units.setVisibility(View.VISIBLE);
            m_Img_split.setVisibility(View.VISIBLE);
        }
        else
        {
            //m_Img_lobby.setImageResource(R.drawable.reboot_back);
            m_Img_lobby.setVisibility(View.VISIBLE);
            m_Img_ampm.setVisibility(View.GONE);
            m_Img_hour_ten.setVisibility(View.GONE);
            m_Img_hour_units.setVisibility(View.GONE);
            m_Img_min_tens.setVisibility(View.GONE);
            m_Img_min_units.setVisibility(View.GONE);
            m_Img_split.setVisibility(View.GONE);
        }
    }

    int m_nHour_Tens_old = 0;
    int m_nHour_Units_old = 0;
    int m_nMin_Tens_old = 0;
    int m_nMin_Units_old = 0;

    protected void setImage_Time() {
        try {

            boolean bSetTime = false;
            Calendar cal = Calendar.getInstance();

            int hour = cal.get(Calendar.HOUR);
            int min = cal.get(Calendar.MINUTE);

            int nAMPM = cal.get(Calendar.AM_PM);

            int nHour_Tens = hour / 10;
            int nHour_Units = hour % 10;
            int nMin_Tens = min / 10;
            int nMin_Units = min % 10;

            if(m_nHour_Tens_old != nHour_Tens) bSetTime = true;
            if(m_nHour_Units_old != nHour_Units) bSetTime = true;
            if(m_nMin_Tens_old != nMin_Tens) bSetTime = true;
            if(m_nMin_Units_old != nMin_Units) bSetTime = true;

            m_nHour_Tens_old = nHour_Tens;
            m_nHour_Units_old = nHour_Units;
            m_nMin_Tens_old = nMin_Tens;
            m_nMin_Units_old = nMin_Units;
            LOG("[setImage_Time] nHour_Tens [" + nHour_Tens + "], nHour_Units [" + nHour_Units + "], nMin_Tens [" + nMin_Tens + "], nMin_Units [" + nMin_Units + "]");

            if(bSetTime) {

                if(nAMPM == 1 && nHour_Tens == 0 && nHour_Units == 0)
                {
                    nHour_Tens = 1;
                    nHour_Units = 2;
                }

                int[] AMPMImages_300 = new int[]{R.drawable.image_am, R.drawable.image_pm};
                int[] AMPMImages_700 = new int[]{R.drawable.time_am, R.drawable.time_pm};
                int[] TimeImages_300 = new int[]
                        {R.drawable.main_time_0, R.drawable.main_time_1, R.drawable.main_time_2, R.drawable.main_time_3, R.drawable.main_time_4,
                                R.drawable.main_time_5, R.drawable.main_time_6, R.drawable.main_time_7, R.drawable.main_time_8, R.drawable.main_time_9};
                int[] TimeImages_700 = new int[]
                        {R.drawable.num_time_0, R.drawable.num_time_1, R.drawable.num_time_2, R.drawable.num_time_3, R.drawable.num_time_4,
                                R.drawable.num_time_5, R.drawable.num_time_6, R.drawable.num_time_7, R.drawable.num_time_8, R.drawable.num_time_9};
                m_Img_ampm.setImageResource(AMPMImages_300[nAMPM]);

//                if ((nHour_Tens == 0) && (nMin_Tens == 0))
//                {
//                    nHour_Tens = 1;
//                    nHour_Tens = 2;
//                }

                m_Img_hour_ten.setImageResource(TimeImages_300[nHour_Tens]);
                m_Img_hour_units.setImageResource(TimeImages_300[nHour_Units]);
                m_Img_min_tens.setImageResource(TimeImages_300[nMin_Tens]);
                m_Img_min_units.setImageResource(TimeImages_300[nMin_Units]);
            }


        } catch (Exception e) {
            Log.e(TAG, "[Exception] setImage_Time()");
            e.printStackTrace();
        }
    }

    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            m_UIRefreshSet = false;

            //Log.d(TAG, "jglee - UI Thread m_bSenseSettingState : " + m_bSenseSettingState + ", m_bFaceCatch : " +m_bFaceCatch );

            if(m_bSenseSettingState)
            {
                m_bLauncherStart = false;
                if(lobby_view.getVisibility() == View.VISIBLE)
                    lobby_view.setVisibility(View.GONE);

                if(Residence_view.getVisibility() == View.VISIBLE)
                    Residence_view.setVisibility(View.GONE);

                if(Residence_view.getVisibility() == View.VISIBLE)
                    Residence_view.setVisibility(View.GONE);

                if(m_iSenseSettingPage == 1)
                {
                    if(sensepw_view.getVisibility() == View.GONE)
                        sensepw_view.setVisibility(View.VISIBLE);

                    if(userpw_view.getVisibility() == View.VISIBLE)
                        userpw_view.setVisibility(View.GONE);

                    if(sensemain_view.getVisibility() == View.VISIBLE)
                        sensemain_view.setVisibility(View.GONE);

                    if(sensedistance_view.getVisibility() == View.VISIBLE)
                        sensedistance_view.setVisibility(View.GONE);

                    if(senseadd_view.getVisibility() == View.VISIBLE)
                        senseadd_view.setVisibility(View.GONE);

                    if(sensesettingall_view.getVisibility() == View.VISIBLE)
                        sensesettingall_view.setVisibility(View.GONE);

                }
                else if(m_iSenseSettingPage == 2)
                {
                    if(sensepw_view.getVisibility() == View.VISIBLE)
                        sensepw_view.setVisibility(View.GONE);

                    if(userpw_view.getVisibility() == View.VISIBLE)
                        userpw_view.setVisibility(View.GONE);

                    if(sensemain_view.getVisibility() == View.GONE)
                        sensemain_view.setVisibility(View.VISIBLE);

                    if(sensedistance_view.getVisibility() == View.VISIBLE)
                        sensedistance_view.setVisibility(View.GONE);

                    if(senseadd_view.getVisibility() == View.VISIBLE)
                        senseadd_view.setVisibility(View.GONE);

                    if(sensesettingall_view.getVisibility() == View.VISIBLE)
                        sensesettingall_view.setVisibility(View.GONE);
                }
                else if(m_iSenseSettingPage == 3)
                {
                    if(sensepw_view.getVisibility() == View.VISIBLE)
                        sensepw_view.setVisibility(View.GONE);

                    if(userpw_view.getVisibility() == View.VISIBLE)
                        userpw_view.setVisibility(View.GONE);

                    if(sensemain_view.getVisibility() == View.VISIBLE)
                        sensemain_view.setVisibility(View.GONE);

                    if(sensedistance_view.getVisibility() == View.GONE)
                        sensedistance_view.setVisibility(View.VISIBLE);

                    if(senseadd_view.getVisibility() == View.VISIBLE)
                        senseadd_view.setVisibility(View.GONE);

                    if(sensesettingall_view.getVisibility() == View.VISIBLE)
                        sensesettingall_view.setVisibility(View.GONE);
                }
                else if(m_iSenseSettingPage == 4)
                {
                    if(sensepw_view.getVisibility() == View.VISIBLE)
                        sensepw_view.setVisibility(View.GONE);

                    if(userpw_view.getVisibility() == View.VISIBLE)
                        userpw_view.setVisibility(View.GONE);

                    if(sensemain_view.getVisibility() == View.VISIBLE)
                        sensemain_view.setVisibility(View.GONE);

                    if(sensedistance_view.getVisibility() == View.VISIBLE)
                        sensedistance_view.setVisibility(View.GONE);

                    if(senseadd_view.getVisibility() == View.GONE)
                        senseadd_view.setVisibility(View.VISIBLE);

                    if(sensesettingall_view.getVisibility() == View.VISIBLE)
                        sensesettingall_view.setVisibility(View.GONE);
                }
                else if(m_iSenseSettingPage == 5)
                {
                    if(sensepw_view.getVisibility() == View.VISIBLE)
                        sensepw_view.setVisibility(View.GONE);

                    if(userpw_view.getVisibility() == View.VISIBLE)
                        userpw_view.setVisibility(View.GONE);

                    if(sensemain_view.getVisibility() == View.VISIBLE)
                        sensemain_view.setVisibility(View.GONE);

                    if(sensedistance_view.getVisibility() == View.VISIBLE)
                        sensedistance_view.setVisibility(View.GONE);

                    if(senseadd_view.getVisibility() == View.VISIBLE)
                        senseadd_view.setVisibility(View.GONE);

                    if(sensesettingall_view.getVisibility() == View.GONE)
                        sensesettingall_view.setVisibility(View.VISIBLE);
                }
                else if(m_iSenseSettingPage == 99)
                {
                    if(userpw_view.getVisibility() == View.GONE)
                        userpw_view.setVisibility(View.VISIBLE);

                    if(sensepw_view.getVisibility() == View.VISIBLE)
                        sensepw_view.setVisibility(View.GONE);

                    if(sensemain_view.getVisibility() == View.VISIBLE)
                        sensemain_view.setVisibility(View.GONE);

                    if(sensedistance_view.getVisibility() == View.VISIBLE)
                        sensedistance_view.setVisibility(View.GONE);

                    if(senseadd_view.getVisibility() == View.VISIBLE)
                        senseadd_view.setVisibility(View.GONE);

                    if(sensesettingall_view.getVisibility() == View.VISIBLE)
                        sensesettingall_view.setVisibility(View.GONE);
                }

                clearCanvas();
            }
            else if(!m_bSenseSettingState)
            {
                if(sensepw_view.getVisibility() == View.VISIBLE)
                    sensepw_view.setVisibility(View.GONE);

                if(userpw_view.getVisibility() == View.VISIBLE)
                    userpw_view.setVisibility(View.GONE);

                if(sensemain_view.getVisibility() == View.VISIBLE)
                    sensemain_view.setVisibility(View.GONE);

                if(sensedistance_view.getVisibility() == View.VISIBLE)
                    sensedistance_view.setVisibility(View.GONE);

                if(senseadd_view.getVisibility() == View.VISIBLE)
                    senseadd_view.setVisibility(View.GONE);

                if(sensepw_view.getVisibility() == View.VISIBLE)
                    sensepw_view.setVisibility(View.GONE);

                if(userpw_view.getVisibility() == View.VISIBLE)
                    userpw_view.setVisibility(View.GONE);

                if(sensemain_view.getVisibility() == View.VISIBLE)
                    sensemain_view.setVisibility(View.GONE);

                if(sensedistance_view.getVisibility() == View.VISIBLE)
                    sensedistance_view.setVisibility(View.GONE);

                if(senseadd_view.getVisibility() == View.VISIBLE)
                    senseadd_view.setVisibility(View.GONE);

                if(sensesettingall_view.getVisibility() == View.VISIBLE)
                    sensesettingall_view.setVisibility(View.GONE);

/*                if(!m_isSwitchState)
                {
                    if(lobby_view.getVisibility() == View.GONE)
                        lobby_view.setVisibility(View.VISIBLE);

                    if(Global.bDevicebootup)
                    {

                        if(m_Img_lobby.getVisibility() == View.VISIBLE)
                            m_Img_lobby.setVisibility(View.GONE);
                        //m_Img_lobby.setImageResource(R.drawable.bg_time_new);
                        if(m_Img_ampm.getVisibility() == View.GONE)
                            m_Img_ampm.setVisibility(View.VISIBLE);

                        if(m_Img_hour_ten.getVisibility() == View.GONE)
                            m_Img_hour_ten.setVisibility(View.VISIBLE);

                        if(m_Img_hour_units.getVisibility() == View.GONE)
                            m_Img_hour_units.setVisibility(View.VISIBLE);

                        if(m_Img_min_tens.getVisibility() == View.GONE)
                            m_Img_min_tens.setVisibility(View.VISIBLE);

                        if(m_Img_min_units.getVisibility() == View.GONE)
                            m_Img_min_units.setVisibility(View.VISIBLE);

                        if(m_Img_split.getVisibility() == View.GONE)
                            m_Img_split.setVisibility(View.VISIBLE);
                        setImage_Time();
                        lobby_down.setText("   세대 호출 : 호수 + 호출");

                    }
                    else
                    {
                        if(m_Img_lobby.getVisibility() == View.GONE)
                            m_Img_lobby.setVisibility(View.VISIBLE);

                        //m_Img_lobby.setImageResource(R.drawable.reboot_back);

                        if(m_Img_ampm.getVisibility() == View.VISIBLE)
                            m_Img_ampm.setVisibility(View.GONE);

                        if(m_Img_hour_ten.getVisibility() == View.VISIBLE)
                            m_Img_hour_ten.setVisibility(View.GONE);

                        if(m_Img_hour_units.getVisibility() == View.VISIBLE)
                            m_Img_hour_units.setVisibility(View.GONE);

                        if(m_Img_min_tens.getVisibility() == View.VISIBLE)
                            m_Img_min_tens.setVisibility(View.GONE);

                        if(m_Img_min_units.getVisibility() == View.VISIBLE)
                            m_Img_min_units.setVisibility(View.GONE);

                        if(m_Img_split.getVisibility() == View.VISIBLE)
                            m_Img_split.setVisibility(View.GONE);

                        lobby_down.setText("경비실 호출 : 경비실 + 호출");

                    }

                }
                else if((m_isSwitchState))
                {
                    if(lobby_view.getVisibility() == View.VISIBLE)
                        lobby_view.setVisibility(View.GONE);
                }*/


                if(m_bFaceCatch < 0)
                {
                    if(lobby_view.getVisibility() == View.GONE)
                        lobby_view.setVisibility(View.VISIBLE);

                    if(Global.bDevicebootup)
                    {

                        if(m_Img_lobby.getVisibility() == View.VISIBLE)
                            m_Img_lobby.setVisibility(View.GONE);
                        //m_Img_lobby.setImageResource(R.drawable.bg_time_new);
                        if(m_Img_ampm.getVisibility() == View.GONE)
                            m_Img_ampm.setVisibility(View.VISIBLE);

                        if(m_Img_hour_ten.getVisibility() == View.GONE)
                            m_Img_hour_ten.setVisibility(View.VISIBLE);

                        if(m_Img_hour_units.getVisibility() == View.GONE)
                            m_Img_hour_units.setVisibility(View.VISIBLE);

                        if(m_Img_min_tens.getVisibility() == View.GONE)
                            m_Img_min_tens.setVisibility(View.VISIBLE);

                        if(m_Img_min_units.getVisibility() == View.GONE)
                            m_Img_min_units.setVisibility(View.VISIBLE);

                        if(m_Img_split.getVisibility() == View.GONE)
                            m_Img_split.setVisibility(View.VISIBLE);
                        setImage_Time();
                        lobby_down.setText("   세대 호출 : 호수 + 호출");

                    }
                    else
                    {
                        if(m_Img_lobby.getVisibility() == View.GONE)
                            m_Img_lobby.setVisibility(View.VISIBLE);

                        //m_Img_lobby.setImageResource(R.drawable.reboot_back);

                        if(m_Img_ampm.getVisibility() == View.VISIBLE)
                            m_Img_ampm.setVisibility(View.GONE);

                        if(m_Img_hour_ten.getVisibility() == View.VISIBLE)
                            m_Img_hour_ten.setVisibility(View.GONE);

                        if(m_Img_hour_units.getVisibility() == View.VISIBLE)
                            m_Img_hour_units.setVisibility(View.GONE);

                        if(m_Img_min_tens.getVisibility() == View.VISIBLE)
                            m_Img_min_tens.setVisibility(View.GONE);

                        if(m_Img_min_units.getVisibility() == View.VISIBLE)
                            m_Img_min_units.setVisibility(View.GONE);

                        if(m_Img_split.getVisibility() == View.VISIBLE)
                            m_Img_split.setVisibility(View.GONE);

                        lobby_down.setText("경비실 호출 : 경비실 + 호출");

                    }

                    m_bm_bFaceCatchCheck = false;

                }
                else if((m_bFaceCatch > 0))
                {
                    if(lobby_view.getVisibility() == View.VISIBLE)
                        lobby_view.setVisibility(View.GONE);
                    m_bm_bFaceCatchCheck = false;
                }


                if(!m_bCallState)
                {
                    residence_ho = "";
                    if(!m_bCallGuardState)
                    {
                        m_bLauncherStart = true;
                        //m_bEncoderState = false;
                    }
                    if(Residence_view.getVisibility() == View.VISIBLE)
                        Residence_view.setVisibility(View.GONE);

                }
                else if(m_bCallState)
                {

                    //m_isSwitchState = true;
                    m_bLauncherStart = false;
                    if(Residence_view.getVisibility() == View.GONE)
                        Residence_view.setVisibility(View.VISIBLE);

                    //m_bEncoderState = true;
                    if(kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.IDLE)
                    {
                        mTxtView_ment.setText(TextResources.strInputResidenceInfo);
                    }else if(kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.TRYING_CALL){
                        mTxtView_ment.setText(TextResources.strTryingResidence);
                        //m_bEncoderState = true;
                    }else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.WAITNG_INVITE_ACK || kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.CALLING){
                        mTxtView_ment.setText(TextResources.strCallingResidence);
                    }else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.TALKING){
                        mTxtView_ment.setText(TextResources.strTalkingResidence);
                    }else{
                        mTxtView_ment.setText(TextResources.strInputResidenceInfo);
                    }

                    updateScreen();
                    clearCanvas();
                }

                if(!m_bCallGuardState)
                {

                    if(!m_bCallState)
                    {
                        m_bLauncherStart = true;
                        //m_bEncoderState = false;
                    }

                    if(layout_guard_view.getVisibility() == View.VISIBLE)
                        layout_guard_view.setVisibility(View.GONE);

                }
                else if(m_bCallGuardState)
                {
                    //LOG("m_bCallGuardState true");
                    m_bLauncherStart = false;
                    m_isSwitchState = true;

                    if(m_bSettingIRLED == true) {
                        if (!m_bIRLEDState) {
                            setDeviceIRLedON();
                            m_bIRLEDState = true;
                        }
                    }

                    if(layout_guard_view.getVisibility() == View.GONE)
                        layout_guard_view.setVisibility(View.VISIBLE);
                    //m_bEncoderState = true;

                    if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.IDLE) {
                        guard_text.setText(TextResources_guad.strPressCallButton);
                    } else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.TRYING_CALL) {

                        guard_text.setText(TextResources_guad.strTryingGuard);
                    } else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.WAITNG_INVITE_ACK) {

                        guard_text.setText(TextResources_guad.strTryingGuard);
                    } else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.CALLED) {

                        guard_text.setText(TextResources_guad.strCallingGuard);

                        // 애니메이션 시작

                        if(!m_bAnimation_state)
                        {
                            mAnimation.setDuration(kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCTT.CALLED * 1000);
                            mAnimation.setFillAfter(false);
                            m_guard_img.setVisibility(View.VISIBLE);
                            m_guard_img.startAnimation(mAnimation);
                            m_bAnimation_state = true;
                        }

                    } else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.TALKING) {
                        guard_text.setText(TextResources_guad.strTalkingGuard);

                        // 애니메이션 해제
                        if(m_bAnimation_state)
                        {
                            m_guard_img.clearAnimation();
                            m_guard_img.setVisibility(View.GONE);
                            m_bAnimation_state = false;
                        }

                        //
                        displayTalkVolume();
                    }

//                    if(kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.IDLE)
//                    {
//                        LOG("m_bCallGuardState 1");
//
//                        //mTxtView_ment.setText(TextResources.strInputResidenceInfo);
//                    }else if(kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.TRYING_CALL){
//                        guard_text.setText("경비실을 호출 합니다.");
//                        mAnimation.setDuration(kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCTT.CALLED * 1000);
//                        mAnimation.setFillAfter(false);
//                        m_guard_img.setAnimation(mAnimation);
//                        m_bEncoderState = true;
//                        LOG("m_bCallGuardState 2");
//                    }else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.WAITNG_INVITE_ACK || kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI() == CallManager.CALLSTATUS.CALLING){
//                        //mTxtView_ment.setText(TextResources.strCallingResidence);
//                        LOG("m_bCallGuardState 3");
//                    }else if (kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getGUARD() == CallManager.CALLSTATUS.TALKING){
//                        //mTxtView_ment.setText(TextResources.strTalkingResidence);
//                        LOG("m_bCallGuardState 4");
//                    }else{
//                        //LOG("m_bCallGuardState 5");
//                        mTxtView_ment.setText(TextResources.strInputResidenceInfo);
//                    }

                    //m_bEncoderState = false;

                    //updateScreen();
                    clearCanvas();
                }

            }
            //LOG("[updateScreen] MainActivity.mCallController.mCallInfo.getRESI() = " + kr.co.icontrols.ilp300_700.MainActivity.mCallController.mCallInfo.getRESI());

        }
    };


//    public static Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
////            Log.d(TAG, "[mPathCheckHandler.handleMessage]");
//
//        }
//    };

//    class NewThread extends Thread {
//        NewThread() {
//
//        }
//
//        public void run() {
//            // TODO : thread running codes.
//            while (true) {
//                try {
//                    Thread.sleep(500);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                //if(!m_bAdd_test)
//                {
//                    //Log.d("KSJ", "applyAddImage_test");
//                    applyAddImage_test("/sdcard/101_101_1.jpg", "101_101_" + m_test_i++);
//                    m_bAdd_test = true;
//                }
//            }
//        }
//    }

    int m_setTime = 0;
    boolean m_bAnimation_state = false;
    String m_strErr = "";
    class NewRunnable implements Runnable {
        @Override
        public void run() {
            while (true) {

                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //Log.d("KSJ", "" + Global.bDevicebootup);
                //Handler mHandler = new Handler();

                m_setTime++;
                if(m_setTime > (10*15))
                {
                    m_UIRefreshSet = true;
                    m_setTime = 0;
                }

                if(m_UIRefreshSet || m_bCallGuardState || m_bCallState || m_bm_bFaceCatchCheck) {
                    //m_setTime = 0;
                    //Log.d(TAG, "jglee ---- Check UI");
                    myHandler.post(runnable);

                }
            }
        }
    }


//    public int applyAddImage_test(String path, String id) {
//        byte[] data = FileUtils.read(path);
//        int ret = MtcCode.ERR_NO_IMAGE.getRetCode();
//        if (data != null) {
//            ret = mClient.mtcAiAddLargeImageFromExternal(data, id);
//            if (ret != 0) {
//                //System.setProperty("test.senstime.fail", id);
//                m_strErr += id + " ";
////                File file = new File("/sdcard/erorr.txt") ;
////                FileWriter fw = null ;
////                String text = m_strErr;
////                try {
////                    fw = new FileWriter(file) ;
////                    fw.write(text);
////                    fw.close();
////                } catch (IOException e) {
////                    e.printStackTrace();
////                }
//                m_bAdd_test = false;
////                Log.e("KSJ", "applyAddImage_test e " + m_test_i);
//
//
//            }
//            else
//            {
//                //System.setProperty("test.senstime.succ", id);
////                File file = new File("/sdcard/suc.txt") ;
////                FileWriter fw = null ;
////                String text = id;
////                try {
////                    fw = new FileWriter(file) ;
////                    fw.write(text);
////                    fw.close();
////                } catch (IOException e) {
////                    e.printStackTrace();
////                }
//                m_bAdd_test = false;
//                Log.d("KSJ", "applyAddImage_test " + m_test_i);
//            }
//        }
//        return ret;
//    }

    @Override
    protected void initData() {
        //setAiConfig_first();


        // mUSBMonitor = new USBMonitor(this, myDeviceConnectListener);
    }

    protected void InitDataFunction()
    {
        mUSBMonitor = new USBMonitor(this, myDeviceConnectListener);
    }



    private void irRGBSwitch(int command) {
        mClient.mtcDeviceCameraSwitch(command, senseTimeMtc.getIsMirror(), (mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS) {
                if (command == 0) {
                    senseTimeMtc.setIsIRRGBMode(SenseTimeMtc.RGB);
                } else {
                    senseTimeMtc.setIsIRRGBMode(SenseTimeMtc.IR);
                }
                if (senseTimeMtc.getPreviewHeight() == 360) {
                    // 如果360p 需要再发一次
                    mClient.mtcDeviceScreenSizeSet(0x01, (mtcCode1, result1) -> {
                        if (mtcCode1 != MtcCode.SUCCESS) {
                            showToast("mtcCode1:" + mtcCode1);
                        }
                    });//360p
                }
            } else {
                showToast("mtcCode:" + mtcCode);
            }
        });
    }

    private void recognitionCount(int val)
    {
//        mClient.mtcAiRecognitionCountGet((mtcCode, result) -> {
//            if (mtcCode == MtcCode.SUCCESS && !TextUtils.isEmpty(result)) {
//                String[] recogLivingCount = result.split(",");
//                //int recognitionCount = Integer.parseInt(recogLivingCount[0], 16);// 底层给的是16进制的，所以需要更换一下
//                //int livingCount = Integer.parseInt(recogLivingCount[1], 16);// 底层给的是16进制的，所以需要更换一下
//                //Log.d(TAG, "[mtcAiRecognitionCountGet] recognitionCount " + recognitionCount + " livingCount " + livingCount);
//                Log.d(TAG, "[mtcAiRecognitionCountGet] " + result.toString());
//            }
//        });

        mClient.mtcAiRecognitionCountSet(val, val, (mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS) {
                //showToast(R.string.notice_success);
            } else {
                //showToast(getMtcErrorMsg(mtcCode));
            }
        });
    }


    private void initTextPaint() {
        mTextPaint = new Paint();
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setStyle(Paint.Style.FILL);
        mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
        mTextPaint.setTextSize(30);

        mTextPaintResult = new Paint();
        mTextPaintResult.setColor(Color.WHITE);
        mTextPaintResult.setStyle(Paint.Style.FILL);
        mTextPaintResult.setTextSize(50);
        //绘制字符串所占区域
        mTextAreaPaint = new Paint();
        mTextAreaPaint.setColor(Color.BLACK);
        mTextAreaPaint.setStyle(Paint.Style.FILL);
    }

    private void verifyFrame(ByteBuffer frame, ByteBuffer verifyResultBuffer) {
        if (!isRunning) {
            return;
        }
        int len = verifyResultBuffer.capacity();
        if (len <= 0) {
            drawFaces(null);

            return;
        }
        byte[] verifyResultBytes = new byte[len];
        verifyResultBuffer.get(verifyResultBytes);
        String facesJson = new String(verifyResultBytes);
        //Log.e(TAG, "facesJson:" + facesJson); // only for DEBUG, it is easy to cause memory leak

        if (!TextUtils.isEmpty(facesJson)) {
            TrackingResult trackingResult = mGson.fromJson(facesJson, TrackingResult.class);
            List<TrackingResult.Tracking> trackingList = trackingResult.getTrack_infos();
            TrackingResult.Tracking tracking = trackingList.get(0);
            if (tracking.getRecognizeScore() > 0 && senseTimeMtc.getAutoUploadAiInfoMode() == SenseTimeMtc.TURN_OFF_AUTO_UPLOAD_AI_INFO) { //关闭了主动上报，才走这里
                int maskSign = tracking.getMaskSign();
                int safetyHat = tracking.getSafetyHat();
                StringBuilder takeOffTips = new StringBuilder();
                if (maskSign == 1 || maskSign == 2) { //戴口罩的，有可能产生误识，这个数据可丢弃。提示用户摘下口罩。
                    takeOffTips.append(getString(R.string.take_off_mask) + "\n");
                }

                if (safetyHat == 1 || safetyHat == 2) { //戴了帽子，有可能产生误识，这数据可丢弃，提示用户摘下帽子再做识别。
                    takeOffTips.append(getString(R.string.take_off_hat));
                }

                //runOnUiThread(() -> takeOffTipsTv.setText(takeOffTips.toString()));

                if (!TextUtils.isEmpty(takeOffTips.toString())) {
                    lastTakeOffMaskTime = System.currentTimeMillis();
                    isHaveMaskOrHat = true;
                    myHandler.postDelayed(() -> {
                        if ((System.currentTimeMillis() - lastTakeOffMaskTime) > 5 * 1000) {
                            isHaveMaskOrHat = false;
                            //takeOffTipsTv.setText("");
                        }
                    }, 5 * 1000);
                } else {
                    isHaveMaskOrHat = false;
                }

            }

            try {
                drawFaces(facesJson);   // 45ms

            } catch (JsonSyntaxException ex) {
                ex.printStackTrace();

                drawFaces(null);
            }
        }
    }

    private void verifyResult(String verifyData) {
        if (!TextUtils.isEmpty(verifyData)) {
            VerifyResult verifyResult = mGson.fromJson(verifyData, VerifyResult.class);
            int maskSign = verifyResult.getMaskSign();
            int safetyHat = verifyResult.getSafetyHat();
            StringBuilder takeOffTips = new StringBuilder();
            if (maskSign == 1 || maskSign == 2) { //戴口罩的，有可能产生误识，这个数据可丢弃。提示用户摘下口罩。
                takeOffTips.append(getString(R.string.take_off_mask) + "\n");
            }

            if (safetyHat == 1 || safetyHat == 2) { //戴了帽子，有可能产生误识，这数据可丢弃，提示用户摘下帽子再做识别。
                takeOffTips.append(getString(R.string.take_off_hat));
            }
            //runOnUiThread(() -> takeOffTipsTv.setText(takeOffTips.toString()));

            if (!TextUtils.isEmpty(takeOffTips.toString())) {

                lastTakeOffMaskTime = System.currentTimeMillis();
                isHaveMaskOrHat = true;
                myHandler.postDelayed(() -> {

                    if ((System.currentTimeMillis() - lastTakeOffMaskTime) > 5 * 1000) {
                        isHaveMaskOrHat = false;
                        //takeOffTipsTv.setText("");

                    }
                }, 5 * 1000);
            } else {

                isHaveMaskOrHat = false;
            }

            drawFaces(verifyData);
        }
    }


    private void drawFaces(String trackingData) {
        if(!m_bLauncherStart) {
            //Log.d("KSJ", "m_bLauncherStart " + m_bLauncherStart);
            return;
        }
        synchronized (mTrackView.getmSyncSurface()) {
            if (!isRunning || senseTimeMtc.getIsIRRGBMode() == SenseTimeMtc.IR || TextUtils.isEmpty(trackingData) || !mTrackView.ismDrawFlag()) {
                //IR模式不框脸
                //Log.d("test_KSJ", "1");
                if(m_bFaceCatch == 0)
                {
                    m_bm_bFaceCatchCheck = true;
                }

                m_bFaceCatch--;


                if(m_bFaceCatch == -100)
                    m_bFaceCatch = -1;
                return;
            }
            TrackingResult trackingResult = mGson.fromJson(trackingData, TrackingResult.class);
            if (trackingResult == null) {
                if (System.currentTimeMillis() - lastTime > mDelayCleanCanva) {
                    Log.d("test_KSJ", "2");
                    //setMainViewDisable(false);
                    if(m_isSwitchState) {
                        m_isSwitchState = false;
                        m_UIRefreshSet = true;
                    }
                    m_isSwitchState = false;

                    m_isResultView = false;
                    m_isSwitchState_check = false;

                    clearCanvas();
                }

                if(m_bFaceCatch == 0)
                {
                    m_bm_bFaceCatchCheck = true;
                }

                m_bFaceCatch--;


                if(m_bFaceCatch == -100)
                    m_bFaceCatch = -1;

                return;
            }

            if(m_bFaceCatch<0)
            {
                m_bm_bFaceCatchCheck = true;
            }

            m_bFaceCatch = 30;

            Canvas canvas = null;
            try {
                if (!mTrackView.getHolder().getSurface().isValid()) {
                    //Log.d("test_KSJ", "3");
                    return;
                }
                canvas = mTrackView.getHolder().lockCanvas();
                if (canvas == null) {
                    //Log.d("test_KSJ", "4");
                    return;
                }
                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
                canvas.save();
                canvas.setMatrix(mScaleMatrix);

                for (int i = 0; trackingResult.getTrack_infos() != null && i < trackingResult.getTrack_infos().size(); i++) {//跟踪的人脸
                    TrackingResult.Tracking tracking = trackingResult.getTrack_infos().get(i);

                    FaceStatus faceStatus = FaceStatus.getByStatus(tracking.getRecognitionStatus());
                    if (faceStatus == AI_STATUS_NONLIVENESS
                            || faceStatus == AI_STATUS_USER
                            || faceStatus == AI_STATUS_STRANGER
                            || faceStatus == AI_STATUS_UNKNOWN
                            || faceStatus == AI_STATUS_ALREADY) {

                        //Log.d("test_KSJ", "5");

                        int iLeft = tracking.getFaceInfo().getRect().left;
                        int iRight = tracking.getFaceInfo().getRect().right;
                        int iTop = tracking.getFaceInfo().getRect().top;
                        int iBottom = tracking.getFaceInfo().getRect().bottom;

                        //Log.d("test_KSJ", "iLeft " + iLeft + " iRight " + iRight + " iTop " + iTop + " iBottom " + iBottom);
                        //Log.d("test_KSJ", "Width: " + (iRight-iLeft) + ", Height: " + (iBottom-iTop));

                        if((((iBottom-iTop) > m_iDetectLen) && ((iRight-iLeft) > m_iDetectLen))) {

                            if(m_bSettingShowVideo) {
                                if(m_isSwitchState) {
                                    m_isSwitchState = false;
                                    m_UIRefreshSet = true;
                                }
                                m_isSwitchState = false;
                                m_isSwitchState_check = false;
                            }
                            else
                            {
                                if(!m_isSwitchState) {
                                    m_isSwitchState = true;
                                    m_UIRefreshSet = true;

                                }
                                m_isSwitchState = true;
                                m_isSwitchState_check = true;
                                //Log.d("KSJ", "m_bSettingIRLED 2" + m_bSettingIRLED);
                                if(m_bSettingIRLED == true) {
                                    if (!m_bIRLEDState) {
                                        setDeviceIRLedON();
                                        m_bIRLEDState = true;
                                        //mMediaPlayer1.start();
                                    }
                                }
                            }


                            tracking.getFaceInfo().setShowRect(FaceStatus.calcShowRect(tracking.getFaceInfo().getRect()));
                            Rect rect = new Rect();
                            //Log.d("test_KSJ", "iLeft " + iLeft + " iRight " + iRight + " iTop " + iTop + " iBottom " + iBottom);

                            rect.set(830-iRight , iTop-380, 940-iLeft, iBottom-350);

                            //Log.d("test_KSJ 1111", "iLeft " + rect.left + " iRight " + rect.right + " iTop " + rect.top + " iBottom " + rect.bottom);
                            //Log.d("test_KSJ", "111 iLeft " + (800-iRight) + " iRight " + (800-iLeft) + " iTop " + iTop + " iBottom " + iBottom);

                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_trigger_1280_red);

                            //canvas.drawBitmap(bitmap, null, tracking.getFaceInfo().getShowRect(), null);//绘制人脸框
                            if(!m_bSenseSettingState)
                                canvas.drawBitmap(bitmap, null, rect , null);//绘制人脸框

                            if (bitmap != null) {
                                bitmap.recycle();
                                bitmap = null;
                            }

                            String displayStr = tracking.getRecognitionId();
                            //LOG("track displayStr:"+displayStr);
                            //if(!showFaceTracker) displayStr = ""; // ID.SCREENS.Main 인 경우에만 표시


                            if (faceStatus != AI_STATUS_UNKNOWN && !isHaveMaskOrHat) { // 没有戴安全帽和口罩，可以拿
                                if(!m_bSenseSettingState)
                                    drawText(displayStr, rect, canvas);
                            }

                            if (faceStatus == AI_STATUS_USER || faceStatus == AI_STATUS_ALREADY) {
                                //识别返回的数据
                                String recognitionId = tracking.getRecognitionId();
                                if (!TextUtils.isEmpty(recognitionId)
                                        && !recognitionId.equals("STRANGER")
                                        && !recognitionId.equals("UNKNOWN")
                                        && !recognitionId.equals("NONLIVENESS")
                                        && !recognitionId.equals("VERIFY_FAIL")) {
                                    Log.v(TAG, "Identification success");

                                    bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_trigger_1280_green);

                                    if(!m_bSenseSettingState)
                                        canvas.drawBitmap(bitmap, null, rect , null);//绘制人脸框

                                    if (bitmap != null) {
                                        bitmap.recycle();
                                        bitmap = null;
                                    }
                                    m_isResultView = true;
                                    m_isResult = true;

                                    if(!m_strRecognitionId.equals(recognitionId))
                                    {
                                        Log.v(MainActivity.class.getSimpleName(), "Identification success1 " + recognitionId);
                                        String[] strSplit = recognitionId.split(",");
                                        //strSplit[0] = dong
                                        //strSplit[1] = ho
                                        //strSplit[2] = alias
                                        String ip = Configure.ConfigValue.strMainServerIPAddress;
                                        String dong = strSplit[0].trim();
                                        String ho = strSplit[1].trim();
                                        String alias = strSplit[2].trim();

                                        //SoundPool sound;
                                        //sound = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
                                        //int soundId = sound.load(this, R.raw.opendoor, 1);
                                        //sound.play(soundId, 1.0F, 1.0F, 1, 0, 1.0F);
                                        mMediaPlayer.start();

                                        if(Configure.ConfigValue.nDoorOpenDuration > 0)
                                        {
                                            //if(Global.nDoorOpenCntDN < 1)
                                            {
                                                setSystemCall("wpd_interface 0xff95 0");
                                                kr.co.icontrols.ilp300_700.MainActivity.mIOInterface.ctrlDoorOpen(true);
                                            }


                                        }

                                        //mIOInterface.ctrlDoorOpen(true);
                                        String strMsg = dong + "동 " + ho + "호 안면인식에 의한 출입 성공 - " + alias+"씨";
                                        replyAddFacepic.save_facepic_request(ip,dong,ho,alias,"face","pass",strMsg);
                                        Global.sendElevCallRequest(dong, ho, true);

                                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                            @Override
                                            public void run() {

                                                //Intent intent = new Intent(MainActivity.this, DetectResult.class);
                                                //intent.putExtra("result_id", recognitionId);
                                                //startActivity(intent);
                                                //finish();
                                                m_strRecognitionId="";

                                            }
                                        }, 5000);

                                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                            @Override
                                            public void run() {

                                                //Intent intent = new Intent(MainActivity.this, DetectResult.class);
                                                //intent.putExtra("result_id", recognitionId);
                                                //startActivity(intent);
                                                //finish();
                                                if(Global.FireAlarmTimer == null) {
                                                    if (Configure.ConfigValue.nDoorOpenDuration > 0)
                                                    {
                                                        if (KeyTimer_door != null) {
                                                            KeyTimer_door.cancel();
                                                            KeyTimer_door = null;
                                                        }
                                                        KeyPressTimer_door();
                                                        KeyTimer_door.start();
                                                    }

                                                }
                                            }
                                        }, 0);
                                    }
                                    m_strRecognitionId = recognitionId;

                                }
                            }
                        }
                        else
                        {

                            if(!m_isSwitchState_check) {
                                if(m_isSwitchState) {
                                    m_isSwitchState = false;
                                    m_UIRefreshSet = true;
                                }
                                m_isResultView = false;
                                m_isSwitchState = false;

                            }
                            m_isSwitchState_check = false;

                            if(m_bSettingIRLED == true)
                            {
                                if(m_bIRLEDState)
                                {
                                    setDeviceIRLedOFF();
                                    m_bIRLEDState = false;
                                }
                            }

                            //return;
                            //Log.d("KSJ2","drawFaces 5");

                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (canvas != null) {
                        canvas.restore();
                    }
                    mTrackView.getHolder().unlockCanvasAndPost(canvas);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                trackingData = null;
                trackingResult = null;
                System.gc();
            }
            lastTime = System.currentTimeMillis();
            myHandler.removeCallbacks(clearCanvasRunable);
            myHandler.postDelayed(clearCanvasRunable, mDelayCleanCanva + 20);
        }
    }


    private void drawFaces_old(String trackingData) {
        if(!m_bLauncherStart) {
            //Log.d("KSJ", "m_bLauncherStart " + m_bLauncherStart);
            return;
        }
        synchronized (mTrackView.getmSyncSurface()) {

            if (!isRunning || senseTimeMtc.getIsIRRGBMode() == SenseTimeMtc.IR || TextUtils.isEmpty(trackingData) || !mTrackView.ismDrawFlag()) {
                //IR模式不框脸
                //Log.d("test_KSJ", "1");
                if(m_bFaceCatch == 0)
                {
                    m_bm_bFaceCatchCheck = true;
                }

                m_bFaceCatch--;


                if(m_bFaceCatch == -100)
                    m_bFaceCatch = -1;
                return;
            }

            TrackingResult trackingResult = mGson.fromJson(trackingData, TrackingResult.class);
            if (trackingResult == null) {
                //Log.d("KSJ2","drawFaces6");
                if (System.currentTimeMillis() - lastTime > mDelayCleanCanva) {
                    //Log.d("KSJ2","drawFaces1");

                    if(m_isSwitchState) {
                        m_isSwitchState = false;
                        m_UIRefreshSet = true;
                    }
                    m_isSwitchState = false;

                    m_isResultView = false;
                    m_isSwitchState_check = false;

                    clearCanvas();

                    //Log.d("KSJ", "m_bSettingIRLED 1" + m_bSettingIRLED);
/*                    if(m_bSettingIRLED == true) {
                        if (m_bIRLEDState) {
                            setDeviceIRLedOFF();
                            m_bIRLEDState = false;
                        }
                    }*/
                }
                if(m_bFaceCatch == 0)
                {
                    m_bm_bFaceCatchCheck = true;
                }

                m_bFaceCatch--;


                if(m_bFaceCatch == -100)
                    m_bFaceCatch = -1;
                return;
            }

            if(m_bFaceCatch<0)
            {
                m_bm_bFaceCatchCheck = true;
            }

            m_bFaceCatch = 30;

            Canvas canvas = null;
            try {
                if (!mTrackView.getHolder().getSurface().isValid()) {
                    //Log.d("KSJ2","drawFaces2");

                    return;
                }
                canvas = mTrackView.getHolder().lockCanvas();
                if (canvas == null) {
                    //Log.d("KSJ2","drawFaces3");
                    return;
                }
                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
                canvas.save();

                canvas.setMatrix(mScaleMatrix);

/*
                if (trackingResult.getFaceInfo() != null) {//识别到的人脸
                    FaceInfoItem faceInfoItem = trackingResult.getFaceInfo();
                    faceInfoItem.setShowRect(FaceStatus.calcShowRect(faceInfoItem.getRect()));
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_track_focus);

                    canvas.drawBitmap(bitmap, null, faceInfoItem.getShowRect(), null);//绘制人脸框
                    if (bitmap != null) {
                        //Log.d("KSJ2","drawFaces4");
                        bitmap.recycle();
                        bitmap = null;
                    }
                    String displayStr = trackingResult.getRecognitionId();
                    if (!isHaveMaskOrHat) {// 没有带口罩和安全帽，可以拿取其识别结果
                        drawText(displayStr, faceInfoItem.getShowRect(), canvas);
                    }
                }
                else
                {
                    //Log.d("KSJ2","drawFaces5");
                }
*/
                Rect rect = new Rect();

                int iLeft_old =0;
                int iRight_old = 0;
                int iTop_old = 0;
                int iBottom_old = 0;


                for (int i = 0; i < trackingResult.getTrack_infos().size(); i++) {//跟踪的人脸
                    //for (int i = 0; i < 1; i++) {
                    TrackingResult.Tracking tracking = trackingResult.getTrack_infos().get(i);

                    FaceStatus faceStatus = FaceStatus.getByStatus(tracking.getRecognitionStatus());

                    //Log.d("KSJ", "canvas.getWidth(); " +canvas.getWidth() + " canvas.getWidth(); " + canvas.getHeight());
                    if (faceStatus == AI_STATUS_NONLIVENESS
                            || faceStatus == AI_STATUS_USER
                            || faceStatus == AI_STATUS_STRANGER
                            || faceStatus == AI_STATUS_UNKNOWN
                            || faceStatus == AI_STATUS_ALREADY) {

                        Log.d(TAG, "jglee - face Detect Status : " + faceStatus.getStatus());



                        tracking.getFaceInfo().setShowRect(FaceStatus.calcShowRect(tracking.getFaceInfo().getRect()));

                        //Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_trigger_1280_green);
                        //Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.mipmap.image_trigger_1280_red);

                        //int iMargin = 350;
                        int iMargin = 350;
                        //Log.d("KSJ", i + " iTop " + tracking.getFaceInfo().getRect().top + " iLeft " + tracking.getFaceInfo().getRect().left + " iRight " + tracking.getFaceInfo().getRect().right + " iBottom " + tracking.getFaceInfo().getRect().bottom);
                        //int iLeft = tracking.getFaceInfo().getRect().left-60;
                        //int iRight = tracking.getFaceInfo().getRect().right+10;
                        //int iTop = tracking.getFaceInfo().getRect().top+100;
                        //int iBottom = tracking.getFaceInfo().getRect().bottom+130;

                        int iLeft = tracking.getFaceInfo().getRect().left;
                        int iRight = tracking.getFaceInfo().getRect().right;
                        int iTop = tracking.getFaceInfo().getRect().top-iMargin;
                        int iBottom = tracking.getFaceInfo().getRect().bottom+iMargin;

                        if((((iBottom-iTop) > m_iDetectLen) &&  ((iRight-iLeft) > m_iDetectLen))) {


                            if(m_bSettingShowVideo) {
                                if(m_isSwitchState) {
                                    m_isSwitchState = false;
                                    m_UIRefreshSet = true;
                                }
                                m_isSwitchState = false;
                                m_isSwitchState_check = false;
                            }
                            else
                            {
                                if(!m_isSwitchState) {
                                    m_isSwitchState = true;
                                    m_UIRefreshSet = true;

                                }
                                m_isSwitchState = true;
                                m_isSwitchState_check = true;
                                //Log.d("KSJ", "m_bSettingIRLED 2" + m_bSettingIRLED);
                                if(m_bSettingIRLED == true) {
                                    if (!m_bIRLEDState) {
                                        setDeviceIRLedON();
                                        m_bIRLEDState = true;
                                        //mMediaPlayer1.start();
                                    }
                                }
                            }
                            rect.set((int) 760 - (iRight),iTop,(int) 760 - (iLeft),iBottom);
                            tracking.getFaceInfo().getRect().set(rect);




                            if (faceStatus == AI_STATUS_USER || faceStatus == AI_STATUS_ALREADY) {
                                //识别返回的数据
                                String recognitionId = tracking.getRecognitionId();
                                if (!TextUtils.isEmpty(recognitionId) && !recognitionId.equals("STRANGER") && !recognitionId.equals("UNKNOWN")
                                        && !recognitionId.equals("NONLIVENESS") && !recognitionId.equals("VERIFY_FAIL")) {

                                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_trigger_1280_green);

                                    if(!m_bSenseSettingState)
                                        canvas.drawBitmap(bitmap, null, rect , null);//绘制人脸框


                                    if (bitmap != null) {
                                        bitmap.recycle();
                                        bitmap = null;
                                    }
                                    //Log.v(MainActivity.class.getSimpleName(), i + " Identification success" + m_strRecognitionId);
                                    m_isResultView = true;
                                    m_isResult = true;
                                    //if(!m_isResultActivity)
                                    if(!m_strRecognitionId.equals(recognitionId))
                                    {
                                        Log.v(MainActivity.class.getSimpleName(), "Identification success1 " + recognitionId);
                                        String[] strSplit = recognitionId.split(",");
                                        //strSplit[0] = dong
                                        //strSplit[1] = ho
                                        //strSplit[2] = alias
                                        String ip = Configure.ConfigValue.strMainServerIPAddress;
                                        String dong = strSplit[0].trim();
                                        String ho = strSplit[1].trim();
                                        String alias = strSplit[2].trim();

                                        //SoundPool sound;
                                        //sound = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
                                        //int soundId = sound.load(this, R.raw.opendoor, 1);
                                        //sound.play(soundId, 1.0F, 1.0F, 1, 0, 1.0F);
                                        mMediaPlayer.start();

                                        if(Configure.ConfigValue.nDoorOpenDuration > 0)
                                        {
                                            //if(Global.nDoorOpenCntDN < 1)
                                            {
                                                setSystemCall("wpd_interface 0xff95 0");
                                                kr.co.icontrols.ilp300_700.MainActivity.mIOInterface.ctrlDoorOpen(true);
                                            }


                                        }

                                        //mIOInterface.ctrlDoorOpen(true);
                                        String strMsg = dong + "동 " + ho + "호 안면인식에 의한 출입 성공 - " + alias+"씨";
                                        replyAddFacepic.save_facepic_request(ip,dong,ho,alias,"face","pass",strMsg);
                                        Global.sendElevCallRequest(dong, ho, true);

                                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                            @Override
                                            public void run() {

                                                //Intent intent = new Intent(MainActivity.this, DetectResult.class);
                                                //intent.putExtra("result_id", recognitionId);
                                                //startActivity(intent);
                                                //finish();
                                                m_strRecognitionId="";

                                            }
                                        }, 5000);

                                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                            @Override
                                            public void run() {

                                                //Intent intent = new Intent(MainActivity.this, DetectResult.class);
                                                //intent.putExtra("result_id", recognitionId);
                                                //startActivity(intent);
                                                //finish();
                                                if(Global.FireAlarmTimer == null) {
                                                    if (Configure.ConfigValue.nDoorOpenDuration > 0)
                                                    {
                                                        if (KeyTimer_door != null) {
                                                            KeyTimer_door.cancel();
                                                            KeyTimer_door = null;
                                                        }
                                                        KeyPressTimer_door();
                                                        KeyTimer_door.start();
                                                    }

                                                }
                                            }
                                        }, 0);

                                    }
                                    m_strRecognitionId = recognitionId;
                                    //m_isResultActivity = true;


/*


                                    mClient.mtcAiPause((mtcCode, result) -> {
                                        Logger.d("mtcAiPause's result:" + getMtcErrorMsg(mtcCode));
                                    });

                                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mClient.mtcAiResume((mtcCode, result) -> {
                                                Logger.d("mtcAiResume's result:" + getMtcErrorMsg(mtcCode));
                                            });
                                        }
                                    }, 3000);
*/
                                    //Log.v("KSJ", "Identification success");
                                    //hdcResultView.setVisibility(View.VISIBLE);
                                    //showToast("실패되었습니다.", 270);
                                    //showToast("인증되었습니다", 270);

                                    //drawText_result("인증되었습니다.", tracking.getFaceInfo().getRect(), canvas);
                                } else {
                                    m_isResultView = true;
                                    m_isResult = false;

                                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_trigger_1280_red);

                                    if(!m_bSenseSettingState)
                                        canvas.drawBitmap(bitmap, null, rect , null);//绘制人脸框


                                    if (bitmap != null) {
                                        bitmap.recycle();
                                        bitmap = null;
                                    }

                                    //hdcResultView.setVisibility(View.VISIBLE);
                                    //Log.v("KSJ", "Identification failure");

                                    //showToast("실패되었습니다.", 270);

                                    //drawText_result("인증되었습니다.", tracking.getFaceInfo().getRect(), canvas);
                                    //Log.v(MainActivity.class.getSimpleName(), "Identification failure");
                                }
                            }
                            else
                            {
                                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_trigger_1280_red);

                                if(!m_bSenseSettingState)
                                    canvas.drawBitmap(bitmap, null, rect , null);//绘制人脸框


                                if (bitmap != null) {
                                    bitmap.recycle();
                                    bitmap = null;
                                }
                                m_isResultView = false;
                                m_isResult = false;
                            }
                            String displayStr = tracking.getRecognitionId();
                            if (faceStatus != AI_STATUS_UNKNOWN && !isHaveMaskOrHat) { // 没有戴安全帽和口罩，可以拿
                                if(!m_bSenseSettingState)
                                    drawText(displayStr, tracking.getFaceInfo().getRect(), canvas);
                            }


                        }
                        else if((((iBottom-iTop) > m_iDetectLen-m_iDetectLen_1) &&  ((iRight-iLeft) > m_iDetectLen-m_iDetectLen_1)))
                        {
                            //Log.d("KSJ", "test1");
                        }
                        else
                        {

                            if(!m_isSwitchState_check) {
                                if(m_isSwitchState) {
                                    m_isSwitchState = false;
                                    m_UIRefreshSet = true;
                                }
                                m_isResultView = false;
                                m_isSwitchState = false;

                            }
                            m_isSwitchState_check = false;

                            if(m_bSettingIRLED == true)
                            {
                                if(m_bIRLEDState)
                                {
                                    setDeviceIRLedOFF();
                                    m_bIRLEDState = false;
                                }
                            }

                            //return;
                            //Log.d("KSJ2","drawFaces 5");

                        }



                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (canvas != null) {
                        canvas.restore();
                    }
                    mTrackView.getHolder().unlockCanvasAndPost(canvas);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                trackingData = null;
                trackingResult = null;
                System.gc();
            }
            lastTime = System.currentTimeMillis();
            myHandler.removeCallbacks(clearCanvasRunable);
            myHandler.postDelayed(clearCanvasRunable, mDelayCleanCanva + 20);
        }
    }

    private void setSystemCall(String strCmd)
    {
        Runtime runtime = Runtime.getRuntime();
        Process process;
        try {
            process = runtime.exec(strCmd);

        }
        catch (Exception exception)
        {
            Log.e("KSJ", "system call error");
        }
        //return "";
    }


    private void clearCanvas() {
        if (mTrackView == null) {
            return;
        }
        Canvas canvas = mTrackView.getHolder().lockCanvas();
        if (canvas != null) {
            try {
                canvas.drawColor(0, PorterDuff.Mode.CLEAR);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    mTrackView.getHolder().unlockCanvasAndPost(canvas);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    protected void KeyPressTimer() {
        try {
            if (KeyTimer != null) {
                KeyTimer.cancel();
                KeyTimer = null;
            }

            KeyTimer = new CountDownTimer(1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    LOG("[KeyPressTimer] onTick!!");
                }

                @Override
                public void onFinish() {
                    LOG("[KeyPressTimer] onFinish!!");
                    bPressedSTAR = false;
                    //m_iKeyValue = 0;
                }
            };
        } catch (Exception e) {
            Log.e(TAG, "[Exception] KeyPressTimer()");
            e.printStackTrace();
        }
    }

    protected void KeyPressTimer_setting() {
        try {
            if (KeyTimer_setting != null) {
                KeyTimer_setting.cancel();
                KeyTimer_setting = null;
            }

            KeyTimer_setting = new CountDownTimer(10000, 10000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    LOG("[KeyPressTimer_setting] onTick!!");
                }

                @Override
                public void onFinish() {
                    LOG("[KeyPressTimer_setting] onFinish!!");
                    m_bSenseSettingState = false;

                    m_iSenseSettingCount = 0;
                    setSensePW_all();
                    m_strSettingPW="";
                    m_iAccessPW_type = 0;
                    m_iSenseSettingPage = 0;
                    Global.strInputPW = "";
                    m_UIRefreshSet = true;
                }
            };
        } catch (Exception e) {
            Log.e(TAG, "[Exception] KeyPressTimer()");
            e.printStackTrace();
        }
    }

    protected void KeyPressTimer_door() {
        try {
            if (KeyTimer_door != null) {
                KeyTimer_door.cancel();
                KeyTimer_door = null;
            }

            KeyTimer_door = new CountDownTimer(Configure.ConfigValue.nDoorOpenDuration*1000, Configure.ConfigValue.nDoorOpenDuration*1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    LOG("[KeyPressTimer_door] onTick!!");
                }

                @Override
                public void onFinish() {
                    LOG("[KeyPressTimer_door] onFinish!!");
                    if(Global.nDoorOpenCntDN < 1)
                        kr.co.icontrols.ilp300_700.MainActivity.mIOInterface.ctrlDoorOpen(false);

                }
            };
        } catch (Exception e) {
            Log.e(TAG, "[Exception] KeyPressTimer_door()");
            e.printStackTrace();
        }
    }

    public static void KeyPressTimer_reboot() {
        try {
            if (KeyTimer_reboot != null) {
                KeyTimer_reboot.cancel();
                KeyTimer_reboot = null;
            }

            KeyTimer_reboot = new CountDownTimer(10000, 10000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    Log.d("KSJ","[KeyPressTimer_reboot] onTick!!");
                }

                @Override
                public void onFinish() {
                    Log.d("KSJ","[KeyPressTimer_reboot] onFinish!!");
                    //kr.co.icontrols.ilp300_700.MainActivity.mIOInterface.Reboot(0);
                }
            };
        } catch (Exception e) {
            Log.e("KSJ", "[Exception] KeyPressTimer_reboot()");
            e.printStackTrace();
        }
    }

    private void drawText_result(String text, Rect faceRect, Canvas canvas) {
        canvas.drawText(text, 0, 0, mTextPaintResult);
    }

    private void drawText(String text, Rect faceRect, Canvas canvas) {
        if (TextUtils.isEmpty(text)) {
            return;
        }

        mTextPaint.setTextSize(25);
        float width = mTextPaint.measureText(text);//获取字符串所占宽度

        int baselineX = faceRect.left + 20;//(int) (faceRect.right + faceRect.height() / 1.0f - width / 1.0f);
        int baselineY = faceRect.bottom + 40;

        //获取当前线到baseline线的距离
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        float top = fontMetrics.top;
        float bottom = fontMetrics.bottom;

        //获取字符串所占高度
        float height = fontMetrics.bottom - fontMetrics.top;

        //绘制背景
        canvas.drawRect(baselineX - 10, baselineY + top - 5, width + baselineX + 10, bottom + baselineY + 5, mTextAreaPaint);

        //绘制文本
        canvas.drawText(text, baselineX, baselineY, mTextPaint);
    }


    class TextResources {
        static final String strInputResidenceInfo = "세대 호수를 입력하세요.";
        static final String strTryingResidence = "세대를 호출합니다.";
        static final String strCallingResidence = "세대를 호출중입니다.";
        static final String strTalkingResidence = "세대와 통화중입니다.";
    }

    class TextResources_guad {
        static final String strPressCallButton = "호출버튼을 누르세요.";
        static final String strTryingGuard = "경비실을 호출합니다.";
        static final String strCallingGuard = "경비실을 호출중입니다.";
        static final String strTalkingGuard = "경비실과 통화중입니다.";
    }


    @SuppressLint("CheckResult")
    private void releaseAndRequestCamera(UsbDevice device) {
        Logger.d("releaseAndRequestCamera");
        Observable.create((ObservableOnSubscribe<String>) emitter -> {
            synchronized (mSyncUVCCamera) {
                Logger.d("mUVCCamera:" + mUVCCamera);
                if (mUVCCamera != null) {
                    try {
                        mUVCCamera.close();
                        mUVCCamera.destroy();
                    } catch (final Exception e) {
                        e.printStackTrace();
                    }
                    mUVCCamera = null;
                }
                isConnect = false;
            }
            emitter.onNext("complete");
//        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        }).subscribeOn(Schedulers.single()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    Logger.d("requestPermission device:" + device + ",  mUSBMonitor:" + mUSBMonitor);
                    if (device != null && mUSBMonitor != null) {
                        mUSBMonitor.requestPermission(device);
                    }
                });
    }


    private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            float scaleX;
            float scaleY;
            float modulus;

            Logger.e("onSurfaceTextureAvailable  width:" + width + ",  height:" + height);
            SenseTimeMtc senseTimeMtc = SenseTimeMtc.getInstance();
            int PREVIEW_W, PREVIEW_H;
            if (senseTimeMtc.getmM10_L_P() == SenseTimeMtc.LANDSCAPE_0 || senseTimeMtc.getmM10_L_P() == SenseTimeMtc.LANDSCAPE_180) {
                PREVIEW_W = senseTimeMtc.getPreviewWidth();
                PREVIEW_H = senseTimeMtc.getPreviewHeight();
            } else {//竖屏状态
                PREVIEW_W = senseTimeMtc.getPreviewHeight();
                PREVIEW_H = senseTimeMtc.getPreviewWidth();
            }
            if (SenseTimeMtc.M10 == senseTimeMtc.getmDeviceModule() && (senseTimeMtc.getmM10_L_P() == SenseTimeMtc.LANDSCAPE_0
                    || senseTimeMtc.getmM10_L_P() == SenseTimeMtc.LANDSCAPE_180)) {
                modulus = 720.0f / (float) PREVIEW_H;
            } else {
                modulus = 1280.0f / (float) PREVIEW_H;
            }

            if (width > height) {
                scaleX = width / (float) PREVIEW_W / modulus;
                scaleY = height / (float) PREVIEW_H / modulus;
            } else {
                scaleX = height / (float) PREVIEW_H / modulus;
                scaleY = width / (float) PREVIEW_W / modulus;
            }

            Logger.e("test_KSJ  modulus:" + modulus + ",  PREVIEW_H:" + PREVIEW_H + ",  PREVIEW_W:" + PREVIEW_W );
            Logger.e("test_KSJ  width:" + width + ",  height:" + height + ",  scaleX:" + scaleX + ",  scaleY:" + scaleY);
            //mScaleMatrix.setScale(scaleX, scaleY);

            scaleX = 0.480875f;
            scaleY = 0.46805555f;

            mScaleMatrix.setScale(scaleX, scaleY);
            //requestPermissionDevice();
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            Log.e(TAG, "onSurfaceTextureSizeChanged  width:" + width + ",  height:" + height);
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            Log.e(TAG, "onSurfaceTextureDestroyed   surface:" + surface);
            return false;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {
//			Logger.d("onSurfaceTextureUpdated  surface:"+surface);
        }
    };

    public int[] getDataInfo()
    {
        int[] iDataInfo = new int[4];
        iDataInfo[0] = m_iDistanceValue_old;
        iDataInfo[1] = (m_bSettingAI) ? 2 : 1;
        iDataInfo[2] = (m_bHaveMaskOrHat) ? 2 : 1;
        iDataInfo[3] = m_iThrescase;
        return iDataInfo;
    }

    public void setCallState(boolean onoff, String strIP)
    {
        if(onoff == true)
        {
            Log.d(TAG, "setCallState on strIP " + strIP);
            m_bEncoderState = true;
            try {
                mAVcEncoder = new AvcEncoder();
                mAVcEncoder.Init(strIP, isM30);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else
        {
            Log.d(TAG, "setCallState off ");
            m_bEncoderState = false;
            try {
                mAVcEncoder.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void setDataInfo(int type, String value)
    {
        SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();

        if(type == 1)
        {
            m_iDistanceValue_old = Integer.parseInt(value);
            m_iDistanceValue = m_iDistanceValue_old;
            editor.putInt(Face_Detect_Value, m_iDistanceValue);
            m_iDetectLen = m_DetectCase[Configure.ConfigValue.DEVICE_MODELTYPE][m_iDistanceValue-1];

        }
        else if(type == 2)
        {
            if(value.equalsIgnoreCase("enable"))
                m_bSettingAI = true;
            else
                m_bSettingAI = false;

            setTemplateUpdate((m_bSettingAI) ? 1 : 0);
            editor.putBoolean(Face_AI_Set, m_bSettingAI);

        }
        else if(type == 3)
        {
            if(value.equalsIgnoreCase("enable"))
                m_bHaveMaskOrHat = true;
            else
                m_bHaveMaskOrHat = false;

            editor.putBoolean(Face_Mask_Value, m_bHaveMaskOrHat);
        }
        else if(type == 4)
        {
            m_iThrescase = Integer.parseInt(value);

            editor.putInt(MainActivity.Face_Thres_Value, m_iThrescase);

            try {
                m_fThreshValue = m_ThresCase[m_iThrescase-1];
            }
            catch (ArrayIndexOutOfBoundsException e)
            {
                m_fThreshValue = 0.9f;
                m_iThrescase = 5;
            }
            setAiConfig();

        }
        else if(type == 5)
        {

            if(Integer.parseInt(value) == 0)
                m_bAEMode = false;
            else if(Integer.parseInt(value) == 1)
                m_bAEMode = true;

            editor.putBoolean(Face_AEMode_Value, m_bAEMode);

            setDeviceAntiFlickerset(m_bAEMode);
        }

        editor.commit();

    }


    int m_iAICount = 0;

    public void delData(Socket Sock, String data, int type) {
        int bRet = 0;
        boolean bSameName = false;
        boolean bAllDel = false;
        LOG("[USBCameraActivity2] test : " + data + type);

        String[] strSplit = data.split(";;");


        // type 2
        // strSplit[0] IP
        // strSplit[1] dong
        // strSplit[2] ho
        // strSplit[3] alias


        if (type == 2) {
            String name;
            String ip,dong,ho,alias;

            ip = strSplit[0].trim();
            dong = strSplit[1].trim();
            ho = strSplit[2].trim();
            alias = strSplit[3].trim();

            name = strSplit[1].trim() + "," + strSplit[2].trim() + "," + strSplit[3].trim();

            m_bSenseListResult = false;
            getList();

            while (!m_bSenseListResult)
            {

                if(m_bSenseListResult) {
                    //Log.d("KSJ","getList2");
                    break;
                }
            }

            m_iAICount = 0;

            if (m_strSenseList.startsWith("{")) {
                String strName = dong + "," + ho;
                String strName1 = dong + "," + ho + "," +alias;
                Log.d("KSJ","result:1 " + strName);
                try {
                    JSONObject jsonObject = new JSONObject(m_strSenseList);
                    JSONArray movieArray = jsonObject.getJSONArray("id");
                    Log.d("KSJ","result:2 " + movieArray.length());
                    for (int i = 0; i < movieArray.length(); i++) {

                        String s = "Hello welcome to the this place";
                        if(movieArray.getString(i).contains(strName)) {
                            Log.d("KSJ","문자가 포함되어 있습니다. " + movieArray.getString(i));
                            m_iAICount++;
                            if(movieArray.getString(i).contains(strName1)) {
                                bSameName = true;
                            }

                            if(alias.equals("*"))
                            {

                                int ret = delUserImage(movieArray.getString(i));
                                while (!m_bDelRet) {

                                }
                                if (mRet == 1) {
                                    m_iAICount--;
                                }

                                bAllDel = true;
                            }
                        }else {
                            Log.d("KSJ","문자가 포함되어 있지 않습니다.");
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

//            if(!m_bSenseListResult)
//            {
//                replyAddFacepic.fail_del_pic_reply(Sock, ip,"lobby_err","10",dong,ho,alias,""+(10-(m_iAICount)),""+m_iAICount);
//            }

            if(!bAllDel)
            {
                int ret = delUserImage(name);
                while (!m_bDelRet) {

                }
                if (mRet == 0) {
                    LOG("delUserImage fail");
                    if(!bSameName)
                    {
                        replyAddFacepic.send_del_pic_reply(Sock, ip,"info_err","10",dong,ho,alias,""+(10-(m_iAICount)),""+(m_iAICount));
                    }
                    else
                    {
                        replyAddFacepic.fail_del_pic_reply(Sock, ip,"lobby_err","10",dong,ho,alias,""+(10-(m_iAICount)),""+m_iAICount);
                    }

                } else {
                    LOG("delUserImage success");
                    if(!bSameName)
                        replyAddFacepic.send_del_pic_reply(Sock, ip,"info_err","10",dong,ho,alias,""+(10-(m_iAICount)),""+(m_iAICount));
                    else
                        replyAddFacepic.send_del_pic_reply(Sock, ip,"null","10",dong,ho,alias,""+(10-(m_iAICount-1)),""+(m_iAICount-1));

                    File f = new File(SAVEPICTURE_PATH + "/" + name + ".jpg");
                    f.delete();

                }
            }
            else
            {
                if(m_iAICount == 0)
                {
                    replyAddFacepic.send_del_pic_reply(Sock, ip,"null","10",dong,ho,alias,""+(10-(m_iAICount)),""+(m_iAICount));
                }
                else if(m_iAICount > 0)
                {
                    replyAddFacepic.fail_del_pic_reply(Sock, ip,"info_err","10",dong,ho,alias,""+(10-(m_iAICount)),""+m_iAICount);
                }
            }

        }
    }


    boolean m_bSenseListResult = false;
    String m_strSenseList = "";
    //jslee start
    public void setFirmwareUpgrade(Socket Sock, String data) {
        boolean bRet = false;
        boolean bSameName = false;
        //여기서 받은 데이터를 가지고 작업하면 됨
        LOG("[USBCameraActivity2] test : " + data);

        //type 1
        // strSplit[0] IP
        // strSplit[1] ID
        // strSplit[2] PWD
        // strSplit[3] PATH
        // strSplit[4] FILE NAME

        String[] strSplit = data.split(";;");
        Log.d("KSJ", "[USBCameraActivity2] test : " + strSplit);

        String name, ip, id, pwd, path, fileName, dong, ho , alias;

        ip =  strSplit[0].trim();
        id =  strSplit[1].trim();
        pwd =  strSplit[2].trim();
        path = strSplit[3].trim();
        fileName = strSplit[4].trim();

        //bRet = addPicSFTPDown(ip, id, pwd, path, fileName, name);

        ftp_FileDownload ftp_fileDownload = new ftp_FileDownload(ip, id, pwd, path, fileName, "/sdcard/"+fileName);
        bRet = ftp_fileDownload.run();


        if(!bRet)
        {
            LOG("addPicFTPDown error");
            replyAddFacepic.upgrade_pic_reply(Sock, ip,"network_err", "fail");
            hdcsftpManager.logoutFTP();
            return;
        }

        replyAddFacepic.upgrade_pic_reply(Sock, ip,"null", "ok");

        Intent intent = new Intent(this, kr.co.icontrols.ilp300_700.screen.SettingActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        //intent.putExtra("test",1);
        startActivity(intent);


    }

    public void setData(Socket Sock, String data, int type) {
        boolean bRet = false;
        boolean bSameName = false;
        //여기서 받은 데이터를 가지고 작업하면 됨
        LOG("[USBCameraActivity2] test : " + data + type);

        //type 1
        // strSplit[0] IP
        // strSplit[1] dong
        // strSplit[2] ho
        // strSplit[3] alias
        // strSplit[4] ID
        // strSplit[5] PWD
        // strSplit[6] PATH
        // strSplit[7] FILE NAME

        String[] strSplit = data.split(";;");
        Log.d("KSJ", "[USBCameraActivity2] test : " + strSplit);

        if (type == 1)
        {
            String name, ip, id, pwd, path, fileName, dong, ho , alias;

            dong = strSplit[1].trim();
            ho = strSplit[2].trim();
            alias = strSplit[3].trim();

            name = strSplit[1].trim() + "," +strSplit[2].trim() + "," + strSplit[3].trim();
            ip =  strSplit[0].trim();
            id =  strSplit[4].trim();
            pwd =  strSplit[5].trim();
            path = strSplit[6].trim();
            fileName = strSplit[7].trim();

            //bRet = addPicSFTPDown(ip, id, pwd, path, fileName, name);

            ftps_FileDownload ftps_down = new ftps_FileDownload(ip, id, pwd, path, fileName, SAVEPICTURE_PATH+ "/" +name+".jpg");
            ftps_down.start();
            //ftp_FileDownload ftp_fileDownload = new ftp_FileDownload(ip, id, pwd, path, fileName, SAVEPICTURE_PATH+ "/" +name+".jpg");
            //bRet = ftp_fileDownload.run();

            m_bSenseListResult = false;

            getList();

            //for(int i = 0; i < 100000; i++)
            while (!m_bSenseListResult)
            {

                if(m_bSenseListResult) {
                    //Log.d("KSJ","getList2");
                    break;
                }
            }
            m_iAICount = 0;

            if (m_strSenseList.startsWith("{")) {
                String strName = dong + "," + ho;
                String strName1 = dong + "," + ho + "," +alias;
                Log.d("KSJ","result:1 " + strName);
                try {
                    JSONObject jsonObject = new JSONObject(m_strSenseList);
                    JSONArray movieArray = jsonObject.getJSONArray("id");
                    Log.d("KSJ","result:2 " + movieArray.length());
                    for (int i = 0; i < movieArray.length(); i++) {

                        String s = "Hello welcome to the this place";
                        if(movieArray.getString(i).contains(strName)) {
                            Log.d("KSJ","문자가 포함되어 있습니다. " + movieArray.getString(i));
                            m_iAICount++;
                            if(movieArray.getString(i).contains(strName1)) {
                                bSameName = true;
                            }
                        }else {
                            Log.d("KSJ","문자가 포함되어 있지 않습니다.");
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


//            if(!m_bSenseListResult)
//            {
//                replyAddFacepic.fail_add_pic_reply(Sock, ip,"lobby_err","10",dong,ho,alias,""+(10-(m_iAICount)),"null",""+m_iAICount);
//            }

            while (true)
            {
                if(ftps_down.m_iDownRet != 0)
                    break;
            }

            if(ftps_down.m_iDownRet == -1)
            //if(!bRet)
            {
                LOG("addPicFTPDown error");
                replyAddFacepic.fail_add_pic_reply(Sock, ip,"network_err","10",dong,ho,alias,""+(10-(m_iAICount)),"null",""+m_iAICount);
                hdcsftpManager.logoutFTP();
                setDirEmpty(SAVEPICTURE_PATH);
                return;
            }



            if(!bSameName)
            {
                if (m_iAICount > 9) {
                    replyAddFacepic.fail_add_pic_reply(Sock, ip, "limit", "10", dong, ho, alias, "10", "null", "10");
                    setDirEmpty(SAVEPICTURE_PATH);
                    return;
                }
            }

            //LOG("decryptPictureFile " + SAVEPICTURE_PATH + "/" + name + ".jpg");
            File file_source = new File(SAVEPICTURE_PATH + "/" + name + ".jpg");
            File file_dest = new File(SAVEPICTURE_PATH + "/" + name + "_dest.jpg");
            m_aes.decryptPictureFile(file_source, file_dest);
            //LOG("decryptPictureFile " + SAVEPICTURE_PATH + "/" + name + "_dest.jpg");

            int ret = applyAddImage(SAVEPICTURE_PATH, name);

            if (ret != 0) {
                LOG("applyAddImage1 fail");

                replyAddFacepic.fail_add_pic_reply(Sock, ip,"pic_err","10",dong,ho,alias,""+(10-(m_iAICount)),"null",""+m_iAICount);
            }
            else {

                LOG("applyAddImage1 success");
                if(bSameName)
                    replyAddFacepic.send_add_pic_reply(Sock, ip,"null","10",dong,ho,alias,""+(10-(m_iAICount)),"exist",""+(m_iAICount));
                else
                    replyAddFacepic.send_add_pic_reply(Sock, ip,"null","10",dong,ho,alias,""+(10-(m_iAICount+1)),"new",""+(m_iAICount+1));
            }

            setDirEmpty(SAVEPICTURE_PATH);

        }
    }
    //jslee end

    public void setdownload(Socket Sock, String data, int type) {
        boolean bRet = false;
        boolean bSameName = false;
        //여기서 받은 데이터를 가지고 작업하면 됨
        LOG("[USBCameraActivity2] test : " + data + type);

        //type 1

        // strSplit[1] ID
        // strSplit[2] PWD
        // strSplit[3] PATH
        // strSplit[4] FILE NAME

        String[] strSplit = data.split(";;");
        Log.d("KSJ", "[USBCameraActivity2] test : " + strSplit);

        if (type == 1)
        {
            String name, ip, id, pwd, path, fileName, dong, ho , alias;


            ip =  strSplit[0].trim();
            id =  strSplit[1].trim();
            pwd =  strSplit[2].trim();
            path = strSplit[3].trim();
            fileName = strSplit[4].trim();

            //bRet = addPicSFTPDown(ip, id, pwd, path, fileName, name);

            ftp_FileDownload ftp_fileDownload = new ftp_FileDownload(ip, id, pwd, path, fileName, SAVEPICTURE_PATH+ "/update.zip");
            bRet = ftp_fileDownload.run();


            if(!bRet)
            {
                LOG("addPicFTPDown error");
                replyAddFacepic.fail_down_pic_reply(Sock);
                hdcsftpManager.logoutFTP();
                setDirEmpty(SAVEPICTURE_PATH);
                return;
            }
            else
            {

                //replyAddFacepic.send_down_pic_reply(Sock);
//                Runtime mRuntime = Runtime.getRuntime();
//                Process mProcess;
//
//                setDirEmpty(SAVEPICTURE_PATH+"/tmp");
//                String cmd = "/sbin/busybox unzip " + SAVEPICTURE_PATH+ "/update.zip -d " + SAVEPICTURE_PATH+"/tmp";
//                try {
//                    mProcess = mRuntime.exec(cmd);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }

//                try {
//                    unzip(SAVEPICTURE_PATH+ "/update.zip", SAVEPICTURE_PATH+"/tmp");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                LOG("addPicFTPDown suc");




                LOG("addPicFTPDown suc");

                //System.setProperty("persist.sys.faceunzip", "0");

                File directory = new File(SAVEPICTURE_PATH+"/tmp");

                if (!directory.isDirectory()) {
                    directory.mkdirs();
                }

                Runtime mRuntime = Runtime.getRuntime();
                Process mProcess;
                String cmd = "setprop persist.sys.faceunzip 1";
                try {
                    mProcess = mRuntime.exec(cmd);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //System.setProperty("persist.sys.faceunzip", "1");

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                cmd = "setprop persist.sys.faceunzip 0";
                try {
                    mProcess = mRuntime.exec(cmd);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                File[] files = directory.listFiles();

                boolean bError = false;
                for (int i=0; i< files.length; i++) {
                    LOG("addPicFTPDown files[i].getName() " +files[i].getName());

                    String[] strSplitFile = files[i].getName().split("_");
                    String[] strSplitFile1 = strSplitFile[2].split(".");

                    LOG("addPicFTPDown strSplitFile " + strSplitFile[0] + " " + strSplitFile[1] + " " + strSplitFile[2]);

                    dong = strSplitFile[0].replace("동", "");
                    ho = strSplitFile[1].replace("호", "");
                    alias = strSplitFile[2].replace(".jpg", "");

                    LOG("addPicFTPDown passing " + dong + " " + ho + " " + alias);

                    File file_source = new File(SAVEPICTURE_PATH+"/tmp/"+files[i].getName());
                    File file_dest = new File(SAVEPICTURE_PATH+"/tmp/" + "dest_" +files[i].getName());
                    m_aes.decryptPictureFile(file_source, file_dest);

                    int ret = applyAllAddImage(SAVEPICTURE_PATH+"/tmp/" + "dest_" +files[i].getName(), dong + "," + ho+ "," + alias);

                    if (ret != 0) {
                        LOG("addPicFTPDown error files[i].getName() " +files[i].getName());
                        bError = true;
                    }
                    else
                    {
                        LOG("addPicFTPDown success files[i].getName() " +files[i].getName());
                    }

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

                //setDirEmpty(SAVEPICTURE_PATH);

                if(bError)
                    replyAddFacepic.fail_down_pic_reply(Sock);
                else
                    replyAddFacepic.send_down_pic_reply(Sock);


            }



        }
    }

    public void setDirEmpty(String dirName){
        String path = dirName;
        File dir = new File(path);
        File[] childFileList = dir.listFiles();
        if (dir.exists())
        {
            for (File childFile : childFileList)
            {
                if (childFile.isDirectory())
                {
                    setDirEmpty(childFile.getAbsolutePath()); //하위 디렉토리
                } else {
                    childFile.delete(); //하위 파일
                }
            }
            //dir.delete();
        }
    }

    private File[] FileList(String strFolderName)
    {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + strFolderName;

        File directory = new File(path);
        File[] files = directory.listFiles();

//        List<String> filesNameList = new ArrayList<>();
//
//        for (int i=0; i< files.length; i++) {
//            filesNameList.add(files[i].getName());
//
//        }

        return  files;
    }

    public static void unzip(String zipFile, String location) throws IOException {
        try {
            File f = new File(location);
            if (!f.isDirectory()) {
                f.mkdirs();
            }
            ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
            try {
                ZipEntry ze = null;
                while ((ze = zin.getNextEntry()) != null) {
                    String path = location + File.separator + ze.getName();

                    if (ze.isDirectory()) {
                        File unzipFile = new File(path);
                        if (!unzipFile.isDirectory()) {
                            unzipFile.mkdirs();
                        }
                    } else {
                        FileOutputStream fout = new FileOutputStream(path, false);

                        try {
                            for (int c = zin.read(); c != -1; c = zin.read()) {
                                fout.write(c);
                            }
                            zin.closeEntry();
                        } finally {
                            fout.close();
                        }
                    }
                }
            } finally {
                zin.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("KSJ", "Unzip exception", e);
        }
    }

    public void getList()
    {
        mClient.mtcAllIdListGet((mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS) {

                result = result.trim();
                m_strSenseList = result;
                Log.d("KSJ","result:" + result);
                m_bSenseListResult = true;

//
//                m_iAICount = 0;
//                if (result.startsWith("{")) {
//                    String strName = dong;
//                    Log.d("KSJ","result:1 " + strName);
//                    try {
//                        JSONObject jsonObject = new JSONObject(result);
//
//                        JSONArray movieArray = jsonObject.getJSONArray("id");
//                        m_strSenseList = new String[movieArray.length()]
//                        for (int i = 0; i < movieArray.length(); i++) {
//
////                            String s = "Hello welcome to the this place";
////                            if(s.contains("welcoma"));
////                            {
////                                Log.d("KSJ", "search list " + i + " " + movieArray.getString(i));
////                                m_iAICount++;
////                            }
//                        }
//
//
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }

            }
        });
    }

    public int applyAddImage(String path, String id) {
        byte[] data = FileUtils.read(path + "/" + id + "_dest.jpg");
        int ret = MtcCode.ERR_NO_IMAGE.getRetCode();
        if (data != null) {
            ret = mClient.mtcAiAddLargeImageFromExternal(data, id);
        }
        return ret;
    }

    public int applyAllAddImage(String path, String id) {
        byte[] data = FileUtils.read(path);
        int ret = MtcCode.ERR_NO_IMAGE.getRetCode();
        if (data != null) {
            ret = mClient.mtcAiAddLargeImageFromExternal(data, id);
        }
        return ret;
    }

    int mRet = 0;
    boolean m_bDelRet = false;
    public int delUserImage(String id)
    {
        m_bDelRet = false;
        mClient.mtcAiDelUserImageById(id, (mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS) {
                Log.d(TAG, "mRet = 1 Success remove the file");
                mRet = 1;
                m_bDelRet = true;
            } else {
                Log.d(TAG, "mRet = 0 Couldn't remove the file");
                mRet = 0;
                m_bDelRet = true;
            }
        });

        return mRet;
    }
    HDCSFTPManager hdcsftpManager = new HDCSFTPManager();
    public boolean addPicSFTPDown(String strIP, String strID, String strPWD, String strPATH, String strFileName, String strName)
    {
        boolean result = false;

        Log.d(TAG, "hdcsftpManager [START]");

//        if(hdcsftpManager.isFTPConnected())
//        {
//            Log.d(TAG, "hdcsftpManager.isFTPConnected()");
//
//        }

        hdcsftpManager.setCtrlEncoding("euc-kr");
        Log.d(TAG, "hdcsftpManager [START]");
        try {
            hdcsftpManager.setReceiveBufferSize(1024*512);
        }
        catch (RuntimeException re)
        {
            Log.d(TAG, "setReceiveBufferSize" + re.toString());
            return false;
        }
        catch (Exception e1) {
            e1.printStackTrace();

            return false;
        }

        result = hdcsftpManager.connectFTP(strIP);
        if(!result)
        {
            Log.d(TAG, "hdcsftpManager.connectFTP() error");
            return false;
        }

        result = hdcsftpManager.loginFTP(strID, strPWD);
        if(!result)
        {
            Log.d(TAG, "hdcsftpManager.loginFTP() error");
            return false;
        }

        if (!hdcsftpManager.setPassiveMode()) {
            Log.d(TAG, "[uploadVisitorPicture.run()] FAIL!! -> setPassiveMode(...)");
            try {
                if (hdcsftpManager.logoutFTP()) {
                    if (hdcsftpManager.disconnectFTP()) {
                        Log.d(TAG, "[disconnectFTP] disconnectFTP OK!!");
                    }
                }
                Log.d(TAG, "[disconnectFTP] disconnectFTP FAIL!!");
            } catch (RuntimeException re) {
                re.fillInStackTrace();
            }
            catch (Exception e) {
                Log.d(TAG,  "[Exception] disconnectFTP()");

            }
        }

        result = hdcsftpManager.changeWorkingDirectory(strPATH);
        if(!result)
        {
            Log.d(TAG, "hdcsftpManager.changeWorkingDirectory() error");
            return false;
        }

        result = hdcsftpManager.setFileType(FTP.BINARY_FILE_TYPE);
        if (result == false) {
            Log.d(TAG, "setFileType False");
        }


        result = hdcsftpManager.downloadFile(strFileName,SAVEPICTURE_PATH+ "/" +strName+".jpg");

        hdcsftpManager.logoutFTP();
        Log.d(TAG, "hdcsftpManager [STOP]");
        return result;
    }


    @SuppressLint("CheckResult")
    private void getCountOfId() {
        mClient.mtcAiIDCountGet((mtcCode, result) -> {
            if (mtcCode == MtcCode.SUCCESS && !TextUtils.isEmpty(result)) {
                m_iAICount = Integer.parseInt(result);
                //showBasicDialogNoCancel(R.string.quantity_of_id, idCount + "");

            } else {
                //showToast(getMtcErrorMsg(mtcCode));
            }
        });
    }

    public void senstime_FWUdate()
    {
        //WriteFirmwareTask writeFirmwareTask = new WriteFirmwareTask(this, FileUtils.getStreamFromExternal("/sdcard/m20_V2.5.6_update_tar.bin"), 0);
        //writeFirmwareTask.execute();
        //startActivity(new Intent(USBCameraActivity2.this, SettingActivity.class));

        Intent intent = new Intent(this, kr.co.icontrols.ilp300_700.screen.SettingActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //intent.putExtra("test",1);
        startActivity(intent);

//        m_bLauncherStart = false;
//        m_isResultView = false;
//        m_isSwitchState = false;
//
//        MClient.getInstance().setReceiveCallback(null);
//
//        clearCanvas();
//        isRunning = false;
//        releaseAndRequestCamera(null);
//        lastUpdatePreviewDataMillis = 0;
//
//        mClient.mtcAiPause((mtcCode, result) -> {
//            if (mtcCode != MtcCode.SUCCESS) {
//                Log.e(TAG, "mtcAiPause error message:" + getMtcErrorMsg(mtcCode));
//            }
//            else
//            {
//                File file = new File(Environment.getExternalStorageDirectory().getPath()+"/m20_V2.5.6_update_tar.bin");
//                Uri uri = null;
//                if (file.exists()) {
//                    uri = Uri.fromFile(file);
//                }
//                int length = (int) file.length();
//                WriteFirmwareTask writeFirmwareTask = new WriteFirmwareTask(this, uri, length);
//                writeFirmwareTask.execute();
//            }
//        });


    }



    private void checkUserPermission() {
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if(permissionGranted(permissions, 0)) {
            if(UsbDeviceHelper.getInstance().isConnceion)
            {
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Todo
                        if (senseTimeMtc.isInitSuccess() && senseTimeMtc.getmDeviceModule() != SenseTimeMtc.UNKNOWN_DEVICE_MODULE) {
                            initMtc();
                        } else {
                            initMtc();
                        }
                    }
                }, 500);


            }

            UsbDeviceHelper.getInstance().setCallBack(new UsbStateCallBack() {
                @Override
                public void usbConnect() {
                    Log.d(TAG, "jglee --------------------- Usb Connect");
                    Log.d(TAG, "Connect usb");
                    if (senseTimeMtc.isInitSuccess() && senseTimeMtc.getmDeviceModule() != SenseTimeMtc.UNKNOWN_DEVICE_MODULE) {
                        initMtcInfo();
                    } else {
                        initMtc();
                    }
                }

                @Override
                public void usbDisConnect() {
                    Log.d(TAG, "jglee --------------------- Usb DisConnect");
                    Log.d(TAG, "disconnect usb");
                    MClient.getInstance().mtcDestroy();
                    senseTimeMtc.setInitStatus(false);
                }
            });
        }
    }

    @SuppressLint("CheckResult")
    private void initMtc() {
        senseTimeMtc.initMtc(new SenseTimeMtc.InitCallback() {
            @Override
            public void onFinish() {
                Log.d(TAG, "jglee ------------ initMacFinish()");
                initMtcInfo();
                initCtrl();
                InitDataFunction();

                if (senseTimeMtc.getmDeviceModule() == SenseTimeMtc.M10) {
                    if (senseTimeMtc.getmM10_L_P() == SenseTimeMtc.PORTRAIT_90 || senseTimeMtc.getmM10_L_P() == SenseTimeMtc.PORTRAIT_270) {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //force portrait if you wish.
                    } else {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    }
                } else {
//                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }

                synchronized (mSyncUSBMonitor) {
                    Log.d(TAG, "jglee - register");
                    mUSBMonitor.register();
                }

                if (!isRunning) {
                    isRunning = true;
                    boolean isSetCallbackSuccess = MClient.getInstance().setReceiveCallback(myIReceiveCallback);
                    if (!isSetCallbackSuccess) {
                        Log.d(TAG, "Actively reported callback interface setup failed");
                    }

                    //requestPermissionDevice();

                    if (senseTimeMtc.isPauseAI()) {//Camera Tracking view On/Off 하는 부분
                        mClient.mtcAiPause((mtcCode, result) -> {
                            Log.d(TAG,"mtcAiPause's result: " + getMtcErrorMsg(mtcCode));
                        });
                    } else {//用户手动去恢复了AI识别算法，默认模式
                        mClient.mtcAiResume((mtcCode, result) -> {
                            Log.d(TAG, "mtcAiResume's result: " + getMtcErrorMsg(mtcCode));
                        });
                    }

                    if (senseTimeMtc.getIsIRRGBMode() == SenseTimeMtc.IR_RGB_NONE && SenseTimeMtc.M10 != senseTimeMtc.getmDeviceModule()) {
                        Log.d(TAG, "IRRGBMode == SenseTimeMtc.IR_RGB_NONE and DeviceModule != M10");
                        //不知道是IR还是RGB模式下，默认换成RGB模式
                        senseTimeMtc.setIsMirror(0x01); // default
                        irRGBSwitch(0);
                    } else {
                        requestPermissionDevice();
                    }
                }
            }
        });
    }
    boolean isM30;
    private void initCtrl()
    {

        m_iDetectLen = DETECTLEN;

        replyAddFacepic = new reply_add_facepic(this);

        File dir = new File(
                SAVEPICTURE_PATH);
        if(!dir.exists())
        {
            dir.mkdirs();
        }

        SharedPreferences pref = getSharedPreferences(PREFERENCE, MODE_PRIVATE);

//        m_RebootCnt = pref.getInt(Reboot_Count, 0);
//        Log.d(TAG, "[initCtrl] m_RebootCnt ************ [" + m_RebootCnt + "] ************");
//
//        m_RebootCnt++; // 재부팅 후 count ++
//        SharedPreferences.Editor editor = pref.edit();
//        editor.putInt(Reboot_Count, m_RebootCnt);
//        editor.commit();
        Log.d(TAG, "[initCtrl] ****** M20/M30 ****** MODULE TYPE [" + senseTimeMtc.getmDeviceModule() + "]");

        m_bSettingAI = pref.getBoolean(Face_AI_Set, false);
        m_bSettingShowVideo = pref.getBoolean(Face_Show_Video, true);
        m_iDistanceValue_old = pref.getInt(Face_Detect_Value, 3);
        if (senseTimeMtc.getmDeviceModule() == SenseTimeMtc.M20) m_iThrescase = pref.getInt(Face_Threshold_Value, recog_thres_m20); // 0.9f
        else m_iThrescase = pref.getInt(Face_Threshold_Value, recog_thres_m30); // 0.915f
        m_iRecogValue = pref.getInt(Face_Recog_Value, 10);
        Log.d(TAG, "[initCtrl] m_iThrescase [" + m_iThrescase + "]");

        m_bSettingIRLED = pref.getBoolean(Face_IRLed_Value, true);

        m_bHaveMaskOrHat = pref.getBoolean(Face_Mask_Value, false);
        m_bAEMode = pref.getBoolean(Face_AEMode_Value, false);
        Log.d(TAG, "[initCtrl] m_bAEMode [" + m_bAEMode + "]");


        try {

            m_iDetectLen = m_DetectCase[Configure.ConfigValue.DEVICE_MODELTYPE][m_iDistanceValue_old-1];
            Log.d(TAG, "[initCtrl] m_iDetectLen [" + m_iDetectLen + "], m_iDistanceValue [" + m_iDistanceValue + "]");
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            m_iDistanceValue_old = 3;
            m_iDetectLen = m_DetectCase[Configure.ConfigValue.DEVICE_MODELTYPE][m_iDistanceValue_old-1];
            Log.d(TAG, "[initCtrl] exception m_iDetectLen [" + m_iDetectLen + "], m_iDistanceValue [" + m_iDistanceValue + "]");
        }

        try {

            m_fThreshValue = m_ThresCase[m_iThrescase-1];
            Log.d(TAG, "[initCtrl] m_fThreshValue [" + m_fThreshValue + "]");
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            setRecogThreshold_Default();
        }

        setAiConfig_first();
        setAiConfig();

        setDeviceAntiFlickerset(m_bAEMode);


        setDeviceIRLedON();
        m_bIRLEDState = false;

        if(m_bSettingAI)
            setTemplateUpdate(1);
        else
            setTemplateUpdate(0);

        m_aes = new AES();

        try {
            isM30 = (senseTimeMtc.getmDeviceModule() == SenseTimeMtc.M30) ? true : false;
        }
        catch (Exception ex)
        {
            Logger.e("KSJ", "AvcEncoder init error1");
        }

        //MaterialDialog progressDialog = MaterialDialogUtils.showIndeterminateProgressDialog(this, "", false).show();
        mClient.mtcAllIdListGet((mtcCode, result) -> {

            if (mtcCode == MtcCode.SUCCESS) {
                Log.d(TAG, " KSJ result:" + result);
                //MaterialDialogUtils.showBasicDialogNoCancel(this, getString(R.string.get_all_ids), result).show();
            }
            //progressDialog.dismiss();
        });
    }

    public void setRecogThreshold_Default() {
        try {
            if (senseTimeMtc.getmDeviceModule() == SenseTimeMtc.M20) {
                m_iThrescase = recog_thres_m20; // 0.9f
                m_fThreshValue = 0.9f;
            }
            else {
                m_iThrescase = recog_thres_m30; // 0.915f
                m_fThreshValue = 0.915f;
            }
            Log.d(TAG, "[setRecogThreshold_Default] m_iThrescase [" + m_iThrescase + "]");
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setRecogThreshold_Default()");
            e.printStackTrace();
        }
    }

    private void initMtcInfo() {
        if (senseTimeMtc.isInitSuccess()) {
            if (senseTimeMtc.getmDeviceModule() == SenseTimeMtc.UNKNOWN_DEVICE_MODULE) {
                Log.d(TAG, "initMtcInfo : " + getString(R.string.can_not_get_deviceinfo));
            } else {
                Log.d(TAG, "initMtcInfo : " + getString(R.string.init_success) + ", Device Module : " + senseTimeMtc.getmDeviceModule());
            }
        } else {
            //setBtnEnable(false);
            //showBasicDialogNoCancel(R.string.notice_init_failure, "");
        }

        mClient.mtcAiPause((mtcCode, result) -> {
            if (mtcCode != MtcCode.SUCCESS) {
                Log.d(TAG, "mtcAiPause error message:" + getMtcErrorMsg(mtcCode));
            }
        });
    }

}

