package kr.co.icontrols.wallpadmulticontrolservice; import android.annotation.SuppressLint; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import com.artncore.WallPadDataMgr.WallpadDeviceSet; import com.artncore.WallPadDataMgr.WallpadStatusData; import com.artncore.WallPadDataMgr.wallpaddbmgr; import com.artncore.commons.API_Menu; import com.artncore.commons.DataClasses; import com.artncore.commons.KNX_DataClasses; import com.artncore.commons.define; import com.artncore.wallpadapi.CooktopAPI; import com.artncore.wallpadapi.EnergyMeterAPI; import com.artncore.wallpadapi.GasAPI; import com.artncore.wallpadapi.HeatingV2API; import com.artncore.wallpadapi.IGW300API; import com.artncore.wallpadapi.KnxAPI; import com.artncore.wallpadapi.KnxSystemAirconAPI; import com.artncore.wallpadapi.RealTimeMeterAPI; import com.artncore.wallpadapi.SdbAPI; import com.artncore.wallpadapi.Sdb_LivingRoomLightAPI; import com.artncore.wallpadapi.SystemAirconAPI; import com.artncore.wallpadapi.VentiAPI; import com.artncore.wallpadapi.WallPadAPI; import com.google.gson.Gson; import com.util.LogUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Random; import kr.co.icontrols.wallpadmulticontrolservice.control.AirconControl; import kr.co.icontrols.wallpadmulticontrolservice.control.HeatingControl; import kr.co.icontrols.wallpadmulticontrolservice.control.KnxAirconControl; import kr.co.icontrols.wallpadmulticontrolservice.control.LightControl; import kr.co.icontrols.wallpadmulticontrolservice.control.VentiControl; import kr.co.icontrols.wallpadmulticontrolservice.data.BasicData; import kr.co.icontrols.wallpadmulticontrolservice.data.RequestData; import kr.co.icontrols.wallpadmulticontrolservice.Common.JSON; import kr.co.icontrols.wallpadsupport.Version; import kr.co.icontrols.wallpadsupport.WpadSound; public class DataSenderService extends Service { String TAG = this.getClass().getSimpleName(); private void DebugLogOutput(String s) { if (Common.DEBUG_LOG_ON) Log.d(TAG, s); } protected Context mContext = null; public Context getContext() { return mContext; } private WallPadAPI mWallPadAPI = null; private WallpadStatusData wdb = null; WallpadStatusData DBMGR = null; ServerThread thread; int roomNumber = 0; String myIP = "NONE"; String myDong = "NONE"; String myHo = "NONE"; private final String JSON_SOURCE = "wallpad"; public static final String SENSOR_BR_NAME = "kr.co.icontrols.wallpadmulticontrolservice.BR_IGW300_SENSOR_ALARM"; // 제어 디바이스 드라이버 요청을 위한 BR 정의 public static final class BrID { private final static String BR_ACTION_BASE = "kr.co.icontrols.wallpadmulticontrolservice.BR_"; private final static int BASE = 9999; public final static String BR_LIVING_LIGHT = BR_ACTION_BASE + "LIVING_LIGHT_HDC" + "(" + BASE + ")"; public final static String BR_ENERGY_METER = BR_ACTION_BASE + "ENERGY_METER_HDC" + "(" + BASE + ")"; public final static String BR_BATCH_LIGHT = BR_ACTION_BASE + "BATCH_LIGHT_HDC" + "(" + BASE + ")"; public final static String BR_GAS = BR_ACTION_BASE + "GAS_HDC" + "(" + BASE + ")"; public final static String BR_VENTIL = BR_ACTION_BASE + "VENTIL_HDC" + "(" + BASE + ")"; public final static String BR_HEATING = BR_ACTION_BASE + "HEATING_HDC" + "(" + BASE + ")"; public final static String BR_AIRCON = BR_ACTION_BASE + "AIRCON_HDC" + "(" + BASE + ")"; public final static String BR_SDB_LIVING_EVENT = BR_ACTION_BASE + "LIVING_SDB_HDC" + "(" + BASE + ")"; public final static String BR_SDB_EVENT = BR_ACTION_BASE + "SDB_HDC" + "(" + BASE + ")"; public final static String BR_KNX_EVENT = BR_ACTION_BASE + "KNX_HDC" + "(" + BASE + ")"; } public static boolean bDeviceInitComplete = false; // 월패드 제어기기들의 드라이버의 초기화가 완료된 상태 저장 // 가스 private GasAPI mGasAPI = null; private CooktopAPI cooktopAPI; // 쿡탑 API private CooktopAPI.Data mCookTopData = null; private int nGasCnt = 1; //최대 3대 public byte[] haGasStatus = new byte[]{GasAPI.GASSTATUS.Close, GasAPI.GASSTATUS.Close, GasAPI.GASSTATUS.Close}; // 환기 private VentiAPI mVentiAPI = null; private VentiControl mVentiControl; public Ventilation mVentilation = new Ventilation(); private VentilData mVentilData = null; private class VentilData { DataClasses.Venti VentilStatus; int Type; // 현산,LH,후드 int[] TimerTable; public VentilData(int nType) { VentilStatus = new DataClasses.Venti(); Type = nType; if (Type == API_Menu.SubMenuCtrl.ChangAir_LH) TimerTable = new int[]{0, 30, 60, 90}; else TimerTable = new int[]{0, 10, 20, 30, 60, 120, 180, 240}; } } public static class Ventilation { /** * ON/OFF 상태 */ public boolean OnOff; /** * 바람세기 상태 */ public byte Wind; } //난방 private HeatingV2API mHeatingV2API = null; private Heating mHeating = new Heating(); private HeatingControl mHeatingControl; public class Heating { public HeatingRoom[] eachRoom = new HeatingRoom[10]; public Heating() { for (int i = 0; i < 10; i++) { eachRoom[i] = new HeatingRoom(); } } } //에어컨 private SystemAirconAPI mSystemAirconAPI; private AirconData mAirconData = new AirconData(); private AirconControl mAirconControl; private class AirconData { private SystemAirconAPI.Data systemAircon; public AirconData() { systemAircon = new SystemAirconAPI.Data(); } } //KNX 에어컨 private KnxSystemAirconAPI mKnxSystemAirconAPI; private KnxAirconData mKnxAirconData = new KnxAirconData(); private KnxAirconControl mKnxAirconControl; private class KnxAirconData { private KnxSystemAirconAPI.Data systemAircon; public KnxAirconData() { systemAircon = new KnxSystemAirconAPI.Data(); } } //조명(KNX 분전반) private KnxAPI mKnxAPI = null; private LightControl mLightControl; private Data_KnxLiv mKnxData = null; /** * KNX 에너지미터 데이터 **/ private class Data_KnxLiv { /** * 침실에너지미터 개수 */ public byte BadRoom_Em_Count = 0; /** * [마스터 컨트롤러] 데이터 */ public KNX_DataClasses.MasterControllerClass MasterController = null; /** * [거실 에너지미터] 데이터 */ public KNX_DataClasses.EnergyMeterClass LivingRoom_EnergyMeter = null; /** * [침실 에너지미터] 데이터 */ public KNX_DataClasses.EnergyMeterClass[] BadRoom_EnergyMeter = null; /** * [조명 스위치] 데이터 */ public KNX_DataClasses.LightSwithcClass[] Light_Switch = null; boolean ControlType; //false:밝기, true:색상 public Data_KnxLiv() { ControlType = false; MasterController = new KNX_DataClasses.MasterControllerClass(); LivingRoom_EnergyMeter = new KNX_DataClasses.EnergyMeterClass(); } } // 현산향 에너지미터 ( 각방 조명 , 콘센트 ) private EnergyMeterAPI mEnergyMeterAPI = null; // 조그 월패드 private Sdb_LivingRoomLightAPI mSdb_LivingRoomLightAPI; // 거실 조명 private SdbAPI mSdbAPI; // 각방 조명/콘센트 //센서 저장 값 boolean bIn_Motion = false; boolean bOut_Motion = false; boolean bMagnetic_Motion = false; // 에너지 미터 public EMeter mEMeter = null; public class EMeter { public EachRoom[] eachRoom = new EachRoom[6]; public EMeter() { for (int i = 0; i < 2; i++) eachRoom[i] = new EachRoom(); } } public class EachRoom { public boolean[] lampStatus = new boolean[]{false, false, false, false, false, false}; public boolean[] concentStatus = new boolean[]{false, false, false, false}; public boolean[] ConMode = new boolean[]{false, false, false, false}; } // 에너지 미터의 조명/콘센트 값을 저장한다. public SDBEMInfo mSDBEMInfo = null; public class SDBEMInfo { int nEachRoomCnt = 6; public SpaceInfo LivingRoom; public SpaceInfo[] EachRoom = new SpaceInfo[nEachRoomCnt]; public SDBEMInfo() { LivingRoom = new SpaceInfo(); for (int i = 0; i < nEachRoomCnt; i++) EachRoom[i] = new SpaceInfo(); } } public class SpaceInfo { public boolean[] Light_bOnOff = new boolean[]{false, false, false, false, false, false}; public byte[] Light_hDim = new byte[]{(byte) 0x0A, (byte) 0x0A, (byte) 0x0A, (byte) 0x0A, (byte) 0x0A, (byte) 0x0A}; public byte[] Light_hColor = new byte[]{(byte) 0x0A, (byte) 0x0A, (byte) 0x0A, (byte) 0x0A, (byte) 0x0A, (byte) 0x0A}; public byte[] Outlet_hOnOff = new byte[]{DataClasses.MultiSwitch.OUTLET_STATUS.Off, DataClasses.MultiSwitch.OUTLET_STATUS.Off, DataClasses.MultiSwitch.OUTLET_STATUS.Off, DataClasses.MultiSwitch.OUTLET_STATUS.Off}; public byte[] Outlet_hCutoff = new byte[]{DataClasses.MultiSwitch.OUTLET_MODE.Always, DataClasses.MultiSwitch.OUTLET_MODE.Always, DataClasses.MultiSwitch.OUTLET_MODE.Always, DataClasses.MultiSwitch.OUTLET_MODE.Always}; } public static class HeatingRoom { public byte mode; public double curTemper; public double setTemper; } public DataSenderService() { } public static final String INTENT_ACTION = "com.icontrols.service.data.IDataSenderService"; private static final int MSG_WORK = 1; @Override public IBinder onBind(Intent intent) { return null; } class ServerThread extends Thread { @Override public void run() { int port = 9998; try { ServerSocket server = new ServerSocket(port); Log.d("ServerThread", "서버가 실행됨."); while (true) { Socket socket = server.accept(); // server 대기상태. 클라이언트 접속 시 소켓 객체 리턴 ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream()); // 들어오는 데이터 처리 ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); String data = null; try { socket.setSoTimeout(5000); data = (String) inputStream.readObject(); if (data == null) { inputStream.close(); continue; } Log.d("ServerThread", "data=" + data); } catch (Exception e) { Log.d("ServerThread_error", "e : " + e); inputStream.close(); continue; } Gson gson = new Gson(); JSONObject allObject = null; BasicData basicData = null; try { allObject = new JSONObject(data); basicData = gson.fromJson(allObject.toString(), BasicData.class); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if (data != null && !data.trim().equals("") && basicData.getType().equalsIgnoreCase("request") && basicData.getReason() == JSON.REASON.Control) { //제어 요청 int result = controlRequest(allObject, basicData.getMenu(), basicData.getKind(), basicData.getPosition()); String json = ""; String resultStr = "ok"; if (result == 0) { resultStr = "ok"; } else if (result == -100) { resultStr = "service not supported"; } else if (result == -2) { resultStr = "internal server error"; } else if (result == -1000) { resultStr = "invalid syntax"; } else if (result == -1111) { resultStr = "service not supported"; } resultStr = "ok"; // build jsonObject JSONObject jsonObject = new JSONObject(); JSONObject dataJsonObject = new JSONObject(); try { jsonObject.accumulate("type", "controlResponse"); jsonObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); jsonObject.accumulate("ip", myIP); jsonObject.accumulate("menu", basicData.getMenu()); jsonObject.accumulate("result", resultStr); } catch (JSONException e) { resultStr = "invalid syntax"; jsonObject.accumulate("result", resultStr); e.printStackTrace(); } //jsonObject.accumulate("data", dataJsonObject); // convert JSONObject to JSON to String json = jsonObject.toString(); outputStream.writeObject(json); outputStream.close(); Log.d("ServerThread", "result 보냄 : " + result); } else if (data != null && !data.trim().equals("") && basicData.getType().equalsIgnoreCase("request") && basicData.getReason() == JSON.REASON.Status) { try { JSONObject result = updateRequest(basicData.getMenu(), basicData.getKind(), basicData.getPosition()); Random rand = new Random(); int iValue = rand.nextInt(4); // 0 <= iValue < 10 int menu = basicData.getMenu(); String sampleAirconResult = "{\"type\" : \"updateResponse\", " + "\"timestamp\" : \"2020-09-08T03:03:04\", " + "\"ip\" : \"52.33.222.11\", " + "\"menu\" : 1004, " + "\"aircon_status\" : 3, " + "\"support_auto\" : true, " + "\"support_cooling\" : true, " + "\"support_dehumidify\" : true, " + "\"support_fan\" : true, " + "\"support_heating\" : true, " + "\"data_array\" : [" + "{ \"roomNumber\" : 1, \"power\" : 1, \"mode\" : " + iValue + ", \"airvol\" : 1,\"setTemp\" : 10,\"nowTemp\" : 20 }," + "{ \"roomNumber\" : 2, \"power\" : 1, \"mode\" : " + iValue + ", \"airvol\" : 1,\"setTemp\" : 10,\"nowTemp\" : 20 }," + "{ \"roomNumber\" : 3, \"power\" : 2, \"mode\" : " + iValue + ", \"airvol\" : 1,\"setTemp\" : 10,\"nowTemp\" : 20 }," + "{ \"roomNumber\" : 4, \"power\" : 2, \"mode\" : " + iValue + ", \"airvol\" : 1,\"setTemp\" : 10,\"nowTemp\" : 20 } ]" + "}"; iValue = rand.nextInt(30); // 0 <= iValue < 10 String sampleHeatingResult = "{\"type\" : \"updateResponse\", " + "\"timestamp\" : \"2020-09-08T03:03:04\", " + "\"ip\" : \"52.33.222.11\", " + "\"menu\" : 1002, " + "\"support_setpoint05\" : true, " + "\"support_outing\" : true, " + "\"support_sleep\" : true, " + "\"support_reservation\" : true, " + "\"support_pause\" : true, " + "\"support_ai\" : true, " + "\"support_outsidetempuse\" : true, " + "\"support_boiler\" : true, " + "\"boiler_heatwater_temp\" : 60, " + "\"boiler_hotwater_temp\" : 50, " + "\"boiler_frost_protect\" : true, " + "\"boiler_error_code\" : 0, " + "\"data_array\" : [" + "{ \"roomNumber\" : 1, \"mode\" : " + 1 + ", \"setTemp\" : " + iValue + ",\"nowTemp\" : 20, \"reservationArray\" : [0,1,2,3,20], \"sleepTemp\" : 1, \"sleepTime\" : 1 }," + "{ \"roomNumber\" : 2, \"mode\" : " + 2 + ", \"setTemp\" : " + iValue + ",\"nowTemp\" : 21, \"reservationArray\" : [0,1,2,3,21], \"sleepTemp\" : 2, \"sleepTime\" : 2 }," + "{ \"roomNumber\" : 3, \"mode\" : " + 5 + ", \"setTemp\" : " + iValue + ",\"nowTemp\" : 22, \"reservationArray\" : [0,1,2,3,22], \"sleepTemp\" : 3, \"sleepTime\" : 3 }," + "{ \"roomNumber\" : 4, \"mode\" : " + 6 + ", \"setTemp\" : " + iValue + ",\"nowTemp\" : 23, \"reservationArray\" : [0,1,2,3,23], \"sleepTemp\" : 1, \"sleepTime\" : 4 } ]" + "}"; iValue = rand.nextInt(2); boolean onoff = false; if (iValue == 1) onoff = true; String sampleLightResult; if (myIP.equals("10.1.1.2")) { sampleLightResult = "{\"type\" : \"updateResponse\", " + "\"timestamp\" : \"2020-09-08T03:03:04\", " + "\"ip\" : " + myIP + ", " + "\"menu\" : 1001, " + "\"master_info_fault\" : true, " + "\"master_data_batch\" : " + iValue + ", " + "\"master_info_liv_count\" : 1, " + "\"master_info_bad_count\" : 3, " + "\"master_info_switch_count\" : 3, " + "\"liv_info_install\" : true, " + "\"liv_info_lightcount\" : 2, " + "\"liv_data_array\" : [" + "{ \"info_install\" : true, \"info_type\" : 2, \"data_onoff\" : " + onoff + ", \"data_dimming\" : 1 }," + "{ \"info_install\" : true, \"info_type\" : 2, \"data_onoff\" : " + onoff + ", \"data_dimming\" : 1 } ]," + "\"bed_data_array\" : [" + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 15,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"lightArray\" : [true, true] }," + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 15,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"lightArray\" : [true, true] }," + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 15,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"lightArray\" : [true, true] } ]," + "\"switch_data_array\" : [" + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 14,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"switchArray\" : [true, true] }," + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 14,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"switchArray\" : [true, true] }," + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 15,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"switchArray\" : [true, true] } ]" + "}"; } else { sampleLightResult = "{\"type\" : \"updateResponse\", " + "\"timestamp\" : \"2020-09-08T03:03:04\", " + "\"ip\" : " + myIP + ", " + "\"menu\" : 1001, " + "\"master_info_fault\" : true, " + "\"master_data_batch\" : " + iValue + ", " + "\"master_info_liv_count\" : 1, " + "\"master_info_bad_count\" : 2, " + "\"master_info_switch_count\" : 2, " + "\"liv_info_install\" : true, " + "\"liv_info_lightcount\" : 2, " + "\"liv_data_array\" : [" + "{ \"info_install\" : true, \"info_type\" : 2, \"data_onoff\" : " + onoff + ", \"data_dimming\" : 1 }," + "{ \"info_install\" : true, \"info_type\" : 2, \"data_onoff\" : " + onoff + ", \"data_dimming\" : 1 } ]," + "\"bed_data_array\" : [" + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 15,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"lightArray\" : [true, true] }," + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 15,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"lightArray\" : [true, true] } ]," + "\"switch_data_array\" : [" + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 14,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"switchArray\" : [true, true] }," + "{ \"info_install\" : true, \"info_lightcount\" : 2, \"info_light_type1\" : 1,\"info_light_type2\" : 15,\"info_light_type3\" : 1,\"info_light_type4\" : 1,\"switchArray\" : [true, true] } ]" + "}"; } iValue = rand.nextInt(2); String sampleCookTopResult = "{\"type\" : \"updateResponse\", " + "\"timestamp\" : \"2020-09-08T03:03:04\", " + "\"ip\" : \"52.33.222.11\", " + "\"menu\" : 1004, " + "\"device_count\" : 3, " + "\"data_array\" : [" + "{ \"hID\" : 1, \"hStatus\" : 3, \"hType\" : " + iValue + ", \"hErrorStatus\" : 0}," + "{ \"hID\" : 2, \"hStatus\" : 3, \"hType\" : " + iValue + ", \"hErrorStatus\" : 0}," + "{ \"hID\" : 3, \"hStatus\" : 2, \"hType\" : " + iValue + ", \"hErrorStatus\" : 0} ]" + "}"; outputStream.writeObject(result.toString()); String resultTemp; if (menu == 1003) resultTemp = sampleHeatingResult; else if (menu == 1001) resultTemp = sampleLightResult; else if (menu == 1006) resultTemp = sampleCookTopResult; else resultTemp = sampleAirconResult; //outputStream.writeObject(resultTemp); outputStream.close(); Log.d("ServerThread", "result 보냄 : " + resultTemp); } catch (Exception e) { outputStream.close(); e.printStackTrace(); } } else if (data != null && !data.trim().equals("") && basicData.getType().equalsIgnoreCase("request") && basicData.getReason() == JSON.REASON.PassWordChange) { //제어 요청 int result = passwordChangeRequest(basicData.getNumber()); String json = ""; String resultStr = "ok"; if (result == 0) { resultStr = "ok"; } else if (result == JSON.ERROR.Exception) { resultStr = "internal server error"; } // build jsonObject JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("type", "controlResponse"); jsonObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); jsonObject.accumulate("ip", myIP); jsonObject.accumulate("menu", basicData.getMenu()); jsonObject.accumulate("result", resultStr); } catch (JSONException e) { resultStr = "invalid syntax"; jsonObject.accumulate("result", resultStr); e.printStackTrace(); } json = jsonObject.toString(); outputStream.writeObject(json); outputStream.close(); Log.d("ServerThread", "result 보냄 : " + result); } inputStream.close(); socket.close(); // 연결을 유지할 필요 없으면 끊어줌. } } catch (Exception e) { e.printStackTrace(); } } } /** * 개별 에어컨 전원 제어 (개별 항목 제어) * * @return true: 성공, false: 실패 */ private int ctrlPowerToggle(byte roomIndex) { try { byte hPower = mAirconData.systemAircon.Device.Aircon[roomIndex].hPower; DebugLogOutput("[ctrlPowerToggle] Current hPower [" + hPower + "]"); if (hPower == DataClasses.SystemAircon.POWER.On) hPower = DataClasses.SystemAircon.POWER.Off; else hPower = DataClasses.SystemAircon.POWER.On; int nResult = -100; if (mAirconData.systemAircon.Device.info.Support.bV2CMDUsage) { nResult = mAirconControl.ctrlUnitAirconPowerV2((byte) roomIndex, hPower); } else { byte hMode = mAirconData.systemAircon.Device.Aircon[roomIndex].hMode; byte hAirVol = mAirconData.systemAircon.Device.Aircon[roomIndex].hAirVol; byte hSetTemper = mAirconData.systemAircon.Device.Aircon[roomIndex].hSetTemper; boolean bAirSwing = mAirconData.systemAircon.Device.Aircon[roomIndex].bAirSwing; nResult = mAirconControl.ctrlUnitAircon((byte) roomIndex, hPower, hMode, hAirVol, hSetTemper, bAirSwing); } return nResult; } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { Log.e(TAG, "[Exception] ctrlPowerToggle()"); LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 에어컨 전원 제어 */ private int ctrlPowerToggle() { try { int nResult = -100; boolean bCurrentAllOnOff = false; // 전체제어 영역 상태 갱신을 위해 for (int i = 0; i < mAirconData.systemAircon.Device.info.hInsideAirconCnt; i++) { if (mAirconData.systemAircon.Device.Aircon[i].hPower == DataClasses.SystemAircon.POWER.On) { bCurrentAllOnOff = true; break; } } byte onoff = DataClasses.SystemAircon.POWER.On; if (bCurrentAllOnOff) { onoff = DataClasses.SystemAircon.POWER.Off; } if (mAirconData.systemAircon.Device.info.Support.bV2CMDUsage) { nResult = mAirconControl.ctrlEntireAirconPowerV2((byte) onoff); } else { nResult = mAirconControl.ctrlEntireAirconPower((byte) onoff); } return nResult; } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { Log.e(TAG, "[Exception] ctrlPowerToggle()"); //e.printStackTrace(); LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 개별 에어컨 운전모드 제어 (개별 항목 제어) */ private int ctrlMode(byte roomIdx, byte hMode) { try { DebugLogOutput("[ctrlMode] hMode [" + hMode + "]"); int nResult = -100; if (mAirconData.systemAircon.Device.info.Support.bV2CMDUsage) { nResult = mAirconControl.ctrlUnitAirconModeV2((byte) roomIdx, hMode); } else { byte hPower = mAirconData.systemAircon.Device.Aircon[roomIdx].hPower; byte hAirVol = mAirconData.systemAircon.Device.Aircon[roomIdx].hAirVol; byte hSetTemper = mAirconData.systemAircon.Device.Aircon[roomIdx].hSetTemper; boolean bAirSwing = mAirconData.systemAircon.Device.Aircon[roomIdx].bAirSwing; nResult = mAirconControl.ctrlUnitAircon((byte) roomIdx, hPower, hMode, hAirVol, hSetTemper, bAirSwing); } return nResult; } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 전체 에어컨 운전모드 제어 (전체 항목 제어) */ private int ctrlMode(byte hMode) { try { DebugLogOutput("[ctrlMode] hMode [" + hMode + "]"); int nResult = -100; if (mAirconData.systemAircon.Device.info.Support.bV2CMDUsage) { nResult = mAirconControl.ctrlEntireAirconModeV2((byte) hMode); } else { nResult = mAirconControl.ctrlEntireAirconMode((byte) hMode); } return nResult; } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 개별 에어컨 풍량 제어 (개별 항목 제어) */ private int ctrlAirVol(byte roomIdx, byte hAirVol) { try { DebugLogOutput("[ctrlAirVol] hAirVol [" + hAirVol + "]"); int nResult = -100; if (mAirconData.systemAircon.Device.info.Support.bV2CMDUsage) { nResult = mAirconControl.ctrlUnitAirconAirVolV2((byte) roomIdx, hAirVol); } else { byte hPower = mAirconData.systemAircon.Device.Aircon[roomIdx].hPower; byte hMode = mAirconData.systemAircon.Device.Aircon[roomIdx].hMode; byte hSetTemper = mAirconData.systemAircon.Device.Aircon[roomIdx].hSetTemper; boolean bAirSwing = mAirconData.systemAircon.Device.Aircon[roomIdx].bAirSwing; nResult = mAirconControl.ctrlUnitAircon((byte) roomIdx, hPower, hMode, hAirVol, hSetTemper, bAirSwing); } return nResult; } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { Log.e(TAG, "[Exception] ctrlAirVol(byte hAirVol)"); LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 전체 에어컨 풍량 제어 (전체 항목 제어) */ private int ctrlAirVol(byte hAirVol) { try { DebugLogOutput("[ctrlAirVol] hAirVol [" + hAirVol + "]"); int nResult = -100; if (mAirconData.systemAircon.Device.info.Support.bV2CMDUsage) { nResult = mAirconControl.ctrlEntireAirconAirVolV2((byte) hAirVol); } else { nResult = mAirconControl.ctrlEntireAirconAirVol((byte) hAirVol); } return nResult; } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { Log.e(TAG, "[Exception] ctrlAirVol(byte hAirVol)"); LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 풍량 데이터를 증가 또는 감소 시킨다. */ private int ctrlAirVolUpDown(byte roomIndex, int bUp) { try { if (mAirconData == null) return JSON.ERROR.NotReady; if (mAirconData.systemAircon.Device.Aircon == null) return JSON.ERROR.NotReady; byte hAirVol = mAirconData.systemAircon.Device.Aircon[roomIndex].hAirVol; byte hMode = mAirconData.systemAircon.Device.Aircon[roomIndex].hMode; byte VolumeRange = 0x01; if (bUp == 1) { hAirVol += VolumeRange; //송풍인 경우와 이외의 경우의 풍량 모드가 다르다. (풍량 자동이 없음) if ((hAirVol > DataClasses.SystemAircon.AIRVOLUME.High) && !(hMode == DataClasses.SystemAircon.MODE.Fan)) hAirVol = DataClasses.SystemAircon.AIRVOLUME.Auto; else if ((hAirVol > DataClasses.SystemAircon.AIRVOLUME.High) && (hMode == DataClasses.SystemAircon.MODE.Fan)) hAirVol = DataClasses.SystemAircon.AIRVOLUME.Low; } else { hAirVol -= VolumeRange; //송풍인 경우와 이외의 경우의 풍량 모드가 다르다. (풍량 자동이 없음) if ((hAirVol < DataClasses.SystemAircon.AIRVOLUME.Auto) && !(hMode == DataClasses.SystemAircon.MODE.Fan)) hAirVol = DataClasses.SystemAircon.AIRVOLUME.High; else if ((hAirVol < DataClasses.SystemAircon.AIRVOLUME.Low) && (hMode == DataClasses.SystemAircon.MODE.Fan)) hAirVol = DataClasses.SystemAircon.AIRVOLUME.High; } return ctrlAirVol(roomIndex, hAirVol); } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { Log.e(TAG, "[Exception] ctrlAirVolUpDown(boolean bUp)"); //e.printStackTrace(); LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 개별 에어컨 풍량 제어 (개별 항목 제어) * * @return true: 성공, false: 실패 */ private int ctrlAirSwingToggle(byte roomIndex) { try { boolean bAirSwing = mAirconData.systemAircon.Device.Aircon[roomIndex].bAirSwing; DebugLogOutput("[ctrlAirSwingToggle] Current bAirSwing [" + bAirSwing + "]"); int nResult = -100; if (mAirconData.systemAircon.Device.info.Support.bV2CMDUsage) { nResult = mAirconControl.ctrlUnitAirconAirSwingV2((byte) roomIndex, !bAirSwing); } else { byte hPower = mAirconData.systemAircon.Device.Aircon[roomIndex].hPower; byte hMode = mAirconData.systemAircon.Device.Aircon[roomIndex].hMode; byte hAirVol = mAirconData.systemAircon.Device.Aircon[roomIndex].hAirVol; byte hSetTemper = mAirconData.systemAircon.Device.Aircon[roomIndex].hSetTemper; nResult = mAirconControl.ctrlUnitAircon((byte) roomIndex, hPower, hMode, hAirVol, hSetTemper, !bAirSwing); } return nResult; } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { Log.e(TAG, "[Exception] ctrlAirSwingToggle()"); //e.printStackTrace(); LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 개별 에어컨 풍량 제어 (개별 항목 제어) * * @return true: 성공, false: 실패 */ private int ctrlSetTemper(byte roomIndex, byte hSetTemper) { try { DebugLogOutput("[ctrlSetTemper] hSetTemper [" + hSetTemper + "]"); int nResult = -100; if (mAirconData.systemAircon.Device.info.Support.bV2CMDUsage) { nResult = mAirconControl.ctrlUnitAirconSetTemperV2((byte) roomIndex, hSetTemper); } else { byte hPower = mAirconData.systemAircon.Device.Aircon[roomIndex].hPower; byte hMode = mAirconData.systemAircon.Device.Aircon[roomIndex].hMode; byte hAirVol = mAirconData.systemAircon.Device.Aircon[roomIndex].hAirVol; boolean bAirSwing = mAirconData.systemAircon.Device.Aircon[roomIndex].bAirSwing; nResult = mAirconControl.ctrlUnitAircon((byte) roomIndex, hPower, hMode, hAirVol, hSetTemper, bAirSwing); } return nResult; } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { Log.e(TAG, "[Exception] ctrlSetTemper(byte hSetTemper)"); LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 설정온도 데이터를 증가 또는 감소 시킨다. */ private int ctrlSetTemperUpDown(byte roomIndex, int bUp) { try { if (mAirconData == null) return JSON.ERROR.NotReady; if (mAirconData.systemAircon.Device.Aircon == null) return JSON.ERROR.NotReady; DataClasses.SystemAircon.Info info = mAirconData.systemAircon.Device.info; byte hSetTemper = mAirconData.systemAircon.Device.Aircon[roomIndex].hSetTemper; byte hMode = mAirconData.systemAircon.Device.Aircon[roomIndex].hMode; byte TempRange = 0x01; if (bUp == 1) { // UP if (hMode == DataClasses.SystemAircon.MODE.Cooling) { hSetTemper += TempRange; if (hSetTemper >= info.Support.hMaxCoolSetTemper) hSetTemper = info.Support.hMaxCoolSetTemper; } else if (hMode == DataClasses.SystemAircon.MODE.Heating) { hSetTemper += TempRange; if (hSetTemper >= info.Support.hMaxHeatSetTemper) hSetTemper = info.Support.hMaxHeatSetTemper; } else if (hMode == DataClasses.SystemAircon.MODE.Auto) { hSetTemper += TempRange; byte hMaxTemper = (byte) Math.max(info.Support.hMaxHeatSetTemper, info.Support.hMaxCoolSetTemper); if (hSetTemper > hMaxTemper) hSetTemper = hMaxTemper; } else { // 냉방/난방/자동이 아닌경우에는 온도조절 불가 Log.w(TAG, "[ctrlSetTemperUpDown] SetTemper setting not supported!!! hMode -> " + hMode); return JSON.ERROR.NotSupported; } } else { // DOWN if (hMode == DataClasses.SystemAircon.MODE.Cooling) { hSetTemper -= TempRange; if (hSetTemper <= info.Support.hMinCoolSetTemper) hSetTemper = info.Support.hMinCoolSetTemper; } else if (hMode == DataClasses.SystemAircon.MODE.Heating) { hSetTemper -= TempRange; if (hSetTemper <= info.Support.hMinHeatSetTemper) hSetTemper = info.Support.hMinHeatSetTemper; } else if (hMode == DataClasses.SystemAircon.MODE.Auto) { hSetTemper -= TempRange; byte hMinTemper = (byte) Math.min(info.Support.hMinHeatSetTemper, info.Support.hMinCoolSetTemper); if (hSetTemper < hMinTemper) hSetTemper = hMinTemper; } else { // 냉방/난방/자동이 아닌경우에는 온도조절 불가 Log.w(TAG, "[ctrlSetTemperUpDown] SetTemper setting not supported!!! hMode -> " + hMode); return JSON.ERROR.NotSupported; } } return ctrlSetTemper(roomIndex, hSetTemper); } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); return JSON.ERROR.RuntimeException; } catch (Exception e) { Log.e(TAG, "[Exception] ctrlSetTemperUpDown(boolean bUp)"); LogUtil.errorLogInfo("", TAG, e); return JSON.ERROR.Exception; } } /** * 난방제어기 V2의 운전모드를 제어한다. * * @param RoomIdx - (byte) 제어할 방 인덱스 (0~5) * @param DeiveMode - (byte) 변경할 운전모드 (지원 타입별로 범위 상이함) HeatingAPI.V2DRIVEMODE_NONE 은 변경하지않음 * @return (int) - >=0 : 성공, <0 : 실패 */ private int ctrlDeviceMode(byte RoomIdx, byte DeiveMode) { DebugLogOutput("[ctrlDeviceMode] - (RoomIdx:" + RoomIdx + ", DeiveMode:" + String.format("%02x", DeiveMode) + ")"); return mHeatingControl.ctrlDeviceUnitStatus(RoomIdx, DeiveMode, 0); } private WpadSound mSound; private int setOnOff_BadRoom_EnergyMeter(int index) { boolean OnOff = false; for (int i = 0; i < mKnxData.BadRoom_EnergyMeter[index].Info.LightCount; i++) { if (mKnxData.BadRoom_EnergyMeter[index].Info.Install) { if (mKnxData.BadRoom_EnergyMeter[index].Data.BadLight[i].Data.OnOff == true) { OnOff = false; break; } if (i == mKnxData.BadRoom_EnergyMeter[index].Info.LightCount - 1) { OnOff = true; } } } int ret = mKnxAPI.SetLightOnOff((byte) (index), define.DEVICE_ALL_OR_NOTHING, OnOff); if (ret >= 0) mSound.Play(WpadSound.SND.effect.TOUCH_LATCHED); else mSound.Play(WpadSound.SND.effect.TOUCH_UNLATCHED); return ret; } private int setOnOff_Light_Switch(int index) { boolean OnOff = false; for (int i = 0; i < mKnxData.Light_Switch[index].Info.LightCount; i++) { if (mKnxData.Light_Switch[index].Info.Install) { if (mKnxData.Light_Switch[index].Data.LightSwitch[i].Data.OnOff == true) { OnOff = false; break; } if (i == mKnxData.Light_Switch[index].Info.LightCount - 1) { OnOff = true; } } } int ret = mKnxAPI.SetLightSwitchOnOff((byte) (index), define.DEVICE_ALL_OR_NOTHING, OnOff); if (ret >= 0) mSound.Play(WpadSound.SND.effect.TOUCH_LATCHED); else mSound.Play(WpadSound.SND.effect.TOUCH_UNLATCHED); return ret; } /** * 각방 전체 조명제어기를 켜고 끈다. * * @param RoomIdx - (byte) 제어할 기기 인덱스 (0~5 각방인덱스, 0xFF 전체방) * @param OnOff - true : ON / false : OFF * @return (int) - >=0 : 성공, <0 : 실패 */ private int Device_LightOnOffAll(byte RoomIdx, boolean OnOff) { DebugLogOutput("[Device_LightOnOff] - Start (RoomIdx : " + RoomIdx + " / OnOff : " + OnOff + ")"); int ret = 0; // 1. Api Load Check if (mKnxAPI == null) { Log.e(TAG, "[Device_LightOnOff] multiSwitchAPI unload !!!"); ret = JSON.ERROR.ApiNull; } // 2. Param Range Check if ((RoomIdx < 0) || (RoomIdx >= AllEMcount)) { Log.w(TAG, "[Device_LightOnOff] Param (RoomIdx) Out of range!!! (" + RoomIdx + ")"); ret = JSON.ERROR.OutOfRange; } // 3. Light Control try { if (ret == 0) { int emCount = 0; emCount = mKnxData.MasterController.Info.Liv_EnergyMeterCount + mKnxData.MasterController.Info.Bad_EnergyMeterCount; if (mKnxData.LivingRoom_EnergyMeter.Info.Install) { if (RoomIdx == 0) ret = mKnxAPI.SetLivingLightOnOff(define.DEVICE_ALL_OR_NOTHING, OnOff); else if (RoomIdx > 0 && RoomIdx < emCount) { ret = mKnxAPI.SetLightOnOff((byte) (RoomIdx - 1), define.DEVICE_ALL_OR_NOTHING, OnOff); } else { ret = mKnxAPI.SetLightSwitchOnOff((byte) (RoomIdx - emCount), define.DEVICE_ALL_OR_NOTHING, OnOff); } } else { if (RoomIdx < emCount) { ret = mKnxAPI.SetLightOnOff(RoomIdx, define.DEVICE_ALL_OR_NOTHING, OnOff); } else { ret = mKnxAPI.SetLightSwitchOnOff((byte) (RoomIdx - emCount), define.DEVICE_ALL_OR_NOTHING, OnOff); } } if (ret < 0) { Log.e(TAG, "[Device_LightOnOff] - [Return Error] multiSwitchAPI.SetLightOnOff(Index:" + RoomIdx + ", OnOff:" + OnOff + ")"); Log.e(TAG, "[Device_LightOnOff] - Error (" + ret + ") ErrorCode = " + mKnxAPI.ErrorCode.ErrStr()); } } if (ret >= 0) mSound.Play(WpadSound.SND.effect.TOUCH_LATCHED); else mSound.Play(WpadSound.SND.effect.TOUCH_UNLATCHED); } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); ret = JSON.ERROR.RuntimeException; ; } catch (Exception e) { Log.e(TAG, "[Device_LightOnOff] - [Exception Error] multiSwitchAPI.SetLightOnOff(Index:" + RoomIdx + ",OnOff:" + OnOff + ")"); //e.printStackTrace(); LogUtil.errorLogInfo("", TAG, e); ret = JSON.ERROR.Exception; } DebugLogOutput("[Device_LightOnOff] - OK"); return ret; } /** * 각방 개별 조명제어기를 켜고 끈다. * * @param RoomIdx - (byte) 제어할 기기 인덱스 (0~5 각방인덱스, 0xFF 전체방) * @param LightIdx - (byte) 제어할 조명 인덱스 * @return (int) - >=0 : 성공, <0 : 실패 */ private int Device_LightOnOffIndividual(byte RoomIdx, byte LightIdx) { DebugLogOutput("[Device_LightOnOffIndividual] - Start (RoomIdx : " + RoomIdx + " / LightIdx : " + LightIdx + ")"); int ret = 0; // 1. Api Load Check if (mKnxAPI == null) { Log.e(TAG, "[Device_LightOnOff] multiSwitchAPI unload !!!"); ret = JSON.ERROR.ApiNull; } // 2. Param Range Check if ((RoomIdx < 0) || (RoomIdx >= AllEMcount)) { Log.w(TAG, "[Device_LightOnOff] Param (RoomIdx) Out of range!!! (" + RoomIdx + ")"); ret = JSON.ERROR.OutOfRange; } boolean OnOff = true; // 3. Light Control try { if (ret == 0) { int emCount = 0; emCount = mKnxData.MasterController.Info.Liv_EnergyMeterCount + mKnxData.MasterController.Info.Bad_EnergyMeterCount; if (mKnxData.LivingRoom_EnergyMeter.Info.Install) { if (RoomIdx == 0) { if (mKnxData.LivingRoom_EnergyMeter.Data.LivingLight[LightIdx].Data.OnOff) OnOff = false; ret = mKnxAPI.SetLivingLightOnOff(LightIdx, OnOff); } else if (RoomIdx > 0 && RoomIdx < emCount) { if (mKnxData.BadRoom_EnergyMeter[RoomIdx - 1].Data.BadLight[LightIdx].Data.OnOff) OnOff = false; ret = mKnxAPI.SetLightOnOff((byte) (RoomIdx - 1), LightIdx, OnOff); } else { if (mKnxData.Light_Switch[RoomIdx - emCount].Data.LightSwitch[LightIdx].Data.OnOff) OnOff = false; ret = mKnxAPI.SetLightSwitchOnOff((byte) (RoomIdx - emCount), LightIdx, OnOff); } } else { if (RoomIdx < emCount) { if (mKnxData.BadRoom_EnergyMeter[RoomIdx].Data.BadLight[LightIdx].Data.OnOff) OnOff = false; ret = mKnxAPI.SetLightOnOff(RoomIdx, LightIdx, OnOff); } else { if (mKnxData.Light_Switch[RoomIdx - emCount].Data.LightSwitch[LightIdx].Data.OnOff) OnOff = false; ret = mKnxAPI.SetLightSwitchOnOff((byte) (RoomIdx - emCount), LightIdx, OnOff); } } if (ret < 0) { Log.e(TAG, "[Device_LightOnOff] - [Return Error] multiSwitchAPI.SetLightOnOff(Index:" + RoomIdx + ", LightIdx:" + LightIdx + ", OnOff:" + OnOff + ")"); Log.e(TAG, "[Device_LightOnOff] - Error (" + ret + ") ErrorCode = " + mKnxAPI.ErrorCode.ErrStr()); } } if (ret >= 0) mSound.Play(WpadSound.SND.effect.TOUCH_LATCHED); else mSound.Play(WpadSound.SND.effect.TOUCH_UNLATCHED); } catch (RuntimeException re) { LogUtil.errorLogInfo("", TAG, re); ret = JSON.ERROR.RuntimeException; ; } catch (Exception e) { Log.e(TAG, "[Device_LightOnOff] - [Exception Error] multiSwitchAPI.SetLightOnOff(Index:" + RoomIdx + ", LightIdx:" + LightIdx + ", OnOff:" + OnOff + ")"); //e.printStackTrace(); LogUtil.errorLogInfo("", TAG, e); ret = JSON.ERROR.Exception; } DebugLogOutput("[Device_LightOnOff] - OK"); return ret; } /** * 가스 밸브를 닫는다. * * @return (int) - >=0 : 성공, <0 : 실패 */ private int Device_GasClose() { int result; if (mGasAPI == null) { Log.e(TAG, "[Device_GasClose] - gasApi unload !!!"); return JSON.ERROR.ApiNull; } byte b0 = 0; result = mGasAPI.SetClose(b0); if (result < 0) { Log.e(TAG, "[Device_GasClose] - SetClose (" + result + ") ErrorCode = " + mGasAPI.ErrorCode.ErrStr()); } return result; } private int controlLight(int kind, int pos, RequestData reqData) { int result = JSON.ERROR.ResultFail; String category = reqData.getCategory(); if (kind == 0) { //전체 제어 int state = reqData.getState(); if (category.equalsIgnoreCase("all_execution_release")) { result = mLightControl.Device_All_Excecution_Release(state == 1 ? true : false); } else if (category.equalsIgnoreCase("set_light_dimming")) { result = mLightControl.SetLightDimming((byte) state); } } else if (kind == 1) { //개별 제어 int state = reqData.getState(); int lightNum = reqData.getNumber(); if (category.equalsIgnoreCase("switch_liv")) { boolean onoff = state == 0 ? true : false; result = mLightControl.SetLivingLightOnOff(onoff); } else if (category.equalsIgnoreCase("switch_bed")) { result = setOnOff_BadRoom_EnergyMeter(pos); } else if (category.equalsIgnoreCase("switch_light_switch")) { result = setOnOff_Light_Switch(pos); } else if (category.equalsIgnoreCase("switch_light_switch_individual")) { result = Device_LightOnOffIndividual((byte) pos, (byte) lightNum); } else if (category.equalsIgnoreCase("switch_light_switch_all")) { result = Device_LightOnOffAll((byte) pos, state == 0 ? true : false); } } return result; } private int controlConcent(int kind, RequestData reqData) { int result = JSON.ERROR.ResultFail; String category = reqData.getCategory(); if (kind == 0) { //전체 제어 } else if (kind == 1) { //개별 제어 if (category.equalsIgnoreCase("switch")) { return result; } else if (category.equalsIgnoreCase("temperature")) { } else if (category.equalsIgnoreCase("dimming")) { } } return result; } private int controlHeating(int kind, int pos, RequestData reqData) { int result = JSON.ERROR.ResultFail; String category = reqData.getCategory(); if (kind == 0) { //전체 제어 int state = reqData.getState(); int temp = reqData.getNumber(); if (category.equalsIgnoreCase("set_all_execution")) { //pause on/off result = mHeatingControl.ctrlDeviceEntireMode((byte) state); } else if (category.equalsIgnoreCase("set_all_release")) { //pause on/off result = mHeatingControl.ctrlDeviceEntireMode((byte) state); } else if (category.equalsIgnoreCase("set_boiler")) { //pause on/off result = mHeatingControl.Device_SetBoiler((byte) temp, (byte) state); } } else if (kind == 1) { //개별 제어 int state = reqData.getState(); int time = reqData.getNumber(); if (category.equalsIgnoreCase("set_mode")) { //switch on/off result = ctrlDeviceMode((byte) pos, (byte) state); } else if (category.equalsIgnoreCase("set_temp")) { //설정온도 result = mHeatingControl.Device_SetEachRoomStatus((byte) pos, DataClasses.HeatingV2.MODE.Idle, reqData.getDoubleState()); } else if (category.equalsIgnoreCase("set_reservation")) { //예약 스케줄 저장 result = mHeatingControl.Device_SetReservation((byte) pos, state); } else if (category.equalsIgnoreCase("set_sleep")) { //취침 설정 저장 result = mHeatingControl.Device_SetSleep((byte) pos, (byte) state, (byte) time); } } return result; } private int controlAircon(int kind, int pos, RequestData reqData) { int result = JSON.ERROR.ResultFail; String category = reqData.getCategory(); int state = reqData.getState(); if (kind == 0) { //전체 제어 if (category.equalsIgnoreCase("switch")) { result = ctrlPowerToggle(); } else if (category.equalsIgnoreCase("set_all_mode")) { result = ctrlMode((byte) state); } else if (category.equalsIgnoreCase("set_all_airvol")) { result = ctrlAirVol((byte) state); } } else if (kind == 1) {//개별 제어 if (category.equalsIgnoreCase("switch")) { result = ctrlPowerToggle((byte) pos); } else if (category.equalsIgnoreCase("set_mode")) { result = ctrlMode((byte) pos, (byte) state); } else if (category.equalsIgnoreCase("set_airvol")) { result = ctrlAirVolUpDown((byte) pos, (byte) state); } else if (category.equalsIgnoreCase("set_airswing")) { result = ctrlAirSwingToggle((byte) pos); } else if (category.equalsIgnoreCase("set_temp")) { result = ctrlSetTemperUpDown((byte) pos, (byte) state); } } return result; } private int controlKnxAircon(int kind, int pos, RequestData reqData) { int result = JSON.ERROR.ResultFail; String category = reqData.getCategory(); int state = reqData.getState(); int mode = reqData.getNumber(); if (kind == 0) { //전체 제어 if (category.equalsIgnoreCase("switch")) { result = mKnxAirconControl.Device_AllControl((byte)state); } } else if (kind == 1) {//개별 제어 if (category.equalsIgnoreCase("switch")) { Double doubleState = reqData.getDoubleState(); result = mKnxAirconControl.Device_SetEachRoomStatus((byte) pos, mode, doubleState); } } return result; } private int controlPurity(int kind, RequestData reqData) { int result = JSON.ERROR.ResultFail; String category = reqData.getCategory(); if (kind == 0) { //전체 제어 int state = reqData.getState(); if (category.equalsIgnoreCase("switch")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDevicePower(onoff); } else if (category.equalsIgnoreCase("auto_air_clean")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDeviceAutoAirClean(onoff); } else if (category.equalsIgnoreCase("reservation")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDeviceReservation(onoff); } else if (category.equalsIgnoreCase("wind")) { result = mVentiControl.ctrlDeviceWindType((byte) state); } else if (category.equalsIgnoreCase("natural_ventil")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDeviceNaturalVentil(onoff); } else if (category.equalsIgnoreCase("auto_ventil")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDeviceAutoVentil(onoff); } else if (category.equalsIgnoreCase("internal_ventil")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDeviceInternalVentil(onoff); } else if (category.equalsIgnoreCase("outair_clean")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDeviceOutAirClean(onoff); } else if (category.equalsIgnoreCase("heater")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDeviceHeater(onoff); } else if (category.equalsIgnoreCase("sleep_mode")) { boolean onoff = state == 0 ? true : false; result = mVentiControl.ctrlDeviceSleepMode(onoff); } else if (category.equalsIgnoreCase("timer")) { result = mVentiControl.ctrlDeviceTimer(state); } else if (category.equalsIgnoreCase("reset_filter")) { result = mVentiControl.ctrlDeviceResetFilter(); } else if (category.equalsIgnoreCase("save_shedule")) { result = mVentiControl.Device_SaveSchedule(reqData.getArrayState()); } } else if (kind == 1) { //개별 제어 if (category.equalsIgnoreCase("switch")) { } else if (category.equalsIgnoreCase("temperature")) { } else if (category.equalsIgnoreCase("dimming")) { } } return result; } private int controlGas(int kind, RequestData reqData) { int result = JSON.ERROR.ResultFail; String category = reqData.getCategory(); if (kind == 0) { //전체 제어 if (category.equalsIgnoreCase("close")) { //gas close int close = reqData.getState(); roomNumber = reqData.getNumber() - 1; result = Device_GasClose(); return result; } } else if (kind == 1) { //개별 제어 if (category.equalsIgnoreCase("close")) { //gas close int close = reqData.getState(); roomNumber = reqData.getNumber() - 1; result = Device_GasClose(); return result; } } return result; } private int controlCurtain(int kind, RequestData reqData) { int result = JSON.ERROR.ResultFail; String category = reqData.getCategory(); if (kind == 0) { //전체 제어 } else if (kind == 1) { //개별 제어 if (category.equalsIgnoreCase("switch")) { } else if (category.equalsIgnoreCase("temperature")) { } else if (category.equalsIgnoreCase("dimming")) { } } return result; } private int controlRequest(JSONObject requestData, int menu, int kind, int pos) { Gson gson = new Gson(); try { JSONObject dataObject = requestData.getJSONObject("data"); RequestData reqData = gson.fromJson(dataObject.toString(), RequestData.class); if (menu == JSON.MENU.LIGHT) { //조명 상태, 제어 return controlLight(kind, pos, reqData); } else if (menu == JSON.MENU.HEATING) { //난방 상태, 제어 return controlHeating(kind, pos, reqData); } else if (menu == JSON.MENU.AIRCON) { //에어컨 상태, 제어 //return controlAircon(kind, pos, reqData); return controlKnxAircon(kind, pos, reqData); } else if (menu == JSON.MENU.VENTI) { //환기 상태, 제어 return controlPurity(kind, reqData); } else if (menu == JSON.MENU.GAS) { //가스 상태, 제어 return controlGas(kind, reqData); } } catch (JSONException e) { e.printStackTrace(); return JSON.ERROR.JsonException; } catch (Exception e) { e.printStackTrace(); return JSON.ERROR.Exception; } return -1; } private JSONObject updateLight(int kind, int position) { if (mKnxData == null) { deviceApiLoadLight(); return null; } int livDataCount = mKnxData.LivingRoom_EnergyMeter.Info.LightCount; int bedDataCount = mKnxData.MasterController.Info.Bad_EnergyMeterCount; int switchDataCount = mKnxData.MasterController.Info.Light_SwitchCount; if ((livDataCount + bedDataCount + switchDataCount) == 0) { deviceApiLoadLight(); return null; } JSONObject responseObject = new JSONObject(); try { responseObject.accumulate("type", "updateResponse"); responseObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); responseObject.accumulate("ip", myIP); responseObject.accumulate("menu", JSON.MENU.LIGHT); responseObject.accumulate("master_info_fault", mKnxData.MasterController.Info.Fault_KnxGwSet); responseObject.accumulate("master_data_batch", mKnxData.MasterController.Data.BatchOffStatus); responseObject.accumulate("master_info_liv_count", mKnxData.MasterController.Info.Liv_EnergyMeterCount); responseObject.accumulate("master_info_bad_count", bedDataCount); responseObject.accumulate("master_info_switch_count", switchDataCount); responseObject.accumulate("liv_info_install", mKnxData.LivingRoom_EnergyMeter.Info.Install); responseObject.accumulate("liv_info_lightcount", livDataCount); JSONArray livDataArray = new JSONArray(); for (int i = 0; i < livDataCount; i++) { // build jsonObject JSONObject livDataObject = new JSONObject(); livDataObject.accumulate("info_install", mKnxData.LivingRoom_EnergyMeter.Data.LivingLight[i].Info.Install); livDataObject.accumulate("info_type", mKnxData.LivingRoom_EnergyMeter.Data.LivingLight[i].Info.Type); livDataObject.accumulate("data_onoff", mKnxData.LivingRoom_EnergyMeter.Data.LivingLight[i].Data.OnOff); livDataObject.accumulate("data_dimming", mKnxData.LivingRoom_EnergyMeter.Data.LivingLight[i].Data.Dimming); livDataArray.put(livDataObject); } responseObject.accumulate("liv_data_array", livDataArray); JSONArray bedDataArray = new JSONArray(); for (int j = 0; j < bedDataCount; j++) { // build jsonObject JSONObject bedDataObject = new JSONObject(); bedDataObject.accumulate("info_install", mKnxData.BadRoom_EnergyMeter[j].Info.Install); bedDataObject.accumulate("info_lightcount", mKnxData.BadRoom_EnergyMeter[j].Info.LightCount); bedDataObject.accumulate("info_light_type1", mKnxData.BadRoom_EnergyMeter[j].Info.LightType_1); bedDataObject.accumulate("info_light_type2", mKnxData.BadRoom_EnergyMeter[j].Info.LightType_2); bedDataObject.accumulate("info_light_type3", mKnxData.BadRoom_EnergyMeter[j].Info.LightType_3); bedDataObject.accumulate("info_light_type4", mKnxData.BadRoom_EnergyMeter[j].Info.LightType_4); JSONArray lightArray = new JSONArray(); for (int k = 0; k < mKnxData.BadRoom_EnergyMeter[j].Info.LightCount; k++) { lightArray.put(mKnxData.BadRoom_EnergyMeter[j].Data.BadLight[k].Data.OnOff); } bedDataObject.accumulate("lightArray", lightArray); bedDataArray.put(bedDataObject); } responseObject.accumulate("bed_data_array", bedDataArray); JSONArray switchDataArray = new JSONArray(); for (int j = 0; j < switchDataCount; j++) { // build jsonObject JSONObject switchDataObject = new JSONObject(); switchDataObject.accumulate("info_install", mKnxData.Light_Switch[j].Info.Install); switchDataObject.accumulate("info_lightcount", mKnxData.Light_Switch[j].Info.LightCount); switchDataObject.accumulate("info_light_type1", mKnxData.Light_Switch[j].Info.LightType_1); switchDataObject.accumulate("info_light_type2", mKnxData.Light_Switch[j].Info.LightType_2); switchDataObject.accumulate("info_light_type3", mKnxData.Light_Switch[j].Info.LightType_3); switchDataObject.accumulate("info_light_type4", mKnxData.Light_Switch[j].Info.LightType_4); JSONArray switchArray = new JSONArray(); for (int k = 0; k < mKnxData.Light_Switch[j].Info.LightCount; k++) { switchArray.put(mKnxData.Light_Switch[j].Data.LightSwitch[k].Data.OnOff); } switchDataObject.accumulate("switchArray", switchArray); switchDataArray.put(switchDataObject); } responseObject.accumulate("switch_data_array", switchDataArray); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return responseObject; } private JSONObject updateConcent(int kind, int position) { int roomCount = mHeatingV2API.data.Device.info.RoomCount; JSONObject jsonObject = new JSONObject(); return jsonObject; } private JSONObject updateHeating(int kind, int pos) { int roomCount = mHeatingV2API.data.Device.info.RoomCount; JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("type", "updateResponse"); jsonObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); jsonObject.accumulate("ip", myIP); jsonObject.accumulate("menu", JSON.MENU.HEATING); jsonObject.accumulate("support_setpoint05", mHeatingV2API.data.Device.info.Support.SetTempPoint05); jsonObject.accumulate("support_outing", mHeatingV2API.data.Device.info.Support.Outing); jsonObject.accumulate("support_sleep", mHeatingV2API.data.Device.info.Support.Sleep); jsonObject.accumulate("support_reservation", mHeatingV2API.data.Device.info.Support.Reservation); jsonObject.accumulate("support_pause", mHeatingV2API.data.Device.info.Support.Pause); jsonObject.accumulate("support_ai", mHeatingV2API.data.Device.info.Support.AI); jsonObject.accumulate("support_outsidetempuse", mHeatingV2API.data.Device.info.Support.OutsideTempUse); jsonObject.accumulate("support_boiler", mHeatingV2API.data.Device.info.Support.Boiler); jsonObject.accumulate("boiler_heatwater_temp", mHeatingV2API.data.Boiler.HeatingWater.SetTemp); jsonObject.accumulate("boiler_hotwater_temp", mHeatingV2API.data.Boiler.HotWater.SetTemp); jsonObject.accumulate("boiler_frost_protect", mHeatingV2API.data.Boiler.bFrostProtectMode); jsonObject.accumulate("boiler_error_code", mHeatingV2API.data.Boiler.ErrorCode); JSONArray dataArray = new JSONArray(); if (kind == 0) { //전체 응답 for (int i = 0; i < roomCount; i++) { // build jsonObject JSONObject dataObject = new JSONObject(); dataObject.accumulate("roomNumber", i); dataObject.accumulate("mode", mHeatingV2API.data.Device.Room[i].Mode); dataObject.accumulate("setTemp", mHeatingV2API.data.Device.Room[i].SetTemp); dataObject.accumulate("nowTemp", mHeatingV2API.data.Device.Room[i].NowTemp); JSONArray reserveArray = new JSONArray(); for (int j = 0; j < 24; j++) { if (mHeatingV2API.data.Device.Room[i].Reservation.getSchedule(j)) { reserveArray.put(j); } } dataObject.accumulate("reservationArray", reserveArray); dataObject.accumulate("sleepTemp", mHeatingV2API.data.Device.Room[i].Sleep.getTemp()); dataObject.accumulate("sleepTime", mHeatingV2API.data.Device.Room[i].Sleep.getTime()); dataArray.put(dataObject); } } else if (kind == 1) { // 데이터 전송 String mode = "off"; switch (mHeatingV2API.data.Device.Room[pos].Mode) { case MODE.HeatingON: mode = "on"; break; case MODE.HeatingOFF: mode = "off"; break; case MODE.Outing: mode = "away"; break; case MODE.Sleep: mode = "sleep"; break; case MODE.Reservation: mode = "schedule"; break; case MODE.Pause: mode = "pause"; break; default: break; } // build jsonObject JSONObject dataObject = new JSONObject(); dataObject.accumulate("roomNumber", pos); dataObject.accumulate("mode", mode); dataObject.accumulate("setTemp", mHeatingV2API.data.Device.Room[pos].SetTemp); dataObject.accumulate("NowTemp", mHeatingV2API.data.Device.Room[pos].NowTemp); dataArray.put(dataObject); } jsonObject.accumulate("data_array", dataArray); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } private JSONObject updateAircon(int kind, int pos) { int roomCount = mSystemAirconAPI.data.Device.info.hInsideAirconCnt; JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("type", "updateResponse"); jsonObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); jsonObject.accumulate("ip", myIP); jsonObject.accumulate("menu", JSON.MENU.AIRCON); jsonObject.accumulate("support_auto", mSystemAirconAPI.data.Device.info.Support.bModeAuto); jsonObject.accumulate("support_cooling", mSystemAirconAPI.data.Device.info.Support.bModeCooling); jsonObject.accumulate("support_dehumidify", mSystemAirconAPI.data.Device.info.Support.bModeDehumidify); jsonObject.accumulate("support_fan", mSystemAirconAPI.data.Device.info.Support.bModeFan); jsonObject.accumulate("support_heating", mSystemAirconAPI.data.Device.info.Support.bModeHeating); JSONArray dataArray = new JSONArray(); if (kind == 0) { //전체 응답 for (int i = 0; i < roomCount; i++) { // build jsonObject JSONObject dataObject = new JSONObject(); dataObject.accumulate("roomNumber", i); dataObject.accumulate("mode", mSystemAirconAPI.data.Device.Aircon[i].hMode); dataObject.accumulate("airvol", mSystemAirconAPI.data.Device.Aircon[i].hAirVol); dataObject.accumulate("setTemp", mSystemAirconAPI.data.Device.Aircon[i].hSetTemper); dataObject.accumulate("NowTemp", mSystemAirconAPI.data.Device.Aircon[i].hCurrentTemper); dataArray.put(dataObject); } } else if (kind == 1) { // build jsonObject JSONObject dataObject = new JSONObject(); dataObject.accumulate("roomNumber", pos); dataObject.accumulate("mode", mSystemAirconAPI.data.Device.Aircon[pos].hMode); dataObject.accumulate("airvol", mSystemAirconAPI.data.Device.Aircon[pos].hAirVol); dataObject.accumulate("setTemp", mSystemAirconAPI.data.Device.Aircon[pos].hSetTemper); dataObject.accumulate("NowTemp", mSystemAirconAPI.data.Device.Aircon[pos].hCurrentTemper); dataArray.put(dataObject); } jsonObject.accumulate("data_array", dataArray); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } private JSONObject updateKnxAircon(int kind, int pos) { int roomCount = mKnxSystemAirconAPI.data.Device.info.InsideAirconCount; JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("type", "updateResponse"); jsonObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); jsonObject.accumulate("ip", myIP); jsonObject.accumulate("menu", JSON.MENU.AIRCON); JSONArray dataArray = new JSONArray(); if (kind == 0) { //전체 응답 for (int i = 0; i < roomCount; i++) { // build jsonObject JSONObject dataObject = new JSONObject(); dataObject.accumulate("roomNumber", i); dataObject.accumulate("power", mKnxSystemAirconAPI.data.Device.Aircon[i].OnOff); dataObject.accumulate("mode", mKnxSystemAirconAPI.data.Device.Aircon[i].Mode); dataObject.accumulate("airvol", mKnxSystemAirconAPI.data.Device.Aircon[i].Volume); dataObject.accumulate("setTemp", mKnxSystemAirconAPI.data.Device.Aircon[i].SetTemp); dataObject.accumulate("NowTemp", mKnxSystemAirconAPI.data.Device.Aircon[i].NowTemp); dataArray.put(dataObject); } } else if (kind == 1) { // build jsonObject JSONObject dataObject = new JSONObject(); dataObject.accumulate("roomNumber", pos); dataObject.accumulate("power", mKnxSystemAirconAPI.data.Device.Aircon[pos].OnOff); dataObject.accumulate("mode", mKnxSystemAirconAPI.data.Device.Aircon[pos].Mode); dataObject.accumulate("airvol", mKnxSystemAirconAPI.data.Device.Aircon[pos].Volume); dataObject.accumulate("setTemp", mKnxSystemAirconAPI.data.Device.Aircon[pos].SetTemp); dataObject.accumulate("NowTemp", mKnxSystemAirconAPI.data.Device.Aircon[pos].NowTemp); dataArray.put(dataObject); } jsonObject.accumulate("data_array", dataArray); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } private JSONObject updateVenti(int kind, int position) { JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("type", "updateResponse"); jsonObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); jsonObject.accumulate("ip", myIP); jsonObject.accumulate("menu", JSON.MENU.VENTI); jsonObject.accumulate("support_heater", mVentiAPI.data.Support.Heater); jsonObject.accumulate("support_innercycle", mVentiAPI.data.Support.InnerCycle); jsonObject.accumulate("support_outairclean", mVentiAPI.data.Support.OutAirClean); jsonObject.accumulate("support_autodriving", mVentiAPI.data.Support.AutoDriving); jsonObject.accumulate("support_bypass", mVentiAPI.data.Support.ByPass); jsonObject.accumulate("support_filterreset", mVentiAPI.data.Support.FilterReset); jsonObject.accumulate("support_bathroom", mVentiAPI.data.Support.BathRoom); jsonObject.accumulate("support2_windowventi", mVentiAPI.data.Support2.WindowVenti); jsonObject.accumulate("support2_sleepmode", mVentiAPI.data.Support2.SleepMode); jsonObject.accumulate("fault_motorerror", mVentiAPI.data.Fault.MotorError); jsonObject.accumulate("fault_tempsensorerror", mVentiAPI.data.Fault.TempSensorError); jsonObject.accumulate("fault_supplyfanerror", mVentiAPI.data.Fault.SupplyFanError); jsonObject.accumulate("fault_exhaustfanerror", mVentiAPI.data.Fault.ExhaustFanError); jsonObject.accumulate("fault_filterchangefree", mVentiAPI.data.Fault.FilterChangeFree); jsonObject.accumulate("fault_filterchangemedium", mVentiAPI.data.Fault.FilterChangeMedium); jsonObject.accumulate("fault_safemode", mVentiAPI.data.Fault.SafeMode); jsonObject.accumulate("OnOff", mVentiAPI.data.OnOff); jsonObject.accumulate("Reservation", mVentiAPI.data.Reservation); jsonObject.accumulate("Wind", mVentiAPI.data.Wind); jsonObject.accumulate("Sleep", mVentiAPI.data.Sleep); jsonObject.accumulate("Timer", mVentiAPI.data.Timer); jsonObject.accumulate("ByPass", mVentiAPI.data.ByPass); jsonObject.accumulate("HeaterTimeRemaining", mVentiAPI.data.HeaterTimeRemaining); jsonObject.accumulate("HeaterStatus", mVentiAPI.data.HeaterStatus); jsonObject.accumulate("AutoDriving", mVentiAPI.data.AutoDriving); jsonObject.accumulate("BathRoom", mVentiAPI.data.BathRoom); jsonObject.accumulate("InnerCycle", mVentiAPI.data.InnerCycle); jsonObject.accumulate("OutAirClean", mVentiAPI.data.OutAirClean); jsonObject.accumulate("AirCleanAuto", mVentiAPI.data.AirCleanAuto); jsonObject.accumulate("HDCAutoAirClean", mVentiAPI.data.HDCAutoAirClean); JSONArray reserveArray = new JSONArray(); byte[] ReserveList = mVentiAPI.GetReservationSchedule(); for (int j = 0; j < ReserveList.length; j++) { reserveArray.put(ReserveList[j]); } jsonObject.accumulate("reservationArray", reserveArray); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } private JSONObject updateGas(int kind, int position) { int nGasCnt = (int) mGasAPI.data.DeviceCnt; JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("type", "updateResponse"); jsonObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); jsonObject.accumulate("ip", myIP); jsonObject.accumulate("menu", "gas"); JSONArray dataArray = new JSONArray(); if (kind == 0) { for (int j = 0; j < nGasCnt; j++) { // 데이터 전송 String status = "close"; if (mGasAPI.data.Device[j].GasStatus == GasAPI.GASSTATUS.Close) status = "close"; else if (mGasAPI.data.Device[j].GasStatus == GasAPI.GASSTATUS.Open) status = "open"; else if (mGasAPI.data.Device[j].GasStatus == GasAPI.GASSTATUS.Operation) status = "working"; JSONObject dataObject = new JSONObject(); String roomName; if (j == 0) { roomName = "living_room"; } else { roomName = "room" + j; } dataObject.accumulate("roomNumber", roomName); jsonObject.accumulate("state", status); dataArray.put(dataObject); } } else if (kind == 1) { } jsonObject.accumulate("data_array", dataArray); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } private JSONObject updateCookTop(int kind, int pos) { int nCookTopCnt = mCookTopData.DeviceCnt; JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("type", "updateResponse"); jsonObject.accumulate("timestamp", millToDate(System.currentTimeMillis())); jsonObject.accumulate("ip", myIP); jsonObject.accumulate("menu", JSON.MENU.COOKTOP); jsonObject.accumulate("device_count", nCookTopCnt); JSONArray dataArray = new JSONArray(); if (kind == 0) { //전체 응답 for (int i = 0; i < nCookTopCnt; i++) { // build jsonObject JSONObject dataObject = new JSONObject(); dataObject.accumulate("hID", mCookTopData.Device[0].circuit[i].hID); dataObject.accumulate("hStatus", mCookTopData.Device[0].circuit[i].hStatus); dataObject.accumulate("hType", mCookTopData.Device[0].circuit[i].hType); dataObject.accumulate("hErrorStatus", mCookTopData.Device[0].circuit[i].hErrorStatus); dataArray.put(dataObject); } } jsonObject.accumulate("data_array", dataArray); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } private JSONObject updateCurtain(int kind, int position) { int roomCount = mHeatingV2API.data.Device.info.RoomCount; JSONObject jsonObject = new JSONObject(); return jsonObject; } private JSONObject updateRequest(int menu, int kind, int position) { try { if (menu == JSON.MENU.LIGHT) { return updateLight(kind, position); } else if (menu == JSON.MENU.CONCENT) { return updateConcent(kind, position); } else if (menu == JSON.MENU.HEATING) { return updateHeating(kind, position); } else if (menu == JSON.MENU.AIRCON) { return updateKnxAircon(kind, position); //return updateAircon(kind, position); } else if (menu == JSON.MENU.VENTI) { return updateVenti(kind, position); } else if (menu == JSON.MENU.GAS) { return updateGas(kind, position); } else if (menu == JSON.MENU.COOKTOP) { return updateCookTop(kind, position); } } catch (Exception e) { e.printStackTrace(); return null; } return null; } private int passwordChangeRequest(String passwordNumber) { //패스워드 변경 try { WallpadStatusData wd = new WallpadStatusData(this.getContext()); if (wd != null) { wd.SetUserPW(passwordNumber); Log.d(TAG, "[passwordNumber]" + passwordNumber); wd.closeDB(); } return 0; } catch (Exception e) { e.printStackTrace(); return JSON.ERROR.Exception; } } @Override public void onCreate() { //handler.sendEmptyMessage(MSG_WORK); super.onCreate(); mContext = this; this.mSound = new WpadSound(this); // 3.1. mWallPadAPI 생성 int OPERATION_MODE = Common.MODE; if (OPERATION_MODE == Common.MODE_NOMAL) { Log.d(TAG, "OperationMode = MODE_NOMAL"); try { mWallPadAPI = new WallPadAPI(this); } catch (Exception e) { Log.e(TAG, "[ExceptionError] - new WallPadAPI : " + e); } } else if (OPERATION_MODE == Common.MODE_BUSINESS_SAMPLE) { Log.d(TAG, "OperationMode = MODE_BUSINESS_SAMPLE"); myDong = "101"; myHo = "102"; } registerEventAlarmBr(); mKnxData = new Data_KnxLiv(); mSDBEMInfo = new SDBEMInfo(); deviceApiLoad(); setIPInfo(); thread = new ServerThread(); thread.start(); } private void setIPInfo() { DBMGR = new WallpadStatusData(mContext); wallpaddbmgr.AddressSet addc = DBMGR.getAddressMGR(); DBMGR.closeDB(); myIP = addc.IPAddress; myDong = addc.Dong; myHo = addc.Ho; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("StartService", "onStartCommand()"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { //handler.removeMessages(MSG_WORK); super.onDestroy(); } int AllEMcount; public void deviceApiLoadLight() { WallpadDeviceSet wds = new WallpadDeviceSet(mContext); int nDPType = wds.Get_DistributionPannelType_Info(); wds.closeDB(); try { if (mWallPadAPI.Check_Connect()) { if (Version.getModelType() == Version.MODEL_TYPE.IHN_D101 || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K_I || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I_OCF) { if (nDPType == Version.DISTRIBUTION_MODEL.SMART_DIST) { // 스마트 분전반 mSdb_LivingRoomLightAPI = mWallPadAPI.Get_Sdb_LivingRoomLightAPI(); mSdb_LivingRoomLightAPI.Refresh(); mSdbAPI = mWallPadAPI.Get_SdbController(); for (int i = 0; i < mSdbAPI.data.BadRoom_Em_Count; i++) { mSdbAPI.Refresh((byte) 0x00, (byte) i); } } else if (nDPType == Version.DISTRIBUTION_MODEL.KNX_DIST) { // KNX 분전반 mKnxAPI = mWallPadAPI.Get_KnxController(); if (mKnxAPI != null) { mLightControl = new LightControl(mKnxAPI, mContext); mKnxAPI.Refresh(KnxAPI.DEVICE_INDEX.ALL, (byte) define.DEVICE_ALL_OR_NOTHING); // 4. Data Copy mKnxData.MasterController = mKnxAPI.data.MasterController; mKnxData.LivingRoom_EnergyMeter = mKnxAPI.data.LivingRoom_EnergyMeter; mKnxData.BadRoom_EnergyMeter = mKnxAPI.data.BadRoom_EnergyMeter; mKnxData.Light_Switch = mKnxAPI.data.Light_Switch; AllEMcount = mKnxData.MasterController.Info.Light_SwitchCount + mKnxData.MasterController.Info.Bad_EnergyMeterCount + mKnxData.MasterController.Info.Liv_EnergyMeterCount; } } } } } catch (Exception e) { Log.e(TAG, "[Exception] deviceApiLoadLight()"); e.printStackTrace(); } } public void deviceApiLoad() { WallpadDeviceSet wds = new WallpadDeviceSet(mContext); int nDPType = wds.Get_DistributionPannelType_Info(); wds.closeDB(); try { if (mWallPadAPI.Check_Connect()) { if (Version.getModelType() == Version.MODEL_TYPE.IHN_D101 || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K_I || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I_OCF) { deviceApiLoadLight(); } iGW300API = mWallPadAPI.Get_IGW300Controller(); if (iGW300API == null) { Log.w(TAG, "[onCreate] iGW300API is null!!"); } mIGW300Data = getIGW300UpdateData(); //가스 mGasAPI = mWallPadAPI.Get_GasController(); cooktopAPI = mWallPadAPI.Get_CookTopController(); if (mGasAPI != null) { mGasAPI.Refresh((byte) 0, false); nGasCnt = (int) mGasAPI.data.DeviceCnt; for (int j = 0; j < nGasCnt; j++) { mGasAPI.Refresh((byte) j, false); haGasStatus[j] = mGasAPI.data.Device[j].GasStatus; } } if (cooktopAPI != null) { cooktopAPI.Refresh(SystemAirconAPI.REFRESH_IDX.ALL, false); // 4. Data Copy mCookTopData = cooktopAPI.data; } WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(getApplicationContext()); int[] BatchInfo = mWallpadDeviceSet.Get_BatchSW_Info(); int[] retVentil = mWallpadDeviceSet.Get_Ventil_Info(); mWallpadDeviceSet.closeDB(); //환기 if (retVentil != null && retVentil[0] == 1) { mVentiAPI = mWallPadAPI.Get_VentiController(); if (mVentiAPI != null) { mVentiControl = new VentiControl(mVentiAPI, mContext); mVentiAPI.Refresh(false); // 3. Data Copy //mVentilData.VentilStatus = mVentiAPI.data; mVentilation.OnOff = mVentiAPI.data.OnOff; mVentilation.Wind = mVentiAPI.data.Wind; } } //난방 mHeatingV2API = mWallPadAPI.Get_HeatingV2Controller(); if (mHeatingV2API != null) { mHeatingControl = new HeatingControl(mHeatingV2API, mContext); mHeatingV2API.Refresh(HeatingV2API.REFRESH_IDX.ALL, false); int roomCount = mHeatingV2API.data.Device.info.RoomCount; for (int i = 0; i < roomCount; i++) { mHeating.eachRoom[i].mode = mHeatingV2API.data.Device.Room[i].Mode; mHeating.eachRoom[i].curTemper = mHeatingV2API.data.Device.Room[i].NowTemp; mHeating.eachRoom[i].setTemper = mHeatingV2API.data.Device.Room[i].SetTemp; } } if (nDPType == Version.DISTRIBUTION_MODEL.KNX_DIST) { //에어컨 mKnxSystemAirconAPI = mWallPadAPI.Get_KnxAirconController(); if (mKnxSystemAirconAPI != null) { mKnxAirconControl = new KnxAirconControl(mKnxSystemAirconAPI); mKnxSystemAirconAPI.Refresh(SystemAirconAPI.REFRESH_IDX.ALL, false); // 4. Data Copy mKnxAirconData.systemAircon = mKnxSystemAirconAPI.data; } }else{ //에어컨 mSystemAirconAPI = mWallPadAPI.Get_AirconController(); if (mSystemAirconAPI != null) { mAirconControl = new AirconControl(mSystemAirconAPI); mSystemAirconAPI.Refresh(SystemAirconAPI.REFRESH_IDX.ALL, false); // 4. Data Copy mAirconData.systemAircon = mSystemAirconAPI.data; } } startRealtimemeterInfo(); // 실시간 검침기 전송 스타트 // 각각의 디바이스 컨트롤러를 가져온다음에 맨 마직막에 디바이스쪽에 BR을 등록 시킨다. registerDeviceBR(); } } catch (Exception e) { Log.e(TAG, "[Exception] deviceApiLoad()"); e.printStackTrace(); } } public String SendData(String ui, String type, String menu, String function, Object value, int valueType) { String ret = null; String strValue = null; if (thread == null) { thread = new ServerThread(); thread.start(); } if (valueType == 0) { strValue = String.valueOf(value); } else if (valueType == 1) { strValue = String.valueOf(value); } else if (valueType == 2) { strValue = value.toString(); } else if (valueType == 3) { strValue = value.toString(); } String addData = String.format("%s;%s;%s;%s;%s;%s;%s", String.valueOf(valueType), ui, type, menu, function, strValue, "param4"); Log.d("AIDLTEST", "addData : " + addData); try { //this.mBinder.sendEventData(addData); return "Success"; } catch (Exception var7) { Log.e("AIDLTEST", "Catch Exception Afer Send Data to Service"); return "EXCEPTION"; } } public void saveChangedEnergyMeterStatus() { try { for (int i = 0; i < mEnergyMeterAPI.data.RoomCnt; i++) { // 각 에너지미터에 대한 조명 갯수 for (int j = 0; j < mEnergyMeterAPI.data.Em.eachRoom[i].LightCnt; j++) { mSDBEMInfo.EachRoom[i].Light_bOnOff[j] = mEnergyMeterAPI.data.Em.eachRoom[i].LightOnOff[j]; } Log.d(TAG, "mEnergyMeterAPI.data.Em.EachRoom[i].ConCnt : " + mEnergyMeterAPI.data.Em.eachRoom[i].ConCnt); // 각 에너지미터에 대한 콘센트 갯수 int concentCount = mEnergyMeterAPI.data.Em.eachRoom[i].ConCnt; // 상시 콘센트는 상태를 저장하지 않기 때문에 에러.. // 상시 콘센트는 제어되지 않으므로 3번에 대한건 처러 하지 않는다. if (mEnergyMeterAPI.data.Em.eachRoom[i].ConCnt >= 3) { concentCount = 2; } for (int j = 0; j < concentCount; j++) { mEMeter.eachRoom[i].concentStatus[j] = mEnergyMeterAPI.data.Em.eachRoom[i].ConOnOff[j]; mEMeter.eachRoom[i].ConMode[j] = mEnergyMeterAPI.data.Em.eachRoom[i].ConMode; } } } catch (Exception e) { Log.e(TAG, "[Exception] saveChangedEnergyMeterStatus()"); e.printStackTrace(); } } public void saveChangedSdbStatus_EachOutlet() { try { for (int i = 0; i < mSdbAPI.data.BadRoom_Em_Count; i++) { mSdbAPI.Refresh(SdbAPI.DEVICE_INDEX.ENERGY_METER, (byte) i); for (int j = 0; j < mSdbAPI.data.BadRoom_EnergyMeter[i].Info.ConcentCount; j++) { // 각방 EM 콘센트 상태 업데이트 mSDBEMInfo.EachRoom[i].Outlet_hOnOff[j] = mSdbAPI.data.BadRoom_EnergyMeter[i].Data.Concent[j].Data.CutOffConcent.Status; mSDBEMInfo.EachRoom[i].Outlet_hCutoff[j] = mSdbAPI.data.BadRoom_EnergyMeter[i].Data.Concent[j].Data.CutOffConcent.Mode; } } } catch (Exception e) { Log.e(TAG, "[Exception] saveChangedSdbStatus_EachOutlet()"); e.printStackTrace(); } } public void saveChangedSdbStatus_LivingOutlet() { try { mSdbAPI.Refresh(SdbAPI.DEVICE_INDEX.ENERGY_METER, EM_INDEX_LIVING); for (int i = 0; i < mSdbAPI.data.LivingRoom_EnergyMeter.Info.ConcentCount; i++) { // 거실 EM 콘센트 상태 업데이트 mSDBEMInfo.LivingRoom.Outlet_hOnOff[i] = mSdbAPI.data.LivingRoom_EnergyMeter.Data.Concent[i].Data.CutOffConcent.Status; mSDBEMInfo.LivingRoom.Outlet_hCutoff[i] = mSdbAPI.data.LivingRoom_EnergyMeter.Data.Concent[i].Data.CutOffConcent.Mode; } for (int i = 0; i < mSdbAPI.data.LivingRoom_EnergyMeter.Info.LightCount; i++) { // 거실 EM 콘센트 상태 업데이트 mSDBEMInfo.LivingRoom.Light_hDim[i] = mSdbAPI.data.LivingRoom_EnergyMeter.Data.LedLight[i].Data.Dimming; mSDBEMInfo.LivingRoom.Light_hColor[i] = mSdbAPI.data.LivingRoom_EnergyMeter.Data.LedLight[i].Data.Color; mSDBEMInfo.LivingRoom.Light_bOnOff[i] = mSdbAPI.data.LivingRoom_EnergyMeter.Data.LedLight[i].Data.OnOff; } } catch (Exception e) { Log.e(TAG, "[Exception] saveChangedSdbStatus_LivingOutlet()"); e.printStackTrace(); } } public void saveChangedSdbStatus_EachLight() { try { for (int i = 0; i < mSdbAPI.data.BadRoom_Em_Count; i++) { mSdbAPI.Refresh(SdbAPI.DEVICE_INDEX.ENERGY_METER, (byte) i); for (int j = 0; j < mSdbAPI.data.BadRoom_EnergyMeter[i].Info.LightCount; j++) { // 조명상태 업데이트 mSDBEMInfo.EachRoom[i].Light_bOnOff[j] = mSdbAPI.data.BadRoom_EnergyMeter[i].Data.LedLight[j].Data.OnOff; mSDBEMInfo.EachRoom[i].Light_hDim[j] = mSdbAPI.data.BadRoom_EnergyMeter[i].Data.LedLight[j].Data.Dimming; mSDBEMInfo.EachRoom[i].Light_hColor[j] = mSdbAPI.data.BadRoom_EnergyMeter[i].Data.LedLight[j].Data.Color; } } } catch (Exception e) { Log.e(TAG, "[Exception] saveChangedSdbStatus_EachLight()"); e.printStackTrace(); } } /* * 거실 조명 제어기기의 상태를 비교하여 데이터 수집 연동 서버로 전송한다. * 변경된 상태는 백업한다. */ public void checkChangedSdbLivingLight() { try { if (mSdb_LivingRoomLightAPI != null) { mSdb_LivingRoomLightAPI.Refresh(); boolean bChangeState = false; for (int i = 0; i < mSdb_LivingRoomLightAPI.data.Info.LightCount; i++) { Log.d(TAG, "[checkChangedSdbLivingLight] mSdb_LivingRoomLightAPI.data.Data.LedLight[" + i + "].Data.OnOff = " + mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.OnOff + ", mSDBEMInfo.LivingRoom.Light_bOnOff[" + i + "] = " + mSDBEMInfo.LivingRoom.Light_bOnOff[i]); Log.d(TAG, "[checkChangedSdbLivingLight] mSdb_LivingRoomLightAPI.data.Data.LedLight[" + i + "].Data.Dimming = " + mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.Dimming + ", mSDBEMInfo.LivingRoom.Light_hDim[" + i + "] = " + mSDBEMInfo.LivingRoom.Light_hDim[i]); Log.d(TAG, "[checkChangedSdbLivingLight] mSdb_LivingRoomLightAPI.data.Data.LedLight[" + i + "].Data.Color = " + mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.Color + ", mSDBEMInfo.LivingRoom.Light_hColor[" + i + "] = " + mSDBEMInfo.LivingRoom.Light_hColor[i]); if (mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.OnOff != mSDBEMInfo.LivingRoom.Light_bOnOff[i] || mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.Dimming != mSDBEMInfo.LivingRoom.Light_hDim[i] || mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.Color != mSDBEMInfo.LivingRoom.Light_hColor[i]) { // 조명값이 변경된 경우 String status_power = "off"; int status_dim = 0, status_color = 0; if (mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Info.Support.OnOff) { status_power = (mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.OnOff) ? "on" : "off"; } else { status_power = "null"; } if (mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Info.Support.Dimming) { status_dim = mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.Dimming; } else { status_dim = 0; } if (mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Info.Support.Color) { status_color = mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.Color; } else { status_color = 0; } bChangeState = true; JSONObject jsonObject = new JSONObject(); try { if (i == 0) { jsonObject.accumulate("category", "livingroom"); } else { jsonObject.accumulate("category", "hall"); } jsonObject.accumulate("state", status_power); jsonObject.accumulate("dimming", status_dim); jsonObject.accumulate("colorTemperature", status_color); } catch (JSONException e) { e.printStackTrace(); } SendData("icon", "device", "light", "each_control", jsonObject, 2); } } if (bChangeState == true) { for (int i = 0; i < mSdb_LivingRoomLightAPI.data.Info.LightCount; i++) { mSDBEMInfo.LivingRoom.Light_bOnOff[i] = mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.OnOff; mSDBEMInfo.LivingRoom.Light_hDim[i] = mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.Dimming; mSDBEMInfo.LivingRoom.Light_hColor[i] = mSdb_LivingRoomLightAPI.data.Data.LedLight[i].Data.Color; } } } else { mSdb_LivingRoomLightAPI = mWallPadAPI.Get_Sdb_LivingRoomLightAPI(); Log.d(TAG, "[checkChangedSdbLivingLight] mSdb_LivingRoomLightAPI == null"); } } catch (Exception e) { Log.e(TAG, "[Exception] checkChangedSdbLivingLight()"); e.printStackTrace(); } } /* * 환기 제어기기의 상태를 비교하여 데이터 수집 연동 서버로 전송한다. * 변경된 상태는 백업한다. */ public void checkChangedVentilation() { try { Log.i(TAG, "[checkChangedVentilation] ===== START ====="); if (mVentiAPI != null) { mVentiAPI.Refresh(false); // 4. Data Copy //mVentilData.VentilStatus = mVentiAPI.data; } else { mVentiAPI = mWallPadAPI.Get_VentiController(); } } catch (Exception e) { Log.e(TAG, "[Exception] checkChangedVentilation()"); e.printStackTrace(); } } /* * 조명 제어기기의 상태를 비교하여 데이터 수집 연동 서버로 전송한다. * 변경된 상태는 백업한다. */ /** * 거실에너지미터 INDEX */ public static byte EM_INDEX_LIVING = (byte) 14; long before; boolean bSending = true; public void checkChangedSdb(boolean bForce) { try { //추후 필요하면 추가. } catch (Exception e) { Log.e(TAG, "[Exception] checkChangedSdb()"); e.printStackTrace(); } } /* * 난방 제어기기의 상태를 비교하여 데이터 수집 연동 서버로 전송한다. * 변경된 상태는 백업한다. */ /** * 운전상태 정의 */ public static class MODE { /** * 미설정 ( * 설정전용 : 읽기시 해당없음) */ public static final byte Idle = 0x00; /** * 난방 ON */ public static final byte HeatingON = 0x01; /** * 난방 OFF */ public static final byte HeatingOFF = 0x02; /** * 외출 */ public static final byte Outing = 0x03; /** * 외출해제 ( * 설정전용 : 읽기시 해당없음) */ public static final byte OutingRelease = 0x04; /** * 취침 */ public static final byte Sleep = 0x05; /** * 예약 */ public static final byte Reservation = 0x06; /** * 일시정지 */ public static final byte Pause = 0x07; /** * 일시정지 해제 ( * 설정전용 : 읽기시 해당없음) */ public static final byte PauseRelease = 0x08; } public String getTimeData(int Time) { String[] str = new String[] {"0", "3:00", "3:30", "4:00", "4:30", "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00", "9:30", "10:00", "10:30", "11:00", "11:30", "12:00"}; try { return str[Time]; } catch (Exception e) { Log.e("DataClasses", "[getTimeStr]"); e.printStackTrace(); } return null; } public void checkChangedAircon() { try { Log.i(TAG, "[checkChangedAircon] ===== START ====="); if (mSystemAirconAPI != null) { mSystemAirconAPI.Refresh(SystemAirconAPI.REFRESH_IDX.ALL, false); // 4. Data Copy mAirconData.systemAircon = mSystemAirconAPI.data; } else { mHeatingV2API = mWallPadAPI.Get_HeatingV2Controller(); } } catch (Exception e) { Log.e(TAG, "[Exception] checkChangedAircon()"); e.printStackTrace(); } } public void checkChangedHeating() { try { Log.i(TAG, "[checkChangedHeating] ===== START ====="); if (mHeatingV2API != null) { mHeatingV2API.Refresh(HeatingV2API.REFRESH_IDX.ALL, false); boolean bChangeUnitState = false; boolean bChangeTotalState = false; int roomCount = mHeatingV2API.data.Device.info.RoomCount; for (int i = 0; i < roomCount; i++) { bChangeUnitState = false; // 전원 상태 변화 확인 if (mHeating.eachRoom[i].mode != mHeatingV2API.data.Device.Room[i].Mode) { bChangeUnitState = true; } // 0.5 도 단위로 전송 double old_temer = mHeating.eachRoom[i].curTemper; double new_temer = mHeatingV2API.data.Device.Room[i].NowTemp; double diff = old_temer - new_temer; // 현재온도 변화 확인 if (diff > 0.5 || diff < -0.5) { bChangeTotalState = true; } // 설정온도 변화 확인 if (mHeating.eachRoom[i].setTemper != mHeatingV2API.data.Device.Room[i].SetTemp) { bChangeUnitState = true; } if (bChangeUnitState == true) { Log.d(TAG, "[checkChangedHeating] temper old_mode : " + mHeating.eachRoom[i].mode + " , new_mode : " + mHeatingV2API.data.Device.Room[i].Mode); Log.d(TAG, "[checkChangedHeating] temper old_set : " + mHeating.eachRoom[i].setTemper + " , new_set : " + mHeatingV2API.data.Device.Room[i].SetTemp); Log.d(TAG, "[checkChangedHeating] temper old_temer : " + old_temer + " , new_temer : " + new_temer); // 데이터 전송 String mode = ""; switch (mHeatingV2API.data.Device.Room[i].Mode) { case MODE.HeatingON: mode = "on"; break; case MODE.HeatingOFF: mode = "off"; break; case MODE.Outing: mode = "away"; break; case MODE.Sleep: mode = "sleep"; break; case MODE.Reservation: mode = "schedule"; break; case MODE.Pause: mode = "pause"; break; default: break; } if (bChangeUnitState) { Log.i(TAG, "[checkChangedHeating] room[" + i + "] temper changed!!!"); bChangeTotalState = true; } else { Log.w(TAG, "[checkChangedHeating] room[" + i + "] temper is not changed!!!"); } JSONArray errorArray = new JSONArray(); if (mHeatingV2API.data.Device.Room[i].Error.bRoomComm) { errorArray.put("thermostat_comm_fail"); } if (mHeatingV2API.data.Device.Room[i].Error.bRoomTempSensor) { errorArray.put("thermostat_thermo_sensor_error"); } if (mHeatingV2API.data.Device.Room[i].Error.bRoomSystem) { errorArray.put("thermostat_system_error"); } if (mHeatingV2API.data.Device.Room[i].Error.bMainTempSensor) { errorArray.put("valve_thermo_sensor_error"); } if (mHeatingV2API.data.Device.Room[i].Error.bMainSystem) { errorArray.put("valve_system_error"); } if (mHeatingV2API.data.Device.Room[i].Error.bBoiler) { errorArray.put("boiler_error"); } if (mHeatingV2API.data.Device.Room[i].Error.bLeak) { errorArray.put("water_leakage_detection"); } if (mHeatingV2API.data.Device.Room[i].Error.bEtc) { errorArray.put("etc_error"); } JSONArray reserveArray = new JSONArray(); for (int j = 0; j < 24; j++) { if (mHeatingV2API.data.Device.Room[i].Reservation.getSchedule(j)) { reserveArray.put(j); } } // build jsonObject JSONObject jsonObject = new JSONObject(); try { String roomName; if (i == 0) { roomName = "living_room"; } else { roomName = "room" + i; } jsonObject.accumulate("roomNumber", roomName); jsonObject.accumulate("mode", mode); jsonObject.accumulate("valveState", mHeatingV2API.data.Device.Room[i].bValveStatus == true ? "on" : "off"); jsonObject.accumulate("setTemperature", mHeatingV2API.data.Device.Room[i].SetTemp); jsonObject.accumulate("setUnit", "0.5"); jsonObject.accumulate("currentTemperature", mHeatingV2API.data.Device.Room[i].NowTemp); jsonObject.accumulate("sleepDuration", getTimeData(mHeatingV2API.data.Device.Room[i].Sleep.getTime())); jsonObject.accumulate("sleepTemperature", mHeatingV2API.data.Device.Room[i].Sleep.getTempDouble()); jsonObject.accumulate("reservation", reserveArray); if (errorArray.length() > 0) { jsonObject.accumulate("errorCode", errorArray); } else { jsonObject.accumulate("errorCode", JSONObject.NULL); } } catch (JSONException e) { e.printStackTrace(); } SendData("icon", "controller", "heating", "each_control", jsonObject, 2); } } //데이터 저장 if (bChangeTotalState == true) { for (int i = 0; i < roomCount; i++) { mHeating.eachRoom[i].mode = mHeatingV2API.data.Device.Room[i].Mode; mHeating.eachRoom[i].curTemper = mHeatingV2API.data.Device.Room[i].NowTemp; mHeating.eachRoom[i].setTemper = mHeatingV2API.data.Device.Room[i].SetTemp; } } } else { mHeatingV2API = mWallPadAPI.Get_HeatingV2Controller(); } } catch (Exception e) { Log.e(TAG, "[Exception] checkChangedHeating()"); e.printStackTrace(); } } /* * 에너지미터의 조명과 콘센트의 상태를 비교하여 변경되었으면 데이터 수집 연동 서버로 메세지를 전송한다. * 변경된 상태는 백업한다. */ public void checkChangedEnergyMeter() { String installed, comm, relay; String constantOutlet; int lightCount; try { if (mEnergyMeterAPI != null) { mEnergyMeterAPI.Refresh((byte) 0xFF, false); boolean bChangeState = false; for (int i = 0; i < mEnergyMeterAPI.data.RoomCnt; i++) { JSONArray state = new JSONArray(); JSONArray lightState = new JSONArray(); JSONArray outletState = new JSONArray(); //installed if (mEnergyMeterAPI.data.Em.eachRoom[i].Install) { installed = "installed"; } else { installed = "not_installed"; } if (mEnergyMeterAPI.data.Em.eachRoom[i].CommStatus) { comm = "comm_ok"; } else { comm = "comm_error"; } if (mEnergyMeterAPI.data.Em.eachRoom[i].AllLightRelay_Use) { if (mEnergyMeterAPI.data.Em.eachRoom[i].AllLightRelay_OnOff) { relay = "relay_on"; } else { relay = "relay_off"; } } else { relay = "relay_not_supported"; } state.put(installed); state.put(comm); state.put(relay); lightCount = mEnergyMeterAPI.data.Em.eachRoom[i].LightCnt; // 각 에너지미터에 대한 조명 갯수 for (int j = 0; j < mEnergyMeterAPI.data.Em.eachRoom[i].LightCnt; j++) { if (mSDBEMInfo.EachRoom[i].Light_bOnOff[j] != mEnergyMeterAPI.data.Em.eachRoom[i].LightOnOff[j]) { // 같지 않다면 각각에 대해서 상태 메세지를 보낸다. bChangeState = true; String status = "off"; if (mEnergyMeterAPI.data.Em.eachRoom[i].LightOnOff[j] == true) status = "on"; lightState.put(status); } } if (mEnergyMeterAPI.data.Em.eachRoom[i].ConMode) { constantOutlet = "disable"; } else { constantOutlet = "enable"; } // 각 에너지미터에 대한 콘센트 갯수 int concentCount = mEnergyMeterAPI.data.Em.eachRoom[i].ConCnt; if (concentCount >= 3) concentCount = 2; for (int j = 0; j < concentCount; j++) { String conMode = "set/"; if (mEnergyMeterAPI.data.Em.eachRoom[i].ConMode == false) conMode = "unset/"; Log.d(TAG, "before => room number : " + i + ", switch : " + j + ", status : " + mEMeter.eachRoom[i].concentStatus[j]); Log.d(TAG, "current => room number : " + i + ", switch : " + j + ", status : " + mEnergyMeterAPI.data.Em.eachRoom[i].ConOnOff[j]); // 콘센트 자동/수동에 대한 변경 이벤트도 보내달라 함 /** 콘센트 모드상태 (true : 자동 ,false : 상시) C1, C2에 일괄적용 */ //boolean ConMode; if (mEMeter.eachRoom[i].concentStatus[j] != mEnergyMeterAPI.data.Em.eachRoom[i].ConOnOff[j] || mEMeter.eachRoom[i].ConMode[j] != mEnergyMeterAPI.data.Em.eachRoom[i].ConMode) { // 같지 않다면 각각에 대해서 상태 메세지를 보낸다. bChangeState = true; String status = "off"; if (mEnergyMeterAPI.data.Em.eachRoom[i].ConOnOff[j] == true) status = "on"; outletState.put(status); } } JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("roomNumber", (i + 1)); jsonObject.accumulate("state", state); jsonObject.accumulate("lightCount", lightCount); jsonObject.accumulate("lightState", lightState); jsonObject.accumulate("constantOutlet", constantOutlet); jsonObject.accumulate("outletState", outletState); } catch (JSONException e) { e.printStackTrace(); } SendData("icon", "meter", "energyMeter", "each_control", jsonObject, 2); } if (bChangeState == true) saveChangedEnergyMeterStatus(); } } catch (Exception e) { Log.e(TAG, "[Exception] checkChangedEnergyMeter()"); e.printStackTrace(); } } /** * 디바이스 API 를 Load 한다. * * @param wpapi - 생성시 전달받은 WallPadAPI * @return (int) - >=0 : 성공, <0 : 실패 */ private int loadRealtimemeterAPI(WallPadAPI wpapi) { Log.i(TAG, "[loadRealtimemeterAPI] - Start"); // 2. wpapi Check if (wpapi == null) { Log.e(TAG, "[loadRealtimemeterAPI] - wpapi is null"); return -2; } // 3. Load API Log.i(TAG, "[loadRealtimemeterAPI] - Step1 : RemoteMeter API Load..."); try { mRealTimeMeterAPI = wpapi.Get_RealTimeMeterController(); } catch (Exception e) { Log.e(TAG, "[loadRealtimemeterAPI] - [Exception Error] wpapi.Get_RealTimeMeterController"); e.printStackTrace(); return -100; } if (mRealTimeMeterAPI == null) { Log.e(TAG, "[loadRealtimemeterAPI] - mRealTimeMeterAPI is null"); return -4; } Log.i(TAG, "[loadRealtimemeterAPI] - OK"); return 0; } /** * 제어기 상태를 가져온다. * * @param real - (boolean) true : 실시간 , false : 가장최근 * @return (int) - >=0 : 성공, <0 : 실패 */ @SuppressWarnings("unused") private int updateRealtimemeterData(boolean real) { try { // 1. Api Load Check if (mRealTimeMeterAPI == null) { Log.e(TAG, "[updateRealtimemeterData] - remoteMeterApi unload !!!"); return -1; } // 2. reflash try { int ret = mRealTimeMeterAPI.Refresh(real); if (ret < 0) { Log.e(TAG, "[updateRealtimemeterData] - mRealTimeMeterAPI.Refresh - ret (" + ret + ")" + mRealTimeMeterAPI.ErrorCode.ErrStr()); return -2; } } catch (Exception e) { e.printStackTrace(); return -100; } // 3. Range Check if (mRealTimeMeterAPI.data == null) { Log.e(TAG, "[updateRealtimemeterData] - mRealTimeMeterAPI.mRealTimeMeterData is null !!!"); return -9; } if (mRealTimeMeterAPI.data.Elec.Now >= 1000000) { return -10; } if (mRealTimeMeterAPI.data.Water.Now >= 1000) { return -11; } if (mRealTimeMeterAPI.data.HotWater.Now >= 1000) { return -12; } if (mRealTimeMeterAPI.data.Gas.Now >= 1000) { return -13; } if (mRealTimeMeterAPI.data.Calorie.Now >= 1000) { return -14; } // 4. Data Copy mRealTimeMeterData = mRealTimeMeterAPI.data; // 5. Debug msg if (DEBUG_REALMETER_DATA_LOG_ON) { Log.i(TAG, mRealTimeMeterData.ToDebugString()); } return 0; } catch (Exception e) { e.printStackTrace(); return -99; } } /** * 실시간검침 데이터를 서버에 전송하는 쓰레드.
* 10분에 한번씩 저장 */ @SuppressLint("UseValueOf") class saveRealmeterData extends Thread { @Override public void run() { super.run(); Log.i(TAG, "[saveRealmeterData] ========== START =========="); int ret; wallpaddbmgr WallpadDBMGRforThread = null; while (true) { try { Thread.sleep(1000 * 60); //1분마다, 이 시간 설정은 같이 논의 할 필요가 있음. if (mRealTimeMeterAPI != null) { ret = mRealTimeMeterAPI.Refresh(false); if (ret == 0) { Log.i(TAG, "[saveRealmeterData] mRealTimeMeterAPI.Refresh is success"); Log.i(TAG, "[saveRealmeterData] mRealTimeMeterAPI.ElecAccrued :" + mRealTimeMeterAPI.data.Elec.Acc); double electricNow = mRealTimeMeterAPI.data.Elec.Now; double electricAcc = mRealTimeMeterAPI.data.Elec.Acc; double waterNow = mRealTimeMeterAPI.data.Water.Now; double waterAcc = mRealTimeMeterAPI.data.Water.Acc; double gasNow = mRealTimeMeterAPI.data.Gas.Now; double gasAcc = mRealTimeMeterAPI.data.Gas.Acc; double hotwaterNow = mRealTimeMeterAPI.data.HotWater.Now; double hotwaterAcc = mRealTimeMeterAPI.data.HotWater.Acc; double heatNow = mRealTimeMeterAPI.data.Calorie.Now; double heatAcc = mRealTimeMeterAPI.data.Calorie.Acc; JSONArray errorArray = new JSONArray(); if (mRealTimeMeterAPI.data.nElecErrorCnt > 0) { errorArray.put("electric"); } if (mRealTimeMeterAPI.data.nGasErrorCnt > 0) { errorArray.put("gas"); } if (mRealTimeMeterAPI.data.nHeatingErrorCnt > 0) { errorArray.put("heat"); } if (mRealTimeMeterAPI.data.nHotWaterErrorCnt > 0) { errorArray.put("hotwater"); } if (mRealTimeMeterAPI.data.nWaterErrorCnt > 0) { errorArray.put("water"); } JSONArray electricArray = new JSONArray(); JSONArray gasArray = new JSONArray(); JSONArray heatArray = new JSONArray(); JSONArray hotwaterArray = new JSONArray(); JSONArray waterArray = new JSONArray(); try { electricArray.put(electricNow); electricArray.put(electricAcc); gasArray.put(gasNow); gasArray.put(gasAcc); heatArray.put(heatNow); heatArray.put(heatAcc); hotwaterArray.put(hotwaterNow); hotwaterArray.put(hotwaterAcc); waterArray.put(waterNow); waterArray.put(waterAcc); } catch (JSONException e) { e.printStackTrace(); } JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("error", errorArray); jsonObject.accumulate("electric", electricArray); jsonObject.accumulate("water", waterArray); jsonObject.accumulate("hotwater", hotwaterArray); jsonObject.accumulate("gas", gasArray); jsonObject.accumulate("heating", heatArray); } catch (JSONException e) { e.printStackTrace(); } SendData("icon", "meter", "amr", "metering", jsonObject, 2); } else { Log.i(TAG, "[saveRealmeterData] mRealTimeMeterAPI.Refresh is fail"); } } else { Log.i(TAG, "[saveRealmeterData] mRealTimeMeterAPI is null"); } //난방 현재 온도도 같이 보내준다. if (bSending && mHeatingV2API != null) { int roomCount = mHeatingV2API.data.Device.info.RoomCount; JSONObject jsonTempObject = new JSONObject(); for (int ii = 0; ii < roomCount; ii++) { // build jsonObject try { jsonTempObject.accumulate("room" + (ii + 1), mHeatingV2API.data.Device.Room[ii].NowTemp); } catch (JSONException e) { e.printStackTrace(); } } SendData("icon", "controller", "heating", "current_temperture", jsonTempObject, 2); } else { mHeatingV2API = mWallPadAPI.Get_HeatingV2Controller(); } //주기적으로 에너지 미터 체크 checkChangedSdb(true); } catch (InterruptedException e1) { // TODO Auto-generated catch block if (WallpadDBMGRforThread != null) { WallpadDBMGRforThread.closeDB(); } Log.i(TAG, "saveRealmeterData extends Thread occurs exception Error"); e1.printStackTrace(); } } } } /** * 실시간검침기 드라이버 초기생성시 Connect 에 시간이 걸리며,
* 실시간검침기 드라이버 초기화후 바로 API 를 가져올수 없기에,
* 본 딜레이 코드를 임시로 적용한다. */ @SuppressLint("HandlerLeak") protected Handler initRealtimemeterFunctionHandler = new Handler() { @SuppressLint("HandlerLeak") @Override public void handleMessage(Message msg) { Log.i(TAG, "[initRealtimemeterFunctionHandler] msg.what [" + msg.what + "]"); if (msg.what == 0) { if (loadRealtimemeterAPI(mWallPadAPI) >= 0) { if (updateRealtimemeterData(false) == 0) { initRealtimemeterFunctionHandler.sendEmptyMessageDelayed(1, 10); } else { initRealtimemeterFunctionHandler.sendEmptyMessageDelayed(0, 30000); } } else { Log.i(TAG, "mInitDriverCheckHandler --> mRealTimeMeterAPI == null"); initRealtimemeterFunctionHandler.sendEmptyMessageDelayed(0, 10000); } } else if (msg.what == 1) { Log.i(TAG, "[initRealtimemeterFunctionHandler] succes addBrActionName"); if (mRealTimeMeterAPI != null) { WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(getApplicationContext()); int[] setdata = mWallpadDeviceSet.Get_RealTimeMetor_Info(); mWallpadDeviceSet.closeDB(); if ((saveRealmeterDataThread == null) && (setdata[0] == 1)) { saveRealmeterDataThread = new saveRealmeterData(); saveRealmeterDataThread.start(); } } } } }; /* 실시간 검침기 정보 전송 관리 */ private RealTimeMeterAPI mRealTimeMeterAPI; private DataClasses.RealTimeMeter mRealTimeMeterData = null; private boolean DEBUG_REALMETER_DATA_LOG_ON = false; public Thread saveRealmeterDataThread = null; private void startRealtimemeterInfo() { try { Log.w(TAG, "[startRealtimemeterInfo] Normal working mode!!!"); // 실시간 검침기 사용유무 판단 WallpadDeviceSet mWallpadDeviceSet = new WallpadDeviceSet(getApplicationContext()); int[] naRealtimemtInfo = mWallpadDeviceSet.Get_RealTimeMetor_Info(); mWallpadDeviceSet.closeDB(); boolean bRealtimemeterUsage = false; int nRealtimemeterCntDB = -99; if (naRealtimemtInfo[0] == WallpadDeviceSet.DO_USE) { // 실시간 검침 사용함 bRealtimemeterUsage = true; nRealtimemeterCntDB = naRealtimemtInfo[1]; initRealtimemeterFunctionHandler.sendEmptyMessage(0); } else { // 실시간 검침 사용하지 않음 bRealtimemeterUsage = false; } Log.i(TAG, "[startRealtimemeterInfo] bRealtimemeterUsage [" + bRealtimemeterUsage + "], nRealtimemeterCntDB [" + nRealtimemeterCntDB + "]"); } catch (Exception e) { Log.e(TAG, "[Exception] startRealtimemeterInfo()"); e.printStackTrace(); } } BroadcastReceiver mSendDataEventBR = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String strActionName = intent.getAction(); if (strActionName.equals(BrID.BR_GAS)) { try { if (mGasAPI != null) { for (int j = 0; j < nGasCnt; j++) { mGasAPI.Refresh((byte) j, false); Log.d(TAG, " j : " + j + " , haGasStatus[j] : " + haGasStatus[j] + " mGasAPI.data.Device[j].GasStatus : " + mGasAPI.data.Device[j].GasStatus); if (mGasAPI.data.Device[j].GasStatus != GasAPI.GASSTATUS.Operation && haGasStatus[j] != mGasAPI.data.Device[j].GasStatus) { String status = "close"; if (mGasAPI.data.Device[j].GasStatus == GasAPI.GASSTATUS.Close) status = "close"; else if (mGasAPI.data.Device[j].GasStatus == GasAPI.GASSTATUS.Open) status = "open"; else if (mGasAPI.data.Device[j].GasStatus == GasAPI.GASSTATUS.Operation) status = "working"; //JSONArray errorArray = new JSONArray(); String fault = "no"; if (mGasAPI.data.Device[j].Fault > 0) { //errorArray.put("gas_sensor"); fault = "yes"; } JSONObject jsonObject = new JSONObject(); try { jsonObject.accumulate("state", status); jsonObject.accumulate("fault", fault); } catch (JSONException e) { e.printStackTrace(); } // 상태가 변경되었기 때문에 이전 상태를 백업한다. haGasStatus[j] = mGasAPI.data.Device[j].GasStatus; } } } else { mGasAPI = mWallPadAPI.Get_GasController(); } } catch (Exception e) { e.printStackTrace(); } } else if (strActionName.equals(BrID.BR_HEATING)) { // Log.d(TAG, "********************* BR DataSenderService BR_HEATING ********************"); checkChangedHeating(); } else if (strActionName.equals(BrID.BR_AIRCON)) { // Log.d(TAG, "********************* BR DataSenderService BR_AIRCON ********************"); checkChangedAircon(); } else if (strActionName.equals(BrID.BR_SDB_EVENT)) { // Log.d(TAG, "********************* DataSenderService BR_SDB_EVENT ********************"); checkChangedSdb(false); } else if (strActionName.equals(BrID.BR_KNX_EVENT)) { // Log.d(TAG, "********************* DataSenderService BR_KNX_EVENT ********************"); deviceApiLoadLight(); } else if (strActionName.equals(BrID.BR_SDB_LIVING_EVENT)) { // Log.d(TAG, "********************* DataSenderService.BR_SDB_LIVING_EVENT ******************** -> bDeviceInitComplete [" + bDeviceInitComplete + "]"); //checkChangedSdbLivingLight(); } else if (strActionName.equals(BrID.BR_ENERGY_METER)) { // Log.d(TAG, "********************* BR DataSenderService.BR_ENERGY_METER ********************"); if (bDeviceInitComplete) { checkChangedEnergyMeter(); } } else if (strActionName.equals(BrID.BR_VENTIL)) { // Log.d(TAG, "********************* BR DataSenderService.BR_VENTIL ********************"); checkChangedVentilation(); } else if (strActionName.equals(define.NOTIFY_ACNAME)) { int kind = intent.getIntExtra(define.NOTIBR_KIND, 0); Log.d(TAG, "[mSendDataEventBR] NOTIFY_ACNAME -> kind [" + kind + "]"); switch (kind) { // 일괄소등 상태 업데이트 case define.NOTIFY_ALL_LIGHT_OFF: Log.i(TAG, "[mSendDataEventBR] define.NOTIFY_ALL_LIGHT_OFF"); SendData("icon", "switch", "smart_switch", "turnoffalllight", "on", 1); break; // 일괄소등 해제 (조명 ON) case define.NOTIFY_ALL_LIGHT_ON: Log.i(TAG, "[mSendDataEventBR] define.NOTIFY_ALL_LIGHT_ON"); SendData("icon", "switch", "smart_switch", "turnoffalllight", "off", 1); break; case define.NOTIFY_DEVICE_ELE_CALL_UP: // 제어기기 엘리베이터 상향 호출 요청 Log.i(TAG, "[mWallPadNotifyBR] define.NOTIFY_DEVICE_ELE_CALL_UP"); SendData("icon", "switch", "elevator", "call", "up", 1); break; case define.NOTIFY_DEVICE_ELE_CALL_DOWN: // 제어기기에서 엘리베이터 하향 호출 요청 Log.i(TAG, "[mWallPadNotifyBR] define.NOTIFY_DEVICE_ELE_CALL_DOWN"); SendData("icon", "switch", "elevator", "call", "down", 1); break; // 방범상태 변경 case define.NOTIFY_ALARM_CHANGE: break; // 디바이스 종류 및 갯수 파악 case define.NOTIFY_DEVICE_INIT_COMPLETION: Log.d(TAG, "[mMobileEventBR] ========== DeviceService Complite!! =========="); bDeviceInitComplete = true; deviceApiLoad(); break; // 디바이스 연결 case define.NOTIFY_DEVICECONNECTED: Log.d(TAG, "[mMobileEventBR] ========== DeviceService Complite!! =========="); deviceApiLoad(); break; // 도어락 문열림 case define.NOTIFY_RFDOORLOCK_OPEN: // Log.d(TAG, "********************* NOTIFY_RFDOORLOCK_OPEN ********************"); if (bDeviceInitComplete) { // sendMsgDeviceEvent_DoorLock(true); } break; case define.NOTIFY_SMARTSW_SET_OUTING: // 485 대외향 스마트스위치 외출모드 Log.i(TAG, "[mSendDataEventBR] define.NOTIFY_SMARTSW_SET_OUTING"); SendData("icon", "switch", "smart_switch", "awaymode", "on", 1); break; case define.NOTIFY_SMARTSW_FREE_OUTING: //대외향 485 스마트스위치 외출모드 해제 Log.i(TAG, "[mSendDataEventBR] define.NOTIFY_SMARTSW_FREE_OUTING"); SendData("icon", "switch", "smart_switch", "awaymode", "off", 1); break; } } else if (strActionName.equals(Common.BR_MAIN_NOTI.ACNAME_MAIN_NOTI)) { int nKind = intent.getIntExtra(Common.BR_MAIN_NOTI.KIND, 0); Log.d(TAG, "[mSendDataEventBR] nKind =" + nKind); if (nKind == Common.BR_MAIN_NOTI.RET_ELEVATOR_CALL_STATE) { //엘리베이터 월패드 이벤트는 터치만 적용. /* String strElevatorFloor = intent.getStringExtra("ElevatorFloor"); Log.d(TAG, "[mSendDataEventBR] RET_ELEVATOR_CALL_STATE -> strElevatorFloor [" + strElevatorFloor + "]"); Common.ELEV_STATUS eElevCallStatus = Common.ELEV_STATUS.getEnum(intent.getStringExtra("ElevatorFloor")); Log.d(TAG, "[mSendDataEventBR] RET_ELEVATOR_CALL_STATE -> eElevCallStatus [" + eElevCallStatus + "]"); try { if (eElevCallStatus == Common.ELEV_STATUS.DOWN) { SendData("null", "control", "elevator", "call", "down", 1); } else if (eElevCallStatus == Common.ELEV_STATUS.UP) { SendData("null", "control", "elevator", "call", "up", 1); } else if (eElevCallStatus == Common.ELEV_STATUS.UP_DOWN) { SendData("null", "control", "elevator", "call", "updown", 1); } else { //SendData("null", "switch", "elevator", "call", "none", 1); } } catch (Exception e) { Log.e(TAG, "[Exception] displayElevCallStatus(ELEV_STATUS ElevStatus)"); e.printStackTrace(); } */ } } } }; private IGW300API iGW300API = null; private IGW300API.Data mIGW300Data; public IGW300API.Data getIGW300UpdateData() { if (iGW300API == null) { Log.e(TAG, "[Device_Update] - iGW300API unload !!!"); iGW300API = mWallPadAPI.Get_IGW300Controller(); if (iGW300API == null) { Log.w(TAG, "[Device_Update] iGW300API is null!!"); } return null; } // 2. Reflash try { int ret = iGW300API.Refresh(false); if (ret < 0) { Log.e(TAG, "[Device_Update] getState - ret (" + ret + ") ErrorCode = " + iGW300API.ErrorCode.ErrStr()); return null; } } catch (Exception e) { Log.e(TAG, "[Device_Update] - " + e.toString()); e.printStackTrace(); return null; } return iGW300API.data; } private void checkGWSensorEvent() { try { if (mWallPadAPI.getGatewayType() == Version.GATEWAY_MODEL.IGW_300) { if (iGW300API == null) { Log.w(TAG, "[checkGWSensorEvent] iGW300API is null!!"); return; } if (iGW300API.data == null) { Log.w(TAG, "[checkGWSensorEvent] iGW300API.data is null!!"); return; } // 내부 동체 (동체감지기 2) 2 if (bIn_Motion != iGW300API.data.senIn.In_Motion) { Log.w(TAG, "[checkGWSensorEvent] iGW300API.iGW300API.data.senIn.In_Motion is check!!"); bIn_Motion = iGW300API.data.senIn.In_Motion; SendData("icon", "sensor", "motion", bIn_Motion == true ? "detection" : "release", (String) null, 1); } // 외부 동체 (동체감지기 1) 1 if (bOut_Motion != iGW300API.data.senIn.Out_Motion) { Log.w(TAG, "[checkGWSensorEvent] iGW300API.iGW300API.data.senIn.Out_Motion is check!!"); bOut_Motion = iGW300API.data.senIn.Out_Motion; SendData("icon", "sensor", "motion", bOut_Motion == true ? "detection" : "release", (String) null, 1); } // 마그네틱 0 if (bMagnetic_Motion != iGW300API.data.senIn.Magnetic == true) { Log.w(TAG, "[checkGWSensorEvent] iGW300API.iGW300API.data.senIn.Magnetic is check!!"); bMagnetic_Motion = iGW300API.data.senIn.Magnetic; SendData("icon", "sensor", "magnetic", bMagnetic_Motion == true ? "detection" : "release", (String) null, 1); } } else { Log.w(TAG, "[checkGWSensorEvent] Not supported gateway model -> " + mWallPadAPI.getGatewayType()); } } catch (Exception e) { Log.e(TAG, "[Exception] checkGWSensorEvent()"); e.printStackTrace(); } } BroadcastReceiver mSendDataSensorBR = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String strActionName = intent.getAction(); Log.i(TAG, "[IGW300InterfaceBR.onReceive] strActionName [" + strActionName + "]"); if (strActionName.equals(IGW300API.SENSOR_BR_NAME)) { getIGW300UpdateData(); checkGWSensorEvent(); } } }; private void registerEventAlarmBr() { try { Log.d(TAG, "[registerEventAlarmBr] ========== START =========="); WallpadDeviceSet wds = new WallpadDeviceSet(mContext); int nDPType = wds.Get_DistributionPannelType_Info(); wds.closeDB(); IntentFilter mIntentFilter = new IntentFilter(); mIntentFilter.addAction(define.NOTIFY_ACNAME); mIntentFilter.addAction(Common.BR_MAIN_NOTI.ACNAME_MAIN_NOTI); if (Version.getModelType() == Version.MODEL_TYPE.IHN_D101 || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K_I) { if (nDPType == Version.DISTRIBUTION_MODEL.SMART_DIST) { // 스마트 분전반 mIntentFilter.addAction(BrID.BR_SDB_LIVING_EVENT); mIntentFilter.addAction(BrID.BR_SDB_EVENT); } else if (nDPType == Version.DISTRIBUTION_MODEL.KNX_DIST) { // KNX 분전반 mIntentFilter.addAction(BrID.BR_KNX_EVENT); } } else if (Version.getModelType() == Version.MODEL_TYPE.IHN_1020GL || Version.getModelType() == Version.MODEL_TYPE.IHN_1010GL || Version.getModelType() == Version.MODEL_TYPE.IHN_1010GL_I) { mIntentFilter.addAction(BrID.BR_LIVING_LIGHT); mIntentFilter.addAction(BrID.BR_ENERGY_METER); } mIntentFilter.addAction(BrID.BR_GAS); mIntentFilter.addAction(BrID.BR_VENTIL); mIntentFilter.addAction(BrID.BR_HEATING); getApplicationContext().registerReceiver(mSendDataEventBR, mIntentFilter); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(SENSOR_BR_NAME); registerReceiver(mSendDataSensorBR, mIntentFilter); Log.d(TAG, "[registerEventAlarmBr] ========== END =========="); } catch (Exception e) { Log.e(TAG, "[Exception] registerEventAlarmBr()"); e.printStackTrace(); } } private void registerDeviceBR() { try { Log.d(TAG, "[registerSubcriptionDeviceBR] ========== START =========="); WallpadDeviceSet wds = new WallpadDeviceSet(mContext); int nDPType = wds.Get_DistributionPannelType_Info(); wds.closeDB(); if (Version.getModelType() == Version.MODEL_TYPE.IHN_1020GL || Version.getModelType() == Version.MODEL_TYPE.IHN_1010GL || Version.getModelType() == Version.MODEL_TYPE.IHN_1010GL_I) { if (mEnergyMeterAPI != null) mEnergyMeterAPI.regChangedBR(BrID.BR_ENERGY_METER); } else if (Version.getModelType() == Version.MODEL_TYPE.IHN_D101 || Version.getModelType() == Version.MODEL_TYPE.IHN_D101_I || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K || Version.getModelType() == Version.MODEL_TYPE.IHN_D101K_I) { if (nDPType == Version.DISTRIBUTION_MODEL.SMART_DIST) { // 스마트 분전반 if (mSdb_LivingRoomLightAPI != null) mSdb_LivingRoomLightAPI.regChangedBR(BrID.BR_SDB_LIVING_EVENT); if (mSdbAPI != null) mSdbAPI.regChangedBR(BrID.BR_SDB_EVENT); if (mAirconData != null) mSystemAirconAPI.regChangedBR(BrID.BR_AIRCON); } else if (nDPType == Version.DISTRIBUTION_MODEL.KNX_DIST) { // KNX 분전반 if (mKnxAPI != null) mKnxAPI.regChangedBR(BrID.BR_KNX_EVENT); if (mKnxAirconData != null) mKnxSystemAirconAPI.regChangedBR(BrID.BR_AIRCON); } } else { } if (mGasAPI != null) mGasAPI.regChangedBR(BrID.BR_GAS); if (mVentiAPI != null) mVentiAPI.regChangedBR(BrID.BR_VENTIL); if (mHeatingV2API != null) mHeatingV2API.regChangedBR(BrID.BR_HEATING); } catch (Exception e) { Log.e(TAG, "[Exception] registerSubcriptionDeviceBR()"); e.printStackTrace(); } } public String millToDate(long mills) { String pattern = "yyyy-MM-dd'T'HH:mm:ss"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); String date = (String) formatter.format(new Timestamp(mills)); return date; } }