Commit b88d7729 by patpat

替换为TimerHelper的timeout和loop

parent 6f114843
package com.bgycc.smartcanteen.action;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public abstract class Action {
public enum State {
......@@ -53,40 +49,6 @@ public abstract class Action {
return mAction.equals(action);
}
protected void timeout(final Runnable runnable, long ms) {
Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
@Override
public void run() {
try {
if (runnable != null) runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, ms, TimeUnit.MILLISECONDS);
}
protected void loop(final Runnable runnable, final Runnable endRunnable, final int times, long period) {
final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
int count = 0;
@Override
public void run() {
try {
if (count >= times) {
if (endRunnable != null) endRunnable.run();
exec.shutdown();
return;
}
count++;
if (runnable != null) runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0, period, TimeUnit.MILLISECONDS);
}
protected void success(String message) {
if (mActionResult != null) mActionResult.onSuccess(message);
}
......
......@@ -3,6 +3,7 @@ package com.bgycc.smartcanteen.action;
import com.bgycc.smartcanteen.App;
import com.bgycc.smartcanteen.Storage.PayStorage;
import com.bgycc.smartcanteen.event.PayStateEvent;
import com.bgycc.smartcanteen.helper.TimerHelper;
import com.bgycc.smartcanteen.server.websocket.MainWebSocket;
import com.bgycc.smartcanteen.task.QRCodeTask;
import com.bgycc.smartcanteen.util.DateUtil;
......@@ -48,7 +49,7 @@ public class PayOfflineAction extends Action {
break;
case FAIL:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.FAIL, message));
timeout(new Runnable() {
TimerHelper.INSTANCE.timeout(new Runnable() {
@Override
public void run() {
setState(State.INITED);
......@@ -57,7 +58,7 @@ public class PayOfflineAction extends Action {
break;
case RESQUEST_SUCCESS:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.SUCCESS, message));
timeout(new Runnable() {
TimerHelper.INSTANCE.timeout(new Runnable() {
@Override
public void run() {
setState(State.INITED);
......
......@@ -3,6 +3,7 @@ package com.bgycc.smartcanteen.action;
import android.util.Log;
import com.bgycc.smartcanteen.App;
import com.bgycc.smartcanteen.event.PayStateEvent;
import com.bgycc.smartcanteen.helper.TimerHelper;
import com.bgycc.smartcanteen.server.websocket.MainWebSocket;
import com.bgycc.smartcanteen.util.DateUtil;
import org.greenrobot.eventbus.EventBus;
......@@ -25,14 +26,19 @@ public class PayOnlineAction extends Action {
}
private String mPayCode;
private boolean mWaitResponse;
private long mResponseTimeoutId = -1;
public PayOnlineAction() {
super(ActionEnum.PAY_ONLINE.name());
MainWebSocket.subscribe(ActionEnum.PAY_RESULT.name(), mPayResultResponse);
}
protected void setState(State state, String message) {
private void cancelResponseTimeout() {
TimerHelper.INSTANCE.cancel(mResponseTimeoutId);
mResponseTimeoutId = -1;
}
private void setState(State state, String message) {
if (state != getState()) {
switch (state) {
case INITED:
......@@ -40,25 +46,22 @@ public class PayOnlineAction extends Action {
break;
case STARTED:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.WAIT, message));
mWaitResponse = false;
cancelResponseTimeout();
break;
case RESQUEST_SUCCESS:
mWaitResponse = true;
timeout(new Runnable() {
mResponseTimeoutId = TimerHelper.INSTANCE.timeout(new Runnable() {
@Override
public void run() {
if (!mWaitResponse) return;
setState(State.RESPONSE_TIMEOUT, "交易失败");
}
}, 10000);
break;
case RESPONSE_SUCCESS:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.SUCCESS, message));
mWaitResponse = false;
cancelResponseTimeout();
mPayCode = "";
success(message);
timeout(new Runnable() {
TimerHelper.INSTANCE.timeout(new Runnable() {
@Override
public void run() {
setState(State.INITED, "");
......@@ -70,10 +73,10 @@ public class PayOnlineAction extends Action {
case RESPONSE_FAIL:
case RESPONSE_TIMEOUT:
EventBus.getDefault().post(new PayStateEvent(PayStateEvent.StateEnum.FAIL, message));
mWaitResponse = false;
cancelResponseTimeout();
mPayCode = "";
fail(message);
timeout(new Runnable() {
TimerHelper.INSTANCE.timeout(new Runnable() {
@Override
public void run() {
setState(State.INITED, "");
......@@ -97,27 +100,25 @@ public class PayOnlineAction extends Action {
setActionResult(result);
mPayCode = payCode;
final long timeoutId = TimerHelper.INSTANCE.timeout(new Runnable() {
@Override
public void run() {
setState(State.RESQUEST_TIMEOUT, "交易失败");
}
}, 10000);
final MainWebSocket.Response response = new MainWebSocket.Response() {
@Override
protected void onSuccess(JSONObject data, String message) {
cancel();
TimerHelper.INSTANCE.cancel(timeoutId);
setState(State.RESQUEST_SUCCESS, message);
}
@Override
protected void onFail(JSONObject data, String message, String code) {
cancel();
TimerHelper.INSTANCE.cancel(timeoutId);
setState(State.RESQUEST_FAIL, message);
}
};
timeout(new Runnable() {
@Override
public void run() {
if (response.isCancelled()) return;
response.cancel();
setState(State.RESQUEST_TIMEOUT, "交易失败");
}
}, 10000);
try {
JSONObject params = new JSONObject();
......
......@@ -44,7 +44,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
EventBus.getDefault().post(WifiStateEvent(1, "正在启动Wifi"))
if (!WifiHelpler.setEnable(true)) {
EventBus.getDefault().post(WifiStateEvent(1, "无法启动Wifi"))
timeout({
TimerHelper.timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
......@@ -55,7 +55,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
val config = WifiHelpler.createWifiConfiguration(ssid, identity, pwd, type)
if (config == null) {
EventBus.getDefault().post(WifiStateEvent(10, "Wifi参数有误"))
timeout({
TimerHelper.timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
......@@ -68,7 +68,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
if (!WifiHelpler.enableNetwork(netId)) throw Exception("无法应用Wifi配置")
} catch (e: Exception) {
EventBus.getDefault().post(WifiStateEvent(20, e.message))
timeout({
TimerHelper.timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
......@@ -81,7 +81,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
if (state == State.STARTED) {
state = State.FAIL
EventBus.getDefault().post(WifiStateEvent(30, "无法连接Wifi"))
timeout({
TimerHelper.timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
......@@ -93,7 +93,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
if (info.ipAddress != 0) {
state = State.SUCCESS
EventBus.getDefault().post(WifiStateEvent(30, "已连接Wifi"))
timeout({
TimerHelper.timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
......
......@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit
object TimerHelper {
val TAG = TimerHelper::class.java.simpleName
private val TAG = TimerHelper::class.java.simpleName
private var mId: Long = 0L
get() = ++field
......
......@@ -4,14 +4,14 @@ import android.util.Log;
import com.bgycc.smartcanteen.QRCodeEvent;
import com.bgycc.smartcanteen.action.*;
import com.bgycc.smartcanteen.event.LogEvent;
import com.bgycc.smartcanteen.helper.TimerHelper;
import com.bgycc.smartcanteen.server.websocket.MainWebSocket;
import com.szxb.jni.libszxb;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
public class QRCodeTask {
......@@ -31,7 +31,7 @@ public class QRCodeTask {
return sInstance;
}
private ScheduledExecutorService mScanExec;
private ScanAsyncTask mScanAsyncTask;
private QRCodeTask() {}
......@@ -42,107 +42,101 @@ public class QRCodeTask {
public void start() {
if (!support()) return;
if (mScanExec == null) {
mScanExec = Executors.newSingleThreadScheduledExecutor();
mScanExec.scheduleAtFixedRate(new ScanRunnable(), 0, 200, TimeUnit.MILLISECONDS);
if (mScanAsyncTask == null) {
mScanAsyncTask = new ScanAsyncTask();
TimerHelper.INSTANCE.loop(new Function2<Long, Boolean, Boolean>() {
@Override
public Boolean invoke(Long id, Boolean isLastTime) {
if (mScanAsyncTask == null) return false;
mScanAsyncTask.run();
return true;
}
}, 200, -1);
}
}
public void stop() {
if (mScanExec != null) {
mScanExec.shutdown();
mScanExec = null;
}
mScanAsyncTask = null;
}
private class ScanRunnable implements Runnable {
private class ScanAsyncTask extends AsyncTask {
int lastLen = -1;
byte[] lastBuf;
AsyncTask asyncTask = new AsyncTask() {
@Override
protected void run(int step, int progress) {
// Log.i(TAG, String.format("step: %d progress: %d", step, progress));
switch (step) {
case 0:
if (progress != 0) break;
byte[] buf = new byte[1024];
int len = libszxb.getBarcode(buf);
boolean changed = checkBarCodeChanged(buf, len);
if (!changed || len <= 0) break;
delay(1000);
String str = new String(buf, 0, len);
QRCodeEvent event = new QRCodeEvent(str.getBytes(), str, checkPayCodeType(str));
EventBus.getDefault().post(event);
if (event.payCodeType == null) {
parseCommand(event);
@Override
protected void run(int step, int progress) {
// Log.i(TAG, String.format("step: %d progress: %d", step, progress));
switch (step) {
case 0:
if (progress != 0) break;
byte[] buf = new byte[1024];
int len = libszxb.getBarcode(buf);
boolean changed = checkBarCodeChanged(buf, len);
if (!changed || len <= 0) break;
delay(1000);
String str = new String(buf, 0, len);
QRCodeEvent event = new QRCodeEvent(str.getBytes(), str, checkPayCodeType(str));
EventBus.getDefault().post(event);
if (event.payCodeType == null) {
parseCommand(event);
} else {
if (MainWebSocket.isConnected()) {
// if (false) {
nextProgress();
PayOnlineAction.getDefault().exec(event.string, event.payCodeType, new ActionResult() {
@Override
public void onSuccess(String message) {
timeout(new Runnable() {
@Override
public void run() {
resetStep();
}
}, 1000);
}
@Override
public void onFail(String message) {
timeout(new Runnable() {
@Override
public void run() {
resetStep();
}
}, 1000);
}
});
} else {
if (MainWebSocket.isConnected()) {
// if (false) {
nextProgress();
PayOnlineAction.getDefault().exec(event.string, event.payCodeType, new ActionResult() {
@Override
public void onSuccess(String message) {
timeout(new Runnable() {
@Override
public void run() {
resetStep();
}
}, 1000);
}
@Override
public void onFail(String message) {
timeout(new Runnable() {
@Override
public void run() {
resetStep();
}
}, 1000);
}
});
} else {
PayOfflineAction.getDefault().exec(event.string, event.payCodeType);
// PayOfflineAction.getDefault().upload();
}
PayOfflineAction.getDefault().exec(event.string, event.payCodeType);
// PayOfflineAction.getDefault().upload();
}
break;
case 1:
break;
}
}
break;
case 1:
break;
}
}
boolean checkBarCodeChanged(byte[] buf, int len) {
boolean changed = false;
if (len != lastLen) {
changed = true;
} else if (lastBuf == null) {
changed = true;
} else {
for (int i = 0; i < len; i++) {
if (buf[i] != lastBuf[i]) {
changed = true;
break;
}
boolean checkBarCodeChanged(byte[] buf, int len) {
boolean changed = false;
if (len != lastLen) {
changed = true;
} else if (lastBuf == null) {
changed = true;
} else {
for (int i = 0; i < len; i++) {
if (buf[i] != lastBuf[i]) {
changed = true;
break;
}
}
lastLen = len;
lastBuf = buf;
return changed;
}
};
@Override
public void run() {
try {
asyncTask.run();
} catch (Exception e) {
Log.e(TAG, "ScanRunnable error");
e.printStackTrace();
}
lastLen = len;
lastBuf = buf;
return changed;
}
}
......
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