设备联调优化

This commit is contained in:
马增飞
2025-08-11 17:15:02 +08:00
parent 0d99c4f22a
commit 5b26e7e711
8 changed files with 171 additions and 51 deletions
+2
View File
@@ -73,6 +73,8 @@ dependencies {
implementation("io.github.scwang90:refresh-header-classics:3.0.0-alpha")
implementation("io.github.scwang90:refresh-footer-classics:3.0.0-alpha")
implementation("org.greenrobot:eventbus:3.3.1")
// implementation("io.github.jeremyliao:live-event-bus-x:1.8.0")
// implementation("com.hoho:android-usb-serial:1.3.0")
// implementation("io.github.jeadyx:jserialport:1.5")
@@ -13,14 +13,17 @@ import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter4.util.setOnDebouncedItemClick
import com.shuwei.intelligent.shelves.adapter.ShelfAdapter
import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityHomeBinding
import com.shuwei.intelligent.shelves.model.SendWeightEvent
import com.shuwei.intelligent.shelves.model.ShelfModel
import com.shuwei.intelligent.shelves.model.ShelfResult
import com.shuwei.intelligent.shelves.model.WeightEvent
import com.shuwei.intelligent.shelves.net.Loading
import com.shuwei.intelligent.shelves.net.NetViewModel
import com.shuwei.intelligent.shelves.net.RespData
@@ -36,6 +39,9 @@ import com.shuwei.intelligent.shelves.utils.hexToBinary
import com.shuwei.intelligent.shelves.utils.hexToDec
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -65,18 +71,21 @@ class HomeActivity : BaseActivity() {
const val DEVICE_INFO_CMD = "${HEADER}0301000000000000000000000000${FOOTER}"
val list: MutableList<ShelfModel> = mutableListOf()
val weightArray = SparseArray<Double?>()
var shelfIndex = 0
// public fun getRealWeight():Double = weightArray[shelfIndex]?:0.0
}
private lateinit var binding: ActivityHomeBinding
private val viewModel: NetViewModel by viewModels()
private val weightArray by lazy { SparseArray<Double?>() }
@SuppressLint("NotifyDataSetChanged", "HardwareIds")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHomeBinding.inflate(layoutInflater)
EventBus.getDefault().register(this)
setContentView(binding.root)
updateLeftStatus("1-1冷藏柜 -°C / -%")
@@ -316,12 +325,20 @@ class HomeActivity : BaseActivity() {
it.weight = realWeightDouble
val pos = list.indexOf(it)
shelfAdapter.notifyItemChanged(pos)
Log.d(TAG, "getWeightInfo: deviceNo=${it.deviceNo},realWeight=${realWeight}")
EventBus.getDefault().post(SendWeightEvent(it.deviceNo, realWeight))
}
}
count += 8
index++
}
// ShelfActivity.updateWeight(getRealWeight())
// if (list.isNotEmpty()) {
// val intent = Intent(ShelfActivity.RECEIVER_DEVICE_INFO + list[shelfIndex].deviceNo)
// intent.putExtra(ShelfActivity.SHELF_WEIGHT, weightArray[shelfIndex])
// LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
// }
}
private fun getDeviceInfo(data: String) {
@@ -343,21 +360,14 @@ class HomeActivity : BaseActivity() {
end = temperatureStartIndex,
data = data
)
if (list.isNotEmpty()) {
val intent = Intent(ShelfActivity.RECEIVER_DEVICE_INFO + list[shelfIndex].deviceNo)
intent.putExtra(ShelfActivity.SHELF_WEIGHT, weightArray[shelfIndex])
sendBroadcast(intent)
}
}
private var shelfIndex = 0
override fun onDestroy() {
lifecycleScope.launch {
SerialPortManager.close()
}
TaskManager.cancelTask()
EventBus.getDefault().unregister(this)
super.onDestroy()
}
@@ -365,7 +375,7 @@ class HomeActivity : BaseActivity() {
private val shelfAdapter by lazy {
ShelfAdapter(list).apply {
setOnDebouncedItemClick { adapter, view, position ->
this@HomeActivity.shelfIndex = position
shelfIndex = position
lifecycleScope.launch {
val openCmd = if (list[position].deviceNo in 1..5)
LEFT_SHELF_OPEN_CMD
@@ -449,4 +459,9 @@ class HomeActivity : BaseActivity() {
it.tvEmptyContent.setTextColor(Color.WHITE)
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public fun weightEvent(event: WeightEvent) {
}
}
@@ -9,7 +9,10 @@ import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.updateLayoutParams
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
@@ -23,21 +26,27 @@ import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityShelfBinding
import com.shuwei.intelligent.shelves.model.GoodsModel
import com.shuwei.intelligent.shelves.model.GoodsRecord
import com.shuwei.intelligent.shelves.model.SendWeightEvent
import com.shuwei.intelligent.shelves.model.ShelfModel
import com.shuwei.intelligent.shelves.net.Loading
import com.shuwei.intelligent.shelves.net.NetViewModel
import com.shuwei.intelligent.shelves.net.RespData
import com.shuwei.intelligent.shelves.net.UiState
import com.shuwei.intelligent.shelves.serial.SerialPortManager
import com.shuwei.intelligent.shelves.task.TaskManager
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
import com.shuwei.intelligent.shelves.utils.KeyboardUtil
import com.shuwei.intelligent.shelves.utils.ext.addOnActionSearchListener
import com.shuwei.intelligent.shelves.utils.ext.clickWithDebounce
import com.shuwei.intelligent.shelves.utils.ext.dp
import com.shuwei.intelligent.shelves.utils.ext.gone
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
import com.shuwei.intelligent.shelves.utils.ext.toast
import com.shuwei.intelligent.shelves.utils.ext.visible
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -55,6 +64,7 @@ class ShelfActivity : BaseActivity() {
const val SHELF_INDEX = "shelfIndex"
const val PAGE_SIZE = 100
}
private lateinit var binding: ActivityShelfBinding
@@ -65,7 +75,6 @@ class ShelfActivity : BaseActivity() {
private var realWeight: Int = 0
private var pageNo: Int = 1
private var shelfIndex: Int = 0
private val viewModel: NetViewModel by viewModels()
@@ -76,13 +85,15 @@ class ShelfActivity : BaseActivity() {
super.onCreate(savedInstanceState)
binding = ActivityShelfBinding.inflate(layoutInflater)
setContentView(binding.root)
EventBus.getDefault().register(this)
// tvFoodWeight =binding.tvFoodWeight
shelfModel = intent.getSerializableExtra(SHELF_MODEL) as ShelfModel?
shelfModel?.let {
binding.tvShelfName.text = it.shelfName
binding.tvFoodName.text = if (it.goodsName.isNullOrBlank()) "-" else it.goodsName
realWeight = ((it.weight ?: 0.0) * 1000).toInt()
// realWeight = (HomeActivity.getRealWeight() * 1000).toInt()
binding.tvFoodWeight.text = "${realWeight}"
}
@@ -137,9 +148,11 @@ class ShelfActivity : BaseActivity() {
SerialPortManager.send(zeroClearingCmd)
//清零
realWeight = 0
binding.tvFoodWeight.text = "${realWeight}"
// binding.tvFoodWeight.text = "${realWeight}克"
SerialPortManager.send(DEVICE_INFO_CMD)
Loading.show(this@ShelfActivity)
v.postDelayed({Loading.dismiss()}, 5000)
}
KeyboardUtil.hideKeyboard(v.context, v)
}
@@ -159,7 +172,7 @@ class ShelfActivity : BaseActivity() {
}
}
registerReceiver(receiver, IntentFilter(RECEIVER_DEVICE_INFO + shelfModel?.deviceNo))
// registerReceiver(receiver, IntentFilter(RECEIVER_DEVICE_INFO + shelfModel?.deviceNo))
binding.refreshLayout.let {
it.setEnableRefresh(true)
@@ -171,6 +184,8 @@ class ShelfActivity : BaseActivity() {
it.setOnLoadMoreListener { getGoodsList() }
}
getGoodsList()
TaskManager.startDeviceTask()
}
private fun finishRefresh() {
@@ -239,20 +254,23 @@ class ShelfActivity : BaseActivity() {
}
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
// val data = it.getStringExtra(RECEIVER_DEVICE_INFO)
val weight = it.getDoubleExtra(SHELF_WEIGHT, 0.0)
Log.d(TAG, "getDeviceInfo:onReceive: weight=$weight")
realWeight = (weight * 1000).toInt()
binding.tvFoodWeight.text = "${realWeight}"
}
}
}
// private val receiver = object : BroadcastReceiver() {
// override fun onReceive(context: Context?, intent: Intent?) {
// intent?.let {
// if (it.action == RECEIVER_DEVICE_INFO + shelfModel?.deviceNo) {
// val weight = it.getDoubleExtra(SHELF_WEIGHT, 0.0)
// Log.d(TAG, "getDeviceInfo:onReceive: weight=$weight")
// realWeight = (weight * 1000).toInt()
// binding.tvFoodWeight.text = "${realWeight}克"
// }
// }
// }
// }
override fun onDestroy() {
unregisterReceiver(receiver)
// unregisterReceiver(receiver)
EventBus.getDefault().unregister(this)
TaskManager.cancelDeviceTask()
super.onDestroy()
}
@@ -315,6 +333,9 @@ class ShelfActivity : BaseActivity() {
getGoodsList()
}
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_gray)
it.ivEmptyIcon.updateLayoutParams<LinearLayout.LayoutParams> {
width = 200.dp
}
}
binding.refreshLayout.run {
setEnableRefresh(false)
@@ -322,4 +343,11 @@ class ShelfActivity : BaseActivity() {
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public fun receiveWeightEvent(event: SendWeightEvent) {
if (event.shelfNo == (shelfModel?.deviceNo?:0)) {
binding.tvFoodWeight.text = "${event.weight}"
}
}
}
@@ -0,0 +1,8 @@
package com.shuwei.intelligent.shelves.model
data class SendWeightEvent(
var shelfNo: Int = 0,
var weight:Int=0
)
data class WeightEvent(var weight: Int)
@@ -0,0 +1,32 @@
package com.shuwei.intelligent.shelves.task
import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.shuwei.intelligent.shelves.HomeActivity
import com.shuwei.intelligent.shelves.serial.SerialPortManager
class SyncDeviceTask(appContext: Context, workerParams: WorkerParameters) :
CoroutineWorker(appContext, workerParams) {
companion object {
private const val TAG = "SyncDeviceTask"
}
override suspend fun doWork(): Result {
return try {
// 执行后台任务逻辑
Log.d(TAG, "doWork: ----------SyncDeviceTask----------")
SerialPortManager.send(HomeActivity.DEVICE_INFO_CMD)
TaskManager.startDeviceTask()
Result.success()
} catch (e: Exception) {
e.printStackTrace()
Result.retry()
}
}
}
@@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit
object TaskManager {
const val TASK_NAME = "IntelligentShelvesSyncTask"
const val DEVICE_TASK_NAME = "IntelligentShelvesDeviceTask"
fun startTask() {
val nextRequest = OneTimeWorkRequestBuilder<SyncTask>()
@@ -41,4 +42,17 @@ object TaskManager {
.cancelUniqueWork(TASK_NAME)
}
fun startDeviceTask() {
val nextRequest = OneTimeWorkRequestBuilder<SyncDeviceTask>()
.setInitialDelay(3, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(App.getInstance())
.enqueueUniqueWork(DEVICE_TASK_NAME, ExistingWorkPolicy.REPLACE, nextRequest)
}
fun cancelDeviceTask() {
WorkManager.getInstance(App.getInstance())
.cancelUniqueWork(DEVICE_TASK_NAME)
}
}
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
@@ -17,4 +17,11 @@
android:layout_marginEnd="12dp"
tools:listitem="@layout/list_item_shelf"/>
</LinearLayout>
<include
android:id="@+id/include"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/layout_empty_view"
android:visibility="gone"/>
</FrameLayout>
@@ -156,12 +156,17 @@
android:textSize="30sp"
tools:ignore="Autofill,HardcodedText,TextFields" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="24dp">
<com.scwang.smart.refresh.layout.SmartRefreshLayout
android:id="@+id/refreshLayout"
android:layout_width="match_parent"
android:layout_marginTop="24dp"
android:layout_height="0dp"
android:layout_weight="1">
android:layout_height="match_parent">
<com.scwang.smart.refresh.header.ClassicsHeader
android:layout_width="match_parent"
@@ -188,6 +193,15 @@
</com.scwang.smart.refresh.layout.SmartRefreshLayout>
<include
android:id="@+id/include"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/layout_empty_view"
android:visibility="gone"/>
</FrameLayout>
<!-- android:layout_marginTop="48dp"-->
<com.google.android.material.button.MaterialButton
android:id="@+id/btnConfirm"