Commit 0d7bc81b by patpat

修复websocket断线慢的问题、增加websocket连接传版本、增加更新下载超时和旧版本不允许安装限制、日志功能未完成

parent a9b237f7
......@@ -67,8 +67,12 @@ dependencies {
implementation 'com.android.support:support-v4:28.0.0'
implementation "org.java-websocket:Java-WebSocket:1.4.0"
implementation 'org.greenrobot:eventbus:3.1.1'
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
implementation 'com.github.salomonbrys.kotson:kotson:2.5.0'
implementation 'com.blankj:utilcode:1.25.9'
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
......
......@@ -13,7 +13,7 @@ object AppConfig {
fun getMainWebSocketServerHost(): String {
return when (SERVER) {
Server.DEV -> "10.187.37.226"
Server.DEV -> "10.187.43.221"
Server.TEST -> "diningservicetest.bgy.com.cn"
Server.UAT -> "diningserviceuat.bgy.com.cn"
else -> "diningservice.bgy.com.cn"
......@@ -24,8 +24,18 @@ object AppConfig {
return when (SERVER) {
Server.DEV -> "ws://${getMainWebSocketServerHost()}:9001/websocket/$id/V$version"
Server.TEST -> "ws://${getMainWebSocketServerHost()}:9001/websocket/$id/V$version"
Server.UAT -> "wss://${getMainWebSocketServerHost()}/websocket/$id"
else -> "wss://${getMainWebSocketServerHost()}/websocket/$id"
Server.UAT -> "wss://${getMainWebSocketServerHost()}/websocket/$id/V$version"
else -> "wss://${getMainWebSocketServerHost()}/websocket/$id/V$version"
}
}
fun getMainHttpServerHost(): String {
return when (SERVER) {
Server.DEV -> "http://diningbackdev.bgy.com.cn"
Server.TEST -> "http://diningbacktest.bgy.com.cn"
Server.UAT -> "http://diningbackuat.bgy.com.cn"
else -> "http://diningback.bgy.com.cn"
}
}
}
\ No newline at end of file
......@@ -11,6 +11,9 @@ public enum ActionEnum {
PAY_OFFLINE,
PAY_RESULT,
// Log
LOG_PULL,
// 配置
CONFIG_,
CONFIG_LOG,
......
package com.bgycc.smartcanteen.action;
public class LogAction extends Action {
protected LogAction(String action) {
super(action);
}
}
package com.bgycc.smartcanteen.action
import com.bgycc.smartcanteen.BuildConfig
import com.bgycc.smartcanteen.server.http.MainHttpClient
import com.bgycc.smartcanteen.util.LogUtil
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.ZipUtils
import org.json.JSONObject
import java.io.File
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
object LogAction : Action(ActionEnum.LOG_PULL.name) {
val TAG = LogAction::class.java.simpleName
fun exec(data: JSONObject) {
if (state != State.INITED) return
try {
val formatSrc = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val type = data.getString("logType")
val startTime = formatSrc.parse(data.getString("startTime"))
val endTime = formatSrc.parse(data.getString("endTime"))
if (startTime > endTime) return
val formatDst = SimpleDateFormat("yyyy_MM_dd", Locale.getDefault())
val dateList = ArrayList<String>()
val c = Calendar.getInstance()
c.time = startTime
while (c.time <= endTime) {
dateList.add(formatDst.format(c.time))
c.add(Calendar.DATE, 1)
}
Thread {
state = State.STARTED
val logZipFile = File(PathUtils.getExternalAppCachePath(), "upload/log.zip")
val logUploadDir = File(PathUtils.getExternalAppCachePath(), "upload/log")
FileUtils.delete(logZipFile)
FileUtils.deleteDir(logUploadDir)
logUploadDir.mkdirs()
when (type) {
"app" -> {
val logDir = File(PathUtils.getExternalAppCachePath(), "log")
dateList.forEach {
val f = File(logDir, "util_${it}_${BuildConfig.APPLICATION_ID}.txt")
if (f.exists() && f.isFile) {
FileUtils.copyFile(f, File(logUploadDir, f.name))
}
}
}
"system" -> {
}
}
ZipUtils.zipFile(logUploadDir, logZipFile)
MainHttpClient.uploadLog(logZipFile)
}.start()
} catch (e: Exception) {}
}
}
\ No newline at end of file
package com.bgycc.smartcanteen.action
import com.bgycc.smartcanteen.BuildConfig
import com.bgycc.smartcanteen.event.SettingStateEvent
import com.bgycc.smartcanteen.helper.TimerHelper
import com.blankj.utilcode.util.*
......@@ -30,6 +31,7 @@ class UpdateAction private constructor() : Action(ActionEnum.CONFIG_UPDATE.name)
}
}
private var mTimeoutId = -1L
private val mHttp = OkHttpClient.Builder()
.connectTimeout(6, TimeUnit.SECONDS)
.readTimeout(6, TimeUnit.SECONDS)
......@@ -37,6 +39,8 @@ class UpdateAction private constructor() : Action(ActionEnum.CONFIG_UPDATE.name)
.build()
private fun finish() {
TimerHelper.cancel(mTimeoutId)
mTimeoutId = -1
TimerHelper.timeout({
state = State.INITED
EventBus.getDefault().post(SettingStateEvent(-1))
......@@ -63,6 +67,10 @@ class UpdateAction private constructor() : Action(ActionEnum.CONFIG_UPDATE.name)
EventBus.getDefault().post(SettingStateEvent(1, "正在下载更新包"))
state = State.STARTED
mTimeoutId = TimerHelper.timeout({
EventBus.getDefault().post(SettingStateEvent(1, "更新包下载超时"))
finish()
}, 10000)
val request = Request.Builder().url(url).build()
mHttp.newCall(request).enqueue(object : okhttp3.Callback {
override fun onFailure(call: Call, e: IOException) {
......@@ -74,9 +82,16 @@ class UpdateAction private constructor() : Action(ActionEnum.CONFIG_UPDATE.name)
val body = response.body()!!
val success = FileIOUtils.writeFileFromIS(FILE_UPDATE_APK, BufferedInputStream(body.byteStream()))
if (success) {
val info = AppUtils.getApkInfo(FILE_UPDATE_APK)
if (info == null ||
(info.packageName == BuildConfig.APPLICATION_ID && info.versionCode < BuildConfig.VERSION_CODE)) {
EventBus.getDefault().post(SettingStateEvent(99, "不允许安装低版本"))
} else {
EventBus.getDefault().post(SettingStateEvent(99, "安装更新包"))
AppUtils.installApp(FILE_UPDATE_APK)
}
finish()
return
}
} catch (e: Exception) {}
EventBus.getDefault().post(SettingStateEvent(99, "更新包安装失败"))
......
......@@ -33,12 +33,13 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
fun exec(data: JSONObject) {
if (state != State.INITED) return
state = State.STARTED
try {
val ssid = data.getString("ssid")
val pwd = data.getString("pwd")
val type = data.optString("type", "wpa")
val identity = data.optString("identity")
state = State.STARTED
WifiHelpler.connect(ssid, identity, pwd, type)
EventBus.getDefault().post(SettingStateEvent(1, "正在启动Wifi"))
......@@ -103,7 +104,7 @@ class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
}
}, 1000, 10)
} catch (e: Exception) {
state = State.INITED
}
}
}
\ No newline at end of file
......@@ -14,10 +14,7 @@ import com.bgycc.smartcanteen.App
import com.bgycc.smartcanteen.AppConfig
import com.bgycc.smartcanteen.BuildConfig
import com.bgycc.smartcanteen.R
import com.bgycc.smartcanteen.action.ActionEnum
import com.bgycc.smartcanteen.action.ActionResult
import com.bgycc.smartcanteen.action.PayOnlineAction
import com.bgycc.smartcanteen.action.UpdateAction
import com.bgycc.smartcanteen.action.*
import com.bgycc.smartcanteen.event.*
import com.bgycc.smartcanteen.helper.EthernetHelper
import com.bgycc.smartcanteen.helper.TimerHelper
......@@ -104,7 +101,12 @@ class MainActivity : BaseActivity() {
_sn.text = "SN: ${App.getDeviceSN()}"
if (BuildConfig.DEBUG) {
_message.setOnClickListener {
App.testQRCode = "380000000000000000"
// App.testQRCode = "380000000000000000"
val json = JSONObject()
json.put("logType", "app")
json.put("startTime", "2019-11-20")
json.put("endTime", "2019-11-29")
LogAction.exec(json)
}
_debug.setOnClickListener {
_debug.visibility = View.GONE
......
package com.bgycc.smartcanteen.server.http
import okhttp3.MultipartBody
import retrofit2.Call
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
interface CommonApi {
@Multipart
@POST("upload")
fun upload(@Part file: MultipartBody.Part): Call<CommonResponse>
}
\ No newline at end of file
package com.bgycc.smartcanteen.server.http
data class CommonResponse(val code: String) {
}
\ No newline at end of file
package com.bgycc.smartcanteen.server.http
import com.bgycc.smartcanteen.AppConfig
import com.bgycc.smartcanteen.BuildConfig
import com.bgycc.smartcanteen.util.LogUtil
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit
object MainHttpClient {
val TAG = MainHttpClient::class.java.simpleName
private val mClient: Retrofit
init {
val httpBuilder = OkHttpClient.Builder()
.connectTimeout(6, TimeUnit.SECONDS)
.readTimeout(6, TimeUnit.SECONDS)
.writeTimeout(6, TimeUnit.SECONDS)
if (BuildConfig.DEBUG) {
val interceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
LogUtil.i(TAG, it)
})
interceptor.level = HttpLoggingInterceptor.Level.BODY
httpBuilder.addInterceptor(interceptor)
}
mClient = Retrofit.Builder()
.client(httpBuilder.build())
.baseUrl(AppConfig.getMainHttpServerHost())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
fun uploadLog(file: File) {
val requestBody = RequestBody.create(MediaType.parse("application/x-zip-compressed"), file)
val multipartBody = MultipartBody.Part.createFormData("file", file.name, requestBody)
mClient.create(CommonApi::class.java).upload(multipartBody).enqueue(object : retrofit2.Callback<CommonResponse> {
override fun onFailure(call: Call<CommonResponse>, t: Throwable) {
LogUtil.i(TAG, "onFailure")
}
override fun onResponse(call: Call<CommonResponse>, response: Response<CommonResponse>) {
LogUtil.i(TAG, "onResponse")
}
})
}
}
\ No newline at end of file
......@@ -12,8 +12,6 @@ import com.bgycc.smartcanteen.server.websocket.event.ConnectStateEvent;
import com.bgycc.smartcanteen.server.websocket.event.RecvMessageEvent;
import com.bgycc.smartcanteen.server.websocket.event.SendMessageEvent;
import com.bgycc.smartcanteen.util.LogUtil;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.Utils;
import org.greenrobot.eventbus.EventBus;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
......@@ -49,7 +47,6 @@ public class MainWebSocket extends WebSocketClient {
private static MainWebSocket sInstance;
private static String sDeviceSN;
private static int sReconnectTimes = 0;
private static boolean sCanPing = true;
public static void initialize() {
if (sInstance == null) {
......@@ -59,12 +56,12 @@ public class MainWebSocket extends WebSocketClient {
EventBus.getDefault().post(new ConnectStateEvent(ConnectStateEvent.CONNECTING));
sInstance = new MainWebSocket(new URI(AppConfig.INSTANCE.getMainWebSocketServerUrl(sDeviceSN, BuildConfig.VERSION_NAME)));
sInstance.setConnectionLostTimeout(10);
sInstance.connect();
TimerHelper.INSTANCE.loop(new TimerHelper.LoopTask() {
long pingDelay = 0;
@Override
public void run(long id, boolean isLastTime) {
if (!sCanPing || sInstance.isClosed()) {
if (sInstance.isClosed()) {
if (sReconnectTimes < 2) {
sReconnectTimes++;
sInstance.reconnect();
......@@ -74,17 +71,6 @@ public class MainWebSocket extends WebSocketClient {
NetworkManager.INSTANCE.switchNetwork();
EventBus.getDefault().post(new ConnectStateEvent(ConnectStateEvent.CHANGE_NETWORK));
}
} else {
pingDelay--;
if (pingDelay <= 0) {
pingDelay = 5;
NetworkUtils.isAvailableByPingAsync(AppConfig.INSTANCE.getMainWebSocketServerHost(), new Utils.Callback<Boolean>() {
@Override
public void onCall(Boolean data) {
sCanPing = data;
}
});
}
}
}
}, 2000, -1, 2000);
......@@ -187,7 +173,6 @@ public class MainWebSocket extends WebSocketClient {
@Override
public void onOpen(ServerHandshake handshakeData) {
LogUtil.i(TAG, String.format("onOpen: %d %s", handshakeData.getHttpStatus(), handshakeData.getHttpStatusMessage()));
sCanPing = true;
sReconnectTimes = 0;
EventBus.getDefault().post(new ConnectStateEvent(ConnectStateEvent.CONNECTED));
}
......
package com.bgycc.smartcanteen
import android.util.Log
import org.junit.Test
import org.junit.Assert.*
import java.text.SimpleDateFormat
import java.util.*
/**
* Example local unit test, which will execute on the development machine (host).
......@@ -14,4 +17,9 @@ class ExampleUnitTest {
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
@Test
fun test() {
val date = SimpleDateFormat("yyyy-MM-dd").parse("2019-10-1 10:10:10")
Log.i("test", date.toLocaleString())
}
}
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