Commit 6cd22534 by pye52

1、避免loop重复生成

2、完善连接状态的日志输出

用于下一发版测试
parent 258bc0aa
......@@ -48,24 +48,55 @@ public class MainWebSocket extends WebSocketClient {
public static final String CODE_FAIL = "-1";
private static MainWebSocket sInstance;
private static long lastLoopId = -1;
private static String sDeviceSN;
private static int sReconnectTimes = 0;
private static int sAutoCheckCount = 0;
public static void initialize() {
if (sInstance == null) {
try {
if (sInstance != null) {
return;
}
sDeviceSN = App.Companion.getDeviceSN();
if (sDeviceSN.isEmpty()) return;
if (sDeviceSN.isEmpty()) {
LogUtils.file(TAG, "device id is empty");
return;
}
EventBus.getDefault().post(new ConnectStateEvent(ConnectStateEvent.CONNECTING));
sInstance = new MainWebSocket(new URI(AppConfig.INSTANCE.getMainWebSocketServerUrl(sDeviceSN, BuildConfig.VERSION_NAME)));
String host = AppConfig.INSTANCE.getMainWebSocketServerUrl(sDeviceSN, BuildConfig.VERSION_NAME);
LogUtil.i(TAG, "try connecting to host: " + host);
try {
sInstance = new MainWebSocket(new URI(host));
} catch (URISyntaxException e) {
LogUtil.i(TAG, "invalidate host: " + host, e);
}
sInstance.setConnectionLostTimeout(10);
sInstance.connect();
TimerHelper.INSTANCE.loop(new TimerHelper.LoopTask() {
// 保证只有一个loop在运行
if (lastLoopId != -1) {
TimerHelper.INSTANCE.cancel(lastLoopId);
}
lastLoopId = TimerHelper.INSTANCE.loop(new TimerHelper.LoopTask() {
@Override
public void run(long id, boolean isLastTime) {
try {
if (sInstance == null) {
LogUtils.file(TAG, "instance of socket could not be null!!!");
initialize();
return;
}
if (sInstance.isClosed()) {
doReconnect();
} else {
doHeartbeat();
}
} catch (Exception e) {
LogUtils.file(TAG, "fatal error: " + e.getMessage());
}
}
private void doReconnect() {
if (sReconnectTimes < 2) {
sReconnectTimes++;
sInstance.reconnect();
......@@ -76,11 +107,14 @@ public class MainWebSocket extends WebSocketClient {
EventBus.getDefault().post(new ConnectStateEvent(ConnectStateEvent.CHANGE_NETWORK));
}
sAutoCheckCount = 0;
} else {
// 每10分钟发一次心跳包给后端
}
private void doHeartbeat() {
// 每3分钟发一次心跳包给后端
// 原为10分钟一次,现改为3分钟一次以方便后台预警功能
sAutoCheckCount -= 2;
if (sAutoCheckCount < 0) {
sAutoCheckCount = 10 * 60;
sAutoCheckCount = 3 * 60;
try {
JSONObject data = new JSONObject();
data.put(FieldEnum.equipmentId.name(), sDeviceSN);
......@@ -90,12 +124,7 @@ public class MainWebSocket extends WebSocketClient {
}
}
}
}
}, 2000, -1, 2000);
} catch (URISyntaxException e) {
LogUtils.file(TAG, "fatal error: " + e.getMessage());
}
}
}
public static boolean isInited() {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment