Commit 93a43838 by patpat

已初步完成websocket通讯,差请求回调未实现

parent 4b73ef50
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bgycc.smartcanteen"> package="com.bgycc.smartcanteen">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
...@@ -15,13 +16,21 @@ ...@@ -15,13 +16,21 @@
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme"> android:theme="@style/AppTheme">
<activity android:name=".MainActivity"> <activity android:name=".activity.MainActivity">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN"/> <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/> <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter> </intent-filter>
</activity> </activity>
<receiver android:name=".receiver.BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<!--<category android:name="android.intent.category.LAUNCHER" />-->
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application> </application>
</manifest> </manifest>
\ No newline at end of file
package com.bgycc.smartcanteen package com.bgycc.smartcanteen
import android.app.Application import android.app.Application
import com.bgycc.smartcanteen.helper.WifiHelpler
class App : Application() { class App : Application() {
......
...@@ -10,4 +10,15 @@ public class QRCodeEvent { ...@@ -10,4 +10,15 @@ public class QRCodeEvent {
this.string = string; this.string = string;
this.payCodeType = payCodeType; this.payCodeType = payCodeType;
} }
public boolean isEmpty() {
return this.string == null || this.string.isEmpty();
}
public boolean equal(QRCodeEvent event) {
if (event == null) return false;
if (isEmpty() != event.isEmpty()) return false;
if (isEmpty()) return true;
return this.string.equals(event.string);
}
} }
package com.bgycc.smartcanteen package com.bgycc.smartcanteen.activity
import android.app.Activity import android.app.Activity
import android.view.View import android.view.View
......
package com.bgycc.smartcanteen package com.bgycc.smartcanteen.activity
import android.os.Bundle import android.os.Bundle
import android.widget.TextView import android.widget.TextView
import com.example.zhoukai.modemtooltest.ModemToolTest import com.bgycc.smartcanteen.QRCodeEvent
import com.example.zhoukai.modemtooltest.NvConstants import com.bgycc.smartcanteen.R
import com.bgycc.smartcanteen.helper.QRCodeHelper
import com.bgycc.smartcanteen.server.websocket.ConnectStateEvent
import com.bgycc.smartcanteen.server.websocket.MainWebSocket
import com.bgycc.smartcanteen.server.websocket.RecvMessageEvent
import com.bgycc.smartcanteen.server.websocket.SendMessageEvent
import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : BaseActivity() { class MainActivity : BaseActivity() {
...@@ -14,8 +21,10 @@ class MainActivity : BaseActivity() { ...@@ -14,8 +21,10 @@ class MainActivity : BaseActivity() {
var TAG: String = MainActivity::class.java.simpleName var TAG: String = MainActivity::class.java.simpleName
} }
lateinit var mServerText: TextView
lateinit var mQRCodeText: TextView lateinit var mQRCodeText: TextView
lateinit var mServerText: TextView
lateinit var mSendText: TextView
lateinit var mRecvText: TextView
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
...@@ -38,8 +47,10 @@ class MainActivity : BaseActivity() { ...@@ -38,8 +47,10 @@ class MainActivity : BaseActivity() {
} }
fun initView() { fun initView() {
mServerText = findViewById(R.id.server)
mQRCodeText = findViewById(R.id.qrcode) mQRCodeText = findViewById(R.id.qrcode)
mServerText = findViewById(R.id.server)
mSendText = findViewById(R.id.send_msg)
mRecvText = findViewById(R.id.recv_msg)
} }
fun printQRCode(event: QRCodeEvent) { fun printQRCode(event: QRCodeEvent) {
...@@ -69,4 +80,17 @@ class MainActivity : BaseActivity() { ...@@ -69,4 +80,17 @@ class MainActivity : BaseActivity() {
else if (event.state == ConnectStateEvent.CONNECTED) mServerText.text = "Server: 已连接" else if (event.state == ConnectStateEvent.CONNECTED) mServerText.text = "Server: 已连接"
else if (event.state == ConnectStateEvent.RECONNECTING) mServerText.text = "Server: 正在重连..." else if (event.state == ConnectStateEvent.RECONNECTING) mServerText.text = "Server: 正在重连..."
} }
@Subscribe(threadMode = ThreadMode.MAIN)
fun onMessageEvent(event: SendMessageEvent) {
val time = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()).format(Date())
mSendText.text = String.format("Send: %s - %s", time, event.message);
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onMessageEvent(event: RecvMessageEvent) {
val time = SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault()).format(Date())
mRecvText.text = String.format("Receive: %s - %s", time, event.message);
}
} }
package com.bgycc.smartcanteen; package com.bgycc.smartcanteen.helper;
import android.util.Log;
import okhttp3.*; import okhttp3.*;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class OkHttpHelper { public class OkHttpHelper {
......
package com.bgycc.smartcanteen; package com.bgycc.smartcanteen.helper;
import com.bgycc.smartcanteen.QRCodeEvent;
import com.szxb.jni.libszxb; import com.szxb.jni.libszxb;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
......
package com.bgycc.smartcanteen; package com.bgycc.smartcanteen.helper;
import android.content.Context; import android.content.Context;
import android.net.DhcpInfo; import android.net.DhcpInfo;
......
package com.bgycc.smartcanteen.lib;
import android.util.Log;
public class libszxb {
private static boolean sUsable = false;
static {
try {
System.loadLibrary("szxb");
sUsable = true;
} catch (Throwable e) {
Log.e("jni", "i can't find business so!");
e.printStackTrace();
}
}
public static boolean usable() {
return sUsable;
}
// public static native int getBarcode(byte[] recv);
}
package com.bgycc.smartcanteen.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.bgycc.smartcanteen.activity.MainActivity;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent intent2 = new Intent(context, MainActivity.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
}
package com.bgycc.smartcanteen; package com.bgycc.smartcanteen.server.websocket;
public class ConnectStateEvent { public class ConnectStateEvent {
......
package com.bgycc.smartcanteen; package com.bgycc.smartcanteen.server.websocket;
import android.util.Log; import android.util.Log;
import com.example.zhoukai.modemtooltest.ModemToolTest; import com.example.zhoukai.modemtooltest.ModemToolTest;
import com.example.zhoukai.modemtooltest.NvConstants; import com.example.zhoukai.modemtooltest.NvConstants;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
import org.java_websocket.client.WebSocketClient; import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -29,7 +29,7 @@ public class MainWebSocket extends WebSocketClient { ...@@ -29,7 +29,7 @@ public class MainWebSocket extends WebSocketClient {
if (sDeviceSN == null || sDeviceSN.isEmpty()) return; if (sDeviceSN == null || sDeviceSN.isEmpty()) return;
EventBus.getDefault().post(new ConnectStateEvent(ConnectStateEvent.CONNECTING)); EventBus.getDefault().post(new ConnectStateEvent(ConnectStateEvent.CONNECTING));
sInstance = new MainWebSocket(new URI("ws://l-patpat.cn:5000/websocket/" + sDeviceSN)); sInstance = new MainWebSocket(new URI("ws://10.187.5.223:9001/websocket/" + sDeviceSN));
sInstance.connect(); sInstance.connect();
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
e.printStackTrace(); e.printStackTrace();
...@@ -63,7 +63,7 @@ public class MainWebSocket extends WebSocketClient { ...@@ -63,7 +63,7 @@ public class MainWebSocket extends WebSocketClient {
json.put("payCode", payCode); json.put("payCode", payCode);
json.put("terminalType", payCodeType); json.put("terminalType", payCodeType);
json.put("time", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault()).format(new Date())); json.put("time", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault()).format(new Date()));
sInstance.send(json); sInstance.send("PAY_ONLINE", json);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -72,21 +72,23 @@ public class MainWebSocket extends WebSocketClient { ...@@ -72,21 +72,23 @@ public class MainWebSocket extends WebSocketClient {
private int mSessionId = 0; private int mSessionId = 0;
private MainWebSocket(URI serverUri) { private MainWebSocket(URI serverUri) {
super(serverUri); super(serverUri, new Draft_6455(), null, 10000);
} }
private void send(JSONObject data) { private void send(String action, JSONObject data) {
try { try {
if (mSessionId >= Integer.MAX_VALUE) mSessionId = 0;
mSessionId++; mSessionId++;
if (mSessionId > 10000) mSessionId= 0;
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
json.put("equipmentId", sDeviceSN); json.put("equipmentId", sDeviceSN);
json.put("serialNumber", mSessionId); json.put("serialNumber", mSessionId);
json.put("action", action);
json.put("data", data); json.put("data", data);
String tmp = json.toString(); String msg = json.toString();
Log.i(TAG, String.format("send: %s", tmp)); Log.i(TAG, String.format("send: %s", msg));
super.send(tmp); EventBus.getDefault().post(new SendMessageEvent(msg));
super.send(msg);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -101,6 +103,7 @@ public class MainWebSocket extends WebSocketClient { ...@@ -101,6 +103,7 @@ public class MainWebSocket extends WebSocketClient {
@Override @Override
public void onMessage(String message) { public void onMessage(String message) {
Log.i(TAG, String.format("onMessage: %s", message)); Log.i(TAG, String.format("onMessage: %s", message));
EventBus.getDefault().post(new RecvMessageEvent(message));
} }
@Override @Override
...@@ -114,4 +117,10 @@ public class MainWebSocket extends WebSocketClient { ...@@ -114,4 +117,10 @@ public class MainWebSocket extends WebSocketClient {
Log.i(TAG, "onError"); Log.i(TAG, "onError");
ex.printStackTrace(); ex.printStackTrace();
} }
public static interface Response {
void onSuccess(JSONObject data);
void onFail(String code, String message);
}
} }
package com.bgycc.smartcanteen.server.websocket;
public class RecvMessageEvent {
public String message;
public RecvMessageEvent(String message) {
this.message = message;
}
}
package com.bgycc.smartcanteen.server.websocket;
public class SendMessageEvent {
public String message;
public SendMessageEvent(String message) {
this.message = message;
}
}
package com.bgycc.smartcanteen.task;
import android.os.Bundle;
import org.json.JSONObject;
public class AsyncTask implements Runnable {
protected long mLastRunTime = 0;
protected int mStep = 0;
protected int mProgress = 0;
protected int mDelay = 0;
protected long mTimeout = 0;
protected Runnable mTimeoutRunnable = null;
@Override
public void run() {
long time = System.currentTimeMillis();
if (mLastRunTime == 0) mLastRunTime = time;
long expendTime = time - mLastRunTime;
mLastRunTime = time;
if (mDelay > 0) {
mDelay -= expendTime;
if (mDelay > 0) return;
}
if (mTimeout > 0) {
mTimeout -= expendTime;
if (mTimeout <= 0 && mTimeoutRunnable != null) {
mTimeoutRunnable.run();
}
}
run(mStep, mProgress);
}
public void callback(JSONObject args) {
}
public void callback(Bundle args) {
}
protected void resetStep() {
mProgress = 0;
mDelay = 0;
clearTimeout();
}
protected void nextStep() {
resetStep();
mStep++;
}
protected void nextProgress() {
mProgress++;
}
protected void delay(int delay) {
mDelay = delay;
}
protected void clearTimeout() {
mTimeout = 0;
mTimeoutRunnable = null;
}
protected void timeout(Runnable runnable, long timeout) {
mTimeout = timeout;
mTimeoutRunnable = runnable;
}
protected void run(int step, int progress) {
}
}
package com.bgycc.smartcanteen.task;
import com.bgycc.smartcanteen.QRCodeEvent;
import com.bgycc.smartcanteen.helper.QRCodeHelper;
import com.bgycc.smartcanteen.server.websocket.MainWebSocket;
import com.szxb.jni.libszxb;
import org.greenrobot.eventbus.EventBus;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;
public class QRCodeTask {
public static String TYPE_ALIPAY = "ALIPAY";
public static String TYPE_WXPAY = "WXPAY";
public static String TYPE_BHPAY = "BHPAY";
private static QRCodeTask sInstance;
public static synchronized QRCodeTask getInstance() {
if (sInstance == null) {
sInstance = new QRCodeTask();
}
return sInstance;
}
private Timer mScanTimer;
private QRCodeTask() {}
public boolean support() {
return true;
}
public void start() {
if (!support()) return;
if (mScanTimer == null) {
mScanTimer = new Timer();
mScanTimer.scheduleAtFixedRate(new LoopTimerTask(), 0, 200);
}
}
public void stop() {
if (mScanTimer != null) {
mScanTimer.cancel();
mScanTimer = null;
}
}
private class LoopTimerTask extends TimerTask {
QRCodeEvent lastEvent;
AsyncTask asyncTask = new AsyncTask() {
@Override
protected void run(int step, int progress) {
switch (step) {
case 0: // 获取二维码
byte[] buf = new byte[1024];
int len = libszxb.getBarcode(buf);
if (len <= 0) break;
delay(1000);
String str = new String(buf, 0, len);
QRCodeEvent event = new QRCodeEvent(str.getBytes(), str, checkPayCodeType(str));
QRCodeEvent le = lastEvent;
lastEvent = event;
if (event.equal(le)) break;
EventBus.getDefault().post(event);
if (event.payCodeType == null) {
parseCommand(event);
} else {
MainWebSocket.payOnline(event.string, event.payCodeType);
nextStep();
}
break;
}
}
};
@Override
public void run() {
asyncTask.run();
}
}
private void parseCommand(QRCodeEvent event) {
}
private String checkPayCodeType(String code) {
if (Pattern.matches("^(10|11|12|13|14|15)\\d{16}$", code)) return TYPE_WXPAY;
if (Pattern.matches("^(25|26|27|28|29|30)\\d{14,22}$", code)) return TYPE_ALIPAY;
if (Pattern.matches("^(38|39)\\d{16}$", code)) return TYPE_BHPAY;
return null;
}
}
...@@ -5,11 +5,13 @@ ...@@ -5,11 +5,13 @@
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"> tools:context=".activity.MainActivity">
<LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp"> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp">
<TextView android:id="@+id/server" android:text="Server: 未连接" android:textSize="18sp" android:textColor="#888" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/qrcode" android:text="QRCode: 扫描中..." android:textSize="18sp" android:textColor="#888" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/qrcode" android:text="QRCode: 扫描中..." android:textSize="18sp" android:textColor="#888" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/server" android:text="Server: 未连接" android:textSize="18sp" android:textColor="#888" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/send_msg" android:text="Send: null" android:textSize="18sp" android:textColor="#488" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/recv_msg" android:text="Receive: null" android:textSize="18sp" android:textColor="#800" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout> </LinearLayout>
<TextView <TextView
......
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