HDLSDK/app/src/main/java/com/hdl/hdlsdk/App.java
@@ -5,23 +5,24 @@ import com.hdl.sdk.common.HDLSdk; import com.hdl.sdk.common.event.EventListener; import com.hdl.sdk.common.utils.LogUtils; import com.hdl.sdk.connect.HDLLink; import com.hdl.sdk.connect.bean.LinkResponse; /** * Created by Tong on 2021/10/8. */ public class App extends Application { private String deviceStatusUpdateTopic; @Override public void onCreate() { super.onCreate(); //初始化SDK HDLSdk.getInstance().init(this); HDLLink.getInstance().registerAllTopicsListener(new EventListener() { @Override public void onMessage(Object msg) { Log.i("TAG", "AllTopicsListener onMessage: "+msg.toString()); } }); //控制SDK日志打印 HDLSdk.getInstance().setLogEnabled(false); } @Override HDLSDK/app/src/main/java/com/hdl/hdlsdk/MainActivity.java
@@ -17,15 +17,20 @@ import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.listener.OnItemClickListener; import com.hdl.sdk.common.event.EventListener; import com.hdl.sdk.common.exception.HDLLinkException; import com.hdl.sdk.common.utils.IdUtils; import com.hdl.sdk.common.utils.IpUtils; import com.hdl.sdk.connect.HDLLink; import com.hdl.sdk.connect.bean.AuthenticateRequest; import com.hdl.sdk.connect.bean.GatewaySearchBean; import com.hdl.sdk.connect.config.HDLLinkConfig; import com.hdl.sdk.connect.bean.LinkResponse; import com.hdl.sdk.connect.bean.request.AuthenticateRequest; import com.hdl.sdk.connect.bean.request.PropertyReadRequest; import com.hdl.sdk.connect.bean.response.GatewaySearchBean; import com.hdl.sdk.connect.callback.HDLLinkCallBack; import com.hdl.sdk.connect.callback.HDLLinkResponseCallBack; import com.hdl.sdk.connect.socket.HDLAuthSocket; import com.hdl.sdk.connect.socket.HDLSocket; import com.hdl.sdk.connect.bean.DeviceControlRequest; import com.hdl.sdk.connect.bean.request.DeviceControlRequest; import com.hdl.sdk.connect.protocol.LinkMessageDecoder; import com.hdl.sdk.connect.protocol.LinkMessageEncoder; import com.hdl.sdk.socket.SocketOptions; @@ -45,7 +50,14 @@ private TextView tv; private TextView responseTv; boolean isOn; private EventListener allTopicsListener; private String testLightSid = "000101B847C71B02020100010101"; @Override protected void onDestroy() { super.onDestroy(); removeAllTopicsListener(); } @Override protected void onCreate(Bundle savedInstanceState) { @@ -57,6 +69,7 @@ rv.setLayoutManager(new LinearLayoutManager(this)); checkIfCertified(); registerAllTopicsListener(); ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() { @Override @@ -68,14 +81,14 @@ launcher.launch(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}); final List<DemoBean> beans = new ArrayList<>(); beans.add(new DemoBean("搜索网关")); beans.add(new DemoBean("入网认证")); beans.add(new DemoBean("搜索指定网关是否在线")); beans.add(new DemoBean("获取功能列表")); beans.add(new DemoBean("功能属性读取")); beans.add(new DemoBean("设备控制")); beans.add(new DemoBean("状态上报")); beans.add(new DemoBean("读取状态")); beans.add(new DemoBean("入网认证")); beans.add(new DemoBean("搜索指定网关是否在线")); beans.add(new DemoBean("获取场景列表")); beans.add(new DemoBean("场景控制")); demoAdapter = new DemoAdapter(beans); rv.setAdapter(demoAdapter); @@ -93,91 +106,36 @@ public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) { switch (position) { case 0: tv.setText("搜索网关中"); responseTv.setText(""); HDLSocket.getInstance().searchGateway(new HDLSocket.CallBack() { @Override public void onError(String error) { tv.setText("网关获取失败"); } @Override public void onResponse(String data) { tv.setText("获取网关成功"); responseTv.setText(data); } }); //入网认证 sendAuthenticateRequest(); break; case 1: tv.setText("获取功能列表中"); responseTv.setText(""); HDLSocket.getInstance().getFunctionList(new HDLSocket.CallBack() { @Override public void onError(String error) { tv.setText(error); } @Override public void onResponse(String data) { tv.setText("获取功能列表成功"); responseTv.setText(data); } }); //搜索网关 searchGatewayBroadcast(); break; case 2: //功能属性读取 // HDLSocket.getInstance().getFunctionAttribute(); //获取功能列表 getFunctionList(); break; case 3: //设备控制 isOn = !isOn; List<DeviceControlRequest> requestList = new ArrayList<>(); DeviceControlRequest request = new DeviceControlRequest(); request.setSid("000101B847C71B02020100010101"); List<DeviceControlRequest.StatusBean> statusBeanList= new ArrayList<>(); DeviceControlRequest.StatusBean bean = new DeviceControlRequest.StatusBean(); bean.setKey("on_off"); bean.setValue(isOn ? "on" : "off"); statusBeanList.add(bean); request.setStatus(statusBeanList); requestList.add(request); HDLAuthSocket.getInstance().propertyDown(requestList,null); //功能属性读取 getFunctionAttribute(); break; case 4: //状态上报 //HDLSocket.getInstance().propertyUp(); //设备控制 controlDecide(); break; case 5: //读取状态 // HDLSocket.getInstance().propertyRead(); propertyRead(); break; case 6: // //入网认证 sendAuthenticateRequest(); //获取场景列表 getSceneList(); break; case 7: // //如果已经认证后,搜索指定网关是否在线 HDLLink.getInstance().searchGateway(new HDLAuthSocket.SearchGatewayCallBack() { @Override public void onEnd(String error) { tv.setText("网关不在线"); } @Override public void onSuccess(GatewaySearchBean gatewaySearchBean) { tv.setText("网关在线"); responseTv.setText("网关id:"+gatewaySearchBean.getGatewayId()); // Log.i("TAG", "onSuccess: 搜索成功:"+gatewaySearchBean.getGatewayId()); } }); //获取场景列表 controlScene(); break; } } @@ -187,16 +145,42 @@ Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } /** * 检测是否认证过 */ void checkIfCertified(){ boolean isCertified = HDLLink.getInstance().checkIfCertified(); showToast(isCertified?"已经认证过":"未认证"); String mes = isCertified?"已经认证过":"未认证"; showToast(mes); tv.setText(mes); } /** * 注册所有主题数据的监听 */ void registerAllTopicsListener(){ allTopicsListener = new EventListener() { @Override public void onMessage(Object msg) { LinkResponse response = (LinkResponse)msg; Log.i("TAG", "AllTopicsListener onMessage: "+msg.toString()); } }; HDLLink.getInstance().registerAllTopicsListener(allTopicsListener); } /** * 移除所有主题数据的监听 */ void removeAllTopicsListener(){ HDLLink.getInstance().removeAllTopicsListener(allTopicsListener); } /** * 入网认证 */ void sendAuthenticateRequest(){ tv.setText("开始入网认证..."); String macStr = "AA000000000000BB"; String secret = "87ae414b7a853f65"; @@ -236,20 +220,21 @@ String ip = IpUtils.getBroadcastAddress(); // ip = "192.168.10.102"; HDLLink.getInstance().sendAuthenticateRequest(ip, request, new HDLAuthSocket.CallBack() { HDLLink.getInstance().startAuthenticateRequest(request, new HDLLinkCallBack() { @Override public void onError(String error) { Log.i("TAG", "onError: 认证失败"); public void onError(HDLLinkException e) { tv.setText("认证失败"); responseTv.setText(e.getMsg()); // Log.i("TAG", "onError: 认证失败"); } @Override public void onSuccess(String data) { public void onSuccess(String msg) { tv.setText("认证成功"); responseTv.setText(data.toString()); responseTv.setText(msg.toString()); } }); } String stringToMD5(String text) { byte[] hash; @@ -272,4 +257,167 @@ return hex.toString(); } /** * 如果已经认证后,搜索指定网关是否在线 * 广播搜索认证过的网关是否在线 */ void searchGatewayBroadcast(){ tv.setText("搜索网关中..."); HDLLink.getInstance().searchGatewayBroadcast(new HDLAuthSocket.SearchGatewayCallBack() { @Override public void onError(HDLLinkException e) { tv.setText("网关不在线"); } @Override public void onSuccess(GatewaySearchBean gatewaySearchBean) { tv.setText("网关在线"); responseTv.setText("搜索成功 网关id:"+gatewaySearchBean.getGatewayId()); // LogUtils.i("TAG", "onSuccess: 搜索成功:"+gatewaySearchBean.getGatewayId()); } }); } /** * 获取功能列表 */ void getFunctionList(){ tv.setText("获取功能列表中..."); responseTv.setText(""); HDLSocket.getInstance().getFunctionList(new HDLLinkCallBack() { @Override public void onError(HDLLinkException error) { tv.setText(error.getMsg()); } @Override public void onSuccess(String data) { tv.setText("获取功能列表成功"); responseTv.setText(data); } }); } /** * 功能属性读取 * 支持批量读取 */ void getFunctionAttribute(){ tv.setText("功能属性读取"); List<String> sids = new ArrayList<>(); sids.add(testLightSid); HDLSocket.getInstance().getFunctionAttribute(sids, new HDLLinkCallBack() { @Override public void onSuccess(String msg) { responseTv.setText(msg); } @Override public void onError(HDLLinkException e) { responseTv.setText(e.getMsg()); } }); } /** * 读取设备状态 * 支持批量读取 */ void propertyRead(){ tv.setText("读取状态中..."); List<String> list = new ArrayList<>(); list.add(testLightSid);//要读取设备的sid HDLSocket.getInstance().propertyRead(list, new HDLLinkCallBack() { @Override public void onSuccess(String data) { tv.setText("读取成功"); responseTv.setText(data); } @Override public void onError(HDLLinkException e) { tv.setText("读取失败"); responseTv.setText(e.getMsg()); } }); } /** * 控制失败 * 回复响应code为200 代表执行成功 */ void controlDecide(){ tv.setText("控制设备"); isOn = !isOn; List<DeviceControlRequest> requestList = new ArrayList<>(); DeviceControlRequest request = new DeviceControlRequest(); request.setSid(testLightSid); List<DeviceControlRequest.StatusBean> statusBeanList= new ArrayList<>(); DeviceControlRequest.StatusBean bean = new DeviceControlRequest.StatusBean(); bean.setKey("on_off"); bean.setValue(isOn ? "on" : "off"); statusBeanList.add(bean); request.setStatus(statusBeanList); requestList.add(request); HDLLink.getInstance().propertyDown(requestList, new HDLLinkCallBack() { @Override public void onSuccess(String data) { responseTv.setText(data); } @Override public void onError(HDLLinkException e) { responseTv.setText(e.getMsg()); } }); } /** * 获取场景列表 */ void getSceneList(){ tv.setText("读取场景列表"); HDLLink.getInstance().getSceneList(new HDLLinkCallBack() { @Override public void onSuccess(String msg) { responseTv.setText(msg); } @Override public void onError(HDLLinkException e) { responseTv.setText(e.getMsg()); } }); } //场景列表 // {"id":"8a5eaa143ce943b987b577df5a66759b","time_stamp":"1637040217235","objects":[{"sid":"04010560D2C7170A0A0100000000","name":"回家模式","status":"off","group":"255","delay":"0","modify_time":"1634871490"},{"sid":"04010560D2C76E0A0A0100010000","name":"离家模式","status":"off","group":"255","delay":"0","modify_time":"1634785823"}]} /** * 控制场景 * 执行成功的话 响应code为200 */ void controlScene(){ tv.setText("场景控制"); //控制场景sid列表,支持批量控制 List<String> sids = new ArrayList<>(); isOn = !isOn; if(isOn){ sids.add("04010560D2C7170A0A0100000000"); }else{ sids.add("04010560D2C76E0A0A0100010000"); } HDLLink.getInstance().controlScene(sids,new HDLLinkCallBack() { @Override public void onSuccess(String msg) { responseTv.setText(msg); } @Override public void onError(HDLLinkException e) { responseTv.setText(e.getMsg()); } }); } } HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/HDLSdk.java
@@ -2,6 +2,8 @@ import android.content.Context; import com.hdl.sdk.common.utils.LogUtils; /** * Created by Tong on 2021/9/28. */ @@ -27,4 +29,12 @@ public Context getContext() { return context; } /** * 设置打印是否开启 * @param enable */ public void setLogEnabled(boolean enable){ LogUtils.setEnabled(enable); } } HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/config/TopicConstant.java
@@ -58,4 +58,23 @@ //读取状态响应 public static final String PROPERTY_READ_REPLY = "/base/%s/thing/property/read_reply"; //8.1获取场景列表 public static final String SCENE_LIST_GET = "/user/%s/custom/scene/list/get"; //8.2获取场景 public static final String SCENE_GET = "/user/%s/custom/scene/get"; //8.3执行场景 public static final String SCENE_CONTROL = "/user/%s/custom/scene/execute"; //8.4场景增加 public static final String SCENE_ADD = "/user/%s/custom/scene/add"; //8.5场景编辑 public static final String SCENE_EDIT = "/user/%s/custom/scene/edit"; //8.6场景删除 public static final String SCENE_DELETE = "/user/%s/custom/scene/delete"; } HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/exception/HDLLinkCode.java
New file @@ -0,0 +1,44 @@ package com.hdl.sdk.common.exception; /** * Created by jlchen on 11/15/21. * * @Description : HDLError */ public enum HDLLinkCode { HDL_DATA_ERROR(-2000,"参数异常"), HDL_DATA_NULL_ERROR(-2001,"参数不能为空"), HDL_AUTH_ERROR(-2002,"认证失败"), HDL_SEND_ERROR(-2003,"发送失败"), HDL_TIMEOUT_ERROR(-2004,"超时"), HDL_UNAUTHORIZED_ERROR(-2005,"未认证,请先认证"), HDL_GET_DEVICE_LIST_ERROR(-2100,"获取设备列表失败"), HDL_GET_FUNCTION_LIST_ERROR(-2101,"获取功能列表失败"), HDL_GET_FUNCTION_PROPERTIES_ERROR(-2102,"获取功能属性失败"), HDL_CONTROL_FAILURE_ERROR(-2103,"控制失败"); private String msg; private int code; private HDLLinkCode(int code, String msg) { this.msg = msg; this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } } HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/exception/HDLLinkException.java
New file @@ -0,0 +1,63 @@ package com.hdl.sdk.common.exception; import androidx.annotation.NonNull; /** * Created by Tong on 2021/11/11. */ public class HDLLinkException extends RuntimeException { private int code = 0; private String msg = ""; private Throwable rawThrowable; public HDLLinkException() { } public HDLLinkException(String msg) { this.msg = msg; } public HDLLinkException(int code, String msg) { this.code = code; this.msg = msg; } public HDLLinkException(int code) { this.code = code; } public HDLLinkException(Throwable rawThrowable) { this.rawThrowable = rawThrowable; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public @NonNull String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Throwable getRawThrowable() { return rawThrowable; } public void setRawThrowable(Throwable rawThrowable) { this.rawThrowable = rawThrowable; } public static HDLLinkException getErrorWithCode(HDLLinkCode code){ return new HDLLinkException(code.getCode(), code.getMsg()); } } HDLSDK/hdl-common/src/main/java/com/hdl/sdk/common/utils/LogUtils.java
@@ -1,55 +1,63 @@ package com.hdl.sdk.common.utils; import android.util.Log; /** * Created by Tong on 2021/9/23. */ public class LogUtils { private static final String TAG = "HDLSocket"; private static final String TAG = "HDLSDK"; private boolean isEnabled = true; private static boolean isEnabled = true; private LogUtils() { } private static class SingletonInstance { private static final LogUtils INSTANCE = new LogUtils(); } public static LogUtils getInstance() { return SingletonInstance.INSTANCE; } public boolean isEnabled() { public static boolean isEnabled() { return isEnabled; } public void setEnabled(boolean enabled) { public static void setEnabled(boolean enabled) { isEnabled = enabled; } public static void d(String tag, String msg) { if (tag != null && msg != null && isEnabled) { Log.d(TAG, tag + "-- " + msg); } } public static void e(String tag, String msg) { } public static void e(String msg, Throwable tr) { if (tag != null && msg != null && isEnabled) { Log.e(TAG, tag + "-- " + msg); } } public static void w(String tag, String msg) { if (tag != null && msg != null && isEnabled) { Log.w(TAG, tag + "-- " + msg); } } public static void v(String tag, String msg) { if (tag != null && msg != null && isEnabled) { Log.v(TAG, tag + "-- " + msg); } } public static void i(String tag, String msg) { if (tag != null && msg != null && isEnabled) { Log.i(TAG, tag + "-- " + msg); } } public static void i(String msg) { if (msg != null && isEnabled) { Log.i(TAG, msg); } } public static void e(String msg) { if (msg != null && isEnabled) { Log.e(TAG, msg); } } } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/HDLLink.java
@@ -1,10 +1,20 @@ package com.hdl.sdk.connect; import com.hdl.sdk.common.utils.IpUtils; import com.hdl.sdk.connect.bean.request.DeviceControlRequest; import com.hdl.sdk.connect.bean.request.PropertyReadRequest; import com.hdl.sdk.connect.callback.HDLLinkCallBack; import com.hdl.sdk.connect.callback.HDLLinkResponseCallBack; import com.hdl.sdk.connect.config.HDLLinkConfig; import com.hdl.sdk.common.event.EventDispatcher; import com.hdl.sdk.common.event.EventListener; import com.hdl.sdk.connect.bean.AuthenticateRequest; import com.hdl.sdk.connect.bean.request.AuthenticateRequest; import com.hdl.sdk.connect.socket.HDLAuthSocket; import com.hdl.sdk.connect.socket.HDLSocket; import com.hdl.sdk.connect.socket.HdlSocketHelper; import com.hdl.sdk.socket.listener.SendListener; import java.util.List; /** * Created by jlchen on 11/15/21. @@ -44,9 +54,11 @@ * @param listener */ public synchronized void removeAllTopicsListener(EventListener listener) { if(listener == null) return; EventDispatcher.getInstance().removeAllTopicsListener(listener); } /***********************三方设备和网关通信之前的认证流程****************************/ /** * 检测是否已经认证过 * 认证通过才能进行设备控制 @@ -57,22 +69,137 @@ } /** * 开始监听和发起入网及认证请求 * * @param request 认证请求信息 * @param callBack 结果回调 */ public void startAuthenticateRequest(AuthenticateRequest request, HDLLinkCallBack callBack) { HDLAuthSocket.getInstance().startAuthenticateRequest(request,callBack); } /** * 发送入网及认证请求 * * @param ip 网关IP * @param request 认证请求信息 * @param callBack 结果回调 */ public void sendAuthenticateRequest(String ip, AuthenticateRequest request, HDLAuthSocket.CallBack callBack) { HDLAuthSocket.getInstance().sendAuthenticateRequest(ip,request,callBack); public void sendAuthenticateRequest(String ip, AuthenticateRequest request, HDLLinkCallBack callBack) { HDLAuthSocket.getInstance().sendAuthenticateRequest(ip, request, callBack); } // /** // * 开始搜索所有网关,有网关回复就回调,上层自己做去重判断 // * // * @param callBack 回调 // */ // public void startSearchAllGateway(HDLAuthSocket.SearchGatewayCallBack callBack) { // // } // // /** // * 暂停搜索网关 // */ // public void endSearchAllGateway() { // // } /***********************三方设备请先认证成功 再调用下面的接口和网关通信****************************/ /** * 组播搜索指定网关是否在线,搜索到则返回指定的网关对象 * @param callBack 回调 */ public void searchGatewayMulticast(HDLAuthSocket.SearchGatewayCallBack callBack) { HDLAuthSocket.getInstance().searchGatewayMulticast(callBack); } /** * 搜索指定网关是否在线,搜索到则返回指定的网关对象 * * 组播搜索指定网关是否在线,搜索到则返回指定的网关对象 * @param callBack 回调 */ public void searchGateway(HDLAuthSocket.SearchGatewayCallBack callBack) { HDLAuthSocket.getInstance().searchGateway(HDLLinkConfig.getInstance().getGatewayId(), callBack); public void searchGatewayBroadcast(HDLAuthSocket.SearchGatewayCallBack callBack) { HDLAuthSocket.getInstance().searchGatewayBroadcast(callBack); } /** * 获取设备列表 */ public void getDeviceList(HDLLinkCallBack callBack) { HDLSocket.getInstance().getDeviceList(callBack); } /** * 获取功能列表 */ public void getFunctionList(HDLLinkCallBack callBack) { HDLSocket.getInstance().getFunctionList(callBack); } /** * 获取功能属性 * * @param sids * @param callBack */ public void getFunctionAttribute(List<String> sids, HDLLinkCallBack callBack) { HDLSocket.getInstance().getFunctionAttribute(sids, callBack); } /** * 设备控制 * @param request 控制状态参数 * @param callBack 结果回调 */ public void propertyDown(List<DeviceControlRequest> request, HDLLinkCallBack callBack) { HDLSocket.getInstance().propertyDown(request, callBack); } /** * 读取状态 * @param sids 请求参数 指定读取的设备sid列表 * @param callBack 回调 */ public void propertyRead(List<String> sids, HDLLinkCallBack callBack) { HDLSocket.getInstance().propertyRead(sids, callBack); } /** * 获取场景列表 */ public void getSceneList(HDLLinkCallBack callBack) { HDLSocket.getInstance().getSceneList(callBack); } /** * 场景控制 * @param sids 场景sid列表 * @param callBack 回调 */ public void controlScene(List<String> sids, HDLLinkCallBack callBack) { HDLSocket.getInstance().controlScene(sids, callBack); } /** * 通用UDP广播发送指令 * 1秒没响应就让他重新发送,重试3次 * @param topic 发送数据 * @param bodyStr body内容 * @param callBack 回调 */ public void udpSendMsg(String topic, String bodyStr, HDLLinkResponseCallBack callBack) { HDLAuthSocket.getInstance().udpSendMsg(topic, bodyStr, callBack); } /** * 通用TCP发送指令 * 1秒没响应就让他重新发送,重试3次 * * @param topic 发送数据 * @param bodyStr body内容 * @param callBack 回调 */ public void tcpSendMsg(String topic, String bodyStr, HDLLinkCallBack callBack) { HDLSocket.getInstance().tcpSendMsg(topic, bodyStr, callBack); } } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/LinkRequest.java
@@ -68,8 +68,7 @@ } private int getBytesLength(String str){ private int getBytesLength(String str) { return ByteUtils.stringToBytes(str).length; } @@ -85,12 +84,11 @@ if (HDLLinkConfig.getInstance().ifNeedEncrypt(topic)) { //需要加密 byte[] dataBytes = AesUtil.aesEncrypt(ByteUtils.stringToBytes(data), HDLLinkConfig.getInstance().getLocalSecret()); // byte[] dataBytes = AESUtils.encryptAES(stringToBytes(data), AuthenticateConfig.getInstance().getLocalSecret()); String headString = "Topic:" + getTopic() + "\r\n" + "Length:" + dataBytes.length + "\r\n" + "\r\n"; byte[] headBytes = headString.getBytes("utf-8"); byte[] sendBytes = ByteUtils.concatBytes(headBytes, dataBytes); return sendBytes; } else { return this.toString().getBytes("utf-8"); } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/AuthenticateRequest.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/AuthenticateRequest.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.request; import java.io.Serializable; HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/BaseLocalRequest.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/BaseLocalRequest.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.request; import java.io.Serializable; HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/DeviceControlRequest.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/DeviceControlRequest.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.request; import java.io.Serializable; import java.util.List; HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/FunctionAttributeRequest.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/FunctionAttributeRequest.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.request; import java.io.Serializable; HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/PropertyReadRequest.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/PropertyReadRequest.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.request; /** * Created by Tong on 2021/10/8. @@ -7,6 +7,10 @@ private String sid; public PropertyReadRequest(String sid) { this.sid = sid; } public String getSid() { return sid; } @@ -14,4 +18,5 @@ public void setSid(String sid) { this.sid = sid; } } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/request/PropertyUpRequest.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/PropertyUpRequest.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.request; import java.io.Serializable; import java.util.List; HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/response/AuthenticateResponse.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/AuthenticateResponseBean.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.response; import java.io.Serializable; @@ -7,18 +7,10 @@ * * @Description : AuthenticateResponseBean */ public class AuthenticateResponseBean implements Serializable { private String id; private String time_stamp; public class AuthenticateResponse extends BaseResponse { private String code; private GatewayObjects objects; private Auth auth; public String getID() { return id; } public void setID(String value) { this.id = value; } public String getTimeStamp() { return time_stamp; } public void setTimeStamp(String value) { this.time_stamp = value; } public String getCode() { return code; } public void setCode(String value) { this.code = value; } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/response/BaseLocalResponse.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/BaseLocalResponse.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.response; import java.io.Serializable; HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/response/BaseResponse.java
New file @@ -0,0 +1,30 @@ package com.hdl.sdk.connect.bean.response; import java.io.Serializable; /** * Created by jlchen on 11/15/21. * * @Description : BaseResponse */ public class BaseResponse implements Serializable { private String id; private String time_stamp; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTime_stamp() { return time_stamp; } public void setTime_stamp(String time_stamp) { this.time_stamp = time_stamp; } } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/response/GatewaySearchBean.java
File was renamed from HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/GatewaySearchBean.java @@ -1,4 +1,4 @@ package com.hdl.sdk.connect.bean; package com.hdl.sdk.connect.bean.response; import java.io.Serializable; @@ -7,8 +7,6 @@ * 网关搜索 */ public class GatewaySearchBean implements Serializable { private String device_model; private String device_name; private String device_mac; HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/bean/response/NetworkAccessBroadcastResponse.java
New file @@ -0,0 +1,22 @@ package com.hdl.sdk.connect.bean.response; /** * Created by jlchen on 11/15/21. * * @Description : NetworkAccessBroadcastResponse */ public class NetworkAccessBroadcastResponse extends BaseResponse { private String ip_address; private String oid; private String homeId; public String getIPAddress() { return ip_address; } public void setIPAddress(String value) { this.ip_address = value; } public String getOID() { return oid; } public void setOID(String value) { this.oid = value; } public String getHomeID() { return homeId; } public void setHomeID(String value) { this.homeId = value; } } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/callback/BaseCallBack.java
New file @@ -0,0 +1,12 @@ package com.hdl.sdk.connect.callback; import com.hdl.sdk.common.exception.HDLLinkException; /** * Created by Tong on 2021/11/11. */ public interface BaseCallBack { void onError(HDLLinkException e); } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/callback/HDLLinkCallBack.java
New file @@ -0,0 +1,13 @@ package com.hdl.sdk.connect.callback; import com.hdl.sdk.common.exception.HDLLinkException; import com.hdl.sdk.connect.bean.LinkResponse; /** * Created by jlchen on 11/16/21. * * @Description : HDLLinkCallBack */ public interface HDLLinkCallBack extends BaseCallBack{ void onSuccess(String msg); } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/callback/HDLLinkResponseCallBack.java
New file @@ -0,0 +1,12 @@ package com.hdl.sdk.connect.callback; import com.hdl.sdk.connect.bean.LinkResponse; /** * Created by jlchen on 11/16/21. * * @Description : HDLLinkResponseCallBack */ public interface HDLLinkResponseCallBack extends BaseCallBack{ void onSuccess(LinkResponse msg); } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/config/HDLLinkConfig.java
@@ -4,7 +4,7 @@ import com.hdl.sdk.common.config.TopicConstant; import com.hdl.sdk.common.utils.SPUtils; import com.hdl.sdk.connect.bean.GatewaySearchBean; import com.hdl.sdk.connect.bean.response.GatewaySearchBean; /** @@ -13,9 +13,10 @@ * @Description : HDLLinkConfig */ public class HDLLinkConfig { private static final String Authenticate_LS_KEY = "auth_ls_key"; private static final String AUTHENTICATE_LS_KEY = "auth_ls_key"; private static final String AUTHENTICATE_GATEWAYID_KEY = "auth_gatewayid_key"; private static final String AUTHENTICATE_IPADDRESS_KEY = "auth_ipaddress_key"; private static final String AUTHENTICATE_IS_LS_KEY = "auth_isls_key"; private String localSecret;//本地加密密钥 private String gatewayId; @@ -51,18 +52,21 @@ this.gatewayId = ""; this.ipAddress = ""; this.localSecret = ""; SPUtils.remove(Authenticate_LS_KEY); this.isLocalEncrypt = false; SPUtils.remove(AUTHENTICATE_LS_KEY); SPUtils.remove(AUTHENTICATE_GATEWAYID_KEY); SPUtils.remove(AUTHENTICATE_IPADDRESS_KEY); SPUtils.remove(AUTHENTICATE_IS_LS_KEY); } /** * 加载缓存 */ void loadConfig(){ localSecret = SPUtils.getString(Authenticate_LS_KEY, ""); localSecret = SPUtils.getString(AUTHENTICATE_LS_KEY, ""); gatewayId = SPUtils.getString(AUTHENTICATE_GATEWAYID_KEY, ""); ipAddress = SPUtils.getString(AUTHENTICATE_IPADDRESS_KEY, ""); isLocalEncrypt = SPUtils.getBoolean(AUTHENTICATE_IS_LS_KEY,false); } /** @@ -75,7 +79,7 @@ this.localSecret = localSecret; this.gatewayId = gatewayId; this.ipAddress = ipAddress; SPUtils.put(Authenticate_LS_KEY, localSecret); SPUtils.put(AUTHENTICATE_LS_KEY, localSecret); SPUtils.put(AUTHENTICATE_GATEWAYID_KEY, gatewayId); SPUtils.put(AUTHENTICATE_IPADDRESS_KEY, ipAddress); } @@ -93,7 +97,7 @@ public void setLocalSecret(String localSecret) { this.localSecret = localSecret; SPUtils.put(Authenticate_LS_KEY, localSecret); SPUtils.put(AUTHENTICATE_LS_KEY, localSecret); } public String getLocalSecret() { @@ -114,6 +118,7 @@ public void setLocalEncrypt(boolean localEncrypt) { isLocalEncrypt = localEncrypt; SPUtils.put(AUTHENTICATE_IS_LS_KEY, isLocalEncrypt); } public GatewaySearchBean getCurrentGateway() { HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/protocol/LinkMessageDecoder.java
@@ -1,6 +1,7 @@ package com.hdl.sdk.connect.protocol; import com.hdl.sdk.common.utils.LogUtils; import com.hdl.sdk.connect.config.HDLLinkConfig; import com.hdl.sdk.common.event.EventDispatcher; import com.hdl.sdk.common.utils.ByteUtils; @@ -59,13 +60,19 @@ if (byteArray.length >= bodyLength + bodyStartIndex) { byte[] body = ByteUtils.getRangeBytes(bytes, bodyStartIndex, bodyStartIndex + bodyLength); if(HDLLinkConfig.getInstance().ifNeedEncrypt(response.getTopic())){ if (HDLLinkConfig.getInstance().ifNeedEncrypt(response.getTopic())) { //需要解密 byte[] bodyBytes = AesUtil.aesDecrypt(body, HDLLinkConfig.getInstance().getLocalSecret()); // byte[] bodyBytes = AESUtils.decryptAES(body,AuthenticateConfig.getInstance().getLocalSecret()); response.setData(new String(bodyBytes, "utf-8")); // Log.i("TAG", "解密 主题:"+response.getTopic()+ " body: "+response.getData()); }else{ if (bodyBytes != null) { response.setData(new String(bodyBytes, "utf-8")); // LogUtils.i("TAG", "解密 主题:"+response.getTopic()+ " body: "+response.getData()); } else { //解密失败,返回原数据 response.setData(new String(body, "utf-8")); } } else { response.setData(new String(body, "utf-8")); } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLAuthSocket.java
@@ -1,24 +1,29 @@ package com.hdl.sdk.connect.socket; import android.text.TextUtils; import android.util.Log; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.hdl.sdk.common.event.EventDispatcher; import com.hdl.sdk.common.event.EventListener; import com.hdl.sdk.connect.bean.AuthenticateResponseBean; import com.hdl.sdk.common.exception.HDLLinkCode; import com.hdl.sdk.common.exception.HDLLinkException; import com.hdl.sdk.common.utils.LogUtils; import com.hdl.sdk.connect.bean.response.AuthenticateResponse; import com.hdl.sdk.connect.bean.response.NetworkAccessBroadcastResponse; import com.hdl.sdk.connect.callback.BaseCallBack; import com.hdl.sdk.connect.callback.HDLLinkCallBack; import com.hdl.sdk.connect.callback.HDLLinkResponseCallBack; import com.hdl.sdk.connect.config.HDLLinkConfig; import com.hdl.sdk.common.config.TopicConstant; import com.hdl.sdk.common.utils.IdUtils; import com.hdl.sdk.common.utils.IpUtils; import com.hdl.sdk.common.utils.gson.GsonConvert; import com.hdl.sdk.connect.bean.AuthenticateRequest; import com.hdl.sdk.connect.bean.AuthenticateRequest.AuthenticateDeviceInfoBean; import com.hdl.sdk.connect.bean.BaseLocalResponse; import com.hdl.sdk.connect.bean.DeviceControlRequest; import com.hdl.sdk.connect.bean.GatewaySearchBean; import com.hdl.sdk.connect.bean.request.AuthenticateRequest; import com.hdl.sdk.connect.bean.response.BaseLocalResponse; import com.hdl.sdk.connect.bean.request.DeviceControlRequest; import com.hdl.sdk.connect.bean.response.GatewaySearchBean; import com.hdl.sdk.connect.bean.LinkRequest; import com.hdl.sdk.connect.bean.LinkResponse; import com.hdl.sdk.connect.protocol.LinkMessageDecoder; @@ -27,10 +32,9 @@ import com.hdl.sdk.socket.SocketOptions; import com.hdl.sdk.socket.client.UdpClient; import com.hdl.sdk.socket.codec.MessagePipeLine; import com.hdl.sdk.socket.listener.SendListener; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import static com.hdl.sdk.common.config.TopicConstant.DEIVCE_AUTH_REQUEST; @@ -41,23 +45,26 @@ * @Description : HDLAuthSocket */ public class HDLAuthSocket { private static final String TAG = "HDLAuth"; /** * udp默认端口 */ private static final int UDP_PORT = 8585; private static SocketBoot updBoot; // private EventListener authEvent; /** * udp默认组播ip */ private static final String UDP_GROUP_IP = "239.0.168.188"; /** * instance */ private volatile static HDLAuthSocket instance; public interface CallBack { void onError(String error); void onSuccess(String msg); } // public interface CallBack extends BaseCallBack { // void onSuccess(String msg); // } /** * getInstance @@ -94,24 +101,42 @@ } /** * 开始入网及认证请求 * 开始监听和发起入网及认证请求 * * @param request 认证请求信息 * @param callBack 结果回调 */ public void startAuthenticateRequest(AuthenticateRequest request, CallBack callBack) { public void startAuthenticateRequest(AuthenticateRequest request, HDLLinkCallBack callBack) { HDLLinkConfig.getInstance().clearConfig(); //1.启动Socket 开启监听 getUdpBoot(IpUtils.getBroadcastAddress()); //监听网关广播的入网指令 //2.构建监听Listener // authEvent = //3.监听网关广播的入网指令 EventDispatcher.getInstance().register(TopicConstant.GATEWAY_AUTH_BROADCAST, new EventListener() { @Override public void onMessage(Object msg) { NetworkAccessBroadcastResponse bean = getNetworkAccessBroadcastResponse(msg); if(bean != null){ LogUtils.i(TAG, "网关入网广播IP: " + bean.getIPAddress()); String ipStr = bean.getIPAddress(); if(!TextUtils.isEmpty(ipStr)){ sendAuthenticateRequest(ipStr, request, callBack); } } //移除监听 // EventDispatcher.getInstance().remove(this); EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_AUTH_BROADCAST); LogUtils.i(TAG, "移除监听 authEvent"); } }); } /** * 结束监听入网及认证广播 */ public void endAuthenticateRequest(){ //移除监听 EventDispatcher.getInstance().remove(TopicConstant.GATEWAY_AUTH_BROADCAST); } /** @@ -121,9 +146,9 @@ * @param request 认证请求信息 * @param callBack 结果回调 */ public void sendAuthenticateRequest(String ip, AuthenticateRequest request, CallBack callBack) { public void sendAuthenticateRequest(String ip, AuthenticateRequest request, HDLLinkCallBack callBack) { if (request == null) { callBack.onError("request null"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_NULL_ERROR)); } String topic = DEIVCE_AUTH_REQUEST; Gson gs = new Gson(); @@ -134,24 +159,24 @@ @Override public void onSucceed(Object msg) { if(callBack == null) return; AuthenticateResponseBean bean = getAuthenticateResponseBean(msg); AuthenticateResponse bean = getAuthenticateResponseBean(msg); if(bean != null){ String localSecret = bean.getAuth().getLocalSecret(); String gatewayId = bean.getObjects().getGatewayID(); String ipAddress = bean.getObjects().getIPAddress(); HDLLinkConfig.getInstance().saveConfig(localSecret,gatewayId,ipAddress); callBack.onSuccess("Success"); callBack.onSuccess("认证成功"); }else{ callBack.onSuccess("参数异常"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_ERROR)); } } @Override public void onFailure() { Log.i("TAG", "onFailure: "); LogUtils.i(TAG, "onFailure: "); if(callBack == null) return; callBack.onError("超时"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_TIMEOUT_ERROR)); } }); } @@ -199,14 +224,7 @@ // sendAuthenticateRequest(ip, request, callBack); // } public interface SearchGatewayCallBack { /** * 搜索结束 * * @param error */ void onEnd(String error); public interface SearchGatewayCallBack extends BaseCallBack{ /** * 搜索网关成功 * @@ -232,17 +250,34 @@ } /** * 组播搜索指定网关是否在线,搜索到则返回指定的网关对象 * @param callBack 回调 */ public void searchGatewayMulticast(SearchGatewayCallBack callBack) { searchGateway(HDLLinkConfig.getInstance().getGatewayId(), UDP_GROUP_IP, callBack); } /** * 组播搜索指定网关是否在线,搜索到则返回指定的网关对象 * @param callBack 回调 */ public void searchGatewayBroadcast(SearchGatewayCallBack callBack) { String ip = IpUtils.getBroadcastAddress(); searchGateway(HDLLinkConfig.getInstance().getGatewayId(), ip, callBack); } /** * 搜索指定网关是否在线,搜索到则返回指定的网关对象 * * @param gatewayId 网关id * @param ip 接收目标的ip地址 * @param callBack 回调 */ public void searchGateway(String gatewayId, SearchGatewayCallBack callBack) { public void searchGateway(String gatewayId, String ip, SearchGatewayCallBack callBack) { String time = String.valueOf(System.currentTimeMillis()); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id", IdUtils.getUUId()); jsonObject.addProperty("time_stamp", time); String ip = IpUtils.getBroadcastAddress(); LinkRequest message = new LinkRequest(TopicConstant.GATEWAY_SEARCH, jsonObject.toString()); @@ -251,7 +286,7 @@ public void onSucceed(Object msg) { GatewaySearchBean searchBean = getGatewaySearchBean(msg); if (searchBean != null && searchBean.getGatewayId().contains(gatewayId)) { Log.i("TAG", "onSuccess: "); LogUtils.i(TAG, "onSuccess: "); HDLLinkConfig.getInstance().setCurrentGateway(searchBean); HDLLinkConfig.getInstance().setLocalEncrypt(searchBean.isLocalEncrypt()); callBack.onSuccess(searchBean); @@ -262,11 +297,76 @@ @Override public void onFailure() { Log.i("TAG", "onFailure: "); callBack.onEnd("超时"); LogUtils.i(TAG, "onFailure: "); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_TIMEOUT_ERROR)); } }); } /** * 设备控制 */ public void propertyDown(List<DeviceControlRequest> request, HDLLinkCallBack callBack) { String time = String.valueOf(System.currentTimeMillis()); final BaseLocalResponse<List<DeviceControlRequest>> data = new BaseLocalResponse<>(); data.setId(IdUtils.getUUId()); data.setTime_stamp(time); data.setObjects(request); String topic = HDLLinkConfig.getInstance().getFullTopic(TopicConstant.PROPERTY_DOWN); LinkRequest message = new LinkRequest(topic, GsonConvert.getGson().toJson(data)); String ip = IpUtils.getBroadcastAddress(); HdlSocketHelper.send(getUdpBoot(ip), message, new HdlSocketHelper.HdlSocketListener() { @Override public void onSucceed(Object msg) { if(callBack == null) return; callBack.onSuccess("控制成功"); } @Override public void onFailure() { if(callBack == null) return; callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_CONTROL_FAILURE_ERROR)); } }); } /** * 通用发送指令 * 1秒没响应就让他重新发送,重试3次 * @param topic 发送数据 * @param bodyStr 回复的主题 * @param callBack 回调 */ public void udpSendMsg(String topic, String bodyStr, HDLLinkResponseCallBack callBack) { if(TextUtils.isEmpty(topic) || TextUtils.isEmpty(bodyStr)) { if(callBack != null){ callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_DATA_NULL_ERROR)); } return; } LinkRequest message = new LinkRequest(topic, bodyStr); String ip = IpUtils.getBroadcastAddress(); HdlSocketHelper.send(getUdpBoot(ip), message, new HdlSocketHelper.HdlSocketListener() { @Override public void onSucceed(Object msg) { if(callBack == null) return; callBack.onSuccess((LinkResponse) msg); } @Override public void onFailure() { if(callBack == null) return; callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_TIMEOUT_ERROR)); } } ); } private GatewaySearchBean getGatewaySearchBean(Object msg) { GatewaySearchBean searchBean = null; @@ -283,15 +383,14 @@ return searchBean; } private AuthenticateResponseBean getAuthenticateResponseBean(Object msg) { AuthenticateResponseBean mBean = null; private AuthenticateResponse getAuthenticateResponseBean(Object msg) { AuthenticateResponse mBean = null; if (msg instanceof LinkResponse) { LinkResponse linkResponse = (LinkResponse) msg; String data = linkResponse.getData(); if (!TextUtils.isEmpty(data)) { AuthenticateResponseBean response = GsonConvert.getGson().fromJson(data, new TypeToken<AuthenticateResponseBean>() { AuthenticateResponse response = GsonConvert.getGson().fromJson(data, new TypeToken<AuthenticateResponse>() { }.getType()); mBean = response; } @@ -299,29 +398,19 @@ return mBean; } /** * 设备控制 */ public void propertyDown(List<DeviceControlRequest> request, HDLSocket.CallBack callBack) { private NetworkAccessBroadcastResponse getNetworkAccessBroadcastResponse(Object msg){ NetworkAccessBroadcastResponse mBean = null; if (msg instanceof LinkResponse) { LinkResponse linkResponse = (LinkResponse) msg; String data = linkResponse.getData(); if (!TextUtils.isEmpty(data)) { NetworkAccessBroadcastResponse response = GsonConvert.getGson().fromJson(data, new TypeToken<NetworkAccessBroadcastResponse>() { }.getType()); mBean = response; } String time = String.valueOf(System.currentTimeMillis()); final BaseLocalResponse<List<DeviceControlRequest>> data = new BaseLocalResponse<>(); data.setId(IdUtils.getUUId()); data.setTime_stamp(time); data.setObjects(request); String topic = HDLLinkConfig.getInstance().getFullTopic(TopicConstant.PROPERTY_DOWN); LinkRequest message = new LinkRequest(topic, GsonConvert.getGson().toJson(data)); String ip = IpUtils.getBroadcastAddress(); HdlSocketHelper.send(getUdpBoot(ip), message, null); } return mBean; } } HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/socket/HDLSocket.java
@@ -7,19 +7,24 @@ import com.hdl.sdk.common.config.TopicConstant; import com.hdl.sdk.common.event.EventDispatcher; import com.hdl.sdk.common.event.EventListener; import com.hdl.sdk.common.exception.HDLLinkCode; import com.hdl.sdk.common.exception.HDLLinkException; import com.hdl.sdk.common.utils.IdUtils; import com.hdl.sdk.common.utils.IpUtils; import com.hdl.sdk.common.utils.SPUtils; import com.hdl.sdk.common.utils.ThreadToolUtils; import com.hdl.sdk.common.utils.gson.GsonConvert; import com.hdl.sdk.connect.bean.BaseLocalResponse; import com.hdl.sdk.connect.bean.DeviceControlRequest; import com.hdl.sdk.connect.bean.FunctionAttributeRequest; import com.hdl.sdk.connect.bean.GatewaySearchBean; import com.hdl.sdk.connect.bean.response.BaseLocalResponse; import com.hdl.sdk.connect.bean.request.DeviceControlRequest; import com.hdl.sdk.connect.bean.request.FunctionAttributeRequest; import com.hdl.sdk.connect.bean.response.GatewaySearchBean; import com.hdl.sdk.connect.bean.LinkRequest; import com.hdl.sdk.connect.bean.LinkResponse; import com.hdl.sdk.connect.bean.PropertyReadRequest; import com.hdl.sdk.connect.bean.PropertyUpRequest; import com.hdl.sdk.connect.bean.request.PropertyReadRequest; import com.hdl.sdk.connect.bean.request.PropertyUpRequest; import com.hdl.sdk.connect.callback.BaseCallBack; import com.hdl.sdk.connect.callback.HDLLinkCallBack; import com.hdl.sdk.connect.config.HDLLinkConfig; import com.hdl.sdk.connect.protocol.LinkMessageDecoder; import com.hdl.sdk.connect.protocol.LinkMessageEncoder; import com.hdl.sdk.socket.SocketBoot; @@ -44,22 +49,14 @@ */ public class HDLSocket { private static final String GATEWAY_KEY = "gateway_key"; private static final String TCP_IP_KEY = "tcp_ip_key"; private String gatewayId; public interface CallBack { void onError(String error); void onResponse(String data); } /** * udp默认组播ip */ private static final String UDP_GROUP_IP = "239.0.168.188"; // public interface CallBack extends BaseCallBack { // void onResponse(String data); // } // // /** // * udp默认组播ip // */ // private static final String UDP_GROUP_IP = "239.0.168.188"; /** * udp默认端口 @@ -71,21 +68,21 @@ */ private static final int TCP_PORT = 8586; private String tcpIp; private int tcpPort; // private String tcpIp; // private int tcpPort; private int udpPort; private String udpIp; // private int udpPort; // private String udpIp; private static SocketBoot updBoot; // private static SocketBoot updBoot; private SocketBoot tcpBoot; private ConnectStatusListener statusListener; private EventListener searchEvent; private CallBack searchCallBack; private ScheduledExecutorService searchGatewayThread; private final AtomicInteger searchCount = new AtomicInteger(0); // private EventListener searchEvent; // private CallBack searchCallBack; // private ScheduledExecutorService searchGatewayThread; // private final AtomicInteger searchCount = new AtomicInteger(0); private HDLSocket() { statusListener = new ConnectStatusListener() { @@ -104,43 +101,43 @@ } }; searchEvent = new EventListener() { @Override public void onMessage(Object msg) { try { if (msg instanceof LinkResponse) { LinkResponse linkResponse = (LinkResponse) msg; String data = linkResponse.getData(); if (!TextUtils.isEmpty(data)) { final BaseLocalResponse<GatewaySearchBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewaySearchBean>>() { }.getType()); GatewaySearchBean searchBean = response.getObjects(); if (searchBean != null) { gatewayId = searchBean.getGatewayId(); if (!TextUtils.isEmpty(gatewayId)) { SPUtils.put(GATEWAY_KEY, gatewayId); } tcpIp = searchBean.getIp_address(); if (!TextUtils.isEmpty(tcpIp)) { SPUtils.put(TCP_IP_KEY, tcpIp); } } if (searchCallBack != null) { searchCallBack.onResponse(linkResponse.toString()); } } } } catch (Exception e) { if (searchCallBack != null) { searchCallBack.onError("解析失败"); } } } }; // searchEvent = new EventListener() { // @Override // public void onMessage(Object msg) { // try { // if (msg instanceof LinkResponse) { // LinkResponse linkResponse = (LinkResponse) msg; // String data = linkResponse.getData(); // if (!TextUtils.isEmpty(data)) { // final BaseLocalResponse<GatewaySearchBean> response = GsonConvert.getGson().fromJson(data, new TypeToken<BaseLocalResponse<GatewaySearchBean>>() { // }.getType()); // GatewaySearchBean searchBean = response.getObjects(); // if (searchBean != null) { //// gatewayId = searchBean.getGatewayId(); //// if (!TextUtils.isEmpty(gatewayId)) { //// SPUtils.put(GATEWAY_KEY, gatewayId); //// } //// tcpIp = searchBean.getIp_address(); //// if (!TextUtils.isEmpty(tcpIp)) { //// SPUtils.put(TCP_IP_KEY, tcpIp); //// } // } // // if (searchCallBack != null) { // searchCallBack.onResponse(linkResponse.toString()); // } // } // // } // } catch (Exception e) { // if (searchCallBack != null) { // searchCallBack.onError("解析失败"); // } // } // // // } // }; } private static class SingletonInstance { @@ -152,15 +149,15 @@ } private SocketOptions getUdpOptions() { final SocketOptions options = new SocketOptions(); final MessagePipeLine pipeLine = new MessagePipeLine(); pipeLine.add(new LinkMessageDecoder()); pipeLine.add(new LinkMessageEncoder()); options.setHandleMessage(pipeLine); options.setEnabledHeartbeat(false); return options; } // private SocketOptions getUdpOptions() { // final SocketOptions options = new SocketOptions(); // final MessagePipeLine pipeLine = new MessagePipeLine(); // pipeLine.add(new LinkMessageDecoder()); // pipeLine.add(new LinkMessageEncoder()); // options.setHandleMessage(pipeLine); // options.setEnabledHeartbeat(false); // return options; // } private SocketOptions getTcpOptions() { final SocketOptions options = new SocketOptions(); @@ -181,107 +178,101 @@ } public String getTcpIp() { if (!TextUtils.isEmpty(tcpIp)) { return tcpIp; } return SPUtils.getString(TCP_IP_KEY, ""); return HDLLinkConfig.getInstance().getIpAddress(); } public String getGatewayId() { if (!TextUtils.isEmpty(gatewayId)) { return gatewayId; } return SPUtils.getString(GATEWAY_KEY, ""); return HDLLinkConfig.getInstance().getGatewayId(); } private String getUdpIp() { if (TextUtils.isEmpty(udpIp)) { udpIp = UDP_GROUP_IP; } return udpIp; } // private String getUdpIp() { // if (TextUtils.isEmpty(udpIp)) { // udpIp = UDP_GROUP_IP; // } // return udpIp; // } public void searchGateway() { searchGateway(null); } /** * 组播搜索 */ public void searchGateway(CallBack callBack) { gatewayId = "";//重置网关ID this.searchCallBack = callBack; if (searchGatewayThread != null) { searchGatewayThread.shutdownNow(); } new Thread(new Runnable() { @Override public void run() { while (TextUtils.isEmpty(gatewayId)) { //搜索网关 searchGateway(IdUtils.getUUId(), searchEvent); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } /** * 通过组播搜索网关 */ public void searchGateway(String msgId, EventListener eventListener) { searchGateway(getUdpIp(), getUdpPort(), msgId, eventListener); } /** * 通过广播搜索网关 */ public void searchGatewayByBroadcast(String msgId, EventListener eventListener) { searchGateway(IpUtils.getBroadcastAddress(), getUdpPort(), msgId, eventListener); } /** * 默认是组播搜索网关 */ public void searchGateway(String ip, int port, String msgId, EventListener eventListener) { if (updBoot == null) { updBoot = UdpClient.init(ip, port, getUdpOptions()); updBoot.connect(); } String time = String.valueOf(System.currentTimeMillis()); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id", msgId); jsonObject.addProperty("time_stamp", time); EventDispatcher.getInstance().registerIo(TopicConstant.GATEWAY_SEARCH_REPLY, eventListener); LinkRequest message = new LinkRequest(TopicConstant.GATEWAY_SEARCH, jsonObject.toString()); try { updBoot.sendMsg(message.toString().getBytes("utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } // public void searchGateway() { // searchGateway(null); // } // // /** // * 组播搜索 // */ // public void searchGateway(CallBack callBack) { //// gatewayId = "";//重置网关ID //// this.searchCallBack = callBack; //// //// if (searchGatewayThread != null) { //// searchGatewayThread.shutdownNow(); //// } //// //// //// new Thread(new Runnable() { //// @Override //// public void run() { //// while (TextUtils.isEmpty(gatewayId)) { //// //搜索网关 //// searchGateway(IdUtils.getUUId(), searchEvent); //// try { //// Thread.sleep(1000L); //// } catch (InterruptedException e) { //// e.printStackTrace(); //// } //// } //// } //// }).start(); // } // // // /** // * 通过组播搜索网关 // */ // public void searchGateway(String msgId, EventListener eventListener) { // searchGateway(getUdpIp(), getUdpPort(), msgId, eventListener); // } // // /** // * 通过广播搜索网关 // */ // public void searchGatewayByBroadcast(String msgId, EventListener eventListener) { // searchGateway(IpUtils.getBroadcastAddress(), getUdpPort(), msgId, eventListener); // } // // /** // * 默认是组播搜索网关 // */ // public void searchGateway(String ip, int port, String msgId, EventListener eventListener) { // // if (updBoot == null) { // updBoot = UdpClient.init(ip, port, getUdpOptions()); // updBoot.connect(); // } // // // String time = String.valueOf(System.currentTimeMillis()); // JsonObject jsonObject = new JsonObject(); // jsonObject.addProperty("id", msgId); // jsonObject.addProperty("time_stamp", time); // // EventDispatcher.getInstance().registerIo(TopicConstant.GATEWAY_SEARCH_REPLY, eventListener); // LinkRequest message = new LinkRequest(TopicConstant.GATEWAY_SEARCH, // jsonObject.toString()); // // try { // updBoot.sendMsg(message.getSendBytes()); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // // } /** * 获取设备列表 */ public void getDeviceList(CallBack callBack) { public void getDeviceList(HDLLinkCallBack callBack) { if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { String time = String.valueOf(System.currentTimeMillis()); JsonObject jsonObject = new JsonObject(); @@ -295,7 +286,7 @@ String replyTopic = String.format(TopicConstant.GET_DEVICE_LIST_REPLY, getGatewayId()); try { sendMsg(message.toString().getBytes("utf-8"), replyTopic, callBack, new SendListener() { sendMsg(message.getSendBytes(), replyTopic, callBack, new SendListener() { @Override public void onSucceed() { @@ -304,18 +295,18 @@ @Override public void onError() { if (callBack != null) { callBack.onError("获取设备列表失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_GET_DEVICE_LIST_ERROR)); } } }); } catch (UnsupportedEncodingException e) { } catch (Exception e) { if (callBack != null) { callBack.onError("获取设备列表失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_GET_DEVICE_LIST_ERROR)); } } } else { if (callBack != null) { callBack.onError("ip地址丢失"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_UNAUTHORIZED_ERROR)); } } } @@ -324,7 +315,7 @@ /** * 获取功能列表 */ public void getFunctionList(CallBack callBack) { public void getFunctionList(HDLLinkCallBack callBack) { if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { String time = String.valueOf(System.currentTimeMillis()); JsonObject jsonObject = new JsonObject(); @@ -338,7 +329,7 @@ String replyTopic = String.format(TopicConstant.GET_FUNCTION_LIST_REPLY, getGatewayId()); try { sendMsg(message.toString().getBytes("utf-8"), replyTopic, callBack, new SendListener() { sendMsg(message.getSendBytes(), replyTopic, callBack, new SendListener() { @Override public void onSucceed() { @@ -347,18 +338,18 @@ @Override public void onError() { if (callBack != null) { callBack.onError("获取功能列表失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_GET_FUNCTION_LIST_ERROR)); } } }); } catch (UnsupportedEncodingException e) { } catch (Exception e) { if (callBack != null) { callBack.onError("获取功能列表失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_GET_FUNCTION_LIST_ERROR)); } } } else { if (callBack != null) { callBack.onError("ip地址丢失"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_UNAUTHORIZED_ERROR)); } } } @@ -367,10 +358,10 @@ /** * 获取功能属性 * * @param sids * @param callBack * @param sid */ public void getFunctionAttribute(CallBack callBack, String... sid) { public void getFunctionAttribute(List<String> sids, HDLLinkCallBack callBack) { if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { String time = String.valueOf(System.currentTimeMillis()); @@ -378,7 +369,7 @@ data.setId(IdUtils.getUUId()); data.setTime_stamp(time); List<FunctionAttributeRequest> list = new ArrayList<>(); for (String s : sid) { for (String s : sids) { list.add(new FunctionAttributeRequest(s)); } data.setObjects(list); @@ -389,7 +380,7 @@ String replyTopic = String.format(TopicConstant.GET_FUNCTION_ATTRIBUTE_REPLY, getGatewayId()); try { sendMsg(message.toString().getBytes("utf-8"), replyTopic, callBack, new SendListener() { sendMsg(message.getSendBytes(), replyTopic, callBack, new SendListener() { @Override public void onSucceed() { @@ -398,18 +389,18 @@ @Override public void onError() { if (callBack != null) { callBack.onError("获取功能属性失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_GET_FUNCTION_PROPERTIES_ERROR)); } } }); } catch (UnsupportedEncodingException e) { } catch (Exception e) { if (callBack != null) { callBack.onError("获取功能属性失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_GET_FUNCTION_PROPERTIES_ERROR)); } } } else { if (callBack != null) { callBack.onError("ip地址丢失"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_UNAUTHORIZED_ERROR)); } } } @@ -417,7 +408,7 @@ /** * 设备控制 */ public void propertyDown(List<DeviceControlRequest> request, CallBack callBack) { public void propertyDown(List<DeviceControlRequest> request, HDLLinkCallBack callBack) { if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { String time = String.valueOf(System.currentTimeMillis()); @@ -427,10 +418,9 @@ data.setTime_stamp(time); data.setObjects(request); String topic = String.format(TopicConstant.PROPERTY_DOWN, getGatewayId()); LinkRequest message = new LinkRequest(topic, GsonConvert.getGson().toJson(request)); GsonConvert.getGson().toJson(data)); String replyTopic = String.format(TopicConstant.PROPERTY_DOWN_REPLY, getGatewayId()); try { @@ -443,87 +433,90 @@ @Override public void onError() { if (callBack != null) { callBack.onError("控制指令发送失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } }); } catch (Exception e) { if (callBack != null) { callBack.onError("控制指令发送失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } } else { if (callBack != null) { callBack.onError("控制指令发送失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } } /** * 状态上报 */ public void propertyUp(List<PropertyUpRequest> request, CallBack callBack) { if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { String time = String.valueOf(System.currentTimeMillis()); final BaseLocalResponse<List<PropertyUpRequest>> data = new BaseLocalResponse<>(); data.setId(IdUtils.getUUId()); data.setTime_stamp(time); data.setObjects(request); String topic = String.format(TopicConstant.PROPERTY_UP, getGatewayId()); LinkRequest message = new LinkRequest(topic, GsonConvert.getGson().toJson(request)); String replyTopic = String.format(TopicConstant.PROPERTY_UP_REPLY, getGatewayId()); try { sendMsg(message.toString().getBytes("utf-8"), replyTopic, callBack, new SendListener() { @Override public void onSucceed() { } @Override public void onError() { if (callBack != null) { callBack.onError("指令发送失败"); } } }); } catch (UnsupportedEncodingException e) { if (callBack != null) { callBack.onError("指令发送失败"); } } } else { if (callBack != null) { callBack.onError("指令发送失败"); } } } // /** // * 状态上报 // */ // public void propertyUp(List<PropertyUpRequest> request, CallBack callBack) { // if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { // String time = String.valueOf(System.currentTimeMillis()); // // final BaseLocalResponse<List<PropertyUpRequest>> data = new BaseLocalResponse<>(); // data.setId(IdUtils.getUUId()); // data.setTime_stamp(time); // data.setObjects(request); // // // String topic = String.format(TopicConstant.PROPERTY_UP, getGatewayId()); // LinkRequest message = new LinkRequest(topic, // GsonConvert.getGson().toJson(request)); // // String replyTopic = String.format(TopicConstant.PROPERTY_UP_REPLY, getGatewayId()); // try { // sendMsg(message.getSendBytes(), replyTopic, callBack, new SendListener() { // @Override // public void onSucceed() { // // } // // @Override // public void onError() { // if (callBack != null) { // callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); // } // } // }); // } catch (Exception e) { // if (callBack != null) { // callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); // } // } // } else { // if (callBack != null) { // callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); // } // } // } /** * 读取状态 */ public void propertyRead(List<PropertyReadRequest> request, CallBack callBack) { public void propertyRead(List<String> sids, HDLLinkCallBack callBack) { if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { String time = String.valueOf(System.currentTimeMillis()); final BaseLocalResponse<List<PropertyReadRequest>> data = new BaseLocalResponse<>(); data.setId(IdUtils.getUUId()); data.setTime_stamp(time); data.setObjects(request); List<PropertyReadRequest> list = new ArrayList<>(); for (String s : sids) { list.add(new PropertyReadRequest(s)); } data.setObjects(list); String topic = String.format(TopicConstant.PROPERTY_READ, getGatewayId()); LinkRequest message = new LinkRequest(topic, GsonConvert.getGson().toJson(request)); GsonConvert.getGson().toJson(data)); String replyTopic = String.format(TopicConstant.PROPERTY_READ_REPLY, getGatewayId()); try { sendMsg(message.toString().getBytes("utf-8"), replyTopic, callBack, new SendListener() { sendMsg(message.getSendBytes(), replyTopic, callBack, new SendListener() { @Override public void onSucceed() { @@ -532,18 +525,18 @@ @Override public void onError() { if (callBack != null) { callBack.onError("指令发送失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } }); } catch (UnsupportedEncodingException e) { } catch (Exception e) { if (callBack != null) { callBack.onError("指令发送失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } } else { if (callBack != null) { callBack.onError("指令发送失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } } @@ -559,11 +552,133 @@ } /** * 清空缓存 * 获取场景列表 */ public void clearCache() { SPUtils.remove(TCP_IP_KEY); SPUtils.remove(GATEWAY_KEY); public void getSceneList(HDLLinkCallBack callBack) { if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { String time = String.valueOf(System.currentTimeMillis()); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id", IdUtils.getUUId()); jsonObject.addProperty("time_stamp", time); String topic = String.format(TopicConstant.SCENE_LIST_GET, getGatewayId()); LinkRequest message = new LinkRequest(topic, jsonObject.toString()); String replyTopic = topic + "_reply"; try { sendMsg(message.getSendBytes(), replyTopic, callBack, new SendListener() { @Override public void onSucceed() { } @Override public void onError() { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_GET_FUNCTION_LIST_ERROR)); } } }); } catch (Exception e) { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_GET_FUNCTION_LIST_ERROR)); } } } else { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_UNAUTHORIZED_ERROR)); } } } /** * 场景控制 * @param sids 场景sid列表 * @param callBack 回调 */ public void controlScene(List<String> sids, HDLLinkCallBack callBack) { if (!TextUtils.isEmpty(getGatewayId()) && !TextUtils.isEmpty(getTcpIp())) { String time = String.valueOf(System.currentTimeMillis()); final BaseLocalResponse<List<PropertyReadRequest>> data = new BaseLocalResponse<>(); data.setId(IdUtils.getUUId()); data.setTime_stamp(time); List<PropertyReadRequest> list = new ArrayList<>(); for (String s : sids) { list.add(new PropertyReadRequest(s)); } data.setObjects(list); String topic = String.format(TopicConstant.SCENE_CONTROL, getGatewayId()); LinkRequest message = new LinkRequest(topic, GsonConvert.getGson().toJson(data)); String replyTopic = topic + "_reply"; try { sendMsg(message.getSendBytes(), replyTopic, callBack, new SendListener() { @Override public void onSucceed() { } @Override public void onError() { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } }); } catch (Exception e) { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } } else { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } } // /** // * 清空缓存 // */ // public void clearCache() { // SPUtils.remove(TCP_IP_KEY); // SPUtils.remove(GATEWAY_KEY); // } /** * 通用TCP发送指令 * 1秒没响应就让他重新发送,重试3次 * * @param topic 发送数据 * @param bodyStr 回复的主题 * @param callBack 回调 */ public void tcpSendMsg(String topic, String bodyStr, HDLLinkCallBack callBack) { try { LinkRequest message = new LinkRequest(topic, bodyStr); String replyTopic = topic + "_reply"; sendMsg(message.getSendBytes(), replyTopic, callBack, new SendListener() { @Override public void onSucceed() { } @Override public void onError() { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } }); } catch (Exception e) { if (callBack != null) { callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } } @@ -571,7 +686,7 @@ * 发送指令 * 1秒没响应就让他重新发送,重试3次 */ public void sendMsg(byte[] data, String eventTag, CallBack callBack, SendListener sendListener) { public void sendMsg(byte[] data, String eventTag, HDLLinkCallBack callBack, SendListener sendListener) { try { final AtomicInteger sendCount = new AtomicInteger(0); @@ -583,7 +698,7 @@ if (msg instanceof LinkResponse) { if (callBack != null) { callBack.onResponse(msg.toString()); callBack.onSuccess(msg.toString()); } threadPool.shutdownNow(); } @@ -603,7 +718,7 @@ @Override public void run() { if (callBack != null) { callBack.onError("发送失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } }); @@ -632,7 +747,7 @@ @Override public void run() { if (callBack != null) { callBack.onError("发送失败"); callBack.onError(HDLLinkException.getErrorWithCode(HDLLinkCode.HDL_SEND_ERROR)); } } }); HDLSDK/hdl-connect/src/main/java/com/hdl/sdk/connect/utils/AesUtil.java
@@ -82,17 +82,17 @@ byte[] result = cipher.doFinal(content); return result; } catch (NoSuchAlgorithmException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (InvalidKeyException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (NoSuchPaddingException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (BadPaddingException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (IllegalBlockSizeException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (InvalidAlgorithmParameterException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } return null; } @@ -126,17 +126,17 @@ byte[] result = cipher.doFinal(contentByte); return result; } catch (NoSuchAlgorithmException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (InvalidKeyException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (NoSuchPaddingException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (BadPaddingException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (IllegalBlockSizeException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } catch (InvalidAlgorithmParameterException e) { LogUtils.e(e.getMessage(), e); LogUtils.e(e.getMessage()); } return null; } HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java
@@ -5,6 +5,7 @@ import androidx.collection.ArrayMap; import com.hdl.sdk.common.utils.LogUtils; import com.hdl.sdk.common.utils.ThreadToolUtils; import com.hdl.sdk.socket.annotation.ConnectStatus; import com.hdl.sdk.socket.client.IClient; @@ -67,7 +68,7 @@ final int maxRetry = client.getOptions().getMaxRetry(); if (maxRetry == 0 && resendCount.get() > 0 || (maxRetry > 0 && maxRetry + 1 < resendCount.get())) { Log.d("====", "===重连次数达到最大=="); LogUtils.d("====", "===重连次数达到最大=="); return; } if (!client.isConnect()) { @@ -82,7 +83,7 @@ try { resendCount.set(resendCount.get() + 1); Thread.sleep(300L); Log.d("====", "==重连第" + resendCount + "次=="); LogUtils.d("====", "==重连第" + resendCount + "次=="); } catch (Exception ignored) { } } @@ -90,7 +91,7 @@ client.connect(); isRun.set(true); if (client.isConnect()) { Log.d("====", "====连接成功===="); LogUtils.d("====", "====连接成功===="); startHeartbeat(); initSendThread(); @@ -103,7 +104,7 @@ } } catch (Exception e) { e.printStackTrace(); Log.d("====", "===连接失败===" + e); LogUtils.d("====", "===连接失败===" + e); //再判断一下有没有连接 if (!client.isConnect()) { isRun.set(false); @@ -126,12 +127,12 @@ public void run() { while (isRun.get()) { if (client.isConnect()) { Log.d("=====", "==发送数据=="); LogUtils.d("=====", "==发送数据=="); try { SocketRequest socketRequest = mMessageQueue.take(); final String sendStr = new String(socketRequest.getData(), 0, socketRequest.getData().length); Log.d("=====", "==发送数据==:"+sendStr); LogUtils.d("=====", "==发送数据==:"+sendStr); final String action = socketRequest.getAction(); try { client.sendMsg(socketRequest.getData()); @@ -165,7 +166,7 @@ } } Log.d("=====", "==发送线程关闭=="); LogUtils.d("=====", "==发送线程关闭=="); } }); @@ -185,7 +186,7 @@ client.onHandleResponse(); } catch (Exception e) { e.printStackTrace(); Log.d("====", "断开连接" + e.getMessage()); LogUtils.d("====", "断开连接" + e.getMessage()); disconnectError(); } } @@ -208,7 +209,7 @@ @Override public void run() { if (isRun.get()) { Log.d("====", "===发送心跳包==="); LogUtils.d("====", "===发送心跳包==="); if (client.getOptions() != null) { final byte[] heartBeat = client.getOptions().getHeartbeatData(); if (heartBeat != null) { HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/client/UdpClient.java
@@ -5,6 +5,7 @@ import com.hdl.sdk.common.HDLSdk; import com.hdl.sdk.common.utils.IpUtils; import com.hdl.sdk.common.utils.LogUtils; import com.hdl.sdk.common.utils.ThreadToolUtils; import com.hdl.sdk.socket.SocketBoot; import com.hdl.sdk.socket.SocketOptions; @@ -148,7 +149,7 @@ } final String receive = new String(receivePacket.getData(), 0, receivePacket.getLength()); Log.d("---->", receive + " from " + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort()); LogUtils.d("---->", receive + " from " + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort()); //重置长度 if (receivePacket != null) {