Compare commits
85
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03e6c9a6bb | ||
|
|
c77c32fde1 | ||
|
|
dec5ecc100 | ||
|
|
5dc0bb2ec5 | ||
|
|
c3682d1ed3 | ||
|
|
e902f2869f | ||
|
|
867cbb77be | ||
|
|
8aaba07cb6 | ||
|
|
4f1a9dd0a1 | ||
|
|
694e20023a | ||
|
|
ac17fca325 | ||
|
|
4b8e5f84e6 | ||
|
|
d6ba6cf527 | ||
|
|
4408acfca4 | ||
|
|
b0739605b9 | ||
|
|
d524da1af3 | ||
|
|
967d06ce1e | ||
|
|
d5c6ec92d4 | ||
|
|
7b28eb03d6 | ||
|
|
4d545ceb46 | ||
|
|
0eede1059c | ||
|
|
8145eb588b | ||
|
|
c91d5656aa | ||
|
|
532b22a5c6 | ||
|
|
e9d04bfb70 | ||
|
|
afba5220b3 | ||
|
|
4ace12c6c7 | ||
|
|
ee36869003 | ||
|
|
c23c215941 | ||
|
|
3d67dd2c2d | ||
|
|
133f309d4b | ||
|
|
3e5c7c6caa | ||
|
|
04fe3ec2c1 | ||
|
|
9a795b9710 | ||
|
|
fff6a2a3b3 | ||
|
|
3b79f6d6aa | ||
|
|
76b67b545d | ||
|
|
3bd60990b9 | ||
|
|
a116c4fc6c | ||
|
|
40cd27fa7b | ||
|
|
e6cfc4dff2 | ||
|
|
85903eb646 | ||
|
|
11e6123cc9 | ||
|
|
14d8064b13 | ||
|
|
8006b0d077 | ||
|
|
dbb7ccf8c7 | ||
|
|
3ff58641aa | ||
|
|
5d58cdc4cf | ||
|
|
9a222037ea | ||
|
|
247a332ff3 | ||
|
|
2fe0381987 | ||
|
|
7e32268a4c | ||
|
|
5b0b98c8b8 | ||
|
|
aff3d5cc69 | ||
|
|
6d1b997145 | ||
|
|
ad669e421b | ||
|
|
119a69bbbc | ||
|
|
096499cd65 | ||
|
|
79d14ca300 | ||
|
|
f8eeb83c6f | ||
|
|
99001fff2f | ||
|
|
10059bf4f6 | ||
|
|
32ea2f1379 | ||
|
|
c20ce471cb | ||
|
|
3366fc02e5 | ||
|
|
647ec0dcb7 | ||
|
|
61c9452295 | ||
|
|
a0737ebbc3 | ||
|
|
a811d296d9 | ||
|
|
9c2c5f073e | ||
|
|
a355828bab | ||
|
|
e153f3e3b9 | ||
|
|
ca2041fe76 | ||
|
|
f8453c7d76 | ||
|
|
2162ba0c9e | ||
|
|
5b26e7e711 | ||
|
|
0d99c4f22a | ||
|
|
9e5ede4a8e | ||
|
|
0b52dad0fe | ||
|
|
383c354f29 | ||
|
|
65199f4c70 | ||
|
|
eb66c2d2ff | ||
|
|
e7e062ebcb | ||
|
|
4d91b9d338 | ||
|
|
c409621e28 |
+39
-12
@@ -4,14 +4,22 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
|
signingConfigs {
|
||||||
|
getByName("debug") {
|
||||||
|
storeFile = file("../app/swkey.jks")
|
||||||
|
storePassword = "123456"
|
||||||
|
keyPassword = "123456"
|
||||||
|
keyAlias = "android"
|
||||||
|
}
|
||||||
|
}
|
||||||
namespace = "com.shuwei.intelligent.shelves"
|
namespace = "com.shuwei.intelligent.shelves"
|
||||||
compileSdk = 34
|
compileSdk = 34
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.shuwei.intelligent.shelves"
|
applicationId = "com.shuwei.intelligent.shelves"
|
||||||
minSdk = 25
|
minSdk = 25
|
||||||
//noinspection ExpiredTargetSdkVersion
|
//noinspection EditedTargetSdkVersion,ExpiredTargetSdkVersion
|
||||||
targetSdk = 25
|
targetSdk = 30
|
||||||
versionCode = 1
|
versionCode = 1
|
||||||
versionName = "1.0"
|
versionName = "1.0"
|
||||||
|
|
||||||
@@ -36,33 +44,52 @@ android {
|
|||||||
}
|
}
|
||||||
buildFeatures {
|
buildFeatures {
|
||||||
viewBinding = true
|
viewBinding = true
|
||||||
|
buildConfig = true
|
||||||
}
|
}
|
||||||
|
|
||||||
ndkVersion = "29.0.13846066"
|
ndkVersion = "29.0.13846066"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//noinspection UseTomlInstead
|
||||||
dependencies {
|
dependencies {
|
||||||
//implementation(fileTree("libs") { include("*.jar", "*.aar") })
|
//implementation(fileTree("libs") { include("*.jar", "*.aar") })
|
||||||
implementation(libs.androidx.core.ktx)
|
implementation(libs.androidx.core.ktx)
|
||||||
implementation(libs.androidx.appcompat)
|
implementation(libs.androidx.appcompat)
|
||||||
implementation(libs.material)
|
implementation(libs.material)
|
||||||
|
implementation(libs.android.core)
|
||||||
|
implementation(libs.core)
|
||||||
testImplementation(libs.junit)
|
testImplementation(libs.junit)
|
||||||
androidTestImplementation(libs.androidx.junit)
|
androidTestImplementation(libs.androidx.junit)
|
||||||
androidTestImplementation(libs.androidx.espresso.core)
|
androidTestImplementation(libs.androidx.espresso.core)
|
||||||
implementation("androidx.activity:activity-ktx:1.8.0")
|
implementation("androidx.activity:activity-ktx:1.8.0")
|
||||||
|
implementation("androidx.work:work-runtime-ktx:2.8.1")
|
||||||
|
|
||||||
implementation("io.github.cymchad:BaseRecyclerViewAdapterHelper4:4.1.2")
|
implementation("io.github.cymchad:BaseRecyclerViewAdapterHelper4:4.1.2")
|
||||||
|
|
||||||
implementation("com.squareup.okhttp3:okhttp:4.9.1")
|
|
||||||
implementation("com.google.code.gson:gson:2.10.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:kmp-serialport:1.0.0")
|
implementation("io.github.jeadyx:kmp-serialport:1.0.0")
|
||||||
|
|
||||||
// implementation("io.github.jeadyx:jserialport:1.5")
|
// // 基础依赖包,必须要依赖
|
||||||
|
// implementation("com.geyifeng.immersionbar:immersionbar:3.2.2")
|
||||||
|
// // kotlin扩展(可选)
|
||||||
|
// implementation("com.geyifeng.immersionbar:immersionbar-ktx:3.2.2")
|
||||||
|
|
||||||
implementation("androidx.work:work-runtime-ktx:2.8.1")
|
implementation("com.squareup.okhttp3:okhttp:4.9.1")
|
||||||
|
implementation("com.squareup.okhttp3:logging-interceptor:4.9.1")
|
||||||
|
implementation("com.google.code.gson:gson:2.10.1")
|
||||||
|
implementation("com.squareup.retrofit2:retrofit:2.9.0")
|
||||||
|
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2")
|
||||||
|
|
||||||
|
implementation("io.github.scwang90:refresh-layout-kernel:3.0.0-alpha")
|
||||||
|
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("com.google.android.flexbox:flexbox:3.0.0")
|
||||||
|
|
||||||
|
// 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")
|
||||||
}
|
}
|
||||||
@@ -2,22 +2,31 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
xmlns:tools="http://schemas.android.com/tools">
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
|
||||||
|
tools:ignore="ProtectedPermissions" />
|
||||||
<uses-permission android:name="android.permission.USB_PERMISSION" />
|
<uses-permission android:name="android.permission.USB_PERMISSION" />
|
||||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
|
||||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||||
|
tools:ignore="ScopedStorage" />
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:name=".App"
|
android:name=".App"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
android:fullBackupContent="@xml/backup_rules"
|
android:fullBackupContent="@xml/backup_rules"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_logo512"
|
||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
|
android:roundIcon="@mipmap/ic_logo512"
|
||||||
android:supportsRtl="true"
|
android:supportsRtl="true"
|
||||||
android:theme="@style/Theme.IntelligentShelves">
|
android:theme="@style/Theme.IntelligentShelves"
|
||||||
|
android:usesCleartextTraffic="true">
|
||||||
<activity
|
<activity
|
||||||
android:name=".HomeActivity"
|
android:name=".activity.InitActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity">
|
tools:ignore="DiscouragedApi,LockedOrientationActivity">
|
||||||
@@ -28,9 +37,25 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
<activity
|
<activity
|
||||||
android:name=".ShelfActivity"
|
android:name=".activity.HomeActivity"
|
||||||
|
android:screenOrientation="portrait"/>
|
||||||
|
<activity
|
||||||
|
android:name=".activity.ShelfActivity"
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
<!-- <activity android:name="com.shuwei.intelligent.shelves.activity.SettingActivity" />-->
|
||||||
|
<activity android:name="com.shuwei.intelligent.shelves.activity.LogActivity" />
|
||||||
|
<activity android:name="com.shuwei.intelligent.shelves.activity.HomeV2Activity" />
|
||||||
|
<activity android:name="com.shuwei.intelligent.shelves.activity.ShelfV2Activity" />
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".utils.BootReceiver"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.BOOT_COMPLETED"/>
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
</application>
|
</application>
|
||||||
|
|
||||||
</manifest>
|
</manifest>
|
||||||
@@ -1,23 +1,78 @@
|
|||||||
package com.shuwei.intelligent.shelves
|
package com.shuwei.intelligent.shelves
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.IntentFilter
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import com.shuwei.intelligent.shelves.utils.BootReceiver
|
||||||
|
import com.shuwei.intelligent.shelves.utils.CrashHandler
|
||||||
|
import com.shuwei.intelligent.shelves.utils.FileLogger
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author: star
|
* @author: star
|
||||||
* @date: 2022-04-26
|
* @date: 2022-04-26
|
||||||
*/
|
*/
|
||||||
class App : Application() {
|
class App : Application() {
|
||||||
|
//"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjYW50ZWVuSWQiOiIiLCJ0eXBlIjoiNiIsInVzZXJJZCI6IjE2NzgyMjY1NTI5MzE1NDkxODYifQ.CQmbELpqT6QzvVCgCeirwvSvPp8Mhft_h6b1Af574Co"
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
app = this
|
app = this
|
||||||
|
CrashHandler.init(this)
|
||||||
|
// 启动时立即清理一次过期日志
|
||||||
|
cleanupLogs()
|
||||||
|
// 设备长期不断电、进程不会重新启动,运行中每24小时定期清理一次
|
||||||
|
logCleanupHandler.postDelayed(logCleanupRunnable, LOG_CLEANUP_INTERVAL)
|
||||||
|
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
|
||||||
|
registerReceiver(BootReceiver(), filter)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理过期的日志文件:文件日志与崩溃日志均保留最近7天
|
||||||
|
*/
|
||||||
|
private fun cleanupLogs() {
|
||||||
|
FileLogger.cleanupExpiredLogs(this)
|
||||||
|
CrashHandler.getInstance()?.cleanupOldCrashReports()
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private lateinit var app: App
|
private lateinit var app: App
|
||||||
|
var canteenId = "0"
|
||||||
|
var appVersion = "1"
|
||||||
|
var configUrl = ""
|
||||||
|
|
||||||
fun get(): App {
|
//从接口获取
|
||||||
|
var accessToken: String = ""
|
||||||
|
|
||||||
|
var deviceId: String = ""
|
||||||
|
@Volatile
|
||||||
|
private var sharedPref: SharedPreferences? = null
|
||||||
|
|
||||||
|
/** 日志定期清理间隔:24小时,与日志文件按天滚动对齐 */
|
||||||
|
private const val LOG_CLEANUP_INTERVAL = 24L * 60 * 60 * 1000
|
||||||
|
|
||||||
|
private val logCleanupHandler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
/** 日志定期清理任务:执行后重新调度自身,形成循环 */
|
||||||
|
private val logCleanupRunnable = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
getInstance().cleanupLogs()
|
||||||
|
logCleanupHandler.postDelayed(this, LOG_CLEANUP_INTERVAL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getInstance(): App {
|
||||||
return app
|
return app
|
||||||
}
|
}
|
||||||
|
fun getSharedPref(): SharedPreferences? {
|
||||||
|
if (sharedPref != null) {
|
||||||
|
return sharedPref
|
||||||
|
}
|
||||||
|
sharedPref = app.getSharedPreferences("sp_intelligent_shelves", Context.MODE_PRIVATE)
|
||||||
|
return sharedPref
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.shuwei.intelligent.shelves
|
||||||
|
|
||||||
|
object GlobalData {
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * 设备id
|
||||||
|
// */
|
||||||
|
// var deviceId: String = ""
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * app版本号
|
||||||
|
// */
|
||||||
|
// var appVersion: String = "1"
|
||||||
|
|
||||||
|
var appBaseUrl: String = ""
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 具体业务 BaseUrl
|
||||||
|
*/
|
||||||
|
// const val LOCAL_BASE_URL = "http://192.168.1.201:14801"
|
||||||
|
const val LOCAL_BASE_URL = "http://192.168.10.101:24801"
|
||||||
|
const val TEST_BASE_URL = "https://dev.yixiong-tech.com:8081"
|
||||||
|
const val PROD_BASE_URL = "https://platform-api.uat.shuziweidao.com"
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全局常量
|
||||||
|
*/
|
||||||
|
object Constants {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* key
|
||||||
|
*/
|
||||||
|
object GlobalKey {
|
||||||
|
const val KEY_BASE_URL = "baseUrlKey"
|
||||||
|
}
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
package com.shuwei.intelligent.shelves
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.content.Intent
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.Looper
|
|
||||||
import android.util.Log
|
|
||||||
import android.util.SparseIntArray
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
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.ShelfModel
|
|
||||||
import com.shuwei.intelligent.shelves.serial.SerialPortManager
|
|
||||||
import com.shuwei.intelligent.shelves.task.TaskManager
|
|
||||||
import com.shuwei.intelligent.shelves.utils.UIUtils
|
|
||||||
import com.shuwei.intelligent.shelves.utils.hexToDec
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import java.text.SimpleDateFormat
|
|
||||||
import java.util.Date
|
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
class HomeActivity : BaseActivity() {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "HomeActivity"
|
|
||||||
|
|
||||||
//协议头
|
|
||||||
const val HEADER = "D6DADEDB"
|
|
||||||
|
|
||||||
//协议尾
|
|
||||||
const val FOOTER = "FFFF"
|
|
||||||
const val ACTIVE_CMD =
|
|
||||||
"${HEADER}000281C5D70A7D428A4FA67B50F7DACA241938938B4B9CBD73673E9C8E7F2E15062D${FOOTER}"
|
|
||||||
|
|
||||||
const val LEFT_SHELF_OPEN_CMD =
|
|
||||||
"${HEADER}020101000000000000000000000000000000000000${FOOTER}"
|
|
||||||
const val RIGHT_SHELF_OPEN_CMD =
|
|
||||||
"${HEADER}020100010000000000000000000000000000000000${FOOTER}"
|
|
||||||
|
|
||||||
//const val TEMPERATURE_CMD = "${HEADER}1001${FOOTER}"
|
|
||||||
|
|
||||||
const val DEVICE_INFO_CMD = "${HEADER}0301000000000000000000000000${FOOTER}"
|
|
||||||
|
|
||||||
val list: MutableList<ShelfModel> = mutableListOf()
|
|
||||||
}
|
|
||||||
|
|
||||||
private lateinit var binding: ActivityHomeBinding
|
|
||||||
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
binding = ActivityHomeBinding.inflate(layoutInflater)
|
|
||||||
setContentView(binding.root)
|
|
||||||
|
|
||||||
updateLeftStatus("1-1冷藏柜 -2°C / 87%")
|
|
||||||
|
|
||||||
initList()
|
|
||||||
initRecyclerView()
|
|
||||||
|
|
||||||
lifecycleScope.launch {
|
|
||||||
val openState = SerialPortManager.open()
|
|
||||||
Log.d(TAG, "onCreate: openState=$openState")
|
|
||||||
if (openState) {
|
|
||||||
SerialPortManager.startReceive { data ->
|
|
||||||
runOnUiThread {
|
|
||||||
// 更新UI显示接收数据
|
|
||||||
runCatching {
|
|
||||||
receiveSerialPortData(data)
|
|
||||||
}.onFailure {
|
|
||||||
it.printStackTrace()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
SerialPortManager.send(ACTIVE_CMD)
|
|
||||||
|
|
||||||
SerialPortManager.send(DEVICE_INFO_CMD)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
TaskManager.startTask()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun receiveSerialPortData(data: String) {
|
|
||||||
Log.d(TAG, "receiveSerialPortData: $data")
|
|
||||||
if (data.startsWith(HEADER).not()) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val cmd = data.substring(HEADER.length, HEADER.length + 2)
|
|
||||||
when (cmd) {
|
|
||||||
"03" -> {
|
|
||||||
//获取设备状态
|
|
||||||
val weightStartIndex = HEADER.length + 4 + 10
|
|
||||||
val temperatureStartIndex = weightStartIndex + 10 * 8
|
|
||||||
val temperatureHex = data.substring(temperatureStartIndex, 2)
|
|
||||||
val temperature = hexToDec(temperatureHex)
|
|
||||||
updateLeftStatus("1-1冷藏柜 $temperature°C / 87%")
|
|
||||||
|
|
||||||
var index = 1
|
|
||||||
var count = weightStartIndex
|
|
||||||
while (count < temperatureStartIndex) {
|
|
||||||
val weightInfo = data.substring(count, count + 8)
|
|
||||||
var weightHex = ""
|
|
||||||
weightInfo.run {
|
|
||||||
weightHex =
|
|
||||||
substring(6, 8) + substring(4, 6) + substring(2, 4) + substring(0, 2)
|
|
||||||
}
|
|
||||||
var realWeight = 0
|
|
||||||
if (weightHex.first() in '8'..'F') {
|
|
||||||
//负数
|
|
||||||
val weightHex2 = "0${weightHex.substring(1)}"
|
|
||||||
realWeight = hexToDec(weightHex2)
|
|
||||||
} else {
|
|
||||||
//整数
|
|
||||||
realWeight = hexToDec(weightHex)
|
|
||||||
}
|
|
||||||
weightArray.put(count, realWeight)
|
|
||||||
count += 8
|
|
||||||
index++
|
|
||||||
}
|
|
||||||
|
|
||||||
val intent = Intent(ShelfActivity.RECEIVER_DEVICE_INFO)
|
|
||||||
intent.putExtra(ShelfActivity.SHELF_WEIGHT, weightArray[clickIndex])
|
|
||||||
intent.putExtra(ShelfActivity.RECEIVER_DEVICE_INFO, data)
|
|
||||||
sendBroadcast(intent)
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private val weightArray by lazy { SparseIntArray() }
|
|
||||||
private var clickIndex = 0
|
|
||||||
|
|
||||||
override fun onDestroy() {
|
|
||||||
lifecycleScope.launch {
|
|
||||||
SerialPortManager.close()
|
|
||||||
}
|
|
||||||
TaskManager.cancelTask()
|
|
||||||
super.onDestroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
private val shelfAdapter by lazy {
|
|
||||||
// val list = viewModel.getCurrentItems()
|
|
||||||
ShelfAdapter(list).apply {
|
|
||||||
setOnDebouncedItemClick { adapter, view, position ->
|
|
||||||
this@HomeActivity.clickIndex = position
|
|
||||||
lifecycleScope.launch {
|
|
||||||
val openCmd = if (list[position].shelfNo in 1..5)
|
|
||||||
LEFT_SHELF_OPEN_CMD
|
|
||||||
else
|
|
||||||
RIGHT_SHELF_OPEN_CMD
|
|
||||||
val openState = SerialPortManager.send(openCmd)
|
|
||||||
if (openState.not()) {
|
|
||||||
UIUtils.toast("${list[position].foodName}柜门开启失败")
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
launch(Intent(this@HomeActivity, ShelfActivity::class.java).also {
|
|
||||||
it.putExtra(ShelfActivity.SHELF_MODEL, list[position])
|
|
||||||
}) {
|
|
||||||
it?.run {
|
|
||||||
val model =
|
|
||||||
getSerializableExtra(ShelfActivity.SHELF_MODEL) as ShelfModel
|
|
||||||
list[position].apply {
|
|
||||||
foodName = model.foodName
|
|
||||||
foodWeight = model.foodWeight
|
|
||||||
storeDate = model.storeDate
|
|
||||||
}
|
|
||||||
notifyItemChanged(position)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun initRecyclerView() {
|
|
||||||
binding.rvShelf.run {
|
|
||||||
layoutManager =
|
|
||||||
GridLayoutManager(this@HomeActivity, 2, GridLayoutManager.VERTICAL, false)
|
|
||||||
adapter = shelfAdapter
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun initList() {
|
|
||||||
// val list: MutableList<ShelfModel> = mutableListOf()
|
|
||||||
list.add(ShelfModel(shelfNo = 1))
|
|
||||||
list.add(ShelfModel(shelfNo = 6))
|
|
||||||
list.add(ShelfModel(shelfNo = 2))
|
|
||||||
list.add(ShelfModel(shelfNo = 7))
|
|
||||||
list.add(ShelfModel(shelfNo = 3))
|
|
||||||
list.add(ShelfModel(shelfNo = 8))
|
|
||||||
list.add(ShelfModel(shelfNo = 4))
|
|
||||||
list.add(ShelfModel(shelfNo = 9))
|
|
||||||
list.add(ShelfModel(shelfNo = 5))
|
|
||||||
list.add(ShelfModel(shelfNo = 10))
|
|
||||||
// viewModel.updateItems(list)
|
|
||||||
}
|
|
||||||
|
|
||||||
private val MM_DD_EEEE__HH_MM_SS = "MM月dd日 EEEE HH:mm:ss"
|
|
||||||
|
|
||||||
private fun updateDateTime() {
|
|
||||||
val sdf = SimpleDateFormat(MM_DD_EEEE__HH_MM_SS, Locale.CHINA)
|
|
||||||
val dateTime = sdf.format(Date())
|
|
||||||
updateRightStatus(dateTime)
|
|
||||||
}
|
|
||||||
|
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
|
||||||
private val updateTask = object : Runnable {
|
|
||||||
override fun run() {
|
|
||||||
updateDateTime()
|
|
||||||
handler.postDelayed(this, 1000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onResume() {
|
|
||||||
super.onResume()
|
|
||||||
hideStatusBar()
|
|
||||||
handler.post(updateTask)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPause() {
|
|
||||||
super.onPause()
|
|
||||||
handler.removeCallbacks(updateTask)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,212 +0,0 @@
|
|||||||
package com.shuwei.intelligent.shelves
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.content.BroadcastReceiver
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.IntentFilter
|
|
||||||
import android.os.Build
|
|
||||||
import android.os.Bundle
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.Looper
|
|
||||||
import android.util.Log
|
|
||||||
import androidx.annotation.RequiresApi
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import androidx.recyclerview.widget.GridLayoutManager
|
|
||||||
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
|
||||||
import com.shuwei.intelligent.shelves.HomeActivity.Companion.ACTIVE_CMD
|
|
||||||
import com.shuwei.intelligent.shelves.HomeActivity.Companion.DEVICE_INFO_CMD
|
|
||||||
import com.shuwei.intelligent.shelves.utils.ext.addOnActionSearchListener
|
|
||||||
import com.shuwei.intelligent.shelves.utils.ext.clickWithDebounce
|
|
||||||
import com.shuwei.intelligent.shelves.utils.ext.toast
|
|
||||||
import com.shuwei.intelligent.shelves.adapter.SearchAdapter
|
|
||||||
import com.shuwei.intelligent.shelves.base.BaseActivity
|
|
||||||
import com.shuwei.intelligent.shelves.databinding.ActivityShelfBinding
|
|
||||||
import com.shuwei.intelligent.shelves.model.SearchModel
|
|
||||||
import com.shuwei.intelligent.shelves.model.ShelfModel
|
|
||||||
import com.shuwei.intelligent.shelves.serial.SerialPortManager
|
|
||||||
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
|
|
||||||
import com.shuwei.intelligent.shelves.utils.KeyboardUtil
|
|
||||||
import com.shuwei.intelligent.shelves.utils.decToHex
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import java.text.SimpleDateFormat
|
|
||||||
import java.util.Date
|
|
||||||
import java.util.Locale
|
|
||||||
import kotlin.random.Random
|
|
||||||
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
|
||||||
class ShelfActivity : BaseActivity() {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "ShelfActivity"
|
|
||||||
const val SHELF_MODEL = "shelfModel"
|
|
||||||
const val RECEIVER_DEVICE_INFO = "receiverDeviceInfo"
|
|
||||||
const val SHELF_WEIGHT = "shelfWeight"
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private lateinit var binding: ActivityShelfBinding
|
|
||||||
|
|
||||||
private var shelfModel: ShelfModel? = null
|
|
||||||
|
|
||||||
private var clickIndex: Int = -1
|
|
||||||
|
|
||||||
private var realWeight: Int = 0
|
|
||||||
|
|
||||||
@SuppressLint("UnspecifiedRegisterReceiverFlag")
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
binding = ActivityShelfBinding.inflate(layoutInflater)
|
|
||||||
setContentView(binding.root)
|
|
||||||
|
|
||||||
shelfModel = intent.getSerializableExtra(SHELF_MODEL) as ShelfModel?
|
|
||||||
|
|
||||||
shelfModel?.let {
|
|
||||||
binding.tvShelfName.text = it.shelfName
|
|
||||||
binding.tvFoodName.text = if (it.foodName.isNullOrBlank()) "-" else it.foodName
|
|
||||||
}
|
|
||||||
|
|
||||||
initRecyclerView()
|
|
||||||
// initWeight()
|
|
||||||
binding.etInputFood.run {
|
|
||||||
addOnActionSearchListener {
|
|
||||||
if (text.isNullOrBlank()) {
|
|
||||||
toast(hint.toString())
|
|
||||||
return@addOnActionSearchListener
|
|
||||||
}
|
|
||||||
loadSearchData()
|
|
||||||
KeyboardUtil.hideKeyboard(context, this)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
binding.btnConfirm.clickWithDebounce {
|
|
||||||
if (clickIndex < 0) {
|
|
||||||
toast("请选择食材")
|
|
||||||
return@clickWithDebounce
|
|
||||||
}
|
|
||||||
val data = ShelfModel(
|
|
||||||
shelfName = shelfModel?.shelfName,
|
|
||||||
foodName = list[clickIndex].foodName,
|
|
||||||
foodWeight = realWeight,
|
|
||||||
storeDate = DateTimeUtil.formatDateTime(dateTime = Date())
|
|
||||||
)
|
|
||||||
val intent = Intent().apply {
|
|
||||||
putExtra(SHELF_MODEL, data)
|
|
||||||
}
|
|
||||||
setResult(RESULT_OK, intent)
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
binding.tvFoodWeight.text = "${realWeight}克"
|
|
||||||
binding.root.setOnClickListener { v ->
|
|
||||||
KeyboardUtil.hideKeyboard(v.context, v)
|
|
||||||
}
|
|
||||||
binding.btnClearZero.setOnClickListener { v ->
|
|
||||||
lifecycleScope.launch {
|
|
||||||
val shelfNo = shelfModel?.shelfNo ?: 0
|
|
||||||
val zeroClearingCmd =
|
|
||||||
"${HomeActivity.HEADER}0401${decToHex(shelfNo)}${HomeActivity.FOOTER}"
|
|
||||||
SerialPortManager.send(zeroClearingCmd)
|
|
||||||
}
|
|
||||||
KeyboardUtil.hideKeyboard(v.context, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
lifecycleScope.launch {
|
|
||||||
SerialPortManager.send(DEVICE_INFO_CMD)
|
|
||||||
}
|
|
||||||
|
|
||||||
registerReceiver(receiver, IntentFilter(RECEIVER_DEVICE_INFO))
|
|
||||||
}
|
|
||||||
|
|
||||||
private val receiver = object : BroadcastReceiver() {
|
|
||||||
override fun onReceive(context: Context?, intent: Intent?) {
|
|
||||||
intent?.let {
|
|
||||||
val data = it.getStringExtra(RECEIVER_DEVICE_INFO)
|
|
||||||
Log.d(TAG, "onReceive: $data")
|
|
||||||
realWeight = it.getIntExtra(SHELF_WEIGHT, 0)
|
|
||||||
binding.tvFoodWeight.text = "${realWeight}克"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDestroy() {
|
|
||||||
unregisterReceiver(receiver)
|
|
||||||
super.onDestroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
// private fun initWeight() {
|
|
||||||
// realWeight = Random.nextInt(1, 5001)
|
|
||||||
// }
|
|
||||||
|
|
||||||
private fun loadSearchData() {
|
|
||||||
list.add(SearchModel(foodId = 1000, foodName = "菲律宾乳猪五花肉"))
|
|
||||||
list.add(SearchModel(foodId = 1001, foodName = "金针菇"))
|
|
||||||
list.add(SearchModel(foodId = 1002, foodName = "大菠菜"))
|
|
||||||
list.add(SearchModel(foodId = 1003, foodName = "清远麻鸡块"))
|
|
||||||
list.add(SearchModel(foodId = 1004, foodName = "普罗旺斯番茄"))
|
|
||||||
list.add(SearchModel(foodId = 1005, foodName = "长条茄子"))
|
|
||||||
list.add(SearchModel(foodId = 1006, foodName = "得莫利鱼"))
|
|
||||||
list.add(SearchModel(foodId = 1007, foodName = "土豆丝"))
|
|
||||||
list.add(SearchModel(foodId = 1008, foodName = "辣椒炒肉"))
|
|
||||||
list.add(SearchModel(foodId = 1009, foodName = "雪菜烧豆腐"))
|
|
||||||
list.add(SearchModel(foodId = 1010, foodName = "冬虫夏草炝拌芥兰苗"))
|
|
||||||
list.add(
|
|
||||||
SearchModel(
|
|
||||||
foodId = 1011,
|
|
||||||
foodName = "蘑菇玉米山药莲藕胡萝卜红枣莲子枸杞清炖排骨汤"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
searchAdapter.notifyDataSetChanged()
|
|
||||||
}
|
|
||||||
|
|
||||||
private val list: MutableList<SearchModel> = mutableListOf()
|
|
||||||
private val searchAdapter by lazy {
|
|
||||||
SearchAdapter(list).apply {
|
|
||||||
setOnDebouncedItemClick { adapter, v, position ->
|
|
||||||
this@ShelfActivity.clickIndex = position
|
|
||||||
list.forEach { it.isClicked = false }
|
|
||||||
list[position].isClicked = true
|
|
||||||
notifyDataSetChanged()
|
|
||||||
binding.tvFoodName.text = list[position].foodName
|
|
||||||
KeyboardUtil.hideKeyboard(v.context, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun initRecyclerView() {
|
|
||||||
binding.rvSearch.run {
|
|
||||||
layoutManager = GridLayoutManager(this@ShelfActivity, 2)
|
|
||||||
adapter = searchAdapter
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private val YYYY_MM_DD__EEEE_HH_MM_SS = "yyyy年MM月dd日 EEEE***HH:mm:ss"
|
|
||||||
|
|
||||||
private fun updateDateTime() {
|
|
||||||
val sdf = SimpleDateFormat(YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
|
|
||||||
val dateTime = sdf.format(Date())
|
|
||||||
val arr = dateTime.split("***")
|
|
||||||
updateLeftStatus(arr[0])
|
|
||||||
updateRightStatus(arr[1])
|
|
||||||
}
|
|
||||||
|
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
|
||||||
private val updateTask = object : Runnable {
|
|
||||||
override fun run() {
|
|
||||||
updateDateTime()
|
|
||||||
handler.postDelayed(this, 1000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onResume() {
|
|
||||||
super.onResume()
|
|
||||||
hideStatusBar()
|
|
||||||
handler.post(updateTask)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPause() {
|
|
||||||
super.onPause()
|
|
||||||
handler.removeCallbacks(updateTask)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,463 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.activity
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Intent
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import androidx.activity.addCallback
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
|
import androidx.recyclerview.widget.DefaultItemAnimator
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
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.dialog.CommonDialog
|
||||||
|
import com.shuwei.intelligent.shelves.model.ClearShelfEvent
|
||||||
|
import com.shuwei.intelligent.shelves.model.SendWeightEvent
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfBody
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfResult
|
||||||
|
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.ProtocolConstants
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.C_TEMP_CMD
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.START_TEMP_CTRL_CMD
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleManager
|
||||||
|
import com.shuwei.intelligent.shelves.utils.GridLayoutTool
|
||||||
|
import com.shuwei.intelligent.shelves.utils.IntervalExecutor
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.copyTextToClipboard
|
||||||
|
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.Job
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.greenrobot.eventbus.EventBus
|
||||||
|
import org.greenrobot.eventbus.Subscribe
|
||||||
|
import org.greenrobot.eventbus.ThreadMode
|
||||||
|
|
||||||
|
class HomeActivity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {}
|
||||||
|
|
||||||
|
override val enableRightStatusMenu: Boolean = true
|
||||||
|
|
||||||
|
// 货架列表数据
|
||||||
|
private val list: MutableList<ShelfModel> = mutableListOf()
|
||||||
|
|
||||||
|
// 当前选中货架下标
|
||||||
|
private var shelfIndex = 0
|
||||||
|
|
||||||
|
// 当前温度(摄氏)
|
||||||
|
private var showTemperatureC = "0"
|
||||||
|
|
||||||
|
// 当前湿度
|
||||||
|
private var showHumidity = "0"
|
||||||
|
|
||||||
|
// 仅特定 deviceId 的部署点需要发送开锁指令
|
||||||
|
private fun isNeedOpenLock() = App.deviceId == "4787e213-90ab-3e32-88e0-ac271a937751"
|
||||||
|
|
||||||
|
private var deviceName = ""
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityHomeBinding
|
||||||
|
|
||||||
|
private val viewModel: NetViewModel by viewModels()
|
||||||
|
|
||||||
|
// 串口协议解析器,通过回调通知本 Activity
|
||||||
|
private fun initScaleManager() {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val ok = ScaleManager
|
||||||
|
.init(activateCode = ProtocolConstants.ACTIVE_MAP[App.deviceId] ?: "")
|
||||||
|
.onHeartbeat { _, data ->
|
||||||
|
data.weights.forEach { weight ->
|
||||||
|
val shelfNo = weight.index
|
||||||
|
if (shelfNo in 1..list.size) {
|
||||||
|
list.firstOrNull { it.deviceNo == shelfNo }?.let { model ->
|
||||||
|
model.weight = weight.grams.toDouble()
|
||||||
|
val pos = list.indexOf(model)
|
||||||
|
shelfAdapter.notifyItemChanged(pos)
|
||||||
|
log("getWeightInfo: deviceNo=${model.deviceNo},realWeight=${weight.grams}")
|
||||||
|
EventBus.getDefault().post(SendWeightEvent(model.deviceNo, weight.grams))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onTempReport { _ ->
|
||||||
|
updateLeftStatus(deviceName)
|
||||||
|
}
|
||||||
|
.onLog { message -> log(message) }
|
||||||
|
.start { data ->
|
||||||
|
lastDataReceivedTime = System.currentTimeMillis()
|
||||||
|
noDataWarningDialog?.takeIf { it.isShowing }?.dismiss()
|
||||||
|
log("receiveSerialPortData: $data")
|
||||||
|
}
|
||||||
|
log("onCreate: openState=$ok")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityHomeBinding.inflate(layoutInflater)
|
||||||
|
EventBus.getDefault().register(this)
|
||||||
|
setBackground()
|
||||||
|
setContentView(binding.root)
|
||||||
|
onBackPressedDispatcher.addCallback(this) {
|
||||||
|
|
||||||
|
}
|
||||||
|
updateLeftStatus("")
|
||||||
|
initRecyclerView()
|
||||||
|
|
||||||
|
// 初始化 ScaleManager:注册回调、打开串口、启动接收
|
||||||
|
initScaleManager()
|
||||||
|
|
||||||
|
// 网络状态监听,独立协程,与串口初始化并行执行
|
||||||
|
lifecycleScope.launch {
|
||||||
|
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||||
|
launch {
|
||||||
|
viewModel.getAccessTokenUiState.collect { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Loading -> {}
|
||||||
|
is UiState.Success<*> -> getTokenSuccess(state.data)
|
||||||
|
is UiState.Error -> toast(state.msg)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
viewModel.getShelfListUiState.collect { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Loading -> showProgress()
|
||||||
|
is UiState.Success<*> -> updateUI(state.data)
|
||||||
|
is UiState.Error -> showError(state.msg)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
viewModel.updateOverdueStateUiState.collect { state ->
|
||||||
|
if (state is UiState.Success<*>) {
|
||||||
|
val respData = state.data as? RespData<*>
|
||||||
|
if (respData == null) {
|
||||||
|
log("updateOverdueState: 数据类型错误,期望 RespData")
|
||||||
|
return@collect
|
||||||
|
}
|
||||||
|
val shelfResult = respData.data as? ShelfResult
|
||||||
|
if (shelfResult == null) {
|
||||||
|
log("updateOverdueState: 数据类型错误,期望 ShelfResult")
|
||||||
|
return@collect
|
||||||
|
}
|
||||||
|
val items = shelfResult.containerGoodsList
|
||||||
|
if (items.isNullOrEmpty()) {
|
||||||
|
log("updateOverdueState: 货架列表为空")
|
||||||
|
return@collect
|
||||||
|
}
|
||||||
|
applyOverdueState(items)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.root.postDelayed({
|
||||||
|
sendCmd(START_TEMP_CTRL_CMD)
|
||||||
|
sendCmd(C_TEMP_CMD)
|
||||||
|
}, 5000)
|
||||||
|
|
||||||
|
saveGoodsTask()
|
||||||
|
overdueTask()
|
||||||
|
|
||||||
|
viewModel.getShelfList(deviceId = App.deviceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val defDeviceList = listOf(
|
||||||
|
//原410货柜
|
||||||
|
"7a991439-3a12-3ef7-809b-c0258b839473",
|
||||||
|
//原1楼餐厅货柜
|
||||||
|
"4787e213-90ab-3e32-88e0-ac271a937751"
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun getTokenSuccess(data: RespData<*>) {
|
||||||
|
log("getTokenSuccess: $data")
|
||||||
|
data.data?.let {
|
||||||
|
App.accessToken = it.toString()
|
||||||
|
viewModel.getShelfList(deviceId = App.deviceId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showProgress() {
|
||||||
|
Loading.show(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun updateUI(data: RespData<*>) {
|
||||||
|
binding.include?.root?.gone()
|
||||||
|
window?.decorView?.postDelayed({ Loading.dismiss() }, 500)
|
||||||
|
val shelfResult = data.data as? ShelfResult
|
||||||
|
if (shelfResult == null) {
|
||||||
|
log("updateUI: 数据类型错误,期望 ShelfResult,实际类型:${data.data?.javaClass?.simpleName}")
|
||||||
|
loadEmptyView()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
deviceName = shelfResult.deviceName
|
||||||
|
updateLeftStatus(deviceName)
|
||||||
|
|
||||||
|
App.canteenId = shelfResult.placeId
|
||||||
|
var tempList = shelfResult.containerGoodsList
|
||||||
|
if (tempList.isNullOrEmpty()) {
|
||||||
|
loadEmptyView()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
list.clear()
|
||||||
|
tempList = GridLayoutTool.initListSort(tempList)
|
||||||
|
list.addAll(tempList)
|
||||||
|
shelfAdapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showError(message: String) {
|
||||||
|
Loading.dismiss()
|
||||||
|
toast(message)
|
||||||
|
loadEmptyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
private var tipDialog: CommonDialog? = null
|
||||||
|
|
||||||
|
/** 最后一次成功收到串口数据的时间戳(毫秒) */
|
||||||
|
private var lastDataReceivedTime = System.currentTimeMillis()
|
||||||
|
|
||||||
|
/** 无数据超时提示弹窗 */
|
||||||
|
private var noDataWarningDialog: CommonDialog? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 无数据看门狗:每30秒检查一次,若超过5分钟未收到数据则弹出提示。
|
||||||
|
* 收到数据后会自动重置计时并关闭弹窗。
|
||||||
|
*/
|
||||||
|
private val noDataWatchdogTask = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
// 生命周期检查,防止 Activity 销毁后继续执行
|
||||||
|
if (isFinishing || isDestroyed) return
|
||||||
|
|
||||||
|
val elapsed = System.currentTimeMillis() - lastDataReceivedTime
|
||||||
|
if (elapsed >= 5 * 60 * 1000L) {
|
||||||
|
if (noDataWarningDialog == null) {
|
||||||
|
noDataWarningDialog = CommonDialog(this@HomeActivity).apply {
|
||||||
|
dialogTitle = "设备提示"
|
||||||
|
dialogContent =
|
||||||
|
"长时间未收到数据,若无法开门或秤重量不更新情况,请考虑断电重启设备"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (noDataWarningDialog?.isShowing == false) {
|
||||||
|
noDataWarningDialog?.show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handler.postDelayed(this, 30 * 1000L)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户超时无操作时关灯
|
||||||
|
*/
|
||||||
|
override fun onUserInactive() {
|
||||||
|
switchLight(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
// 清理 Handler 所有回调,防止内存泄漏
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
|
||||||
|
// 关闭并释放 Dialog 引用,防止内存泄漏
|
||||||
|
tipDialog?.dismiss()
|
||||||
|
tipDialog = null
|
||||||
|
noDataWarningDialog?.dismiss()
|
||||||
|
noDataWarningDialog = null
|
||||||
|
|
||||||
|
runBlocking { ScaleManager.release() }
|
||||||
|
saveTaskJob?.cancel()
|
||||||
|
overdueTaskJob?.cancel()
|
||||||
|
EventBus.getDefault().unregister(this)
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val shelfAdapter by lazy {
|
||||||
|
ShelfAdapter(list).apply {
|
||||||
|
setOnItemClickListener { _, _, position ->
|
||||||
|
onShelfItemClicked(position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理货架格子点击事件:按需开锁,然后跳转 ShelfActivity
|
||||||
|
*/
|
||||||
|
private fun onShelfItemClicked(position: Int) {
|
||||||
|
shelfIndex = position
|
||||||
|
lifecycleScope.launch {
|
||||||
|
if (isNeedOpenLock()) {
|
||||||
|
val openCmd = if (list[position].deviceNo in 1..5)
|
||||||
|
ScaleManager.buildOpenLock1Cmd()
|
||||||
|
else
|
||||||
|
ScaleManager.buildOpenLock2Cmd()
|
||||||
|
ScaleManager.sendCmd(openCmd)
|
||||||
|
}
|
||||||
|
launch(Intent(this@HomeActivity, ShelfActivity::class.java).also {
|
||||||
|
it.putExtra(ShelfActivity.SHELF_MODEL, list[position])
|
||||||
|
}) { result ->
|
||||||
|
result?.let { onShelfActivityResult(position, it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理 ShelfActivity 返回结果:更新本地列表数据并同步到服务端
|
||||||
|
*/
|
||||||
|
private fun onShelfActivityResult(position: Int, intent: Intent) {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val model = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
intent.getSerializableExtra(ShelfActivity.SHELF_MODEL, ShelfModel::class.java)
|
||||||
|
} else {
|
||||||
|
intent.getSerializableExtra(ShelfActivity.SHELF_MODEL) as? ShelfModel
|
||||||
|
} ?: return
|
||||||
|
list[position].apply {
|
||||||
|
goodsId = model.goodsId
|
||||||
|
goodsName = model.goodsName
|
||||||
|
weight = model.weight
|
||||||
|
if (model.putCabinetDay.isNullOrBlank().not()) {
|
||||||
|
putCabinetDay = model.putCabinetDay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
shelfAdapter.notifyItemChanged(position)
|
||||||
|
syncShelfGoodsToServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initRecyclerView() {
|
||||||
|
val layoutManager = GridLayoutTool.getLayoutManager(this@HomeActivity) ?: return
|
||||||
|
binding.rvShelf.let {
|
||||||
|
it.layoutManager = layoutManager
|
||||||
|
it.adapter = shelfAdapter
|
||||||
|
it.itemAnimator.let {
|
||||||
|
if (it is DefaultItemAnimator) {
|
||||||
|
it.supportsChangeAnimations = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
hideStatusBar()
|
||||||
|
// 启动无数据看门狗(每30秒检查一次)
|
||||||
|
handler.postDelayed(noDataWatchdogTask, 30 * 1000L)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
// 停止无数据看门狗
|
||||||
|
handler.removeCallbacks(noDataWatchdogTask)
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun loadEmptyView() {
|
||||||
|
list.clear()
|
||||||
|
shelfAdapter.notifyDataSetChanged()
|
||||||
|
binding.include?.let {
|
||||||
|
it.root.visible()
|
||||||
|
it.root.setOnClickListener {
|
||||||
|
viewModel.getShelfList(deviceId = App.deviceId)
|
||||||
|
}
|
||||||
|
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_white)
|
||||||
|
it.tvEmptyContent.setTextColor(Color.WHITE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Subscribe(threadMode = ThreadMode.MAIN)
|
||||||
|
fun clearEmptyShelf(event: ClearShelfEvent) {
|
||||||
|
val item = list.firstOrNull { it.deviceNo == event.shelfNo }
|
||||||
|
item?.apply {
|
||||||
|
goodsId = ""
|
||||||
|
goodsName = null
|
||||||
|
weight = 0.0
|
||||||
|
weightBak = if (event.weight <= 0.0) 0.0 else -1 * event.weight.toDouble()
|
||||||
|
createTime = null
|
||||||
|
overdueDay = null
|
||||||
|
}
|
||||||
|
shelfAdapter.notifyItemChanged(list.indexOf(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
private val taskExecutor by lazy { IntervalExecutor() }
|
||||||
|
private var saveTaskJob: Job? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存定时任务
|
||||||
|
*/
|
||||||
|
private fun saveGoodsTask() {
|
||||||
|
saveTaskJob =
|
||||||
|
taskExecutor.startIntervalTaskWithInitialDelay(1 * 60 * 1000L, 5 * 60 * 1000L) {
|
||||||
|
syncShelfGoodsToServer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var overdueTaskJob: Job? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 过期时间定时任务
|
||||||
|
*/
|
||||||
|
private fun overdueTask() {
|
||||||
|
overdueTaskJob = taskExecutor.startIntervalTaskWithInitialDelay(5 * 1000L, 5 * 60 * 1000L) {
|
||||||
|
updateOverdueState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateOverdueState() {
|
||||||
|
viewModel.updateOverdueState()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将接口返回的过期状态应用到本地列表,仅在状态变化时刷新对应 item
|
||||||
|
*/
|
||||||
|
private fun applyOverdueState(items: List<ShelfModel>) {
|
||||||
|
if (items.size != list.size) return
|
||||||
|
list.forEachIndexed { index, model ->
|
||||||
|
// 接口过期状态变化后更新状态
|
||||||
|
if (items[index].overdue != model.overdue) {
|
||||||
|
model.overdue = items[index].overdue
|
||||||
|
shelfAdapter.notifyItemChanged(index)
|
||||||
|
log("更新编号为${model.deviceNo}物品:${model.goodsName}的过期状态:${model.overdue}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建 ShelfBody 并提交到服务端(被定时任务与 ShelfActivity 返回共用)
|
||||||
|
*/
|
||||||
|
private fun syncShelfGoodsToServer() {
|
||||||
|
log("performSync显示list:${list.toJsonString()}")
|
||||||
|
val submitList = GridLayoutTool.submitListSort(list)
|
||||||
|
submitList.forEach {
|
||||||
|
if (it.goodsId.isNullOrBlank()) {
|
||||||
|
it.weight = it.weightBak
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val body = ShelfBody().also {
|
||||||
|
it.deviceId = App.deviceId ?: ""
|
||||||
|
it.canteenId = App.canteenId
|
||||||
|
it.temperature = showTemperatureC
|
||||||
|
it.humidity = showHumidity
|
||||||
|
it.goodsList = submitList
|
||||||
|
}
|
||||||
|
log("performSync提交body:${body.toJsonString()}")
|
||||||
|
viewModel.saveShelfGoodsList(body)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,465 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.activity
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Intent
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import androidx.activity.addCallback
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
|
import androidx.recyclerview.widget.DefaultItemAnimator
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
import com.shuwei.intelligent.shelves.adapter.ShelfV2Adapter
|
||||||
|
import com.shuwei.intelligent.shelves.base.BaseActivity
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ActivityHomeBinding
|
||||||
|
import com.shuwei.intelligent.shelves.dialog.CommonDialog
|
||||||
|
import com.shuwei.intelligent.shelves.model.CabinetInitResult
|
||||||
|
import com.shuwei.intelligent.shelves.model.ClearShelfEvent
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfModelV2
|
||||||
|
import com.shuwei.intelligent.shelves.model.SendWeightEvent
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||||
|
import com.shuwei.intelligent.shelves.model.SyncBody
|
||||||
|
import com.shuwei.intelligent.shelves.net.Loading
|
||||||
|
import com.shuwei.intelligent.shelves.net.NetViewModel
|
||||||
|
import com.shuwei.intelligent.shelves.net.NetViewModelV2
|
||||||
|
import com.shuwei.intelligent.shelves.net.RespData
|
||||||
|
import com.shuwei.intelligent.shelves.net.UiState
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.C_TEMP_CMD
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.START_TEMP_CTRL_CMD
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleManager
|
||||||
|
import com.google.android.flexbox.FlexDirection
|
||||||
|
import com.google.android.flexbox.FlexWrap
|
||||||
|
import com.google.android.flexbox.FlexboxLayoutManager
|
||||||
|
import com.shuwei.intelligent.shelves.utils.IntervalExecutor
|
||||||
|
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.Job
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.greenrobot.eventbus.EventBus
|
||||||
|
import org.greenrobot.eventbus.Subscribe
|
||||||
|
import org.greenrobot.eventbus.ThreadMode
|
||||||
|
|
||||||
|
class HomeV2Activity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {}
|
||||||
|
|
||||||
|
override val enableRightStatusMenu: Boolean = true
|
||||||
|
|
||||||
|
// 货架列表数据
|
||||||
|
private val list: MutableList<ShelfModelV2> = mutableListOf()
|
||||||
|
|
||||||
|
// 当前选中货架下标
|
||||||
|
private var shelfIndex = 0
|
||||||
|
|
||||||
|
// 当前温度(摄氏)
|
||||||
|
private var showTemperatureC = "0"
|
||||||
|
|
||||||
|
// 当前湿度
|
||||||
|
private var showHumidity = "0"
|
||||||
|
|
||||||
|
// 仅特定 deviceId 的部署点需要发送开锁指令
|
||||||
|
private fun isNeedOpenLock() = App.deviceId == "4787e213-90ab-3e32-88e0-ac271a937751"
|
||||||
|
|
||||||
|
private var deviceName = ""
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityHomeBinding
|
||||||
|
|
||||||
|
private val viewModel: NetViewModel by viewModels()
|
||||||
|
private val viewModelV2: NetViewModelV2 by viewModels()
|
||||||
|
|
||||||
|
// 串口协议解析器,通过回调通知本 Activity
|
||||||
|
private fun initScaleManager() {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val ok = ScaleManager
|
||||||
|
.init(activateCode = ProtocolConstants.ACTIVE_MAP[App.deviceId] ?: "")
|
||||||
|
.onHeartbeat { _, data ->
|
||||||
|
data.weights.forEach { weight ->
|
||||||
|
val shelfNo = weight.index
|
||||||
|
// if (shelfNo in 1..list.size) {
|
||||||
|
// 用 slotNo 末尾数字与串口编号匹配
|
||||||
|
val pos = list.indexOfFirst {
|
||||||
|
it.slotNo?.filter { c -> c.isDigit() }?.toIntOrNull() == shelfNo
|
||||||
|
}
|
||||||
|
val model = list.getOrNull(pos)?:return@forEach
|
||||||
|
model.weight = (1.0 * weight.grams / 1000.0).toBigDecimal()
|
||||||
|
// if (model.itemType == 1) {
|
||||||
|
// model.actualQty = (weight.grams / 1000.0).toBigDecimal()
|
||||||
|
// } else {
|
||||||
|
// model.totalWeightG = weight.grams.toBigDecimal()
|
||||||
|
// }
|
||||||
|
shelfAdapter.notifyItemChanged(pos)
|
||||||
|
log("getWeightInfo: slotNo=${model.slotNo}, realWeight=${weight.grams}, temp=${data.temperature}, item:${model.toJsonString()}")
|
||||||
|
EventBus.getDefault().post(SendWeightEvent(shelfNo, weight.grams))
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onTempReport { frame ->
|
||||||
|
log("onTempReport: $frame")
|
||||||
|
updateLeftStatus(deviceName)
|
||||||
|
}
|
||||||
|
.onLog { message -> log(message) }
|
||||||
|
.start { data ->
|
||||||
|
lastDataReceivedTime = System.currentTimeMillis()
|
||||||
|
noDataWarningDialog?.takeIf { it.isShowing }?.dismiss()
|
||||||
|
log("receiveSerialPortData: $data")
|
||||||
|
}
|
||||||
|
log("onCreate: openState=$ok")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityHomeBinding.inflate(layoutInflater)
|
||||||
|
EventBus.getDefault().register(this)
|
||||||
|
setBackground()
|
||||||
|
setContentView(binding.root)
|
||||||
|
onBackPressedDispatcher.addCallback(this) {
|
||||||
|
|
||||||
|
}
|
||||||
|
updateLeftStatus("")
|
||||||
|
|
||||||
|
// 初始化 ScaleManager:注册回调、打开串口、启动接收
|
||||||
|
initScaleManager()
|
||||||
|
|
||||||
|
// 网络状态监听,独立协程,与串口初始化并行执行
|
||||||
|
lifecycleScope.launch {
|
||||||
|
viewModelV2.initCabinetUiState.collect { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Loading -> showProgress()
|
||||||
|
is UiState.Success<*> -> updateUI(state.data)
|
||||||
|
is UiState.Error -> showError(state.msg)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.root.postDelayed({
|
||||||
|
sendCmd(START_TEMP_CTRL_CMD)
|
||||||
|
sendCmd(C_TEMP_CMD)
|
||||||
|
}, 5000)
|
||||||
|
|
||||||
|
saveGoodsTask()
|
||||||
|
overdueTask()
|
||||||
|
|
||||||
|
viewModelV2.initCabinet(cabinetId = App.deviceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val defDeviceList = listOf(
|
||||||
|
//原410货柜
|
||||||
|
"7a991439-3a12-3ef7-809b-c0258b839473",
|
||||||
|
//原1楼餐厅货柜
|
||||||
|
"4787e213-90ab-3e32-88e0-ac271a937751"
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun getTokenSuccess(data: RespData<*>) {
|
||||||
|
log("getTokenSuccess: $data")
|
||||||
|
data.data?.let {
|
||||||
|
App.accessToken = it.toString()
|
||||||
|
viewModelV2.initCabinet(cabinetId = App.deviceId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showProgress() {
|
||||||
|
Loading.show(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var cabinetInitResult: CabinetInitResult? = null
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun updateUI(data: RespData<*>) {
|
||||||
|
binding.include.root.gone()
|
||||||
|
window?.decorView?.postDelayed({ Loading.dismiss() }, 500)
|
||||||
|
cabinetInitResult = data.data as? CabinetInitResult
|
||||||
|
if (cabinetInitResult == null) {
|
||||||
|
log("updateUI: 数据类型错误,期望 CabinetInitResult,实际类型:${data.data?.javaClass?.simpleName}")
|
||||||
|
loadEmptyView()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val cabinet = cabinetInitResult!!
|
||||||
|
//行列数量后端返回是反着的
|
||||||
|
val rows = cabinet.horizontalRows
|
||||||
|
val columns = cabinet.verticalCount
|
||||||
|
log("updateUI: rows=$rows, columns=$columns")
|
||||||
|
deviceName = cabinet.deviceName
|
||||||
|
updateLeftStatus(deviceName)
|
||||||
|
App.canteenId = cabinet.canteenId.toString()
|
||||||
|
var tempList = cabinet.containerGoodsList
|
||||||
|
if (tempList.isNullOrEmpty()) {
|
||||||
|
loadEmptyView()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
list.clear()
|
||||||
|
list.addAll(tempList)
|
||||||
|
|
||||||
|
val displayMetrics = resources.displayMetrics
|
||||||
|
shelfAdapter.itemWidth = (displayMetrics.widthPixels - 24.dp) / columns - 24.dp
|
||||||
|
shelfAdapter.itemHeight = (displayMetrics.heightPixels - 68.dp) / rows - 24.dp
|
||||||
|
|
||||||
|
if (binding.rvShelf.adapter == null) {
|
||||||
|
initRecyclerView()
|
||||||
|
} else {
|
||||||
|
shelfAdapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showError(message: String) {
|
||||||
|
Loading.dismiss()
|
||||||
|
toast(message)
|
||||||
|
loadEmptyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
private var tipDialog: CommonDialog? = null
|
||||||
|
|
||||||
|
/** 最后一次成功收到串口数据的时间戳(毫秒) */
|
||||||
|
private var lastDataReceivedTime = System.currentTimeMillis()
|
||||||
|
|
||||||
|
/** 无数据超时提示弹窗 */
|
||||||
|
private var noDataWarningDialog: CommonDialog? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 无数据看门狗:每30秒检查一次,若超过5分钟未收到数据则弹出提示。
|
||||||
|
* 收到数据后会自动重置计时并关闭弹窗。
|
||||||
|
*/
|
||||||
|
private val noDataWatchdogTask = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
// 生命周期检查,防止 Activity 销毁后继续执行
|
||||||
|
if (isFinishing || isDestroyed) return
|
||||||
|
|
||||||
|
val elapsed = System.currentTimeMillis() - lastDataReceivedTime
|
||||||
|
if (elapsed >= 5 * 60 * 1000L) {
|
||||||
|
if (noDataWarningDialog == null) {
|
||||||
|
noDataWarningDialog = CommonDialog(this@HomeV2Activity).apply {
|
||||||
|
dialogTitle = "设备提示"
|
||||||
|
dialogContent =
|
||||||
|
"长时间未收到数据,若无法开门或秤重量不更新情况,请考虑断电重启设备"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (noDataWarningDialog?.isShowing == false) {
|
||||||
|
noDataWarningDialog?.show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handler.postDelayed(this, 30 * 1000L)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户超时无操作时关灯
|
||||||
|
*/
|
||||||
|
override fun onUserInactive() {
|
||||||
|
switchLight(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
// 清理 Handler 所有回调,防止内存泄漏
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
|
||||||
|
// 关闭并释放 Dialog 引用,防止内存泄漏
|
||||||
|
tipDialog?.dismiss()
|
||||||
|
tipDialog = null
|
||||||
|
noDataWarningDialog?.dismiss()
|
||||||
|
noDataWarningDialog = null
|
||||||
|
|
||||||
|
runBlocking { ScaleManager.release() }
|
||||||
|
saveTaskJob?.cancel()
|
||||||
|
overdueTaskJob?.cancel()
|
||||||
|
EventBus.getDefault().unregister(this)
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val shelfAdapter by lazy {
|
||||||
|
ShelfV2Adapter(list).apply {
|
||||||
|
setOnItemClickListener { _, _, position ->
|
||||||
|
onShelfItemClicked(position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理货架格子点击事件:按需开锁,然后跳转 ShelfV2Activity
|
||||||
|
*/
|
||||||
|
private fun onShelfItemClicked(position: Int) {
|
||||||
|
shelfIndex = position
|
||||||
|
lifecycleScope.launch {
|
||||||
|
if (isNeedOpenLock()) {
|
||||||
|
// 解析 slotNo 末尾数字判断锁区(1-5 号格口走锁1,其余走锁2)
|
||||||
|
val slotNum = list[position].slotNo?.filter { it.isDigit() }?.toIntOrNull() ?: 0
|
||||||
|
val openCmd = if (slotNum in 1..5)
|
||||||
|
ScaleManager.buildOpenLock1Cmd()
|
||||||
|
else
|
||||||
|
ScaleManager.buildOpenLock2Cmd()
|
||||||
|
ScaleManager.sendCmd(openCmd)
|
||||||
|
}
|
||||||
|
launch(Intent(this@HomeV2Activity, ShelfV2Activity::class.java).also {
|
||||||
|
it.putExtra(ShelfV2Activity.SHELF_MODEL, list[position])
|
||||||
|
}) { result ->
|
||||||
|
result?.let { onShelfActivityResult(position, it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理 ShelfV2Activity 返回结果
|
||||||
|
* TODO: 待 ShelfV2Activity 迁移到 RecordItem 后重新实现字段更新逻辑
|
||||||
|
*/
|
||||||
|
private fun onShelfActivityResult(position: Int, intent: Intent) {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val model = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
intent.getSerializableExtra(ShelfV2Activity.SHELF_MODEL, ShelfModelV2::class.java)
|
||||||
|
} else {
|
||||||
|
intent.getSerializableExtra(ShelfV2Activity.SHELF_MODEL) as? ShelfModelV2
|
||||||
|
} ?: return
|
||||||
|
list[position].let {
|
||||||
|
it.itemType = model.itemType
|
||||||
|
it.itemName = model.itemName
|
||||||
|
it.traceCode = model.traceCode
|
||||||
|
it.cleanOrderNo = model.cleanOrderNo
|
||||||
|
it.spec = model.spec
|
||||||
|
it.foodId = model.foodId
|
||||||
|
it.storeTime = model.storeTime
|
||||||
|
it.slotStatus = model.slotStatus
|
||||||
|
}
|
||||||
|
shelfAdapter.notifyItemChanged(position)
|
||||||
|
// syncShelfGoodsToServer()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initRecyclerView() {
|
||||||
|
val layoutManager = FlexboxLayoutManager(this).apply {
|
||||||
|
flexDirection = FlexDirection.COLUMN
|
||||||
|
flexWrap = FlexWrap.WRAP
|
||||||
|
}
|
||||||
|
binding.rvShelf.let {
|
||||||
|
it.layoutManager = layoutManager
|
||||||
|
it.adapter = shelfAdapter
|
||||||
|
it.itemAnimator.let { animator ->
|
||||||
|
if (animator is DefaultItemAnimator) {
|
||||||
|
animator.supportsChangeAnimations = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
hideStatusBar()
|
||||||
|
// 启动无数据看门狗(每30秒检查一次)
|
||||||
|
handler.postDelayed(noDataWatchdogTask, 30 * 1000L)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
// 停止无数据看门狗
|
||||||
|
handler.removeCallbacks(noDataWatchdogTask)
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun loadEmptyView() {
|
||||||
|
list.clear()
|
||||||
|
shelfAdapter.notifyDataSetChanged()
|
||||||
|
binding.include?.let {
|
||||||
|
it.root.visible()
|
||||||
|
it.root.setOnClickListener {
|
||||||
|
viewModelV2.initCabinet(cabinetId = App.deviceId)
|
||||||
|
}
|
||||||
|
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_white)
|
||||||
|
it.tvEmptyContent.setTextColor(Color.WHITE)
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadTestData()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @SuppressLint("NotifyDataSetChanged")
|
||||||
|
// private fun loadTestData() {
|
||||||
|
// binding.rvShelf.layoutManager = GridLayoutManager(this, 2)
|
||||||
|
// binding.rvShelf.adapter = shelfAdapter
|
||||||
|
// binding.include.root.gone()
|
||||||
|
// list.clear()
|
||||||
|
// var tempList = (1..10).map { i -> ShelfModelV2(slotNo = i.toString()) }
|
||||||
|
// tempList = GridLayoutTool.initListSortV2(tempList)
|
||||||
|
// list.addAll(tempList)
|
||||||
|
// shelfAdapter.notifyDataSetChanged()
|
||||||
|
// }
|
||||||
|
|
||||||
|
@Subscribe(threadMode = ThreadMode.MAIN)
|
||||||
|
fun clearEmptyShelf(event: ClearShelfEvent) {
|
||||||
|
// 用 slotNo 末尾数字与串口编号匹配
|
||||||
|
val index = list.indexOfFirst {
|
||||||
|
it.slotNo?.filter { c -> c.isDigit() }?.toIntOrNull() == event.shelfNo
|
||||||
|
}
|
||||||
|
if (index < 0) return
|
||||||
|
list[index] = list[index].copy(itemName = "")
|
||||||
|
shelfAdapter.notifyItemChanged(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val taskExecutor by lazy { IntervalExecutor() }
|
||||||
|
private var saveTaskJob: Job? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存定时任务
|
||||||
|
*/
|
||||||
|
private fun saveGoodsTask() {
|
||||||
|
saveTaskJob =
|
||||||
|
// taskExecutor.startIntervalTaskWithInitialDelay(1 * 60 * 1000L, 5 * 60 * 1000L) {
|
||||||
|
taskExecutor.startIntervalTaskWithInitialDelay(10 * 1000L, 2 * 60 * 1000L) {
|
||||||
|
syncShelfGoodsToServer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var overdueTaskJob: Job? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 过期时间定时任务
|
||||||
|
*/
|
||||||
|
private fun overdueTask() {
|
||||||
|
overdueTaskJob = taskExecutor.startIntervalTaskWithInitialDelay(5 * 1000L, 5 * 60 * 1000L) {
|
||||||
|
viewModelV2.initCabinet(cabinetId = App.deviceId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将接口返回的临期状态应用到本地列表,仅在状态变化时刷新对应 item
|
||||||
|
*/
|
||||||
|
private fun applyOverdueState(items: List<ShelfModelV2>) {
|
||||||
|
if (items.size != list.size) return
|
||||||
|
items.forEachIndexed { index, newItem ->
|
||||||
|
val oldItem = list[index]
|
||||||
|
// slotStatus=2 表示临期预警
|
||||||
|
if (oldItem.slotStatus != newItem.slotStatus) {
|
||||||
|
list[index] = newItem
|
||||||
|
shelfAdapter.notifyItemChanged(index)
|
||||||
|
log("更新格口 ${newItem.slotNo} 物品:${newItem.itemName} 的状态:${newItem.slotStatus}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建同步请求并提交到服务端
|
||||||
|
*/
|
||||||
|
private fun syncShelfGoodsToServer() {
|
||||||
|
if (cabinetInitResult == null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val submitList = list.sortedBy { it.slotNo?.toIntOrNull() ?: 0 }
|
||||||
|
viewModelV2.syncCabinetData(SyncBody().apply {
|
||||||
|
// cabinetId = list[0].cabinetId
|
||||||
|
cabinetId = App.deviceId
|
||||||
|
temperature = null
|
||||||
|
humidity = null
|
||||||
|
goodsList = submitList
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.activity
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Intent
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.os.SystemClock
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.KeyEvent
|
||||||
|
import android.view.animation.RotateAnimation
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.core.graphics.toColorInt
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.GlobalData
|
||||||
|
import com.shuwei.intelligent.shelves.base.BaseActivity
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ActivityInitBinding
|
||||||
|
import com.shuwei.intelligent.shelves.model.DeviceConfigInfo
|
||||||
|
import com.shuwei.intelligent.shelves.net.NetViewModel
|
||||||
|
import com.shuwei.intelligent.shelves.net.UiState
|
||||||
|
import com.shuwei.intelligent.shelves.net.UrlConfig
|
||||||
|
import com.shuwei.intelligent.shelves.utils.AppUtil
|
||||||
|
import com.shuwei.intelligent.shelves.utils.NetworkUtils
|
||||||
|
import com.shuwei.intelligent.shelves.utils.QRCodeUtil
|
||||||
|
import com.shuwei.intelligent.shelves.utils.SpTool
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.dp
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.invisible
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.startActivity
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.toObject
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.toast
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.collections.forEach
|
||||||
|
import kotlin.getValue
|
||||||
|
import kotlin.ranges.downTo
|
||||||
|
import kotlin.text.isBlank
|
||||||
|
|
||||||
|
class InitActivity : BaseActivity() {
|
||||||
|
companion object {
|
||||||
|
const val TAG = "InitActivity"
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityInitBinding
|
||||||
|
|
||||||
|
private val viewModel: NetViewModel by viewModels()
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
private var startTime = 0L // 倒计时开始时间
|
||||||
|
private var lastNetworkCheckTime = 0L // 上次检测网络的时间
|
||||||
|
|
||||||
|
@SuppressLint("HardwareIds")
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityInitBinding.inflate(layoutInflater)
|
||||||
|
setContentView(binding.root)
|
||||||
|
|
||||||
|
App.deviceId = AppUtil.getUDID( this)
|
||||||
|
// App.deviceId = "4787e213-90ab-3e32-88e0-ac271a937751"
|
||||||
|
Log.d(TAG, "onCreate: deviceId = ${App.deviceId}")
|
||||||
|
SpTool.put(SpTool.DEVICE_ID, App.deviceId)
|
||||||
|
val appBaseUrl = SpTool.baseUrl
|
||||||
|
if (!appBaseUrl.isBlank()) {
|
||||||
|
GlobalData.appBaseUrl = appBaseUrl
|
||||||
|
} else {
|
||||||
|
GlobalData.appBaseUrl = GlobalData.PROD_BASE_URL
|
||||||
|
}
|
||||||
|
App.canteenId = "0"
|
||||||
|
|
||||||
|
// var deviceId = AppUtil.getUDID(this)
|
||||||
|
// Log.d(TAG, "onCreate: deviceId=$deviceId")
|
||||||
|
//// deviceId = "39a7abdd06b3c7ab"
|
||||||
|
//// deviceId = "3ea47dc0-3cf0-3c2f-909c-265a9a65572e"
|
||||||
|
// App.deviceId = deviceId
|
||||||
|
//
|
||||||
|
// SpTool.put(SpTool.DEVICE_ID, deviceId)
|
||||||
|
// val deviceConfigCache = SpTool.getString(SpTool.DEVICE_CONFIG_CACHE)
|
||||||
|
// val checkResult = checkConfigData(deviceConfigCache)
|
||||||
|
// if (checkResult.not()) {
|
||||||
|
// binding.ivQrCode.visible()
|
||||||
|
// binding.btnInit.visible()
|
||||||
|
// //进行初始化操作
|
||||||
|
// initConfig()
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
binding.ivQrCode.invisible()
|
||||||
|
binding.btnInit.invisible()
|
||||||
|
|
||||||
|
// countDown()
|
||||||
|
initViews()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun countDown() {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
flow {
|
||||||
|
(2 downTo 1).forEach {
|
||||||
|
delay(1000)
|
||||||
|
emit(it)
|
||||||
|
}
|
||||||
|
}.collect {
|
||||||
|
// 倒计时结束执行跳转
|
||||||
|
if (it == 1) {
|
||||||
|
startActivity<HomeActivity>()
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// private fun initConfig() {
|
||||||
|
// binding.ivQrCode.setImageBitmap(
|
||||||
|
// QRCodeUtil.generateQRCode(
|
||||||
|
// content = App.deviceId,
|
||||||
|
// size = 200.dp
|
||||||
|
// )
|
||||||
|
// )
|
||||||
|
//// binding.btnInit.setOnClickListener {
|
||||||
|
//// viewModel.getDeviceToken(App.deviceId)
|
||||||
|
//// }
|
||||||
|
// lifecycleScope.launch {
|
||||||
|
// repeatOnLifecycle(Lifecycle.State.CREATED) {
|
||||||
|
//// launch {
|
||||||
|
//// viewModel.getDeviceTokenUiState.collect { state ->
|
||||||
|
//// when (state) {
|
||||||
|
//// is UiState.Loading -> {}
|
||||||
|
//// is UiState.Success<*> -> {
|
||||||
|
//// state.data.data?.let { deviceToken ->
|
||||||
|
//// Log.d(TAG, "initConfig: $deviceToken")
|
||||||
|
//// viewModel.getDeviceConfig(
|
||||||
|
//// deviceId = App.deviceId,
|
||||||
|
//// deviceToken = deviceToken.toString()
|
||||||
|
//// )
|
||||||
|
//// }
|
||||||
|
//// }
|
||||||
|
//// is UiState.Error -> toast(state.msg)
|
||||||
|
//// else -> {}
|
||||||
|
//// }
|
||||||
|
//// }
|
||||||
|
//// }
|
||||||
|
//// launch {
|
||||||
|
//// viewModel.getDeviceConfigUiState.collect { state ->
|
||||||
|
//// when (state) {
|
||||||
|
//// is UiState.Loading -> {}
|
||||||
|
//// is UiState.Success<*> -> {
|
||||||
|
//// state.data.data?.let {
|
||||||
|
//// if (it is DeviceConfigInfo) {
|
||||||
|
//// SpTool.put(SpTool.DEVICE_CONFIG_CACHE, it.toJsonString())
|
||||||
|
//// GlobalData.appBaseUrl = it.appPackageUrl?:""
|
||||||
|
//// App.canteenId = it.canteenId?:""
|
||||||
|
////
|
||||||
|
//// startActivity<HomeActivity>()
|
||||||
|
//// finish()
|
||||||
|
//// }
|
||||||
|
//// }
|
||||||
|
//// }
|
||||||
|
//// is UiState.Error -> toast(message = state.msg)
|
||||||
|
//// else -> {}
|
||||||
|
//// }
|
||||||
|
//// }
|
||||||
|
//// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
private fun checkConfigData(data: String): Boolean {
|
||||||
|
if (data.isBlank()) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
val config = data.toObject<DeviceConfigInfo?>()
|
||||||
|
if (config == null) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
GlobalData.appBaseUrl = config.appPackageUrl?:""
|
||||||
|
App.canteenId = config.canteenId?:""
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化控件事件
|
||||||
|
*/
|
||||||
|
private fun initViews() {
|
||||||
|
// 连接网络按钮点击事件
|
||||||
|
binding.btnConnectNetwork.setOnClickListener {
|
||||||
|
openNetworkSettings()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动加载动画 - 持续旋转
|
||||||
|
startLoadingAnimation()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动加载动画 - ImageView 持续旋转
|
||||||
|
*/
|
||||||
|
private fun startLoadingAnimation() {
|
||||||
|
val rotateAnimation = RotateAnimation(
|
||||||
|
0f, 360f,
|
||||||
|
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
|
||||||
|
RotateAnimation.RELATIVE_TO_SELF, 0.5f
|
||||||
|
).apply {
|
||||||
|
duration = 1200 // 旋转周期 1.2 秒
|
||||||
|
repeatCount = RotateAnimation.INFINITE // 无限循环
|
||||||
|
repeatMode = RotateAnimation.RESTART
|
||||||
|
}
|
||||||
|
binding.ivLoading.startAnimation(rotateAnimation)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
if (NetworkUtils.isNetworkConnected(this)) {
|
||||||
|
navigateToHome()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
startCountdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
// 页面不可见时停止倒计时
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动 60 秒倒计时
|
||||||
|
*/
|
||||||
|
private fun startCountdown() {
|
||||||
|
startTime = SystemClock.elapsedRealtime()
|
||||||
|
lastNetworkCheckTime = 0
|
||||||
|
binding.llNetwork.setBackgroundColor(Color.TRANSPARENT)
|
||||||
|
binding.llLoading.visibility = android.view.View.VISIBLE
|
||||||
|
binding.llNetworkButton.visibility = android.view.View.GONE
|
||||||
|
binding.tvCountdown.text = "60秒"
|
||||||
|
scheduleCountdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 定时更新倒计时
|
||||||
|
* 使用 SystemClock.elapsedRealtime() 确保精确计时
|
||||||
|
*/
|
||||||
|
private fun scheduleCountdown() {
|
||||||
|
handler.postDelayed({
|
||||||
|
val elapsedTime = SystemClock.elapsedRealtime() - startTime
|
||||||
|
val remainingTime = 60 - (elapsedTime / 1000).toInt()
|
||||||
|
val currentNetworkCheckTime = (elapsedTime / 1000).toInt()
|
||||||
|
|
||||||
|
// 每 10 秒检测一次网络
|
||||||
|
if (currentNetworkCheckTime > 0 && currentNetworkCheckTime % 10 == 0 && currentNetworkCheckTime != lastNetworkCheckTime.toInt()) {
|
||||||
|
lastNetworkCheckTime = currentNetworkCheckTime.toLong()
|
||||||
|
checkNetworkConnection()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 倒计时未结束,继续更新 UI
|
||||||
|
if (remainingTime > 0) {
|
||||||
|
binding.tvCountdown.text = "${remainingTime}秒"
|
||||||
|
scheduleCountdown()
|
||||||
|
} else {
|
||||||
|
// 倒计时结束,最后检测一次网络
|
||||||
|
if (NetworkUtils.isNetworkConnected(this)) {
|
||||||
|
navigateToHome()
|
||||||
|
} else {
|
||||||
|
// 网络未连接,显示"连接网络"按钮
|
||||||
|
showNetworkButton()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 100) // 每 100ms 检查一次,确保精确性
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测网络连接
|
||||||
|
*/
|
||||||
|
private fun checkNetworkConnection() {
|
||||||
|
if (NetworkUtils.isNetworkConnected(this)) {
|
||||||
|
// 网络连接成功,停止倒计时并跳转到 HomeActivity
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
navigateToHome()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 跳转到 HomeActivity
|
||||||
|
*/
|
||||||
|
private fun navigateToHome() {
|
||||||
|
// startActivity<HomeActivity>()
|
||||||
|
startActivity<HomeV2Activity>()
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 显示"连接网络"按钮
|
||||||
|
*/
|
||||||
|
private fun showNetworkButton() {
|
||||||
|
binding.llNetwork.setBackgroundColor("#5C77F7".toColorInt())
|
||||||
|
binding.llLoading.visibility = android.view.View.GONE
|
||||||
|
binding.llNetworkButton.visibility = android.view.View.VISIBLE
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开系统网络设置页面
|
||||||
|
*/
|
||||||
|
private fun openNetworkSettings() {
|
||||||
|
val intent = Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)
|
||||||
|
startActivity(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 禁用返回键
|
||||||
|
*/
|
||||||
|
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
|
||||||
|
return if (keyCode == KeyEvent.KEYCODE_BACK) {
|
||||||
|
// 禁用返回键,不执行任何操作
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
super.onKeyDown(keyCode, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.activity
|
||||||
|
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.widget.TextView
|
||||||
|
import androidx.core.widget.addTextChangedListener
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import com.shuwei.intelligent.shelves.adapter.LogAdapter
|
||||||
|
import com.shuwei.intelligent.shelves.base.BaseActivity
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ActivityLogListBinding
|
||||||
|
import com.shuwei.intelligent.shelves.dialog.CommonDialog
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.copyTextToClipboard
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.dp
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.gone
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.startActivity
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.toast
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.visible
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
class LogActivity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val IS_LOG_DIR = "isLogDir"
|
||||||
|
const val LOG_DATE = "logDate"
|
||||||
|
const val YYYY_MM_DD__EEEE_HH_MM_SS = "yyyy年MM月dd日 EEEE***HH:mm:ss"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 覆写时钟回调:左侧状态栏显示年月日星期,右侧状态栏显示时分秒
|
||||||
|
*/
|
||||||
|
override fun onClockTick() {
|
||||||
|
val sdf = SimpleDateFormat(YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
|
||||||
|
val arr = sdf.format(Date()).split("***")
|
||||||
|
updateLeftStatus(arr[0])
|
||||||
|
updateRightStatus(arr[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var binding:ActivityLogListBinding
|
||||||
|
private var isLogDir = false
|
||||||
|
private var logDate = ""
|
||||||
|
private val logList = mutableListOf<String>()
|
||||||
|
private val originalLogList = mutableListOf<String>() // 原始日志备份
|
||||||
|
private val logAdapter by lazy {
|
||||||
|
LogAdapter(logList).apply {
|
||||||
|
setOnItemClickListener { _, _, position ->
|
||||||
|
if (isLogDir.not()) {
|
||||||
|
showConfirmDialog(logList[position])
|
||||||
|
return@setOnItemClickListener
|
||||||
|
}
|
||||||
|
startActivity<LogActivity> {
|
||||||
|
putExtra(IS_LOG_DIR, false)
|
||||||
|
putExtra(LOG_DATE, logList[position])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showConfirmDialog(content:String) {
|
||||||
|
CommonDialog(this).apply {
|
||||||
|
dialogTitle = "温馨提示"
|
||||||
|
dialogContent = content
|
||||||
|
confirmBlock = {
|
||||||
|
content?.copyTextToClipboard(this@LogActivity)
|
||||||
|
}
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityLogListBinding.inflate(layoutInflater)
|
||||||
|
setBackground()
|
||||||
|
setContentView(binding.root)
|
||||||
|
isLogDir = intent.getBooleanExtra(IS_LOG_DIR, false)
|
||||||
|
logDate = intent.getStringExtra(LOG_DATE) ?: ""
|
||||||
|
binding.ivBack.setOnClickListener { finish() }
|
||||||
|
binding.tvTitle.text = if (isLogDir) "全部日志" else logDate
|
||||||
|
binding.tvTitle.setOnClickListener {
|
||||||
|
logList.reverse()
|
||||||
|
logAdapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.rvLogList.let {
|
||||||
|
it.layoutManager = LinearLayoutManager(this)
|
||||||
|
it.adapter = logAdapter
|
||||||
|
}
|
||||||
|
|
||||||
|
setupSearch()
|
||||||
|
setupJumpButton()
|
||||||
|
|
||||||
|
binding.btnFind.run {
|
||||||
|
if (isLogDir) gone() else visible()
|
||||||
|
}
|
||||||
|
binding.btnFind.setOnClickListener {
|
||||||
|
if (isLogDir) return@setOnClickListener
|
||||||
|
val list = logList.filter { it.contains("${ProtocolConstants.HEADER}${ProtocolConstants.CMD_TEMP_REPORT}") }
|
||||||
|
if (list.isEmpty()) {
|
||||||
|
toast("未找到到1001指令")
|
||||||
|
return@setOnClickListener
|
||||||
|
}
|
||||||
|
logList.clear()
|
||||||
|
logList.addAll(list)
|
||||||
|
logAdapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 后台加载日志数据
|
||||||
|
lifecycleScope.launch {
|
||||||
|
binding.progressBar.visible()
|
||||||
|
val data = withContext(Dispatchers.IO) {
|
||||||
|
if (isLogDir) fileLogger.getLogFiles()
|
||||||
|
else fileLogger.readLogsByName(logDate)
|
||||||
|
}
|
||||||
|
logList.addAll(data)
|
||||||
|
originalLogList.addAll(data)
|
||||||
|
logAdapter.notifyDataSetChanged()
|
||||||
|
binding.progressBar.gone()
|
||||||
|
setupTimeNavigation()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 搜索功能
|
||||||
|
private fun setupSearch() {
|
||||||
|
binding.etSearch.addTextChangedListener(afterTextChanged = { s ->
|
||||||
|
val keyword = s?.toString() ?: ""
|
||||||
|
logList.clear()
|
||||||
|
logList.addAll(if (keyword.isEmpty()) originalLogList else originalLogList.filter { it.contains(keyword, ignoreCase = true) })
|
||||||
|
logAdapter.notifyDataSetChanged()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 快速跳转功能
|
||||||
|
private fun setupJumpButton() {
|
||||||
|
var isAtTop = true
|
||||||
|
binding.fabJump.setOnClickListener {
|
||||||
|
if (isAtTop) {
|
||||||
|
binding.rvLogList.scrollToPosition(logList.size - 1)
|
||||||
|
} else {
|
||||||
|
binding.rvLogList.scrollToPosition(0)
|
||||||
|
}
|
||||||
|
isAtTop = !isAtTop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 时间导航功能
|
||||||
|
private fun setupTimeNavigation() {
|
||||||
|
if (isLogDir) {
|
||||||
|
binding.hsvTimeNav.gone()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val timeMap = mutableMapOf<String, Int>()
|
||||||
|
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
|
||||||
|
|
||||||
|
originalLogList.forEachIndexed { index, log ->
|
||||||
|
val timeStr = log.substringAfter("[").substringBefore("]")
|
||||||
|
try {
|
||||||
|
val date = dateFormat.parse(timeStr)
|
||||||
|
date?.let {
|
||||||
|
val hourKey = SimpleDateFormat("HH:00", Locale.getDefault()).format(it)
|
||||||
|
if (!timeMap.containsKey(hourKey)) {
|
||||||
|
timeMap[hourKey] = index
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// 忽略解析失败的日志
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (timeMap.isEmpty()) {
|
||||||
|
binding.hsvTimeNav.gone()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
timeMap.toSortedMap().forEach { (hour, position) ->
|
||||||
|
val btn = TextView(this).apply {
|
||||||
|
text = hour
|
||||||
|
textSize = 14f
|
||||||
|
setTextColor(Color.BLACK)
|
||||||
|
setPadding(12.dp, 8.dp, 12.dp, 8.dp)
|
||||||
|
gravity = Gravity.CENTER
|
||||||
|
setBackgroundColor(Color.parseColor("#E0E0E0"))
|
||||||
|
setOnClickListener {
|
||||||
|
binding.rvLogList.scrollToPosition(position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val params = android.widget.LinearLayout.LayoutParams(
|
||||||
|
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||||
|
android.widget.LinearLayout.LayoutParams.MATCH_PARENT
|
||||||
|
).apply {
|
||||||
|
marginEnd = 8.dp
|
||||||
|
}
|
||||||
|
binding.llTimeNav.addView(btn, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
//package com.shuwei.intelligent.shelves.activity
|
||||||
|
//
|
||||||
|
//import android.os.Bundle
|
||||||
|
//import android.os.Handler
|
||||||
|
//import android.os.Looper
|
||||||
|
//import com.shuwei.intelligent.shelves.base.BaseActivity
|
||||||
|
//import com.shuwei.intelligent.shelves.databinding.ActivitySettingBinding
|
||||||
|
//import com.shuwei.intelligent.shelves.utils.KeyboardUtil
|
||||||
|
//import java.text.SimpleDateFormat
|
||||||
|
//import java.util.Date
|
||||||
|
//import java.util.Locale
|
||||||
|
//
|
||||||
|
//class SettingActivity: BaseActivity() {
|
||||||
|
//
|
||||||
|
// private lateinit var binding: ActivitySettingBinding
|
||||||
|
// override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
// super.onCreate(savedInstanceState)
|
||||||
|
// binding = ActivitySettingBinding.inflate(layoutInflater)
|
||||||
|
// setBackground()
|
||||||
|
// setContentView(binding.root)
|
||||||
|
// binding.btnSendCmd.setOnClickListener{
|
||||||
|
// val cmd = binding.etInputCmd.text.toString().trim()
|
||||||
|
// if (cmd.isBlank()) {
|
||||||
|
// return@setOnClickListener
|
||||||
|
// }
|
||||||
|
// var record = binding.tvCmdRecord.text.toString().trim()
|
||||||
|
// record = cmd+"\n"+record
|
||||||
|
// binding.tvCmdRecord.text = record
|
||||||
|
// val realCmd = "${HomeActivity.HEADER}0F01${cmd}${HomeActivity.FOOTER}"
|
||||||
|
// sendCmd(realCmd)
|
||||||
|
// }
|
||||||
|
// binding.ivBack.setOnClickListener { finish() }
|
||||||
|
// binding.root.setOnClickListener { v ->
|
||||||
|
// KeyboardUtil.hideKeyboard(v)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
//
|
||||||
|
// private fun updateDateTime() {
|
||||||
|
// val sdf = SimpleDateFormat(ShelfActivity.YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
|
||||||
|
// val dateTime = sdf.format(Date())
|
||||||
|
// val arr = dateTime.split("***")
|
||||||
|
// updateLeftStatus(arr[0])
|
||||||
|
// updateRightStatus(arr[1])
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private val handler = Handler(Looper.getMainLooper())
|
||||||
|
// private val updateTask = object : Runnable {
|
||||||
|
// override fun run() {
|
||||||
|
// updateDateTime()
|
||||||
|
// handler.postDelayed(this, 1000)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// override fun onResume() {
|
||||||
|
// super.onResume()
|
||||||
|
// hideStatusBar()
|
||||||
|
// handler.post(updateTask)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// override fun onPause() {
|
||||||
|
// super.onPause()
|
||||||
|
// handler.removeCallbacks(updateTask)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
//}
|
||||||
@@ -0,0 +1,380 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.activity
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.core.view.updateLayoutParams
|
||||||
|
import androidx.core.widget.addTextChangedListener
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||||
|
import com.scwang.smart.refresh.layout.constant.RefreshState
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleManager
|
||||||
|
import com.shuwei.intelligent.shelves.adapter.SearchAdapter
|
||||||
|
import com.shuwei.intelligent.shelves.base.BaseActivity
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ActivityShelfBinding
|
||||||
|
import com.shuwei.intelligent.shelves.model.ClearShelfEvent
|
||||||
|
import com.shuwei.intelligent.shelves.model.GoodsModel
|
||||||
|
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.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
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
class ShelfActivity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "ShelfActivity"
|
||||||
|
|
||||||
|
const val YYYY_MM_DD__EEEE_HH_MM_SS = "yyyy年MM月dd日 EEEE***HH:mm:ss"
|
||||||
|
const val SHELF_MODEL = "shelfModel"
|
||||||
|
const val RECEIVER_DEVICE_INFO = "receiverDeviceInfo"
|
||||||
|
const val SHELF_WEIGHT = "shelfWeight"
|
||||||
|
const val SHELF_INDEX = "shelfIndex"
|
||||||
|
|
||||||
|
const val PAGE_SIZE = 100
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityShelfBinding
|
||||||
|
|
||||||
|
private var shelfModel: ShelfModel? = null
|
||||||
|
|
||||||
|
private var clickIndex: Int = -1
|
||||||
|
|
||||||
|
private var realWeight: Int = 0
|
||||||
|
private var pageNo: Int = 1
|
||||||
|
|
||||||
|
private val viewModel: NetViewModel by viewModels()
|
||||||
|
|
||||||
|
|
||||||
|
@SuppressLint("UnspecifiedRegisterReceiverFlag")
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityShelfBinding.inflate(layoutInflater)
|
||||||
|
setBackground()
|
||||||
|
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?.toInt()?:0
|
||||||
|
binding.tvFoodWeight.text = if(realWeight < 1000) "${realWeight}克" else "%.3f千克".format(realWeight/1000.0)
|
||||||
|
startTime = System.currentTimeMillis()
|
||||||
|
}
|
||||||
|
|
||||||
|
initRecyclerView()
|
||||||
|
|
||||||
|
binding.etInputFood.run {
|
||||||
|
addOnActionSearchListener {
|
||||||
|
if (text.isNullOrBlank()) {
|
||||||
|
toast(hint.toString())
|
||||||
|
return@addOnActionSearchListener
|
||||||
|
}
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
KeyboardUtil.hideKeyboard(context, this)
|
||||||
|
}
|
||||||
|
addTextChangedListener(afterTextChanged = { editable ->
|
||||||
|
if (editable.isNullOrBlank()) {
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.btnConfirm.clickWithDebounce {
|
||||||
|
if (clickIndex < 0) {
|
||||||
|
toast("请选择食材")
|
||||||
|
return@clickWithDebounce
|
||||||
|
}
|
||||||
|
val currentGoodsId = list[clickIndex].goodsId ?: ""
|
||||||
|
val data = ShelfModel(
|
||||||
|
shelfName = shelfModel?.shelfName,
|
||||||
|
goodsId = currentGoodsId,
|
||||||
|
goodsName = list[clickIndex].goodsName,
|
||||||
|
weight = realWeight.toDouble(),
|
||||||
|
overdueDay = list[clickIndex].overdueDay,
|
||||||
|
// createTime = if (shelfModel?.goodsId == currentGoodsId) null else DateTimeUtil.formatDateTime(dateTime = Date())
|
||||||
|
putCabinetDay = DateTimeUtil.formatDateTime(dateTime = Date())
|
||||||
|
)
|
||||||
|
val intent = Intent().apply {
|
||||||
|
putExtra(SHELF_MODEL, data)
|
||||||
|
}
|
||||||
|
setResult(RESULT_OK, intent)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
binding.root.setOnClickListener { v ->
|
||||||
|
KeyboardUtil.hideKeyboard(v)
|
||||||
|
}
|
||||||
|
binding.btnClearZero.setOnClickListener {
|
||||||
|
clearZero()
|
||||||
|
}
|
||||||
|
binding.btnClearEmpty.setOnClickListener {
|
||||||
|
val tempWeight = shelfModel?.weight?.toInt()?:0
|
||||||
|
clearZero()
|
||||||
|
binding.tvFoodName.text = "-"
|
||||||
|
//binding.tvFoodWeight.text = "0克"
|
||||||
|
EventBus.getDefault().post(ClearShelfEvent(shelfModel!!.deviceNo, tempWeight))
|
||||||
|
}
|
||||||
|
sendCmd(ScaleManager.buildGetStatusCmd())
|
||||||
|
lifecycleScope.launch {
|
||||||
|
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||||
|
viewModel.getGoodsListUiState.collect { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Loading -> showProgress()
|
||||||
|
is UiState.Success<*> -> updateUI(state.data)
|
||||||
|
is UiState.Error -> showError(state.msg)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// registerReceiver(receiver, IntentFilter(RECEIVER_DEVICE_INFO + shelfModel?.deviceNo))
|
||||||
|
binding.ivBack?.setOnClickListener { finish() }
|
||||||
|
binding.refreshLayout.let {
|
||||||
|
it.setEnableRefresh(true)
|
||||||
|
it.setEnableLoadMore(false)
|
||||||
|
it.setOnRefreshListener {
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
}
|
||||||
|
it.setOnLoadMoreListener { getGoodsList() }
|
||||||
|
}
|
||||||
|
getGoodsList()
|
||||||
|
|
||||||
|
// TaskManager.startDeviceTask()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun finishRefresh() {
|
||||||
|
binding.refreshLayout.let {
|
||||||
|
if (it.state == RefreshState.Refreshing) {
|
||||||
|
it.finishRefresh(500)
|
||||||
|
} else if (binding.refreshLayout.state == RefreshState.Loading) {
|
||||||
|
it.finishLoadMore(500)
|
||||||
|
} else {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getGoodsList() {
|
||||||
|
viewModel.getGoodsList(
|
||||||
|
canteenId = App.canteenId,
|
||||||
|
goodsName = binding.etInputFood.text.trim().toString(),
|
||||||
|
pageNo = pageNo,
|
||||||
|
pageSize = PAGE_SIZE
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showProgress() {
|
||||||
|
Loading.show(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun updateUI(data: RespData<*>) {
|
||||||
|
binding.include?.root?.gone()
|
||||||
|
finishRefresh()
|
||||||
|
binding.root.postDelayed({ Loading.dismiss() }, 200)
|
||||||
|
Log.d(TAG, "updateUI: ${data.toJsonString()}")
|
||||||
|
|
||||||
|
val goodsList = data.data as MutableList<GoodsModel>
|
||||||
|
if (data.data.isNullOrEmpty()) {
|
||||||
|
if (pageNo == 1) {
|
||||||
|
loadEmptyView()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if(pageNo == 1){
|
||||||
|
list.clear()
|
||||||
|
}
|
||||||
|
// var firstOne:GoodsModel?=null
|
||||||
|
// if (pageNo == 1) {
|
||||||
|
// if (shelfModel?.goodsId.isNullOrBlank().not()) {
|
||||||
|
// firstOne = list.firstOrNull { it.goodsId == shelfModel?.goodsId }
|
||||||
|
// if (firstOne == null) {
|
||||||
|
// firstOne = GoodsModel(
|
||||||
|
// goodsId = shelfModel?.goodsId,
|
||||||
|
// goodsName = shelfModel?.goodsName,
|
||||||
|
// isClicked = true
|
||||||
|
// )
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// list.clear()
|
||||||
|
// }
|
||||||
|
// val records = data.data.records
|
||||||
|
// if (pageNo == 1) {
|
||||||
|
// firstOne?.let { one ->
|
||||||
|
// val filterResult = records.firstOrNull{one.goodsId == it.goodsId }
|
||||||
|
// if (filterResult != null) {
|
||||||
|
// records.remove(filterResult)
|
||||||
|
// }
|
||||||
|
// clickIndex = 0
|
||||||
|
// list.add(one)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
list.addAll(goodsList)
|
||||||
|
val enableLoadMore = goodsList.size >= PAGE_SIZE
|
||||||
|
binding.refreshLayout.setEnableLoadMore(enableLoadMore)
|
||||||
|
if (enableLoadMore) {
|
||||||
|
pageNo++
|
||||||
|
}
|
||||||
|
searchAdapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showError(message: String) {
|
||||||
|
finishRefresh()
|
||||||
|
Loading.dismiss()
|
||||||
|
toast(message)
|
||||||
|
if (pageNo == 1) {
|
||||||
|
loadEmptyView()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
EventBus.getDefault().unregister(this)
|
||||||
|
// TaskManager.cancelDeviceTask()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val list: MutableList<GoodsModel> = mutableListOf()
|
||||||
|
private val searchAdapter by lazy {
|
||||||
|
SearchAdapter(list).apply {
|
||||||
|
setOnDebouncedItemClick { adapter, v, position ->
|
||||||
|
this@ShelfActivity.clickIndex = position
|
||||||
|
list.forEach { it.isClicked = false }
|
||||||
|
list[position].isClicked = true
|
||||||
|
notifyDataSetChanged()
|
||||||
|
binding.tvFoodName.text = list[position].goodsName
|
||||||
|
KeyboardUtil.hideKeyboard(v.context, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initRecyclerView() {
|
||||||
|
binding.rvSearch.run {
|
||||||
|
layoutManager = GridLayoutManager(this@ShelfActivity, 2)
|
||||||
|
adapter = searchAdapter
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 覆写时钟回调:左侧状态栏显示年月日星期,右侧状态栏显示时分秒
|
||||||
|
*/
|
||||||
|
override fun onClockTick() {
|
||||||
|
val sdf = SimpleDateFormat(YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
|
||||||
|
val arr = sdf.format(Date()).split("***")
|
||||||
|
updateLeftStatus(arr[0])
|
||||||
|
updateRightStatus(arr[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
hideStatusBar()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun loadEmptyView() {
|
||||||
|
list.clear()
|
||||||
|
searchAdapter.notifyDataSetChanged()
|
||||||
|
binding.include?.let {
|
||||||
|
it.root.visible()
|
||||||
|
it.root.setOnClickListener {
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
}
|
||||||
|
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_gray)
|
||||||
|
it.ivEmptyIcon.updateLayoutParams<LinearLayout.LayoutParams> {
|
||||||
|
val swDpValue = resources?.configuration?.smallestScreenWidthDp ?: 0
|
||||||
|
width = if (swDpValue > 600) 200.dp else 120.dp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.refreshLayout.run {
|
||||||
|
setEnableRefresh(false)
|
||||||
|
setEnableLoadMore(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Subscribe(threadMode = ThreadMode.MAIN)
|
||||||
|
public fun receiveWeightEvent(event: SendWeightEvent) {
|
||||||
|
if (event.shelfNo == (shelfModel?.deviceNo ?: 0)) {
|
||||||
|
val intervalTime = System.currentTimeMillis() - startTime
|
||||||
|
val weight = event.weight
|
||||||
|
log("编号${event.shelfNo}货架获取重量成功:${weight}克,数据获取间隔时间为:${intervalTime}")
|
||||||
|
binding.tvFoodWeight.text = if(weight < 1000) "${weight}克" else "%.3f千克".format(weight/1000.0)
|
||||||
|
startTime = System.currentTimeMillis()
|
||||||
|
window.decorView.postDelayed({ Loading.dismiss() }, 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clearZero() {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val shelfNo = shelfModel?.deviceNo ?: 0
|
||||||
|
val zeroClearingCmd = ScaleManager.buildScaleZeroCmd(shelfNo)
|
||||||
|
log("编号${shelfNo}货架执行清零指令:${zeroClearingCmd}")
|
||||||
|
sendCmd(zeroClearingCmd)
|
||||||
|
// sendCmd(
|
||||||
|
// if (shelfNo in 1..5) ProtocolConstants.LEFT_SHELF_OPEN_CMD else ProtocolConstants.RIGHT_SHELF_OPEN_CMD
|
||||||
|
// )
|
||||||
|
//清零
|
||||||
|
realWeight = 0
|
||||||
|
// binding.tvFoodWeight.text = "${realWeight}克"
|
||||||
|
|
||||||
|
sendCmd(ScaleManager.buildGetStatusCmd())
|
||||||
|
startTime = System.currentTimeMillis()
|
||||||
|
Loading.show(this@ShelfActivity)
|
||||||
|
window.decorView.postDelayed({ Loading.dismiss() }, 10000)
|
||||||
|
}
|
||||||
|
KeyboardUtil.hideKeyboard(window.decorView)
|
||||||
|
}
|
||||||
|
private var startTime = 0L
|
||||||
|
}
|
||||||
@@ -0,0 +1,384 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.activity
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.core.view.updateLayoutParams
|
||||||
|
import androidx.core.widget.addTextChangedListener
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||||
|
import com.scwang.smart.refresh.layout.constant.RefreshState
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
import com.shuwei.intelligent.shelves.adapter.CleanPackageAdapter
|
||||||
|
import com.shuwei.intelligent.shelves.adapter.MealPackageAdapter
|
||||||
|
import com.shuwei.intelligent.shelves.base.BaseActivity
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ActivityShelfV2Binding
|
||||||
|
import com.shuwei.intelligent.shelves.model.CleanPackageOption
|
||||||
|
import com.shuwei.intelligent.shelves.model.MealPackageOption
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfModelV2
|
||||||
|
import com.shuwei.intelligent.shelves.model.SendWeightEvent
|
||||||
|
import com.shuwei.intelligent.shelves.net.Loading
|
||||||
|
import com.shuwei.intelligent.shelves.net.NetViewModelV2
|
||||||
|
import com.shuwei.intelligent.shelves.net.RespData
|
||||||
|
import com.shuwei.intelligent.shelves.net.UiState
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleManager
|
||||||
|
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.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
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
class ShelfV2Activity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val SHELF_MODEL = "shelfModel"
|
||||||
|
const val YYYY_MM_DD__EEEE_HH_MM_SS = "yyyy年MM月dd日 EEEE***HH:mm:ss"
|
||||||
|
|
||||||
|
/** itemType=1:净菜包 */
|
||||||
|
private const val TYPE_CLEAN = 1
|
||||||
|
|
||||||
|
/** itemType=2:餐品净菜包 */
|
||||||
|
private const val TYPE_MEAL = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityShelfV2Binding
|
||||||
|
|
||||||
|
private var recordItem: ShelfModelV2? = null
|
||||||
|
private var realWeight: Int = 0
|
||||||
|
private var startTime = 0L
|
||||||
|
|
||||||
|
private val viewModel: NetViewModelV2 by viewModels()
|
||||||
|
|
||||||
|
// 当前选中类型,默认净菜包
|
||||||
|
private var currentType = TYPE_CLEAN
|
||||||
|
|
||||||
|
// 净菜包列表与 Adapter
|
||||||
|
private val cleanList: MutableList<CleanPackageOption> = mutableListOf()
|
||||||
|
private val cleanAdapter by lazy {
|
||||||
|
CleanPackageAdapter(cleanList).apply {
|
||||||
|
setOnDebouncedItemClick { _, _, position ->
|
||||||
|
cleanList.forEachIndexed { index, option -> option.isSelected = index == position }
|
||||||
|
notifyDataSetChanged()
|
||||||
|
binding.tvFoodName.text = cleanList[position].itemName
|
||||||
|
KeyboardUtil.hideKeyboard(this@ShelfV2Activity.window.decorView)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 餐品净菜包列表与 Adapter
|
||||||
|
private val mealList: MutableList<MealPackageOption> = mutableListOf()
|
||||||
|
private val mealAdapter by lazy {
|
||||||
|
MealPackageAdapter(mealList).apply {
|
||||||
|
setOnDebouncedItemClick { _, _, position ->
|
||||||
|
mealList.forEachIndexed { index, option -> option.isSelected = index == position }
|
||||||
|
notifyDataSetChanged()
|
||||||
|
binding.tvFoodName.text = mealList[position].itemName
|
||||||
|
KeyboardUtil.hideKeyboard(this@ShelfV2Activity.window.decorView)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityShelfV2Binding.inflate(layoutInflater)
|
||||||
|
setBackground()
|
||||||
|
setContentView(binding.root)
|
||||||
|
EventBus.getDefault().register(this)
|
||||||
|
|
||||||
|
recordItem = intent.getSerializableExtra(SHELF_MODEL) as? ShelfModelV2
|
||||||
|
recordItem?.let {
|
||||||
|
binding.tvShelfName.text = it.slotNo
|
||||||
|
binding.tvFoodName.text = if (it.itemName.isNullOrBlank()) "-" else it.itemName
|
||||||
|
val weightG = it.weight?.toDouble() ?: 0.0
|
||||||
|
realWeight = (weightG * 1000.0).toInt()
|
||||||
|
binding.tvFoodWeight.text = if (weightG >= 1.0) "%.3f千克".format(weightG)
|
||||||
|
else "${realWeight}克"
|
||||||
|
startTime = System.currentTimeMillis()
|
||||||
|
}
|
||||||
|
|
||||||
|
initChipGroup()
|
||||||
|
initRecyclerView()
|
||||||
|
initSearchBox()
|
||||||
|
initButtons()
|
||||||
|
observeViewModel()
|
||||||
|
|
||||||
|
sendCmd(ScaleManager.buildGetStatusCmd())
|
||||||
|
loadList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initChipGroup() {
|
||||||
|
binding.chipGroupType.setOnCheckedStateChangeListener { _, checkedIds ->
|
||||||
|
currentType = when {
|
||||||
|
checkedIds.contains(R.id.chipClean) -> TYPE_CLEAN
|
||||||
|
checkedIds.contains(R.id.chipMeal) -> TYPE_MEAL
|
||||||
|
else -> currentType
|
||||||
|
}
|
||||||
|
// 切换时清空搜索框并重新加载列表
|
||||||
|
binding.etInputFood.setText("")
|
||||||
|
switchAdapter()
|
||||||
|
loadList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun switchAdapter() {
|
||||||
|
val adapter: BaseQuickAdapter<*, *> =
|
||||||
|
if (currentType == TYPE_CLEAN) cleanAdapter else mealAdapter
|
||||||
|
binding.rvSearch.adapter = adapter
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initRecyclerView() {
|
||||||
|
binding.rvSearch.run {
|
||||||
|
layoutManager = GridLayoutManager(this@ShelfV2Activity, 2)
|
||||||
|
adapter = cleanAdapter
|
||||||
|
}
|
||||||
|
binding.refreshLayout.run {
|
||||||
|
setEnableRefresh(true)
|
||||||
|
setEnableLoadMore(false)
|
||||||
|
setOnRefreshListener { loadList() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initSearchBox() {
|
||||||
|
binding.etInputFood.run {
|
||||||
|
addOnActionSearchListener {
|
||||||
|
loadList()
|
||||||
|
KeyboardUtil.hideKeyboard(context, this)
|
||||||
|
}
|
||||||
|
addTextChangedListener(afterTextChanged = { editable ->
|
||||||
|
if (editable.isNullOrBlank()) loadList()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initButtons() {
|
||||||
|
binding.ivBack.setOnClickListener { finish() }
|
||||||
|
binding.btnClearZero.setOnClickListener {
|
||||||
|
Loading.show(this@ShelfV2Activity)
|
||||||
|
clearZero()
|
||||||
|
window.decorView.postDelayed({ Loading.dismiss() }, 10000)
|
||||||
|
}
|
||||||
|
binding.btnClearEmpty.setOnClickListener { v ->
|
||||||
|
clearZero()
|
||||||
|
binding.tvFoodName.text = "-"
|
||||||
|
|
||||||
|
Loading.show(this@ShelfV2Activity)
|
||||||
|
v.postDelayed({
|
||||||
|
Loading.dismiss()
|
||||||
|
// 3 秒后自动关闭 Activity 并回传空值
|
||||||
|
val emptyRecord = recordItem?.also {
|
||||||
|
it.itemName = ""
|
||||||
|
//4-空置
|
||||||
|
it.slotStatus = 4
|
||||||
|
// it.totalWeightG = null
|
||||||
|
// it.actualQty = null
|
||||||
|
it.weight = null
|
||||||
|
it.itemType = 0
|
||||||
|
it.traceCode = null
|
||||||
|
it.storeTime = null
|
||||||
|
it.spec = null
|
||||||
|
it.specLabel = null
|
||||||
|
it.cleanOrderNo = null
|
||||||
|
}
|
||||||
|
val result = Intent().apply {
|
||||||
|
putExtra(SHELF_MODEL, emptyRecord)
|
||||||
|
}
|
||||||
|
setResult(RESULT_OK, result)
|
||||||
|
finish()
|
||||||
|
}, 3000)
|
||||||
|
}
|
||||||
|
binding.btnConfirm.clickWithDebounce {
|
||||||
|
var shelfModelV2: ShelfModelV2? = null
|
||||||
|
if (currentType == TYPE_CLEAN) {
|
||||||
|
val item = cleanList.firstOrNull { it.isSelected }
|
||||||
|
if (item == null) {
|
||||||
|
toast("请选择净菜包"); return@clickWithDebounce
|
||||||
|
}
|
||||||
|
shelfModelV2 = item.toShelfModelV2(recordItem).also {
|
||||||
|
//1-存放中
|
||||||
|
it.slotStatus = 1
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val item = mealList.firstOrNull { it.isSelected }
|
||||||
|
if (item == null) {
|
||||||
|
toast("请选择餐品净菜包"); return@clickWithDebounce
|
||||||
|
}
|
||||||
|
shelfModelV2 = item.toShelfModelV2(recordItem).also {
|
||||||
|
//1-存放中
|
||||||
|
it.slotStatus = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 将选中结果回传给上层 Activity
|
||||||
|
val result = Intent().apply {
|
||||||
|
putExtra(SHELF_MODEL, shelfModelV2)
|
||||||
|
}
|
||||||
|
setResult(RESULT_OK, result)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun observeViewModel() {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||||
|
launch {
|
||||||
|
viewModel.cleanPackageOptionsUiState.collect { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Loading -> showProgress()
|
||||||
|
is UiState.Success<*> -> updateCleanList(state.data)
|
||||||
|
is UiState.Error -> showError(state.msg)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
viewModel.mealPackageOptionsUiState.collect { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Loading -> showProgress()
|
||||||
|
is UiState.Success<*> -> updateMealList(state.data)
|
||||||
|
is UiState.Error -> showError(state.msg)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadList() {
|
||||||
|
val keyword = binding.etInputFood.text.trim().toString().ifBlank { null }
|
||||||
|
if (currentType == TYPE_CLEAN) {
|
||||||
|
viewModel.getCleanPackageOptions(keyword = keyword)
|
||||||
|
} else {
|
||||||
|
viewModel.getMealPackageOptions(keyword = keyword)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showProgress() {
|
||||||
|
Loading.show(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun updateCleanList(data: RespData<*>) {
|
||||||
|
finishRefresh()
|
||||||
|
binding.include?.root?.gone()
|
||||||
|
binding.root.postDelayed({ Loading.dismiss() }, 200)
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
val items = data.data as? List<CleanPackageOption>
|
||||||
|
if (items.isNullOrEmpty()) {
|
||||||
|
loadEmptyView(); return
|
||||||
|
}
|
||||||
|
cleanList.clear()
|
||||||
|
cleanList.addAll(items)
|
||||||
|
cleanAdapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun updateMealList(data: RespData<*>) {
|
||||||
|
finishRefresh()
|
||||||
|
binding.include?.root?.gone()
|
||||||
|
binding.root.postDelayed({ Loading.dismiss() }, 200)
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
val items = data.data as? List<MealPackageOption>
|
||||||
|
if (items.isNullOrEmpty()) {
|
||||||
|
loadEmptyView(); return
|
||||||
|
}
|
||||||
|
mealList.clear()
|
||||||
|
mealList.addAll(items)
|
||||||
|
mealAdapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showError(message: String) {
|
||||||
|
finishRefresh()
|
||||||
|
Loading.dismiss()
|
||||||
|
toast(message)
|
||||||
|
loadEmptyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun loadEmptyView() {
|
||||||
|
cleanList.clear()
|
||||||
|
mealList.clear()
|
||||||
|
cleanAdapter.notifyDataSetChanged()
|
||||||
|
mealAdapter.notifyDataSetChanged()
|
||||||
|
binding.include?.let {
|
||||||
|
it.root.visible()
|
||||||
|
it.root.setOnClickListener { loadList() }
|
||||||
|
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_gray)
|
||||||
|
it.ivEmptyIcon.updateLayoutParams<LinearLayout.LayoutParams> {
|
||||||
|
val swDpValue = resources?.configuration?.smallestScreenWidthDp ?: 0
|
||||||
|
width = if (swDpValue > 600) 200.dp else 120.dp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.refreshLayout.run {
|
||||||
|
setEnableRefresh(false)
|
||||||
|
setEnableLoadMore(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun finishRefresh() {
|
||||||
|
binding.refreshLayout.let {
|
||||||
|
if (it.state == RefreshState.Refreshing) it.finishRefresh(500)
|
||||||
|
else if (it.state == RefreshState.Loading) it.finishLoadMore(500)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clearZero() {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val slotNum = recordItem?.slotNo?.filter { it.isDigit() }?.toIntOrNull() ?: 0
|
||||||
|
val zeroClearingCmd = ScaleManager.buildScaleZeroCmd(slotNum)
|
||||||
|
log("格口${recordItem?.slotNo}执行清零指令:$zeroClearingCmd")
|
||||||
|
sendCmd(zeroClearingCmd)
|
||||||
|
realWeight = 0
|
||||||
|
sendCmd(ScaleManager.buildGetStatusCmd())
|
||||||
|
startTime = System.currentTimeMillis()
|
||||||
|
}
|
||||||
|
KeyboardUtil.hideKeyboard(window.decorView)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onClockTick() {
|
||||||
|
val sdf = SimpleDateFormat(YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
|
||||||
|
val arr = sdf.format(Date()).split("***")
|
||||||
|
updateLeftStatus(arr[0])
|
||||||
|
updateRightStatus(arr[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
hideStatusBar()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
EventBus.getDefault().unregister(this)
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Subscribe(threadMode = ThreadMode.MAIN)
|
||||||
|
fun receiveWeightEvent(event: SendWeightEvent) {
|
||||||
|
val slotNum = recordItem?.slotNo?.filter { it.isDigit() }?.toIntOrNull() ?: return
|
||||||
|
if (event.shelfNo != slotNum) return
|
||||||
|
val intervalTime = System.currentTimeMillis() - startTime
|
||||||
|
val weight = event.weight
|
||||||
|
log("格口${recordItem?.slotNo}获取重量:${weight}克,间隔:${intervalTime}ms")
|
||||||
|
binding.tvFoodWeight.text = if (weight < 1000) "${weight}克"
|
||||||
|
else "%.3f千克".format(weight / 1000.0)
|
||||||
|
startTime = System.currentTimeMillis()
|
||||||
|
window.decorView.postDelayed({ Loading.dismiss() }, 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.res.ColorStateList
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.annotation.ColorRes
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import androidx.core.graphics.toColorInt
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ListItemSearchBinding
|
||||||
|
import com.shuwei.intelligent.shelves.model.CleanPackageOption
|
||||||
|
|
||||||
|
class CleanPackageAdapter(list: MutableList<CleanPackageOption>) :
|
||||||
|
BaseQuickAdapter<CleanPackageOption, CleanPackageAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(val binding: ListItemSearchBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val binding = ListItemSearchBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: CleanPackageOption?) {
|
||||||
|
item ?: return
|
||||||
|
val isSelected = item.isSelected
|
||||||
|
holder.binding.btnFoodName.run {
|
||||||
|
text = " ${item.itemName}"
|
||||||
|
setTextColor(getColor(if (isSelected) R.color.shelf_name_blue else R.color.black999))
|
||||||
|
strokeColor = ColorStateList.valueOf(
|
||||||
|
(if (isSelected) "#4969F5" else "#E6E6E6").toColorInt()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ListItemLogBinding
|
||||||
|
|
||||||
|
class LogAdapter(list: MutableList<String>) :
|
||||||
|
BaseQuickAdapter<String, LogAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemLogBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val inflater = LayoutInflater.from(context)
|
||||||
|
val binding = ListItemLogBinding.inflate(inflater, parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: String?) {
|
||||||
|
holder.binding.tvLogName.text = item
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.res.ColorStateList
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.annotation.ColorRes
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import androidx.core.graphics.toColorInt
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ListItemSearchBinding
|
||||||
|
import com.shuwei.intelligent.shelves.model.MealPackageOption
|
||||||
|
|
||||||
|
class MealPackageAdapter(list: MutableList<MealPackageOption>) :
|
||||||
|
BaseQuickAdapter<MealPackageOption, MealPackageAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(val binding: ListItemSearchBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
var selectedId: Long = -1L
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val binding = ListItemSearchBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: MealPackageOption?) {
|
||||||
|
item ?: return
|
||||||
|
val isSelected = item.isSelected
|
||||||
|
holder.binding.btnFoodName.run {
|
||||||
|
text = " ${item.itemName}"
|
||||||
|
setTextColor(getColor(if (isSelected) R.color.shelf_name_blue else R.color.black999))
|
||||||
|
strokeColor = ColorStateList.valueOf(
|
||||||
|
(if (isSelected) "#4969F5" else "#E6E6E6").toColorInt()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
|
||||||
|
}
|
||||||
@@ -11,10 +11,10 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
|||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.intelligent.shelves.R
|
import com.shuwei.intelligent.shelves.R
|
||||||
import com.shuwei.intelligent.shelves.databinding.ListItemSearchBinding
|
import com.shuwei.intelligent.shelves.databinding.ListItemSearchBinding
|
||||||
import com.shuwei.intelligent.shelves.model.SearchModel
|
import com.shuwei.intelligent.shelves.model.GoodsModel
|
||||||
|
|
||||||
class SearchAdapter(list: MutableList<SearchModel>) :
|
class SearchAdapter(list: MutableList<GoodsModel>) :
|
||||||
BaseQuickAdapter<SearchModel, SearchAdapter.VH>(list) {
|
BaseQuickAdapter<GoodsModel, SearchAdapter.VH>(list) {
|
||||||
|
|
||||||
inner class VH(var binding: ListItemSearchBinding) : QuickViewHolder(binding.root)
|
inner class VH(var binding: ListItemSearchBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
@@ -24,10 +24,10 @@ class SearchAdapter(list: MutableList<SearchModel>) :
|
|||||||
return VH(binding)
|
return VH(binding)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: SearchModel?) {
|
override fun onBindViewHolder(holder: VH, position: Int, item: GoodsModel?) {
|
||||||
val binding = holder.binding
|
val binding = holder.binding
|
||||||
binding.btnFoodName.run {
|
binding.btnFoodName.run {
|
||||||
text = item!!.foodName
|
text = " ${item!!.goodsName}"
|
||||||
setTextColor(
|
setTextColor(
|
||||||
getColor(if (item.isClicked) R.color.shelf_name_blue else R.color.black999)
|
getColor(if (item.isClicked) R.color.shelf_name_blue else R.color.black999)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|||||||
import com.shuwei.intelligent.shelves.R
|
import com.shuwei.intelligent.shelves.R
|
||||||
import com.shuwei.intelligent.shelves.databinding.ListItemShelfBinding
|
import com.shuwei.intelligent.shelves.databinding.ListItemShelfBinding
|
||||||
import com.shuwei.intelligent.shelves.model.ShelfModel
|
import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||||
|
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.gone
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.visible
|
||||||
|
import java.util.Date
|
||||||
|
import kotlin.math.abs
|
||||||
|
|
||||||
class ShelfAdapter(list: MutableList<ShelfModel>) :
|
class ShelfAdapter(list: MutableList<ShelfModel>) :
|
||||||
BaseQuickAdapter<ShelfModel, ShelfAdapter.VH>(list) {
|
BaseQuickAdapter<ShelfModel, ShelfAdapter.VH>(list) {
|
||||||
@@ -22,12 +27,51 @@ class ShelfAdapter(list: MutableList<ShelfModel>) :
|
|||||||
return VH(binding)
|
return VH(binding)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun stringToDate(createTime: String?): Date? {
|
||||||
|
if (createTime.isNullOrBlank()) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return DateTimeUtil.stringToDate(createTime)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: ShelfModel?) {
|
override fun onBindViewHolder(holder: VH, position: Int, item: ShelfModel?) {
|
||||||
val shelfNo = item!!.shelfNo
|
val shelfNo = item!!.deviceNo
|
||||||
item.shelfName = "货架-${if (shelfNo < 10) "0${shelfNo}" else "$shelfNo" }"
|
//货架-
|
||||||
val weight = item.foodWeight ?: 0
|
item.shelfName = "${if (shelfNo < 10) "0${shelfNo}" else "$shelfNo"}"
|
||||||
|
val weight = item.weight ?: 0.0
|
||||||
val binding = holder.binding
|
val binding = holder.binding
|
||||||
val isBlankShelf = weight <= 0
|
if (item.overdueDay.isNullOrBlank()) {
|
||||||
|
binding.ivStaleFood.gone()
|
||||||
|
} else {
|
||||||
|
runCatching {
|
||||||
|
// val shelfDate = stringToDate(item.putCabinetDay)
|
||||||
|
binding.ivStaleFood.run {
|
||||||
|
if (item.overdue == true) visible() else gone()
|
||||||
|
}
|
||||||
|
// if (shelfDate == null) {
|
||||||
|
// binding.ivStaleFood.gone()
|
||||||
|
// } else {
|
||||||
|
// val days = item.overdueDay!!.toInt()
|
||||||
|
// val resultDate = DateTimeUtil.addDays(shelfDate, days)
|
||||||
|
// if (resultDate.before(Date())) {
|
||||||
|
// binding.ivStaleFood.visible()
|
||||||
|
// } else {
|
||||||
|
// binding.ivStaleFood.gone()
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
}.onFailure {
|
||||||
|
binding.ivStaleFood.gone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//?.setImageResource()
|
||||||
|
binding.tvFoodWeight.run {
|
||||||
|
setTextColor(getColor(R.color.food_weight_orange))
|
||||||
|
//val showWeight = if (weight == 0.toDouble()) "0克" else "%.3f千克".format(weight)
|
||||||
|
text = if(abs(weight) < 1000) "${weight.toInt()}克" else "%.3f千克".format(weight/1000.0)
|
||||||
|
//"${(weight*1000).roundToInt()}克"
|
||||||
|
}
|
||||||
|
//val isBlankShelf = weight <= 0
|
||||||
|
val isBlankShelf = item.goodsName.isNullOrBlank()
|
||||||
if (isBlankShelf) {
|
if (isBlankShelf) {
|
||||||
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_blue))
|
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_blue))
|
||||||
binding.tvShelfName.run {
|
binding.tvShelfName.run {
|
||||||
@@ -38,10 +82,10 @@ class ShelfAdapter(list: MutableList<ShelfModel>) :
|
|||||||
setTextColor(getColor(R.color.white))
|
setTextColor(getColor(R.color.white))
|
||||||
text = "空"
|
text = "空"
|
||||||
}
|
}
|
||||||
binding.tvFoodWeight.run {
|
// binding.tvFoodWeight.run {
|
||||||
setTextColor(getColor(R.color.food_weight_blue))
|
// setTextColor(getColor(R.color.food_weight_blue))
|
||||||
text = "0千克"
|
// text = "0千克"
|
||||||
}
|
// }
|
||||||
binding.tvStoreDate.run {
|
binding.tvStoreDate.run {
|
||||||
setTextColor(getColor(R.color.food_weight_blue))
|
setTextColor(getColor(R.color.food_weight_blue))
|
||||||
text = "-"
|
text = "-"
|
||||||
@@ -55,15 +99,16 @@ class ShelfAdapter(list: MutableList<ShelfModel>) :
|
|||||||
}
|
}
|
||||||
binding.tvFoodName.run {
|
binding.tvFoodName.run {
|
||||||
setTextColor(getColor(R.color.food_name_black))
|
setTextColor(getColor(R.color.food_name_black))
|
||||||
text = item.foodName
|
text = item.goodsName
|
||||||
}
|
|
||||||
binding.tvFoodWeight.run {
|
|
||||||
setTextColor(getColor(R.color.food_weight_orange))
|
|
||||||
text = "${weight/1000F}千克"
|
|
||||||
}
|
}
|
||||||
|
// binding.tvFoodWeight.run {
|
||||||
|
// setTextColor(getColor(R.color.food_weight_orange))
|
||||||
|
//// text = "${weight/1000F}千克"
|
||||||
|
// text = "${weight}克"
|
||||||
|
// }
|
||||||
binding.tvStoreDate.run {
|
binding.tvStoreDate.run {
|
||||||
setTextColor(getColor(R.color.black999))
|
setTextColor(getColor(R.color.black999))
|
||||||
text = item.storeDate
|
text = item.putCabinetDay
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.annotation.ColorRes
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
import com.google.android.flexbox.FlexboxLayoutManager
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.ListItemShelfBinding
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfModelV2
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.gone
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.visible
|
||||||
|
import kotlin.math.abs
|
||||||
|
|
||||||
|
class ShelfV2Adapter(list: MutableList<ShelfModelV2>) :
|
||||||
|
BaseQuickAdapter<ShelfModelV2, ShelfV2Adapter.VH>(list) {
|
||||||
|
|
||||||
|
/** 每个格口 item 的高度(像素),由 Activity 动态计算 */
|
||||||
|
var itemHeight: Int = 0
|
||||||
|
|
||||||
|
/** 每个格口 item 的宽度(像素),由 Activity 动态计算 */
|
||||||
|
var itemWidth: Int = 0
|
||||||
|
|
||||||
|
inner class VH(val binding: ListItemShelfBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val binding = ListItemShelfBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: ShelfModelV2?) {
|
||||||
|
item ?: return
|
||||||
|
// 动态设置 item 宽高
|
||||||
|
val lp = holder.itemView.layoutParams as? FlexboxLayoutManager.LayoutParams
|
||||||
|
lp?.apply {
|
||||||
|
if (itemWidth > 0) width = itemWidth
|
||||||
|
if (itemHeight > 0) height = itemHeight
|
||||||
|
}
|
||||||
|
val binding = holder.binding
|
||||||
|
|
||||||
|
// 格口编号
|
||||||
|
binding.tvShelfName.text = item.slotNo?.padStart(2, '0')
|
||||||
|
|
||||||
|
// 临期预警(slotStatus=2)显示过期图标
|
||||||
|
if (item.slotStatus.toInt() == 2) binding.ivStaleFood.visible()
|
||||||
|
else binding.ivStaleFood.gone()
|
||||||
|
|
||||||
|
// // 重量:itemType=2 用 totalWeightG(g),itemType=1 用 actualQty×1000(g)
|
||||||
|
// val weightG = if (item.itemType == 1) (item.actualQty?.toDouble() ?: 0.0) * 1000.0
|
||||||
|
// else item.totalWeightG?.toDouble() ?: 0.0
|
||||||
|
|
||||||
|
val weightG = item.weight?.toDouble() ?: 0.0
|
||||||
|
binding.tvFoodWeight.run {
|
||||||
|
setTextColor(getColor(R.color.food_weight_orange))
|
||||||
|
text = if (abs(weightG) >= 1.0) "%.3f千克".format(weightG)
|
||||||
|
else "${(weightG * 1000.0).toInt()}克"
|
||||||
|
}
|
||||||
|
|
||||||
|
val isBlank = item.itemName.isNullOrBlank()
|
||||||
|
if (isBlank) {
|
||||||
|
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_blue))
|
||||||
|
binding.tvShelfName.setTextColor(getColor(R.color.shelf_name_white))
|
||||||
|
binding.tvFoodName.run {
|
||||||
|
setTextColor(getColor(R.color.white))
|
||||||
|
text = "空"
|
||||||
|
}
|
||||||
|
binding.tvStoreDate.run {
|
||||||
|
setTextColor(getColor(R.color.food_weight_blue))
|
||||||
|
text = "-"
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_white))
|
||||||
|
binding.tvShelfName.setTextColor(getColor(R.color.shelf_name_blue))
|
||||||
|
binding.tvFoodName.run {
|
||||||
|
setTextColor(getColor(R.color.food_name_black))
|
||||||
|
text = item.itemName
|
||||||
|
}
|
||||||
|
binding.tvStoreDate.run {
|
||||||
|
setTextColor(getColor(R.color.black999))
|
||||||
|
text = item.storeTime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
|
||||||
|
}
|
||||||
@@ -2,18 +2,40 @@ package com.shuwei.intelligent.shelves.base
|
|||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.LayoutInflater
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.widget.TextView
|
import android.widget.PopupWindow
|
||||||
import androidx.activity.enableEdgeToEdge
|
|
||||||
import androidx.activity.result.ActivityResultLauncher
|
import androidx.activity.result.ActivityResultLauncher
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.shuwei.intelligent.shelves.activity.LogActivity
|
||||||
import com.shuwei.intelligent.shelves.R
|
import com.shuwei.intelligent.shelves.R
|
||||||
import com.shuwei.intelligent.shelves.databinding.ActivityBaseBinding
|
import com.shuwei.intelligent.shelves.databinding.ActivityBaseBinding
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.PopupRightStatusMenuBinding
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.LIGHT_CLOSE
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.LIGHT_OPEN
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleManager
|
||||||
|
import com.shuwei.intelligent.shelves.utils.FileLogger
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.clickWithDebounce
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.dp
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.startActivity
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
import androidx.core.view.WindowCompat
|
||||||
|
import androidx.core.view.WindowInsetsCompat
|
||||||
|
import androidx.core.view.WindowInsetsControllerCompat
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.setOnDoubleClickListener
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
open class BaseActivity : AppCompatActivity() {
|
open class BaseActivity : AppCompatActivity() {
|
||||||
|
val TAG = this.javaClass.simpleName
|
||||||
|
|
||||||
private lateinit var binding: ActivityBaseBinding
|
private lateinit var binding: ActivityBaseBinding
|
||||||
private var launcher: ActivityResultLauncher<Intent>? = null
|
private var launcher: ActivityResultLauncher<Intent>? = null
|
||||||
@@ -31,9 +53,10 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
hideSystemBars()
|
||||||
binding = ActivityBaseBinding.inflate(layoutInflater)
|
binding = ActivityBaseBinding.inflate(layoutInflater)
|
||||||
setContentView(binding.root)
|
setContentView(binding.root)
|
||||||
statusBarDarkFont(enable = false)
|
statusBarDarkFont()
|
||||||
launcher =
|
launcher =
|
||||||
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||||
if (result.resultCode == RESULT_OK) {
|
if (result.resultCode == RESULT_OK) {
|
||||||
@@ -41,28 +64,37 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// window.setDecorFitsSystemWindows(false) // 启用 Edge-to-Edge
|
lightSwitchClick()
|
||||||
// window.insetsController?.apply {
|
|
||||||
// hide(WindowInsets.Type.statusBars()) // 隐藏状态栏
|
binding.tvLeftStatus.setOnDoubleClickListener {
|
||||||
// systemBarsBehavior =
|
//finish()
|
||||||
// WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE // 滑动时临时显示
|
val intent = Intent(Intent.ACTION_MAIN).apply {
|
||||||
// }
|
addCategory(Intent.CATEGORY_HOME)
|
||||||
|
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||||
|
}
|
||||||
|
startActivity(intent)
|
||||||
|
|
||||||
|
}
|
||||||
|
binding.tvRightStatus.setOnDoubleClickListener {
|
||||||
|
if (enableRightStatusMenu) showRightStatusPopup(binding.tvRightStatus)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun hideStatusBar() {
|
/** 是否允许右侧状态栏双击弹出菜单,默认关闭,仅 HomeActivity 开启 */
|
||||||
enableEdgeToEdge()
|
protected open val enableRightStatusMenu: Boolean = false
|
||||||
// val uiOptions = (View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
|
|
||||||
// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) // 隐藏导航栏(可选)
|
|
||||||
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
|
|
||||||
}
|
|
||||||
|
|
||||||
fun statusBarDarkFont(enable: Boolean) {
|
fun hideStatusBar() {}
|
||||||
//window.decorView.systemUiVisibility = if (enable) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
|
|
||||||
|
fun statusBarDarkFont() {
|
||||||
val color = ContextCompat.getColor(this, R.color.white)
|
val color = ContextCompat.getColor(this, R.color.white)
|
||||||
binding.tvLeftStatus.setTextColor(color)
|
binding.tvLeftStatus.setTextColor(color)
|
||||||
binding.tvRightStatus.setTextColor(color)
|
binding.tvRightStatus.setTextColor(color)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun setBackground() {
|
||||||
|
binding.root.setBackgroundColor(ContextCompat.getColor(this, R.color.bg_page))
|
||||||
|
}
|
||||||
|
|
||||||
override fun setContentView(view: View?) {
|
override fun setContentView(view: View?) {
|
||||||
if (view == binding.root) {
|
if (view == binding.root) {
|
||||||
super.setContentView(view)
|
super.setContentView(view)
|
||||||
@@ -72,12 +104,154 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun updateLeftStatus(data: String) {
|
fun updateLeftStatus(data: String) {
|
||||||
binding.tvLeftStatus.text = data
|
binding.tvLeftStatus.text = data.ifBlank { " " }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun updateRightStatus(data: String) {
|
fun updateRightStatus(data: String) {
|
||||||
binding.tvRightStatus.text = data
|
binding.tvRightStatus.text = data
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 5分钟
|
||||||
|
private val TIME_OUT: Long = (1 * 60 * 1000).toLong()
|
||||||
|
private val mHandler by lazy { Handler(Looper.getMainLooper()) }
|
||||||
|
private val mTimeoutRunnable = Runnable {
|
||||||
|
// 用户长时间无操作时回调,子类可覆写实现具体逻辑(如关灯)
|
||||||
|
onUserInactive()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 右侧状态栏时钟 ----
|
||||||
|
// 默认时间格式:月日星期 时:分:秒
|
||||||
|
private val CLOCK_FORMAT = "MM月dd日 EEEE HH:mm:ss"
|
||||||
|
private val clockFormatter by lazy { SimpleDateFormat(CLOCK_FORMAT, Locale.CHINA) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每秒时钟回调,默认将当前时间显示在右侧状态栏。
|
||||||
|
* 子类可覆写以自定义格式或同时更新左侧状态栏。
|
||||||
|
*/
|
||||||
|
open fun onClockTick() {
|
||||||
|
updateRightStatus(clockFormatter.format(Date()))
|
||||||
|
}
|
||||||
|
|
||||||
|
private val clockTask = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
onClockTick()
|
||||||
|
mHandler.postDelayed(this, 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户超时无操作时回调,默认空实现,子类按需覆写
|
||||||
|
*/
|
||||||
|
open fun onUserInactive() {}
|
||||||
|
|
||||||
|
override fun onUserInteraction() {
|
||||||
|
super.onUserInteraction()
|
||||||
|
//开灯
|
||||||
|
if (System.currentTimeMillis() - lastTouchTime >= TIME_OUT) {
|
||||||
|
this.switchLight(true)
|
||||||
|
}
|
||||||
|
// 重置定时器
|
||||||
|
mHandler.removeCallbacks(mTimeoutRunnable)
|
||||||
|
mHandler.postDelayed(mTimeoutRunnable, TIME_OUT)
|
||||||
|
lastTouchTime = System.currentTimeMillis()
|
||||||
|
}
|
||||||
|
|
||||||
|
private var lastTouchTime = 0L
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
// 启动超时定时器
|
||||||
|
mHandler.postDelayed(mTimeoutRunnable, TIME_OUT)
|
||||||
|
// 启动右侧状态栏时钟
|
||||||
|
mHandler.post(clockTask)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
// 取消超时定时器
|
||||||
|
mHandler.removeCallbacks(mTimeoutRunnable)
|
||||||
|
// 停止右侧状态栏时钟
|
||||||
|
mHandler.removeCallbacks(clockTask)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun switchLight(isOpen: Boolean) {
|
||||||
|
val tag = binding.tvLeftStatus.tag?.toString()?.toBoolean() ?: true
|
||||||
|
if (tag == isOpen) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sendCmd(if (isOpen) LIGHT_OPEN else LIGHT_CLOSE)
|
||||||
|
binding.tvLeftStatus.tag = isOpen
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lightSwitchClick() {
|
||||||
|
switchLight(true)
|
||||||
|
binding.tvLeftStatus.clickWithDebounce {
|
||||||
|
val tag = binding.tvLeftStatus.tag?.toString()?.toBoolean() ?: true
|
||||||
|
switchLight(tag.not())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showRightStatusPopup(anchor: View) {
|
||||||
|
val menuBinding = PopupRightStatusMenuBinding.inflate(LayoutInflater.from(this))
|
||||||
|
val popup = PopupWindow(
|
||||||
|
menuBinding.root,
|
||||||
|
120.dp,
|
||||||
|
101.dp,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
menuBinding.tvEnvSwitch.setOnClickListener {
|
||||||
|
popup.dismiss()
|
||||||
|
EnvSwitchDialog(this).show()
|
||||||
|
}
|
||||||
|
menuBinding.tvLog.setOnClickListener {
|
||||||
|
popup.dismiss()
|
||||||
|
startActivity<LogActivity> {
|
||||||
|
putExtra(LogActivity.IS_LOG_DIR, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
popup.showAsDropDown(anchor)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
fun sendCmd(cmd: String) {
|
||||||
|
ScaleManager.sendCmd(cmd)
|
||||||
|
log("发送命令: $cmd")
|
||||||
|
}
|
||||||
|
|
||||||
|
val fileLogger by lazy { FileLogger(this) }
|
||||||
|
fun log(message:String) {
|
||||||
|
Log.d(TAG, message)
|
||||||
|
fileLogger.log(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 窗口焦点变化时回调
|
||||||
|
* 场景:弹出 Dialog 后焦点丢失,Dialog 消失后焦点恢复,此时需重新隐藏系统栏,
|
||||||
|
* 避免系统栏在 Dialog 关闭后意外"复活"
|
||||||
|
*/
|
||||||
|
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||||
|
super.onWindowFocusChanged(hasFocus)
|
||||||
|
if (hasFocus) {
|
||||||
|
hideSystemBars()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 隐藏状态栏和导航栏
|
||||||
|
* 使用 WindowInsetsControllerCompat(Androidx 推荐方式,向下兼容性好)
|
||||||
|
* - 状态栏:完全隐藏
|
||||||
|
* - 导航栏:完全隐藏,底部上滑时临时出现,松手后自动收回(BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE)
|
||||||
|
*/
|
||||||
|
private fun hideSystemBars() {
|
||||||
|
// 允许布局延伸到系统栏区域(edge-to-edge),避免内容被系统栏遮挡
|
||||||
|
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||||
|
WindowInsetsControllerCompat(window, window.decorView).apply {
|
||||||
|
// 同时隐藏状态栏和导航栏
|
||||||
|
hide(WindowInsetsCompat.Type.systemBars())
|
||||||
|
// 底部上滑时临时显示导航栏,松手后自动隐藏(沉浸式 Sticky 模式)
|
||||||
|
systemBarsBehavior =
|
||||||
|
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.base
|
||||||
|
|
||||||
|
import android.app.Dialog
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.drawable.ColorDrawable
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.View
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.dp
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.hideKeyboard
|
||||||
|
|
||||||
|
abstract class BaseDialog(
|
||||||
|
context: Context,
|
||||||
|
var defWidth: Int = 400.dp,
|
||||||
|
var defHeight: Int = 300.dp
|
||||||
|
) : Dialog(context, R.style.DialogTheme) {
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
val rootView = getRootView()
|
||||||
|
setContentView(rootView)
|
||||||
|
setCancelable(false)
|
||||||
|
setCanceledOnTouchOutside(false)
|
||||||
|
window?.apply {
|
||||||
|
setLayout(defWidth, defHeight)
|
||||||
|
setBackgroundDrawable(ColorDrawable())
|
||||||
|
setGravity(Gravity.CENTER)
|
||||||
|
}
|
||||||
|
rootView.setOnClickListener { it.hideKeyboard() }
|
||||||
|
initView()
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract fun getRootView(): View
|
||||||
|
|
||||||
|
abstract fun initView()
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.base
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.WindowManager
|
||||||
|
import com.shuwei.intelligent.shelves.GlobalData
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.DialogEnvSwitchBinding
|
||||||
|
import com.shuwei.intelligent.shelves.utils.SpTool
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ToastUtil
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.dp
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 环境切换弹窗
|
||||||
|
*
|
||||||
|
* 提供 TEST / UAT / PROD 三套环境的切换功能,
|
||||||
|
* 初始化时自动根据 [GlobalData.appBaseUrl] 选中当前环境,
|
||||||
|
* 确认后更新 [GlobalData.appBaseUrl] 并通过 [onEnvChanged] 回调通知外部。
|
||||||
|
*
|
||||||
|
* @param context 上下文
|
||||||
|
* @param onEnvChanged 确认切换后的回调,参数为新的 baseUrl
|
||||||
|
*/
|
||||||
|
class EnvSwitchDialog(
|
||||||
|
context: Context,
|
||||||
|
private val onEnvChanged: (newBaseUrl: String) -> Unit = {}
|
||||||
|
) : BaseDialog(
|
||||||
|
context,
|
||||||
|
defWidth = 600.dp,
|
||||||
|
defHeight = WindowManager.LayoutParams.WRAP_CONTENT
|
||||||
|
) {
|
||||||
|
|
||||||
|
private lateinit var binding: DialogEnvSwitchBinding
|
||||||
|
|
||||||
|
override fun getRootView(): View {
|
||||||
|
binding = DialogEnvSwitchBinding.inflate(LayoutInflater.from(context))
|
||||||
|
return binding.root
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun initView() {
|
||||||
|
// 根据当前 appBaseUrl 预选对应 RadioButton,不匹配则不选
|
||||||
|
when (GlobalData.appBaseUrl) {
|
||||||
|
GlobalData.LOCAL_BASE_URL -> binding.rbTest.isChecked = true
|
||||||
|
GlobalData.TEST_BASE_URL -> binding.rbUat.isChecked = true
|
||||||
|
GlobalData.PROD_BASE_URL -> binding.rbProd.isChecked = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 取消按钮
|
||||||
|
binding.btnCancel.setOnClickListener { dismiss() }
|
||||||
|
|
||||||
|
// 确认按钮
|
||||||
|
binding.btnConfirm.setOnClickListener {
|
||||||
|
// 未选中任何选项时提示用户
|
||||||
|
if (binding.rgEnv.checkedRadioButtonId == -1) {
|
||||||
|
ToastUtil.show(context,"请选择环境")
|
||||||
|
return@setOnClickListener
|
||||||
|
}
|
||||||
|
val newUrl = when (binding.rgEnv.checkedRadioButtonId) {
|
||||||
|
binding.rbTest.id -> GlobalData.LOCAL_BASE_URL
|
||||||
|
binding.rbUat.id -> GlobalData.TEST_BASE_URL
|
||||||
|
binding.rbProd.id -> GlobalData.PROD_BASE_URL
|
||||||
|
else -> return@setOnClickListener
|
||||||
|
}
|
||||||
|
GlobalData.appBaseUrl = newUrl
|
||||||
|
SpTool.baseUrl = newUrl
|
||||||
|
onEnvChanged(newUrl)
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.dialog
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import com.shuwei.intelligent.shelves.base.BaseDialog
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.DialogLayoutBinding
|
||||||
|
|
||||||
|
class CommonDialog(context: Context):BaseDialog(context) {
|
||||||
|
|
||||||
|
private lateinit var binding:DialogLayoutBinding
|
||||||
|
|
||||||
|
override fun getRootView(): View {
|
||||||
|
binding = DialogLayoutBinding.inflate(LayoutInflater.from(context))
|
||||||
|
return binding.root
|
||||||
|
}
|
||||||
|
|
||||||
|
var dialogTitle:String?=null
|
||||||
|
var dialogContent:String?=null
|
||||||
|
var confirmBlock:(()->Unit)?=null
|
||||||
|
override fun initView() {
|
||||||
|
binding.btnConfirm.setOnClickListener {
|
||||||
|
confirmBlock?.invoke()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun show() {
|
||||||
|
super.show()
|
||||||
|
binding.tvDialogTitle.text = dialogTitle
|
||||||
|
binding.tvDialogContent.text = dialogContent
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 货柜初始化接口(4.1)响应体
|
||||||
|
*/
|
||||||
|
data class CabinetInitResult(
|
||||||
|
val canteenId: Long = 0,
|
||||||
|
val canteenName: String = "",
|
||||||
|
val deviceName: String = "",
|
||||||
|
val area: String = "",
|
||||||
|
val horizontalRows:Int = 0,
|
||||||
|
val verticalCount:Int = 0,
|
||||||
|
val containerGoodsList: List<ShelfModelV2>? = null,
|
||||||
|
)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
|
||||||
|
import java.math.BigDecimal
|
||||||
|
import java.util.Date
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 净菜包下拉选项,对应接口 4.2.1(itemType=1)
|
||||||
|
*/
|
||||||
|
data class CleanPackageOption(
|
||||||
|
val id: Long = 0,
|
||||||
|
val itemName: String = "",
|
||||||
|
/** 净菜订单号,sync 时作为 cleanOrderNo 回传 */
|
||||||
|
val orderNo: String = "",
|
||||||
|
val packageSpec: String? = null,
|
||||||
|
/** 关联菜品 id */
|
||||||
|
val foodId: Long? = null,
|
||||||
|
/** 需求份数 */
|
||||||
|
val needCount: Int? = null,
|
||||||
|
/** 需求计量(kg) */
|
||||||
|
val needQtyKg: BigDecimal? = null,
|
||||||
|
/** 保质期至,格式 yyyy-MM-dd */
|
||||||
|
val expiryDate: String? = null,
|
||||||
|
/** 申领时间,格式 yyyy-MM-dd HH:mm:ss,仅订单有 */
|
||||||
|
val applyTime: String? = null,
|
||||||
|
/** 数据来源:1=净菜订单,2=食材库 */
|
||||||
|
val source: Short? = null,
|
||||||
|
/** 净菜类型 id,仅订单有 */
|
||||||
|
val vegTypeId: Long? = null,
|
||||||
|
/** 食材库 id,source=2 时有值,sync 时回传 materId */
|
||||||
|
val materId: Long? = null,
|
||||||
|
var isSelected: Boolean = false
|
||||||
|
) {
|
||||||
|
/** 将净菜包选项转换为格口记录 */
|
||||||
|
fun toShelfModelV2(model: ShelfModelV2? = null) = (model ?: ShelfModelV2()).also {
|
||||||
|
it.itemType = 1
|
||||||
|
it.itemName = itemName
|
||||||
|
it.cleanOrderNo = orderNo
|
||||||
|
it.spec = packageSpec
|
||||||
|
it.foodId = foodId
|
||||||
|
it.storeTime = DateTimeUtil.formatDateTime(dateTime = Date())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
class DeviceConfigInfo {
|
||||||
|
var appPackageUrl:String? = null
|
||||||
|
var canteenId:String? = null
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
import java.io.Serializable
|
||||||
|
|
||||||
|
data class GoodsModel(
|
||||||
|
var goodsId: String? = null,
|
||||||
|
var goodsName: String? = null,
|
||||||
|
var overdueDay: String? = null,
|
||||||
|
var isClicked: Boolean = false
|
||||||
|
) : Serializable
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
data class GoodsRecord(
|
||||||
|
val total: Int = 0,
|
||||||
|
val size: Int = 0,
|
||||||
|
val page: Int = 0,
|
||||||
|
val records: MutableList<GoodsModel>? = null
|
||||||
|
)
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
|
||||||
|
import java.math.BigDecimal
|
||||||
|
import java.util.Date
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品净菜包下拉选项,对应接口 4.2.2(itemType=2)
|
||||||
|
*/
|
||||||
|
data class MealPackageOption(
|
||||||
|
val id: Long = 0,
|
||||||
|
val itemName: String = "",
|
||||||
|
/** 净菜订单号,sync 时作为 cleanOrderNo 回传 */
|
||||||
|
val orderNo: String = "",
|
||||||
|
val packageSpec: String? = null,
|
||||||
|
/** 关联菜品 id */
|
||||||
|
val foodId: Long? = null,
|
||||||
|
/** 需求份数 */
|
||||||
|
val needCount: Int? = null,
|
||||||
|
/** 需求计量(kg) */
|
||||||
|
val needQtyKg: BigDecimal? = null,
|
||||||
|
/** 保质期至,格式 yyyy-MM-dd(包装完成后有值) */
|
||||||
|
val expiryDate: String? = null,
|
||||||
|
/** 数据来源:1=净菜订单,2=餐品库 */
|
||||||
|
val source: Short? = null,
|
||||||
|
var isSelected: Boolean = false
|
||||||
|
) {
|
||||||
|
/** 将餐品净菜包选项转换为格口记录 */
|
||||||
|
fun toShelfModelV2(model: ShelfModelV2? = null) = (model ?: ShelfModelV2()).also {
|
||||||
|
it.itemType = 2
|
||||||
|
it.itemName = itemName
|
||||||
|
it.cleanOrderNo = orderNo
|
||||||
|
it.spec = packageSpec
|
||||||
|
it.foodId = foodId
|
||||||
|
it.storeTime = DateTimeUtil.formatDateTime(dateTime = Date())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下拉列表分页请求体
|
||||||
|
*
|
||||||
|
* 用于净菜包/餐品净菜包下拉接口(POST),
|
||||||
|
* pageNum、pageSize 必填,keyword 可选:
|
||||||
|
* - 不传 keyword:返回净菜订单列表
|
||||||
|
* - 传 keyword:搜索食材库/餐品库
|
||||||
|
*/
|
||||||
|
data class PageOptionsReq(
|
||||||
|
/** 页码,从 1 开始 */
|
||||||
|
val pageNum: Long = 1,
|
||||||
|
/** 每页条数 */
|
||||||
|
val pageSize: Long = 50,
|
||||||
|
/** 搜索关键字,不传返回订单列表,传值搜索库表 */
|
||||||
|
val keyword: String? = null
|
||||||
|
)
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
package com.shuwei.intelligent.shelves.model
|
|
||||||
|
|
||||||
import java.io.Serializable
|
|
||||||
|
|
||||||
data class SearchModel(
|
|
||||||
var foodId: Int? = null,
|
|
||||||
var foodName: String? = null,
|
|
||||||
var isClicked: Boolean = false
|
|
||||||
) : Serializable
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
data class SendWeightEvent(
|
||||||
|
var shelfNo: Int = 0,
|
||||||
|
var weight:Int=0
|
||||||
|
)
|
||||||
|
|
||||||
|
data class WeightEvent(var weight: Int)
|
||||||
|
|
||||||
|
data class ClearShelfEvent(var shelfNo: Int, var weight: Int)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
class ShelfBody {
|
||||||
|
|
||||||
|
var deviceId: String = ""
|
||||||
|
var canteenId: String = ""
|
||||||
|
var temperature: String? = null
|
||||||
|
var humidity: String = "0"
|
||||||
|
var goodsList: List<ShelfModel>? = null
|
||||||
|
|
||||||
|
}
|
||||||
@@ -3,9 +3,19 @@ package com.shuwei.intelligent.shelves.model
|
|||||||
import java.io.Serializable
|
import java.io.Serializable
|
||||||
|
|
||||||
data class ShelfModel(
|
data class ShelfModel(
|
||||||
var shelfNo: Int = 0,
|
var id: String? = null,
|
||||||
|
var deviceNo: Int = 0,
|
||||||
var shelfName: String? = null,
|
var shelfName: String? = null,
|
||||||
var foodName: String? = null,
|
var goodsId: String? = "",
|
||||||
var foodWeight: Int? = null,
|
var goodsName: String? = null,
|
||||||
var storeDate: String? = null
|
var deviceId: String? = null,
|
||||||
|
var weight: Double = 0.0,
|
||||||
|
var weightBak: Double = 0.0,
|
||||||
|
var createTime: String? = null,
|
||||||
|
var putCabinetDay: String? = null,
|
||||||
|
var updateTime: String? = null,
|
||||||
|
var overdueDay: String? = null,
|
||||||
|
var temperature: String? = null,
|
||||||
|
var humidity: String = "0",
|
||||||
|
var overdue:Boolean ?= false
|
||||||
) : Serializable
|
) : Serializable
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
import java.io.Serializable
|
||||||
|
import java.math.BigDecimal
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格口存放记录,对应接口 4.1 货柜初始化返回的 containerGoodsList 元素
|
||||||
|
*/
|
||||||
|
data class ShelfModelV2(
|
||||||
|
var id: Long = 0,
|
||||||
|
/** 类型:1-食材净菜 / 2-餐品净菜包 */
|
||||||
|
var itemType: Int = 0,
|
||||||
|
/** 格口编号 */
|
||||||
|
var slotNo: String? = "",
|
||||||
|
/** 格口所在柜子编号 */
|
||||||
|
var cabinetId: String? = "",
|
||||||
|
/** 智能柜名称 */
|
||||||
|
var cabinetName: String? = "",
|
||||||
|
var area: String = "",
|
||||||
|
/** 溯源码 */
|
||||||
|
var traceCode: String? = "",
|
||||||
|
/** 关联净菜订单号 */
|
||||||
|
var cleanOrderNo: String? = "",
|
||||||
|
/** 物料名称 */
|
||||||
|
var itemName: String? = "",
|
||||||
|
/** 订单量 kg(itemType=1) */
|
||||||
|
var orderQty: BigDecimal? = null,
|
||||||
|
/** 实收量 kg(itemType=1) */
|
||||||
|
// var actualQty: BigDecimal? = null,
|
||||||
|
/** 差异量 kg(itemType=1,可为负) */
|
||||||
|
var diffQty: BigDecimal? = null,
|
||||||
|
/** 规格(itemType=2,如:标准份) */
|
||||||
|
var spec: String? = null,
|
||||||
|
var specLabel: String? = null,
|
||||||
|
/** 包数(itemType=2) */
|
||||||
|
var pkgCount: Int? = null,
|
||||||
|
/** 总重量 g(itemType=2) */
|
||||||
|
// var totalWeightG: BigDecimal? = null,
|
||||||
|
/** 统一重量字段,单位千克 */
|
||||||
|
var weight: BigDecimal? = null,
|
||||||
|
/** 验收结果:1-合格 / 2-轻微差异 / 3-不合格 / 4-待验 */
|
||||||
|
var checkResult: Short? = null,
|
||||||
|
/** 存储温度(℃) */
|
||||||
|
var temperature: BigDecimal? = null,
|
||||||
|
/** 存储湿度(%) */
|
||||||
|
var humidity: BigDecimal? = null,
|
||||||
|
/** 剩余保质期(小时) */
|
||||||
|
var shelfLifeRemain: Int? = null,
|
||||||
|
var storeTime: String? = null,
|
||||||
|
/** 格口状态:1-存放中 / 2-临期预警 / 3-温度超标 / 4-空置 / 5-异常 */
|
||||||
|
var slotStatus: Short = 0,
|
||||||
|
/** 绑定菜品 id(itemType=2) */
|
||||||
|
var foodId: Long? = null,
|
||||||
|
var unit: String? = null,
|
||||||
|
var remark: String? = null,
|
||||||
|
var canteenId: Long? = null,
|
||||||
|
var isClicked: Boolean = false
|
||||||
|
) : Serializable
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
data class ShelfResult(
|
||||||
|
val placeId: String = "",
|
||||||
|
val canteenName: String = "",
|
||||||
|
val deviceName: String = "",
|
||||||
|
val containerGoodsList: List<ShelfModel>? = null
|
||||||
|
)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
import java.math.BigDecimal
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全量同步整柜数据请求体,对应接口 4.3
|
||||||
|
* 注意:goodsList 为空或不传时,后端会软删除整柜所有格口数据
|
||||||
|
*/
|
||||||
|
data class SyncBody(
|
||||||
|
var cabinetId: String?=null,
|
||||||
|
var temperature: BigDecimal? = null,
|
||||||
|
var humidity: BigDecimal? = null,
|
||||||
|
var goodsList: List<ShelfModelV2>? = null,
|
||||||
|
)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.model
|
||||||
|
|
||||||
|
import java.math.BigDecimal
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全量同步单格口数据,对应接口 4.3 goodsList 元素
|
||||||
|
*/
|
||||||
|
data class SyncItem(
|
||||||
|
val slotNo: String,
|
||||||
|
/** 类型:1-食材净菜 / 2-餐品净菜包 */
|
||||||
|
val itemType: Short? = null,
|
||||||
|
val itemName: String? = null,
|
||||||
|
/** 关联净菜订单号(从下拉选项 orderNo 取值回传) */
|
||||||
|
val cleanOrderNo: String? = null,
|
||||||
|
/** 绑定菜品 id(itemType=2) */
|
||||||
|
val foodId: Long? = null,
|
||||||
|
/** 订单量 kg(itemType=1) */
|
||||||
|
val orderQty: BigDecimal? = null,
|
||||||
|
/** 实收量 kg(itemType=1,与 totalWeightG 二选一) */
|
||||||
|
val actualQty: BigDecimal? = null,
|
||||||
|
/** 总重量 g(itemType=2,后端自动换算为 kg 存储) */
|
||||||
|
val totalWeightG: BigDecimal? = null,
|
||||||
|
/** 规格:1-标准份 / 2-大份 / 3-小份(itemType=2) */
|
||||||
|
val spec: Int? = null,
|
||||||
|
val pkgCount: Int? = null,
|
||||||
|
/** 验收结果:1-合格 / 2-轻微差异 / 3-不合格 / 4-待验 */
|
||||||
|
val checkResult: Short? = null,
|
||||||
|
/** 格口状态:1-存放中 / 2-临期预警 / 3-温度超标 / 4-空置 / 5-异常 */
|
||||||
|
val slotStatus: Short? = null,
|
||||||
|
/** 剩余保质期(小时) */
|
||||||
|
val shelfLifeRemain: Int? = null,
|
||||||
|
/** 存入时间,仅新增时生效,不传则取当前时间 */
|
||||||
|
val storeTime: String? = null,
|
||||||
|
val remark: String? = null,
|
||||||
|
)
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.model.DeviceConfigInfo
|
||||||
|
import com.shuwei.intelligent.shelves.model.GoodsModel
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfBody
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfResult
|
||||||
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.GET
|
||||||
|
import retrofit2.http.Header
|
||||||
|
import retrofit2.http.POST
|
||||||
|
import retrofit2.http.Query
|
||||||
|
import retrofit2.http.Url
|
||||||
|
|
||||||
|
interface ApiService {
|
||||||
|
// /**
|
||||||
|
// * device获取token
|
||||||
|
// */
|
||||||
|
// @GET("/sys/getEquipmentToken")
|
||||||
|
// suspend fun getDeviceToken(
|
||||||
|
// @Query("qrcodeId") qrcodeId: String,
|
||||||
|
// @Query("appVersion") appVersion: String = App.appVersion
|
||||||
|
// ): RespData<String>
|
||||||
|
//
|
||||||
|
// /**
|
||||||
|
// *获取配置信息
|
||||||
|
// */
|
||||||
|
// @GET("/equipment/stEquipment/queryByEquipmentCode")
|
||||||
|
// suspend fun getDeviceInfo(
|
||||||
|
// @Query("equipmentCode") equipmentCode: String,
|
||||||
|
// @Query("appVersion") appVersion: String = App.appVersion
|
||||||
|
// ): RespData<DeviceConfigInfo>
|
||||||
|
//
|
||||||
|
// @GET
|
||||||
|
// suspend fun getAccessToken(
|
||||||
|
// @Url url: String = UrlConfig.GET_ACCESS_TOKEN,
|
||||||
|
// @Query("qrcodeId") qrcodeId: String
|
||||||
|
// ): RespData<String?>
|
||||||
|
|
||||||
|
@GET
|
||||||
|
suspend fun getShelfList(
|
||||||
|
@Url url: String = UrlConfig.GET_SHELF_LIST,
|
||||||
|
@Query("deviceId") deviceId: String
|
||||||
|
): RespData<ShelfResult>
|
||||||
|
|
||||||
|
@GET
|
||||||
|
suspend fun getGoodsList(
|
||||||
|
@Url url: String = UrlConfig.GET_GOODS_LIST,
|
||||||
|
@Query("canteenId") canteenId: String = "0",
|
||||||
|
@Query("goodsName") goodsName: String? = null,
|
||||||
|
@Query("pageNo") pageNo: Int = 1,
|
||||||
|
@Query("pageSize") pageSize: Int = 50
|
||||||
|
): RespData<MutableList<GoodsModel>?>
|
||||||
|
|
||||||
|
@POST
|
||||||
|
suspend fun saveShelfGoodsList(
|
||||||
|
@Url url: String = UrlConfig.SAVE_SHELF_GOODS_LIST,
|
||||||
|
@Body body: ShelfBody
|
||||||
|
): RespData<Any?>
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.model.CabinetInitResult
|
||||||
|
import com.shuwei.intelligent.shelves.model.CleanPackageOption
|
||||||
|
import com.shuwei.intelligent.shelves.model.MealPackageOption
|
||||||
|
import com.shuwei.intelligent.shelves.model.PageOptionsReq
|
||||||
|
import com.shuwei.intelligent.shelves.model.SyncBody
|
||||||
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.GET
|
||||||
|
import retrofit2.http.POST
|
||||||
|
import retrofit2.http.Query
|
||||||
|
import retrofit2.http.Url
|
||||||
|
|
||||||
|
interface ApiServiceV2 {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 4.1 货柜初始化
|
||||||
|
* 设备启动、Token 刷新后、首页重试时调用
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun initCabinet(
|
||||||
|
@Url url: String = UrlConfig.CABINET_INIT,
|
||||||
|
@Query("cabinetId") cabinetId: String
|
||||||
|
): RespData<CabinetInitResult>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 4.2.1 净菜包下拉列表(itemType=1)
|
||||||
|
* POST + JSON Body 分页请求,data 直接为列表数组
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
suspend fun getCleanPackageOptions(
|
||||||
|
@Url url: String = UrlConfig.CLEAN_PACKAGE_OPTIONS,
|
||||||
|
@Body body: PageOptionsReq
|
||||||
|
): RespData<List<CleanPackageOption>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 4.2.2 餐品净菜包下拉列表(itemType=2)
|
||||||
|
* POST + JSON Body 分页请求,data 直接为列表数组
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
suspend fun getMealPackageOptions(
|
||||||
|
@Url url: String = UrlConfig.MEAL_PACKAGE_OPTIONS,
|
||||||
|
@Body body: PageOptionsReq
|
||||||
|
): RespData<List<MealPackageOption>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 4.3 全量同步整柜数据(定时上报)
|
||||||
|
* 警告:body.goodsList 为 null 或空列表时,后端会软删除整柜所有格口数据
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
suspend fun syncCabinetData(
|
||||||
|
@Url url: String = UrlConfig.CABINET_RECORD_SYNC,
|
||||||
|
@Body body: SyncBody
|
||||||
|
): RespData<Any?>
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.Response
|
||||||
|
|
||||||
|
/**
|
||||||
|
* v1.1 接口专用拦截器
|
||||||
|
* /nutrition/neglect/ 路径无需鉴权,仅注入基础请求头
|
||||||
|
*/
|
||||||
|
class CabinetRequestInterceptor : Interceptor {
|
||||||
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
val request = chain.request().newBuilder()
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("X-DEVICE-CODE", App.deviceId)
|
||||||
|
.header("authorization", "57ee87183f2a4fa59683ec9ef41c8f5d")
|
||||||
|
.build()
|
||||||
|
return chain.proceed(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.util.Log
|
||||||
|
import com.shuwei.intelligent.shelves.BuildConfig
|
||||||
|
import com.shuwei.intelligent.shelves.GlobalData
|
||||||
|
import okhttp3.HttpUrl
|
||||||
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Response
|
||||||
|
import okhttp3.logging.HttpLoggingInterceptor
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.converter.gson.GsonConverterFactory
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
import javax.net.ssl.*
|
||||||
|
import java.security.SecureRandom
|
||||||
|
import java.security.cert.X509Certificate
|
||||||
|
import kotlin.apply
|
||||||
|
|
||||||
|
/** 动态域名拦截器:将 Retrofit 请求的 baseUrl 实时替换为 [GlobalData.appBaseUrl] */
|
||||||
|
class DynamicBaseUrlInterceptor : Interceptor {
|
||||||
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
val request = chain.request()
|
||||||
|
val newUrl = GlobalData.appBaseUrl.toHttpUrlOrNull() ?: return chain.proceed(request)
|
||||||
|
val url = request.url.newBuilder()
|
||||||
|
.scheme(newUrl.scheme)
|
||||||
|
.host(newUrl.host)
|
||||||
|
.port(newUrl.port)
|
||||||
|
.build()
|
||||||
|
return chain.proceed(request.newBuilder().url(url).build())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val apiService: ApiService = Retrofit.Builder()
|
||||||
|
.baseUrl("http://placeholder/")
|
||||||
|
.client(HttpManager.instance.client)
|
||||||
|
.addConverterFactory(GsonConverterFactory.create())
|
||||||
|
.build()
|
||||||
|
.create(ApiService::class.java)
|
||||||
|
|
||||||
|
/** v1.1 接口专用实例,使用轻量拦截器,不携带旧鉴权 Token */
|
||||||
|
val apiServiceV2: ApiServiceV2 = Retrofit.Builder()
|
||||||
|
.baseUrl("http://placeholder/")
|
||||||
|
.client(HttpManager.instance.cabinetClient)
|
||||||
|
.addConverterFactory(GsonConverterFactory.create())
|
||||||
|
.build()
|
||||||
|
.create(ApiServiceV2::class.java)
|
||||||
|
|
||||||
|
class HttpManager private constructor() {
|
||||||
|
val client: OkHttpClient by lazy {
|
||||||
|
OkHttpClient.Builder()
|
||||||
|
.apply {
|
||||||
|
connectTimeout(30, TimeUnit.SECONDS)
|
||||||
|
readTimeout(30, TimeUnit.SECONDS)
|
||||||
|
writeTimeout(30, TimeUnit.SECONDS)
|
||||||
|
sslSocketFactory(createSSLSocketFactory(), TrustAllCerts())
|
||||||
|
hostnameVerifier { _, _ -> true }
|
||||||
|
// addInterceptor(LoggingInterceptor())
|
||||||
|
addInterceptor(DynamicBaseUrlInterceptor())
|
||||||
|
addNetworkInterceptor(HttpLoggingInterceptor(logger = {
|
||||||
|
Log.d("HttpManager","okhttp logger ==>${it}")
|
||||||
|
}).apply {
|
||||||
|
level =
|
||||||
|
if (BuildConfig.DEBUG) {
|
||||||
|
HttpLoggingInterceptor.Level.BODY
|
||||||
|
} else {
|
||||||
|
HttpLoggingInterceptor.Level.NONE
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// addInterceptor { chain ->
|
||||||
|
// val request = chain.request().newBuilder()
|
||||||
|
// .header("x-access-token", App.accessToken)
|
||||||
|
// .build()
|
||||||
|
// chain.proceed(request)
|
||||||
|
// }
|
||||||
|
addInterceptor(RequestInterceptor())
|
||||||
|
}
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** v1.1 接口专用 OkHttpClient,仅注入 Content-Type、Accept、X-DEVICE-CODE */
|
||||||
|
val cabinetClient: OkHttpClient by lazy {
|
||||||
|
OkHttpClient.Builder()
|
||||||
|
.apply {
|
||||||
|
connectTimeout(30, TimeUnit.SECONDS)
|
||||||
|
readTimeout(30, TimeUnit.SECONDS)
|
||||||
|
writeTimeout(30, TimeUnit.SECONDS)
|
||||||
|
sslSocketFactory(createSSLSocketFactory(), TrustAllCerts())
|
||||||
|
hostnameVerifier { _, _ -> true }
|
||||||
|
addInterceptor(DynamicBaseUrlInterceptor())
|
||||||
|
addNetworkInterceptor(HttpLoggingInterceptor(logger = {
|
||||||
|
Log.d("HttpManager", "v2 okhttp ==>${it}")
|
||||||
|
}).apply {
|
||||||
|
level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
|
||||||
|
else HttpLoggingInterceptor.Level.NONE
|
||||||
|
})
|
||||||
|
addInterceptor(CabinetRequestInterceptor())
|
||||||
|
}
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val instance by lazy { HttpManager() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// fun newCall(request: Request): Call = client.newCall(request)
|
||||||
|
|
||||||
|
// inner class LoggingInterceptor : Interceptor {
|
||||||
|
// override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
// val request = chain.request()
|
||||||
|
// // 打印请求日志
|
||||||
|
// Log.d("HttpManager", "--> ${request.method},${request.url},${request.body}")
|
||||||
|
//
|
||||||
|
// val response = chain.proceed(request)
|
||||||
|
// // 打印响应日志
|
||||||
|
// Log.d("HttpManager", "<-- ${response.body}")
|
||||||
|
// return response
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// 信任所有证书的TrustManager实现
|
||||||
|
@SuppressLint("CustomX509TrustManager")
|
||||||
|
class TrustAllCerts : X509TrustManager {
|
||||||
|
@SuppressLint("TrustAllX509TrustManager")
|
||||||
|
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("TrustAllX509TrustManager")
|
||||||
|
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建信任所有证书的SSLSocketFactory
|
||||||
|
fun createSSLSocketFactory(): SSLSocketFactory {
|
||||||
|
val sslContext = SSLContext.getInstance("TLS").apply {
|
||||||
|
init(null, arrayOf(TrustAllCerts()), SecureRandom())
|
||||||
|
}
|
||||||
|
return sslContext.socketFactory
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.Dialog
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.WindowManager
|
||||||
|
import androidx.core.graphics.drawable.toDrawable
|
||||||
|
import com.shuwei.intelligent.shelves.R
|
||||||
|
import com.shuwei.intelligent.shelves.databinding.DialogLoadingBinding
|
||||||
|
import kotlin.let
|
||||||
|
import kotlin.run
|
||||||
|
|
||||||
|
object Loading {
|
||||||
|
|
||||||
|
private var dialog: LoadingDialog? = null
|
||||||
|
|
||||||
|
fun show(activity: Activity) {
|
||||||
|
try {
|
||||||
|
if (activity.isFinishing || activity.isDestroyed) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (dialog?.isShowing == true) {
|
||||||
|
dialog?.dismiss()
|
||||||
|
}
|
||||||
|
if (dialog == null) {
|
||||||
|
dialog = LoadingDialog(activity)
|
||||||
|
}
|
||||||
|
dialog?.show()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dismiss() {
|
||||||
|
try {
|
||||||
|
dialog?.let {
|
||||||
|
if (it.isShowing) {
|
||||||
|
it.dismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dialog = null
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
class LoadingDialog(
|
||||||
|
context: Context,
|
||||||
|
message: String = "加载中……",
|
||||||
|
private var onDismiss: () -> Unit = {}
|
||||||
|
) : Dialog(context, R.style.LoadingDialog) {
|
||||||
|
init {
|
||||||
|
val binding = DialogLoadingBinding.inflate(LayoutInflater.from(context))
|
||||||
|
binding.tvMessage.text = message
|
||||||
|
setContentView(binding.root)
|
||||||
|
setCancelable(true)
|
||||||
|
setCanceledOnTouchOutside(true)
|
||||||
|
window?.run {
|
||||||
|
setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
|
||||||
|
// setFlags(
|
||||||
|
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
|
||||||
|
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
|
||||||
|
// )
|
||||||
|
}
|
||||||
|
setOnDismissListener {
|
||||||
|
onDismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfBody
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
class NetViewModel : ViewModel() {
|
||||||
|
|
||||||
|
private val _getShelfListUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val getShelfListUiState: StateFlow<UiState> = _getShelfListUiState
|
||||||
|
|
||||||
|
private val _getGoodsListUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val getGoodsListUiState: StateFlow<UiState> = _getGoodsListUiState
|
||||||
|
|
||||||
|
private val _getAccessTokenUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val getAccessTokenUiState: StateFlow<UiState> = _getAccessTokenUiState
|
||||||
|
|
||||||
|
private val _getDeviceTokenUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val getDeviceTokenUiState: StateFlow<UiState> = _getDeviceTokenUiState
|
||||||
|
|
||||||
|
private val _getDeviceConfigUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val getDeviceConfigUiState: StateFlow<UiState> = _getDeviceConfigUiState
|
||||||
|
|
||||||
|
private val _updateOverdueStateUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val updateOverdueStateUiState: StateFlow<UiState> = _updateOverdueStateUiState
|
||||||
|
|
||||||
|
// fun getDeviceToken(deviceId: String) {
|
||||||
|
// viewModelScope.launch {
|
||||||
|
// _getDeviceTokenUiState.value = UiState.Loading
|
||||||
|
// runCatching {
|
||||||
|
// val response = apiService.getDeviceToken(qrcodeId = deviceId)
|
||||||
|
// if (response.isSuccess()) {
|
||||||
|
// _getDeviceTokenUiState.value = UiState.Success(response)
|
||||||
|
// } else {
|
||||||
|
// _getDeviceTokenUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
// }
|
||||||
|
// }.onFailure {
|
||||||
|
// _getDeviceTokenUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// fun getDeviceConfig(deviceId: String, deviceToken: String) {
|
||||||
|
// viewModelScope.launch {
|
||||||
|
// _getDeviceConfigUiState.value = UiState.Loading
|
||||||
|
// runCatching {
|
||||||
|
// val response = apiService.getDeviceInfo(equipmentCode = deviceId)
|
||||||
|
// if (response.isSuccess()) {
|
||||||
|
// _getDeviceConfigUiState.value = UiState.Success(response)
|
||||||
|
// } else {
|
||||||
|
// _getDeviceConfigUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
// }
|
||||||
|
// }.onFailure {
|
||||||
|
// _getDeviceConfigUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// fun getAccessToken(deviceId: String) {
|
||||||
|
// viewModelScope.launch {
|
||||||
|
// _getAccessTokenUiState.value = UiState.Loading
|
||||||
|
// runCatching {
|
||||||
|
// val response = apiService.getAccessToken(qrcodeId = deviceId)
|
||||||
|
// if (response.isSuccess()) {
|
||||||
|
// _getAccessTokenUiState.value = UiState.Success(response)
|
||||||
|
// } else {
|
||||||
|
// _getAccessTokenUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
// }
|
||||||
|
// }.onFailure {
|
||||||
|
// _getAccessTokenUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
fun getShelfList(deviceId: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_getShelfListUiState.value = UiState.Loading
|
||||||
|
runCatching {
|
||||||
|
val response = apiService.getShelfList(deviceId = deviceId)
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
_getShelfListUiState.value = UiState.Success(response)
|
||||||
|
} else {
|
||||||
|
_getShelfListUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
_getShelfListUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateOverdueState() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
runCatching {
|
||||||
|
val response = apiService.getShelfList(deviceId = App.deviceId)
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
_updateOverdueStateUiState.value = UiState.Success(response)
|
||||||
|
} else {
|
||||||
|
_updateOverdueStateUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
_updateOverdueStateUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getGoodsList(
|
||||||
|
canteenId: String = "",
|
||||||
|
goodsName: String = "",
|
||||||
|
pageNo: Int = 1,
|
||||||
|
pageSize: Int = 50,
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_getGoodsListUiState.value = UiState.Loading
|
||||||
|
runCatching {
|
||||||
|
val response = apiService.getGoodsList(
|
||||||
|
canteenId = canteenId,
|
||||||
|
goodsName = goodsName,
|
||||||
|
pageNo = pageNo,
|
||||||
|
pageSize = pageSize
|
||||||
|
)
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
_getGoodsListUiState.value = UiState.Success(response)
|
||||||
|
} else {
|
||||||
|
_getGoodsListUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
_getGoodsListUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveShelfGoodsList(body: ShelfBody) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
runCatching {
|
||||||
|
val resp = apiService.saveShelfGoodsList(body = body)
|
||||||
|
Log.d("NetViewModel", "saveShelfGoodsList,performSync: resp:${resp.toJsonString()}")
|
||||||
|
}.onFailure {
|
||||||
|
it.printStackTrace()
|
||||||
|
Log.d("NetViewModel", "saveShelfGoodsList异常:${it.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.shuwei.intelligent.shelves.model.CabinetInitResult
|
||||||
|
import com.shuwei.intelligent.shelves.model.CleanPackageOption
|
||||||
|
import com.shuwei.intelligent.shelves.model.MealPackageOption
|
||||||
|
import com.shuwei.intelligent.shelves.model.PageOptionsReq
|
||||||
|
import com.shuwei.intelligent.shelves.model.SyncBody
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
class NetViewModelV2 : ViewModel() {
|
||||||
|
|
||||||
|
private val _initCabinetUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val initCabinetUiState: StateFlow<UiState> = _initCabinetUiState
|
||||||
|
|
||||||
|
private val _cleanPackageOptionsUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val cleanPackageOptionsUiState: StateFlow<UiState> = _cleanPackageOptionsUiState
|
||||||
|
|
||||||
|
private val _mealPackageOptionsUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val mealPackageOptionsUiState: StateFlow<UiState> = _mealPackageOptionsUiState
|
||||||
|
|
||||||
|
private val _syncCabinetUiState = MutableStateFlow<UiState>(UiState.Initial)
|
||||||
|
val syncCabinetUiState: StateFlow<UiState> = _syncCabinetUiState
|
||||||
|
|
||||||
|
/** 4.1 货柜初始化 */
|
||||||
|
fun initCabinet(cabinetId: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_initCabinetUiState.value = UiState.Loading
|
||||||
|
runCatching {
|
||||||
|
val response = apiServiceV2.initCabinet(cabinetId = cabinetId)
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
_initCabinetUiState.value = UiState.Success(response)
|
||||||
|
} else {
|
||||||
|
_initCabinetUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
_initCabinetUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 4.2.1 净菜包下拉列表(itemType=1) */
|
||||||
|
fun getCleanPackageOptions(keyword: String? = null) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_cleanPackageOptionsUiState.value = UiState.Loading
|
||||||
|
runCatching {
|
||||||
|
val response = apiServiceV2.getCleanPackageOptions(
|
||||||
|
body = PageOptionsReq(pageNum = 1, pageSize = 50, keyword = keyword)
|
||||||
|
)
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
_cleanPackageOptionsUiState.value = UiState.Success(response)
|
||||||
|
} else {
|
||||||
|
_cleanPackageOptionsUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
_cleanPackageOptionsUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 4.2.2 餐品净菜包下拉列表(itemType=2) */
|
||||||
|
fun getMealPackageOptions(keyword: String? = null) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_mealPackageOptionsUiState.value = UiState.Loading
|
||||||
|
runCatching {
|
||||||
|
val response = apiServiceV2.getMealPackageOptions(
|
||||||
|
body = PageOptionsReq(pageNum = 1, pageSize = 50, keyword = keyword)
|
||||||
|
)
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
_mealPackageOptionsUiState.value = UiState.Success(response)
|
||||||
|
} else {
|
||||||
|
_mealPackageOptionsUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
_mealPackageOptionsUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 4.3 全量同步整柜数据
|
||||||
|
* 警告:body.goodsList 为 null 或空列表时,后端会软删除整柜所有格口数据
|
||||||
|
*/
|
||||||
|
fun syncCabinetData(body: SyncBody) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_syncCabinetUiState.value = UiState.Loading
|
||||||
|
runCatching {
|
||||||
|
val response = apiServiceV2.syncCabinetData(body = body)
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
_syncCabinetUiState.value = UiState.Success(response)
|
||||||
|
} else {
|
||||||
|
_syncCabinetUiState.value = UiState.Error(response.msg ?: "请求失败")
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
Log.e("NetViewModelV2", "syncCabinetData 异常:${it.message}")
|
||||||
|
_syncCabinetUiState.value = UiState.Error(it.message ?: "请求异常")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import android.text.TextUtils
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.Response
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 请求拦截器
|
||||||
|
*/
|
||||||
|
class RequestInterceptor : Interceptor {
|
||||||
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
val originalRequest = chain.request()
|
||||||
|
val requestBuilder = originalRequest.newBuilder()
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjYW50ZWVuSWQiOiJiZTE1NDgzMS0zNDY2LTNiYTItYTJlYS01NzY1MmM5MTlmZWQiLCJ0eXBlIjoiNCIsInVzZXJJZCI6IjAwMDAwMDAwMDAwMDAwMDAwMDEifQ.sN40cOC-O5WQFrF4IDUs8fFlkNdUKLbJt_rHyTsgYYM")
|
||||||
|
.header("X-DEVICE-CODE", App.deviceId)
|
||||||
|
.header("authorization", "57ee87183f2a4fa59683ec9ef41c8f5d")
|
||||||
|
|
||||||
|
val newRequest = requestBuilder.build()
|
||||||
|
|
||||||
|
return chain.proceed(newRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// private fun getToken(originRequest: Request): String {
|
||||||
|
// val tokenParam = originRequest.header("X-Access-Token")
|
||||||
|
// if (!TextUtils.isEmpty(tokenParam)) return tokenParam!!
|
||||||
|
// // 从本地获取token的逻辑
|
||||||
|
// val spUtil = SPUtil.getInstance(context = App.getContext())
|
||||||
|
// return spUtil.get(GlobalKey.KEY_TOKEN, "") as String
|
||||||
|
//// return "eyJhbGciOiJIUzUxMiJ9.eyJpZCI6MTQ2LCJ1c2VyTmFtZSI6IjEzNjgxNDQ4ODU2IiwibmFtZSI6IuW-kOejiiIsInBhc3N3b3JkIjoiOTllOTQ1ZmVjZmZjNWIzNDI4MmUwNDRlODYyMzdjM2UxZjU5OWY5OCIsInNhbHQiOiI0NmEzMzUzYWU4OTA0MDYxYjMzODU5ZWNlYTBlMGE2NyIsInBob25lIjoiMTM2ODE0NDg4NTYiLCJzdGF0dXMiOjEsInVzZXJUeXBlIjoyLCJjcmVhdGVVc2VyTm8iOiIxNDEiLCJjcmVhdGVUaW1lIjoxNjI2OTQzNDE2MDAwLCJ1cGRhdGVVc2VyTm8iOiIxNDEiLCJ1cGRhdGVUaW1lIjoxNjI2OTQzNDE2MDAwLCJpc0RlbCI6ZmFsc2UsImVhSWQiOjk5LCJlYUlkTGlzdCI6Ijk5IiwiaXNTaG9wTWFuYWdlciI6dHJ1ZSwidXNlck5vIjoiMWY5Nzk5ZWMtODlkYi00MWYyLTk1YTEtY2UzNTA3Y2QyMTU2In0.f7wImPgBOYMV0AqRchnXGPkUWZN9dFJ9gLPsaB8uNldd21IfXLjJl8y-FiWVuVUvlwUvGpgqGDFR1JKj5H7amw"
|
||||||
|
// }
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
data class RespData<T>(
|
||||||
|
// val success: Boolean = false,
|
||||||
|
val msg: String? = null,
|
||||||
|
val code: String? = null,
|
||||||
|
val data: T? = null,
|
||||||
|
// val total: Int
|
||||||
|
) {
|
||||||
|
fun isSuccess() = code == "00000"
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
sealed class UiState {
|
||||||
|
object Initial : UiState()
|
||||||
|
object Loading : UiState()
|
||||||
|
data class Success<T>(val data: RespData<T>) : UiState()
|
||||||
|
data class Error(val msg: String) : UiState()
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.net
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.GlobalData
|
||||||
|
|
||||||
|
object UrlConfig {
|
||||||
|
// const val DEVICE_BASE_URL = "http://device.shuziweidao.com:8889"
|
||||||
|
// /**
|
||||||
|
// * device获取token
|
||||||
|
// */
|
||||||
|
// const val DEVICE_TOKEN = "${DEVICE_BASE_URL}/sys/getEquipmentToken"
|
||||||
|
// /**
|
||||||
|
// *获取配置信息
|
||||||
|
// */
|
||||||
|
// const val DEVICE_CONFIG = "${DEVICE_BASE_URL}/equipment/stEquipment/queryByEquipmentCode"
|
||||||
|
|
||||||
|
// const val BASE_URL = "https://dev.yixiong-tech.com:8081"
|
||||||
|
//// const val BASE_URL = "https://yyjk.shuziweidao.com/gateway"
|
||||||
|
//// const val BASE_URL = "http://192.168.1.201:14801"
|
||||||
|
// const val DEVICE_BASE_URL = BASE_URL
|
||||||
|
|
||||||
|
var GET_ACCESS_TOKEN = "${GlobalData.appBaseUrl}/restaurant/equipment/stEquipment/getEquipmentToken"
|
||||||
|
var GET_SHELF_LIST =
|
||||||
|
"${GlobalData.appBaseUrl}/terminal/neglect/smartShelves/app/smartShelves/app/getShelvesListByDeviceId"
|
||||||
|
var GET_GOODS_LIST =
|
||||||
|
"${GlobalData.appBaseUrl}/terminal/neglect/smartShelves/app/smartShelves/app/getGoodsPageList"
|
||||||
|
var SAVE_SHELF_GOODS_LIST =
|
||||||
|
"${GlobalData.appBaseUrl}/terminal/neglect/smartShelves/app/smartShelves/app/saveShelvesGoodsList"
|
||||||
|
|
||||||
|
// v1.1 新接口
|
||||||
|
var CABINET_INIT = "${GlobalData.appBaseUrl}/nutrition/neglect/cabinet/init"
|
||||||
|
var CLEAN_PACKAGE_OPTIONS = "${GlobalData.appBaseUrl}/nutrition/neglect/cabinet/clean-package-options"
|
||||||
|
var MEAL_PACKAGE_OPTIONS = "${GlobalData.appBaseUrl}/nutrition/neglect/cabinet/meal-package-options"
|
||||||
|
var CABINET_RECORD_SYNC = "${GlobalData.appBaseUrl}/nutrition/neglect/cabinet/record/sync"
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.serial
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 心跳数据(命令 0x01 / 0x81,终端发起)
|
||||||
|
*
|
||||||
|
* @param scaleCount 秤的数量
|
||||||
|
* @param weights 各台秤的重量列表,索引从1开始
|
||||||
|
* @param simCardNo 物联卡号(20字节ASCII)
|
||||||
|
* @param lock1Door 锁1门状态:0-关 1-开
|
||||||
|
* @param lock1Lock 锁1锁状态:0-关 1-开
|
||||||
|
* @param lock2Door 锁2门状态:0-关 1-开
|
||||||
|
* @param lock2Lock 锁2锁状态:0-关 1-开
|
||||||
|
* @param temperature 温度值(原始字节,单位由温控器决定)
|
||||||
|
*/
|
||||||
|
data class HeartbeatData(
|
||||||
|
val scaleCount: Int,
|
||||||
|
val weights: List<ScaleWeight>,
|
||||||
|
val simCardNo: String,
|
||||||
|
val lock1Door: Int,
|
||||||
|
val lock1Lock: Int,
|
||||||
|
val lock2Door: Int,
|
||||||
|
val lock2Lock: Int,
|
||||||
|
val temperature: Int
|
||||||
|
)
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.serial
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 串口通信协议常量定义
|
||||||
|
* 统一管理所有协议头、协议尾、各类指令及帧解析偏移量
|
||||||
|
*/
|
||||||
|
object ProtocolConstants {
|
||||||
|
|
||||||
|
/** 协议头 */
|
||||||
|
const val HEADER = "D6DADEDB"
|
||||||
|
|
||||||
|
/** 协议尾 */
|
||||||
|
const val FOOTER = "FFFF"
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 指令码(cmd 字段,4字符)
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 终端激活指令 */
|
||||||
|
const val CMD_ACTIVATE = "0001"
|
||||||
|
|
||||||
|
/** 心跳指令(服务端发起) */
|
||||||
|
const val CMD_HEARTBEAT = "0101"
|
||||||
|
|
||||||
|
/** 心跳指令(终端发起) */
|
||||||
|
const val CMD_HEARTBEAT_TERMINAL = "8101"
|
||||||
|
|
||||||
|
/** 开关锁反馈 */
|
||||||
|
const val CMD_LOCK_FEEDBACK = "0202"
|
||||||
|
|
||||||
|
/** 获取设备状态 */
|
||||||
|
const val CMD_DEVICE_STATUS = "0302"
|
||||||
|
|
||||||
|
/** 卡号上发 */
|
||||||
|
const val CMD_CARD_UPLOAD = "0501"
|
||||||
|
|
||||||
|
/** 操作记录上传 */
|
||||||
|
const val CMD_OPERATION_RECORD = "0B01"
|
||||||
|
|
||||||
|
/** 对时 */
|
||||||
|
const val CMD_TIME_SYNC = "0C01"
|
||||||
|
|
||||||
|
/** 终端位置上报 */
|
||||||
|
const val CMD_POSITION_REPORT = "0E01"
|
||||||
|
|
||||||
|
/** 温控信息上报 */
|
||||||
|
const val CMD_TEMP_REPORT = "1001"
|
||||||
|
|
||||||
|
/** 温控信息应答 */
|
||||||
|
const val CMD_TEMP_RESPONSE = "1002"
|
||||||
|
|
||||||
|
/** 温控应答(备用) */
|
||||||
|
const val CMD_TEMP_RESPONSE_ALT = "0F02"
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 帧数据偏移 / 尺寸常量
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 心跳帧中重量数据起始偏移(相对帧起始) */
|
||||||
|
const val HEARTBEAT_WEIGHT_OFFSET = 14
|
||||||
|
|
||||||
|
/** 设备状态帧中重量数据起始偏移(含协议头长度) */
|
||||||
|
const val DEVICE_STATUS_WEIGHT_OFFSET = HEADER.length + 14
|
||||||
|
|
||||||
|
/** 货架数量(每侧5格,共10格,协议中12组) */
|
||||||
|
fun shelfSensorCount(): Int {
|
||||||
|
return if (device2Columns.contains(App.deviceId)) 12
|
||||||
|
else if (device3Columns.contains(App.deviceId)) 24
|
||||||
|
else 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 每组重量数据字节数(十六进制字符数) */
|
||||||
|
const val BYTES_PER_WEIGHT = 8
|
||||||
|
|
||||||
|
/** 温度字段字符长度 */
|
||||||
|
const val TEMPERATURE_FIELD_LEN = 2
|
||||||
|
|
||||||
|
/** 心跳帧最小有效长度 */
|
||||||
|
fun heartbeatMinLength(): Int {
|
||||||
|
return if (device2Columns.contains(App.deviceId)) 200
|
||||||
|
else if (device3Columns.contains(App.deviceId)) 296
|
||||||
|
else 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 心跳帧中温度字段起始偏移(经协议分析得出,前面含重量+其他传感器数据) */
|
||||||
|
fun heartbeatTemperatureStart(): Int {
|
||||||
|
return if (device2Columns.contains(App.deviceId)) 158
|
||||||
|
else if (device3Columns.contains(App.deviceId)) 158+96
|
||||||
|
else 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 激活请求体有效长度 */
|
||||||
|
const val ACTIVATE_BODY_LENGTH = 44
|
||||||
|
|
||||||
|
/** 固定数据体有效长度(terminalId 30 + terminalVersion 10 + 其他 2) */
|
||||||
|
const val FIX_BODY_LENGTH = 42
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 完整指令
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 激活指令(1楼餐厅) */
|
||||||
|
// const val ACTIVE_CMD =
|
||||||
|
// "${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}"
|
||||||
|
|
||||||
|
// 410激活码
|
||||||
|
// const val ACTIVE_CMD = "${HEADER}000281C5D70A7D42894EA17650F5D0BB516838E7863C9ABD766C38958AFF0F3C062D${FOOTER}"
|
||||||
|
|
||||||
|
/** 左货架开锁指令 */
|
||||||
|
const val LEFT_SHELF_OPEN_CMD =
|
||||||
|
"${HEADER}020101000000000000000000000000000000000000${FOOTER}"
|
||||||
|
|
||||||
|
/** 右货架开锁指令 */
|
||||||
|
const val RIGHT_SHELF_OPEN_CMD =
|
||||||
|
"${HEADER}020100010000000000000000000000000000000000${FOOTER}"
|
||||||
|
|
||||||
|
/** 获取设备信息指令 */
|
||||||
|
const val DEVICE_INFO_CMD = "${HEADER}0301000000000000000000000000${FOOTER}"
|
||||||
|
|
||||||
|
/** 启动温控指令 */
|
||||||
|
const val START_TEMP_CTRL_CMD = "${HEADER}0F01360000${FOOTER}"
|
||||||
|
|
||||||
|
/** 华氏温度单位指令 */
|
||||||
|
const val F_TEMP_CMD = "${HEADER}0F01390000${FOOTER}"
|
||||||
|
|
||||||
|
/** 摄氏温度单位指令 */
|
||||||
|
const val C_TEMP_CMD = "${HEADER}0F01390001${FOOTER}"
|
||||||
|
|
||||||
|
/** 关灯指令(继电器1关) */
|
||||||
|
const val LIGHT_CLOSE = "${HEADER}020102020102020000000000000000000000000000${FOOTER}"
|
||||||
|
|
||||||
|
/** 开灯指令(继电器1开) */
|
||||||
|
const val LIGHT_OPEN = "${HEADER}020102020002020000000000000000000000000000${FOOTER}"
|
||||||
|
|
||||||
|
/** 温控指令 */
|
||||||
|
const val TEMPERATURE_CTRL = "${HEADER}0F01040000${FOOTER}"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备2列,10格
|
||||||
|
*/
|
||||||
|
val device2Columns = listOf(
|
||||||
|
//原410货柜
|
||||||
|
"7a991439-3a12-3ef7-809b-c0258b839473",
|
||||||
|
//原1楼餐厅货柜
|
||||||
|
"4787e213-90ab-3e32-88e0-ac271a937751",
|
||||||
|
// TODO: 测试设备----------
|
||||||
|
"2987f0c5-5754-33e9-b00a-251db5e2e55f"
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备3列,15格,左侧1列竖向编号1、2、3、4、5,右侧2列5行编号为6-7、8-9、10-11、12-13、14-15
|
||||||
|
*/
|
||||||
|
val device3ColumnsOrder = listOf(1, 6, 7, 2, 8, 9, 3, 10, 11, 4, 12, 13, 5, 14, 15)
|
||||||
|
/**
|
||||||
|
* 设备2列,10格,左侧1列竖向编号1、2、3、4、5,右侧1列6,7,8,9,10
|
||||||
|
*/
|
||||||
|
val device2ColumnsOrder = listOf(1, 6, 2, 7, 3, 8, 4, 9, 5, 10)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备3列,15格,左侧1列竖向编号1、2、3、4、5,右侧2列5行编号为6-7、8-9、10-11、12-13、14-15
|
||||||
|
*/
|
||||||
|
val device3Columns = listOf(
|
||||||
|
//新设备1
|
||||||
|
"d369f9b0-1c5b-3066-ba72-988e1449cecc",
|
||||||
|
//新设备2
|
||||||
|
"505ce1b1-facc-3eb2-855a-3dadda5ba358"
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 激活指令map,key为设备号,value为激活码 */
|
||||||
|
val ACTIVE_MAP = mutableMapOf(
|
||||||
|
//原410货柜
|
||||||
|
"7a991439-3a12-3ef7-809b-c0258b839473" to "${HEADER}000281C5D70A7D42894EA17650F5D0BB516838E7863C9ABD766C38958AFF0F3C062D${FOOTER}",
|
||||||
|
//原1楼餐厅货柜
|
||||||
|
"4787e213-90ab-3e32-88e0-ac271a937751" to "${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}",
|
||||||
|
//新设备1,临时使用1楼餐厅激活码
|
||||||
|
"d369f9b0-1c5b-3066-ba72-988e1449cecc" to "${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}",
|
||||||
|
//新设备2,临时使用1楼餐厅激活码
|
||||||
|
"505ce1b1-facc-3eb2-855a-3dadda5ba358" to "${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}",
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.serial
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 协议帧通用数据结构
|
||||||
|
* 每一帧解析后的原始信息,所有命令共用此结构
|
||||||
|
*
|
||||||
|
* @param cmd 命令字节,对应 ScaleProtocolConstants.CMD_* 常量
|
||||||
|
* @param flag 标志字节
|
||||||
|
* @param rawBody 数据体原始字节(不含协议头尾、命令、标志、固定数据体)
|
||||||
|
* @param terminalId 终端ID(15字节),ASCII字符串
|
||||||
|
* @param firmwareVersion 固件版本(5字节),ASCII字符串
|
||||||
|
* @param cmdCount 命令次数
|
||||||
|
*/
|
||||||
|
data class ScaleFrame(
|
||||||
|
val cmd: Byte,
|
||||||
|
val flag: Byte,
|
||||||
|
val rawBody: ByteArray,
|
||||||
|
val terminalId: String,
|
||||||
|
val firmwareVersion: String,
|
||||||
|
val cmdCount: Int
|
||||||
|
) {
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other !is ScaleFrame) return false
|
||||||
|
return cmd == other.cmd &&
|
||||||
|
flag == other.flag &&
|
||||||
|
rawBody.contentEquals(other.rawBody) &&
|
||||||
|
terminalId == other.terminalId &&
|
||||||
|
firmwareVersion == other.firmwareVersion &&
|
||||||
|
cmdCount == other.cmdCount
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
var result = cmd.toInt()
|
||||||
|
result = 31 * result + flag.toInt()
|
||||||
|
result = 31 * result + rawBody.contentHashCode()
|
||||||
|
result = 31 * result + terminalId.hashCode()
|
||||||
|
result = 31 * result + firmwareVersion.hashCode()
|
||||||
|
result = 31 * result + cmdCount
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.serial
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.BODY_OFFSET
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.BYTES_PER_WEIGHT
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FIRMWARE_VERSION_LEN
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FIXED_BODY_LEN
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FOOTER_HEX
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FOOTER_LEN
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.HEADER_HEX
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.SIM_CARD_NO_LEN
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.TERMINAL_ID_LEN
|
||||||
|
import com.shuwei.intelligent.shelves.utils.hexToBytes
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 协议帧组装与解析器
|
||||||
|
*
|
||||||
|
* 职责一:将串口原始分片十六进制字符串拼装为完整协议帧
|
||||||
|
* 职责二:将完整帧解析为 ScaleFrame,自动提取固定数据体字段
|
||||||
|
* 职责三:提供心跳、状态等数据体的具体解析方法
|
||||||
|
* 职责四:提供重量字节解析工具(BCD编码、小端序、最高位符号位)
|
||||||
|
*
|
||||||
|
* 设计为无业务依赖,可独立复制到其他项目使用
|
||||||
|
*/
|
||||||
|
class ScaleFrameParser {
|
||||||
|
|
||||||
|
/** 分片拼装缓冲区 */
|
||||||
|
private val buffer = StringBuilder()
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 一、帧组装(串口分片 -> 完整帧十六进制字符串)
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 追加串口原始分片数据,尝试拼装为完整帧
|
||||||
|
*
|
||||||
|
* @param srcData 串口收到的原始十六进制字符串片段
|
||||||
|
* @return 完整协议帧字符串;帧尚不完整时返回 null
|
||||||
|
*/
|
||||||
|
fun appendData(srcData: String): String? {
|
||||||
|
val hasHeader = srcData.contains(HEADER_HEX)
|
||||||
|
val hasFooter = srcData.contains(FOOTER_HEX)
|
||||||
|
return when {
|
||||||
|
hasHeader && hasFooter -> parseCompleteInSingleChunk(srcData)
|
||||||
|
hasHeader && !hasFooter -> {
|
||||||
|
// 只有帧头,等待后续分片
|
||||||
|
buffer.clear()
|
||||||
|
buffer.append(srcData.substring(srcData.lastIndexOf(HEADER_HEX))).append(",")
|
||||||
|
null
|
||||||
|
}
|
||||||
|
!hasHeader && !hasFooter -> {
|
||||||
|
// 中间分片,追加缓冲
|
||||||
|
buffer.append(srcData).append(",")
|
||||||
|
null
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
// 只有帧尾,与缓冲区拼接成完整帧
|
||||||
|
val endIndex = srcData.indexOf(FOOTER_HEX) + FOOTER_HEX.length
|
||||||
|
buffer.append(srcData.substring(0, endIndex))
|
||||||
|
val frame = buffer.toString().replace(",", "")
|
||||||
|
buffer.clear()
|
||||||
|
frame.takeIf { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理单个分片中同时含有帧头和帧尾的情况
|
||||||
|
*/
|
||||||
|
private fun parseCompleteInSingleChunk(srcData: String): String? {
|
||||||
|
buffer.clear()
|
||||||
|
val startIndex = srcData.lastIndexOf(HEADER_HEX)
|
||||||
|
val endIndex = srcData.indexOf(FOOTER_HEX) + FOOTER_HEX.length
|
||||||
|
return if (endIndex <= startIndex) {
|
||||||
|
// 帧尾在帧头之前:是上一帧的残留尾部 + 新帧头部
|
||||||
|
val partial = srcData.substring(startIndex)
|
||||||
|
if (partial.contains(FOOTER_HEX)) {
|
||||||
|
val newEnd = partial.indexOf(FOOTER_HEX) + FOOTER_HEX.length
|
||||||
|
partial.substring(0, newEnd)
|
||||||
|
} else {
|
||||||
|
buffer.append(partial).append(",")
|
||||||
|
null
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 正常完整帧
|
||||||
|
srcData.substring(startIndex, endIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清空分片缓冲区 */
|
||||||
|
fun reset() {
|
||||||
|
buffer.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 二、帧解析(完整帧十六进制字符串 -> ScaleFrame)
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析完整协议帧为 ScaleFrame
|
||||||
|
*
|
||||||
|
* 帧结构:[协议头4] [CMD1] [FLAG1] [数据体N] [终端ID15] [固件版本5] [命令次数1] [协议尾2]
|
||||||
|
*
|
||||||
|
* @param hexFrame 完整帧十六进制字符串(含协议头尾)
|
||||||
|
* @return 解析成功返回 ScaleFrame;校验失败或格式错误返回 null
|
||||||
|
*/
|
||||||
|
fun parseFrame(hexFrame: String): ScaleFrame? {
|
||||||
|
// 最小帧:协议头(8) + cmd(2) + flag(2) + 固定数据体(42) + 协议尾(4) = 58 字符
|
||||||
|
if (hexFrame.length < 58) return null
|
||||||
|
if (!hexFrame.startsWith(HEADER_HEX) || !hexFrame.endsWith(FOOTER_HEX)) return null
|
||||||
|
|
||||||
|
return runCatching {
|
||||||
|
val bytes = hexFrame.hexToBytes()
|
||||||
|
val totalLen = bytes.size
|
||||||
|
|
||||||
|
val cmd = bytes[ScaleProtocolConstants.HEADER_LEN]
|
||||||
|
val flag = bytes[ScaleProtocolConstants.HEADER_LEN + 1]
|
||||||
|
|
||||||
|
// 固定数据体位于协议尾之前
|
||||||
|
val fixedBodyStart = totalLen - FOOTER_LEN - FIXED_BODY_LEN
|
||||||
|
if (fixedBodyStart < BODY_OFFSET) return null
|
||||||
|
|
||||||
|
val fixedBody = bytes.copyOfRange(fixedBodyStart, totalLen - FOOTER_LEN)
|
||||||
|
|
||||||
|
// 解析固定数据体三个字段
|
||||||
|
val terminalId = String(fixedBody, 0, TERMINAL_ID_LEN, Charsets.US_ASCII)
|
||||||
|
val firmwareVersion = String(fixedBody, TERMINAL_ID_LEN, FIRMWARE_VERSION_LEN, Charsets.US_ASCII)
|
||||||
|
val cmdCount = fixedBody[TERMINAL_ID_LEN + FIRMWARE_VERSION_LEN].toInt() and 0xFF
|
||||||
|
|
||||||
|
// 命令专属数据体(固定数据体和协议头尾之间的部分)
|
||||||
|
val rawBody = bytes.copyOfRange(BODY_OFFSET, fixedBodyStart)
|
||||||
|
|
||||||
|
ScaleFrame(
|
||||||
|
cmd = cmd,
|
||||||
|
flag = flag,
|
||||||
|
rawBody = rawBody,
|
||||||
|
terminalId = terminalId,
|
||||||
|
firmwareVersion = firmwareVersion,
|
||||||
|
cmdCount = cmdCount
|
||||||
|
)
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 三、数据体解析
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析心跳数据体(命令 0x01 / 0x81,终端发起)
|
||||||
|
*
|
||||||
|
* rawBody 格式:
|
||||||
|
* [秤数量 1] [秤重量 N×4] [物联卡号 20] [锁1门 1] [锁1锁 1] [锁2门 1] [锁2锁 1] [温度 1]
|
||||||
|
*
|
||||||
|
* @param body ScaleFrame.rawBody
|
||||||
|
* @return 解析成功返回 HeartbeatData;数据不足返回 null
|
||||||
|
*/
|
||||||
|
fun parseHeartbeat(body: ByteArray): HeartbeatData? {
|
||||||
|
if (body.isEmpty()) return null
|
||||||
|
return runCatching {
|
||||||
|
var offset = 0
|
||||||
|
|
||||||
|
val scaleCount = body[offset++].toInt() and 0xFF
|
||||||
|
val minBodyLen = 1 + scaleCount * BYTES_PER_WEIGHT + SIM_CARD_NO_LEN + 4 + 1
|
||||||
|
if (body.size < minBodyLen) return null
|
||||||
|
|
||||||
|
val weights = (1..scaleCount).map { index ->
|
||||||
|
val grams = parseWeightBytes(body, offset)
|
||||||
|
offset += BYTES_PER_WEIGHT
|
||||||
|
ScaleWeight(index, grams)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 物联卡号:ASCII字符串,去除尾部空字符
|
||||||
|
val simCardNo = String(body, offset, SIM_CARD_NO_LEN, Charsets.US_ASCII)
|
||||||
|
.trimEnd('\u0000').trim()
|
||||||
|
offset += SIM_CARD_NO_LEN
|
||||||
|
|
||||||
|
val lock1Door = body[offset++].toInt() and 0xFF
|
||||||
|
val lock1Lock = body[offset++].toInt() and 0xFF
|
||||||
|
val lock2Door = body[offset++].toInt() and 0xFF
|
||||||
|
val lock2Lock = body[offset++].toInt() and 0xFF
|
||||||
|
val temperature = body[offset].toInt() and 0xFF
|
||||||
|
|
||||||
|
HeartbeatData(
|
||||||
|
scaleCount = scaleCount,
|
||||||
|
weights = weights,
|
||||||
|
simCardNo = simCardNo,
|
||||||
|
lock1Door = lock1Door,
|
||||||
|
lock1Lock = lock1Lock,
|
||||||
|
lock2Door = lock2Door,
|
||||||
|
lock2Lock = lock2Lock,
|
||||||
|
temperature = temperature
|
||||||
|
)
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析获取状态响应数据体(命令 0x03,终端响应)
|
||||||
|
*
|
||||||
|
* rawBody 格式:
|
||||||
|
* [锁1锁 1] [锁1门 1] [锁2锁 1] [锁2门 1] [秤数量 1] [秤重量 N×4] [温度 1]
|
||||||
|
*
|
||||||
|
* @param body ScaleFrame.rawBody
|
||||||
|
* @return 解析成功返回 StatusData;数据不足返回 null
|
||||||
|
*/
|
||||||
|
fun parseStatus(body: ByteArray): StatusData? {
|
||||||
|
if (body.size < 6) return null
|
||||||
|
return runCatching {
|
||||||
|
var offset = 0
|
||||||
|
|
||||||
|
val lock1Lock = body[offset++].toInt() and 0xFF
|
||||||
|
val lock1Door = body[offset++].toInt() and 0xFF
|
||||||
|
val lock2Lock = body[offset++].toInt() and 0xFF
|
||||||
|
val lock2Door = body[offset++].toInt() and 0xFF
|
||||||
|
val scaleCount = body[offset++].toInt() and 0xFF
|
||||||
|
|
||||||
|
val minBodyLen = 5 + scaleCount * BYTES_PER_WEIGHT + 1
|
||||||
|
if (body.size < minBodyLen) return null
|
||||||
|
|
||||||
|
val weights = (1..scaleCount).map { index ->
|
||||||
|
val grams = parseWeightBytes(body, offset)
|
||||||
|
offset += BYTES_PER_WEIGHT
|
||||||
|
ScaleWeight(index, grams)
|
||||||
|
}
|
||||||
|
|
||||||
|
val temperature = body[offset].toInt() and 0xFF
|
||||||
|
|
||||||
|
StatusData(
|
||||||
|
lock1Lock = lock1Lock,
|
||||||
|
lock1Door = lock1Door,
|
||||||
|
lock2Lock = lock2Lock,
|
||||||
|
lock2Door = lock2Door,
|
||||||
|
scaleCount = scaleCount,
|
||||||
|
weights = weights,
|
||||||
|
temperature = temperature
|
||||||
|
)
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 四、重量解析工具
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析4字节小端序重量数据
|
||||||
|
*
|
||||||
|
* 编码规则(BCD + 小端序 + 最高位符号位):
|
||||||
|
* - 4字节小端序存储,低字节在前,高字节在后
|
||||||
|
* - 高字节最高位(bit7)为符号位:0=正数,1=负数
|
||||||
|
* - 其余位组成8位BCD十进制字符串,作为十进制整数读取,单位为克
|
||||||
|
*
|
||||||
|
* 示例:
|
||||||
|
* [0x13, 0x10, 0x00, 0x00] → 大端序 "00001013" → 十进制 1013g = 1.013KG
|
||||||
|
* [0x13, 0x01, 0x02, 0x00] → 大端序 "00020113" → 十进制 2113g = 20.113KG(注:原例实为20113g,见下)
|
||||||
|
* [0x13, 0x10, 0x00, 0x80] → 大端序 "80001013" → 符号位=1 → 十进制 -1013g = -1.013KG
|
||||||
|
*
|
||||||
|
* 注意:大端序十六进制字符串按十进制解析(非十六进制),这是BCD编码的关键
|
||||||
|
*
|
||||||
|
* @param bytes 字节数组
|
||||||
|
* @param offset 起始偏移量(连续4字节)
|
||||||
|
* @return 重量(克),负数表示低于去皮零点
|
||||||
|
*/
|
||||||
|
fun parseWeightBytes(bytes: ByteArray, offset: Int): Int {
|
||||||
|
val b0 = bytes[offset].toInt() and 0xFF // 最低字节
|
||||||
|
val b1 = bytes[offset + 1].toInt() and 0xFF
|
||||||
|
val b2 = bytes[offset + 2].toInt() and 0xFF
|
||||||
|
val b3 = bytes[offset + 3].toInt() and 0xFF // 最高字节(含符号位)
|
||||||
|
|
||||||
|
// 检查最高字节的最高位是否为1(负数标志)
|
||||||
|
val isNegative = (b3 and 0x80) != 0
|
||||||
|
val b3Cleared = b3 and 0x7F // 清除符号位
|
||||||
|
|
||||||
|
// 构造大端序8位十六进制字符串
|
||||||
|
val hexStr = "%02X%02X%02X%02X".format(b3Cleared, b2, b1, b0)
|
||||||
|
|
||||||
|
// 将十六进制字符串作为十进制整数解析(BCD解码)
|
||||||
|
// "00001013" → toLong() = 1013,而非 toLong(16) = 4115
|
||||||
|
val absValue = hexStr.toLongOrNull() ?: 0L
|
||||||
|
|
||||||
|
return if (isNegative) -absValue.toInt() else absValue.toInt()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,614 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.serial
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_ACTIVATE
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_CARD_UPLOAD
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_GET_STATUS
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_HEARTBEAT
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_HEARTBEAT_STORE
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_OPERATION_RECORD
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_POSITION_REPORT
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_TEMP_REPORT
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_TIME_SYNC
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_UNLOCK
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FOOTER_HEX
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.HEADER_HEX
|
||||||
|
import com.shuwei.intelligent.shelves.utils.hexToBytes
|
||||||
|
import com.shuwei.intelligent.shelves.utils.toHexString2
|
||||||
|
import io.github.jeadyx.jserialport.AndroidSerialPort
|
||||||
|
import io.github.jeadyx.jserialport.SerialPort
|
||||||
|
import io.github.jeadyx.jserialport.SerialPortFactory
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.TimeZone
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 称重控制板管理器(单例入口)
|
||||||
|
*
|
||||||
|
* 职责:
|
||||||
|
* - 管理串口连接生命周期(start/release)
|
||||||
|
* - 通过内部发送队列(Channel)保证指令按顺序写入串口
|
||||||
|
* - 接收串口原始分片数据,自动拼装帧并分发到对应回调
|
||||||
|
* - 内置各命令的自动应答逻辑(心跳/对时/卡号等)
|
||||||
|
* - 提供链式回调注册 和 常用指令构建
|
||||||
|
*
|
||||||
|
* 典型用法:
|
||||||
|
* ```kotlin
|
||||||
|
* lifecycleScope.launch {
|
||||||
|
* ScaleManager
|
||||||
|
* .init(activateCode = ACTIVE_MAP[deviceId] ?: "")
|
||||||
|
* .onHeartbeat { _, data ->
|
||||||
|
* data.weights.forEach { Log.d("Scale", "秤${it.index}: ${it.grams}g") }
|
||||||
|
* }
|
||||||
|
* .onLog { msg -> Log.d("Scale", msg) }
|
||||||
|
* .start { data ->
|
||||||
|
* // 主线程前置钩子,处理看门狗计时等副作用
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // 主动发送指令
|
||||||
|
* ScaleManager.sendCmd(ScaleManager.buildGetStatusCmd())
|
||||||
|
*
|
||||||
|
* // 页面销毁时释放(关闭串口 + 清空队列 + 清理回调)
|
||||||
|
* runBlocking { ScaleManager.release() }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
object ScaleManager {
|
||||||
|
|
||||||
|
/** 串口端口名,默认 /dev/ttyS1 */
|
||||||
|
var portName: String = "/dev/ttyS1"
|
||||||
|
/** 串口波特率,默认 115200 */
|
||||||
|
var baudRate: Int = 115200
|
||||||
|
|
||||||
|
private val parser = ScaleFrameParser()
|
||||||
|
private var serialPort: AndroidSerialPort? = null
|
||||||
|
private var scope = CoroutineScope(Dispatchers.IO)
|
||||||
|
|
||||||
|
/** 发送队列:保证串口写入顺序,避免并发写冲突 */
|
||||||
|
private val sendChannel = Channel<String>(capacity = Channel.UNLIMITED)
|
||||||
|
|
||||||
|
/** 当前设备激活码,非空时收到激活请求自动应答 */
|
||||||
|
private var activateCode: String = ""
|
||||||
|
|
||||||
|
/** 心跳应答:心跳上报间隔(秒),默认5秒 */
|
||||||
|
var heartbeatInterval: Int = 5
|
||||||
|
|
||||||
|
/** 心跳应答:开锁后未开门自动落锁时间(秒),默认6秒 */
|
||||||
|
var lockTimeout: Int = 6
|
||||||
|
|
||||||
|
// 各命令监听列表
|
||||||
|
private val heartbeatListeners = mutableListOf<(ScaleFrame, HeartbeatData) -> Unit>()
|
||||||
|
private val statusListeners = mutableListOf<(ScaleFrame, StatusData) -> Unit>()
|
||||||
|
private val lockListeners = mutableListOf<(ScaleFrame) -> Unit>()
|
||||||
|
private val cardListeners = mutableListOf<(ScaleFrame) -> Unit>()
|
||||||
|
private val operationListeners = mutableListOf<(ScaleFrame) -> Unit>()
|
||||||
|
private val timeSyncListeners = mutableListOf<(ScaleFrame) -> Unit>()
|
||||||
|
private val positionListeners = mutableListOf<(ScaleFrame) -> Unit>()
|
||||||
|
private val tempReportListeners = mutableListOf<(ScaleFrame) -> Unit>()
|
||||||
|
private val activateListeners = mutableListOf<(ScaleFrame) -> Unit>()
|
||||||
|
/** 任意命令的原始帧监听,用于协议中尚未提供专项解析的命令 */
|
||||||
|
private val rawListeners = mutableMapOf<Byte, MutableList<(ScaleFrame) -> Unit>>()
|
||||||
|
private val logListeners = mutableListOf<(String) -> Unit>()
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 初始化
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化,设置设备激活码
|
||||||
|
*
|
||||||
|
* @param activateCode 当前设备的激活应答帧十六进制字符串,非空时收到激活请求自动应答
|
||||||
|
* @return this,支持链式调用
|
||||||
|
*/
|
||||||
|
fun init(activateCode: String = ""): ScaleManager {
|
||||||
|
this.activateCode = activateCode
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 串口生命周期
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开串口并启动接收,在回调注册完成后调用(链式末尾)
|
||||||
|
*
|
||||||
|
* @param preHook 每帧数据到达时的前置钩子(主线程),用于看门狗计时、UI副作用等
|
||||||
|
* @return true=串口打开成功并已启动接收,false=串口打开失败
|
||||||
|
*/
|
||||||
|
suspend fun start(preHook: ((String) -> Unit)? = null): Boolean {
|
||||||
|
if (!openPort()) return false
|
||||||
|
startReceive(preHook)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun openPort(): Boolean {
|
||||||
|
if (!scope.isActive) {
|
||||||
|
scope = CoroutineScope(Dispatchers.IO)
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
serialPort = SerialPortFactory.create().apply {
|
||||||
|
open(
|
||||||
|
portName = portName,
|
||||||
|
baudRate = baudRate,
|
||||||
|
dataBits = 8,
|
||||||
|
stopBits = 1,
|
||||||
|
parity = SerialPort.PARITY_NONE
|
||||||
|
)
|
||||||
|
} as AndroidSerialPort?
|
||||||
|
// 启动单一消费者协程,顺序消费发送队列
|
||||||
|
scope.launch {
|
||||||
|
for (hexStr in sendChannel) {
|
||||||
|
try {
|
||||||
|
serialPort?.write(hexStr.hexToBytes())
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
log("发送命令失败: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startReceive(preHook: ((String) -> Unit)? = null) {
|
||||||
|
scope.launch {
|
||||||
|
while (isActive) {
|
||||||
|
try {
|
||||||
|
val flow = serialPort?.read()
|
||||||
|
flow?.collect { buffer ->
|
||||||
|
val data = buffer.toHexString2().uppercase(Locale.ROOT)
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
try {
|
||||||
|
preHook?.invoke(data)
|
||||||
|
onDataReceived(data)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
log("串口数据处理异常: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
delay(50)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 数据接收入口
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接收串口原始数据(在串口回调中调用此方法)
|
||||||
|
*
|
||||||
|
* 内部自动完成分片拼装 → 帧解析 → 命令分发 → 自动应答
|
||||||
|
*
|
||||||
|
* @param hexData 串口收到的十六进制字符串(可能为分片数据)
|
||||||
|
*/
|
||||||
|
fun onDataReceived(hexData: String) {
|
||||||
|
val completeFrame = parser.appendData(hexData) ?: return
|
||||||
|
val frame = parser.parseFrame(completeFrame) ?: run {
|
||||||
|
log("帧解析失败,原始数据:$completeFrame")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dispatch(frame, completeFrame)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 回调注册(链式调用)
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册心跳回调(命令 0x01 / 0x81,终端发起)
|
||||||
|
* 回调参数:[ScaleFrame 帧信息] [HeartbeatData 心跳数据(含重量、锁状态、温度)]
|
||||||
|
*/
|
||||||
|
fun onHeartbeat(listener: (ScaleFrame, HeartbeatData) -> Unit): ScaleManager {
|
||||||
|
heartbeatListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册获取状态回调(命令 0x03,服务端请求后终端响应)
|
||||||
|
* 回调参数:[ScaleFrame 帧信息] [StatusData 状态数据(含重量、锁状态、温度)]
|
||||||
|
*/
|
||||||
|
fun onStatus(listener: (ScaleFrame, StatusData) -> Unit): ScaleManager {
|
||||||
|
statusListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册开锁反馈回调(命令 0x02,终端发起,关门后上报)
|
||||||
|
* 回调参数:[ScaleFrame 帧信息],锁状态等信息在 ScaleFrame.rawBody 中
|
||||||
|
*/
|
||||||
|
fun onLockFeedback(listener: (ScaleFrame) -> Unit): ScaleManager {
|
||||||
|
lockListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册卡号上发回调(命令 0x05,终端发起)
|
||||||
|
* 回调参数:[ScaleFrame 帧信息],卡号等信息在 ScaleFrame.rawBody 中
|
||||||
|
*/
|
||||||
|
fun onCardUpload(listener: (ScaleFrame) -> Unit): ScaleManager {
|
||||||
|
cardListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册操作记录上传回调(命令 0x0B,终端发起)
|
||||||
|
* 回调参数:[ScaleFrame 帧信息],操作记录在 ScaleFrame.rawBody 中
|
||||||
|
*/
|
||||||
|
fun onOperationRecord(listener: (ScaleFrame) -> Unit): ScaleManager {
|
||||||
|
operationListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册对时回调(命令 0x0C,终端发起)
|
||||||
|
* 管理器已自动回复当前时间戳,此回调用于业务侧感知对时事件
|
||||||
|
*/
|
||||||
|
fun onTimeSync(listener: (ScaleFrame) -> Unit): ScaleManager {
|
||||||
|
timeSyncListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册终端位置上报回调(命令 0x0E,终端发起,仅4G版本)
|
||||||
|
* 回调参数:[ScaleFrame 帧信息],基站信息(MCC/MNC/LAC/CI)在 ScaleFrame.rawBody 中
|
||||||
|
*/
|
||||||
|
fun onPositionReport(listener: (ScaleFrame) -> Unit): ScaleManager {
|
||||||
|
positionListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册温控信息上报回调(命令 0x10,终端发起)
|
||||||
|
* 回调参数:[ScaleFrame 帧信息],寄存器内容在 ScaleFrame.rawBody 中
|
||||||
|
*/
|
||||||
|
fun onTempReport(listener: (ScaleFrame) -> Unit): ScaleManager {
|
||||||
|
tempReportListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册终端激活回调(命令 0x00,终端发起)
|
||||||
|
* 注意:激活应答(含激活码)需在此回调中手动调用 sendCmd() 发送
|
||||||
|
*/
|
||||||
|
fun onActivate(listener: (ScaleFrame) -> Unit): ScaleManager {
|
||||||
|
activateListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册任意命令的原始帧监听(用于协议中尚未专项解析的命令,或扩展监听)
|
||||||
|
*
|
||||||
|
* @param cmd 命令字节,对应 ScaleProtocolConstants.CMD_* 常量
|
||||||
|
*/
|
||||||
|
fun onRawFrame(cmd: Byte, listener: (ScaleFrame) -> Unit): ScaleManager {
|
||||||
|
rawListeners.getOrPut(cmd) { mutableListOf() }.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册日志回调,所有内部日志通过此回调输出
|
||||||
|
*/
|
||||||
|
fun onLog(listener: (String) -> Unit): ScaleManager {
|
||||||
|
logListeners.add(listener)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 发送指令
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送十六进制字符串指令,指令进入发送队列按顺序写入串口
|
||||||
|
*
|
||||||
|
* @param hexStr 完整帧十六进制字符串,含协议头尾
|
||||||
|
*/
|
||||||
|
fun sendCmd(hexStr: String) {
|
||||||
|
if (!scope.isActive) {
|
||||||
|
log("警告:ScaleManager 串口未打开或已释放")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sendChannel.trySend(hexStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 常用指令构建
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建获取设备状态指令
|
||||||
|
* 协议:CMD=03 FLAG=01 [预留12字节]
|
||||||
|
*/
|
||||||
|
fun buildGetStatusCmd(): String =
|
||||||
|
"${HEADER_HEX}0301${"00".repeat(12)}${FOOTER_HEX}"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建开锁/控制指令
|
||||||
|
*
|
||||||
|
* @param lock1 锁1操作:1=开 0=关 其他值(如0xFF)=不动作
|
||||||
|
* @param lock2 锁2操作:1=开 0=关 其他值=不动作
|
||||||
|
* @param relay1 继电器1:1=开 0=关 其他值=不动作
|
||||||
|
* @param relay2 继电器2:1=开 0=关 其他值=不动作
|
||||||
|
* @param relay3 继电器3:1=开 0=关 其他值=不动作
|
||||||
|
* @param orderId 订单号,超出14字节截断,不足补零
|
||||||
|
*/
|
||||||
|
fun buildUnlockCmd(
|
||||||
|
lock1: Int = 0xFF,
|
||||||
|
lock2: Int = 0xFF,
|
||||||
|
relay1: Int = 0xFF,
|
||||||
|
relay2: Int = 0xFF,
|
||||||
|
relay3: Int = 0xFF,
|
||||||
|
orderId: String = ""
|
||||||
|
): String {
|
||||||
|
val orderBytes = orderId.toByteArray(Charsets.US_ASCII).copyOf(14)
|
||||||
|
val orderHex = orderBytes.joinToString("") { "%02X".format(it) }
|
||||||
|
return "${HEADER_HEX}0201" +
|
||||||
|
"%02X%02X%02X%02X%02X".format(lock1 and 0xFF, lock2 and 0xFF, relay1 and 0xFF, relay2 and 0xFF, relay3 and 0xFF) +
|
||||||
|
orderHex +
|
||||||
|
FOOTER_HEX
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建开锁1指令(左门)
|
||||||
|
* @param orderId 订单号,可选
|
||||||
|
*/
|
||||||
|
fun buildOpenLock1Cmd(orderId: String = ""): String =
|
||||||
|
buildUnlockCmd(lock1 = 1, lock2 = 0xFF, relay1 = 0xFF, relay2 = 0xFF, relay3 = 0xFF, orderId = orderId)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建开锁2指令(右门)
|
||||||
|
* @param orderId 订单号,可选
|
||||||
|
*/
|
||||||
|
fun buildOpenLock2Cmd(orderId: String = ""): String =
|
||||||
|
buildUnlockCmd(lock1 = 0xFF, lock2 = 1, relay1 = 0xFF, relay2 = 0xFF, relay3 = 0xFF, orderId = orderId)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建秤置零指令
|
||||||
|
* 协议:CMD=04 FLAG=01 [秤号1字节]
|
||||||
|
*
|
||||||
|
* @param scaleIndex 秤号,从1开始
|
||||||
|
*/
|
||||||
|
fun buildScaleZeroCmd(scaleIndex: Int): String =
|
||||||
|
"${HEADER_HEX}0401%02X${FOOTER_HEX}".format(scaleIndex and 0xFF)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建秤标定指令
|
||||||
|
* 协议:CMD=06 FLAG=01 [秤号1字节] [砝码值4字节小端序]
|
||||||
|
*
|
||||||
|
* @param scaleIndex 秤号,从1开始
|
||||||
|
* @param weightGrams 砝码重量(克),如10kg砝码传入10000
|
||||||
|
*/
|
||||||
|
fun buildScaleCalibrateCmd(scaleIndex: Int, weightGrams: Int): String {
|
||||||
|
// 砝码值转小端序4字节(BCD编码:克数按十进制写入十六进制位)
|
||||||
|
val weightHex = "%08d".format(weightGrams) // BCD:十进制值直接作为十六进制字符串
|
||||||
|
val leHex = weightHex.chunked(2).reversed().joinToString("")
|
||||||
|
return "${HEADER_HEX}0601%02X${leHex}${FOOTER_HEX}".format(scaleIndex and 0xFF)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建温控器控制指令
|
||||||
|
* 协议:CMD=0F FLAG=01 [操作编码1字节] [设定值2字节]
|
||||||
|
*
|
||||||
|
* @param opCode 操作编码(参考温控器说明书)
|
||||||
|
* @param setValue 设定值
|
||||||
|
*/
|
||||||
|
fun buildTempCtrlCmd(opCode: Int, setValue: Int): String =
|
||||||
|
"${HEADER_HEX}0F01%02X%04X${FOOTER_HEX}".format(opCode and 0xFF, setValue and 0xFFFF)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建临时参数设置指令
|
||||||
|
* 协议:CMD=11 FLAG=01 [参数编码1字节] [设定值1字节]
|
||||||
|
*
|
||||||
|
* @param paramCode 参数编码(1=关门语音触发条件 2=未关门语音提示 3=锁常开设置)
|
||||||
|
* @param value 设定值
|
||||||
|
*/
|
||||||
|
fun buildTempParamSetCmd(paramCode: Int, value: Int): String =
|
||||||
|
"${HEADER_HEX}1101%02X%02X${FOOTER_HEX}".format(paramCode and 0xFF, value and 0xFF)
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 资源释放
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 释放所有资源:清空回调列表、发送函数及帧缓冲
|
||||||
|
* 通常在 Activity/Fragment 销毁或不再使用时调用
|
||||||
|
*/
|
||||||
|
suspend fun release() {
|
||||||
|
sendChannel.close()
|
||||||
|
scope.cancel()
|
||||||
|
serialPort?.close()
|
||||||
|
serialPort = null
|
||||||
|
heartbeatListeners.clear()
|
||||||
|
statusListeners.clear()
|
||||||
|
lockListeners.clear()
|
||||||
|
cardListeners.clear()
|
||||||
|
operationListeners.clear()
|
||||||
|
timeSyncListeners.clear()
|
||||||
|
positionListeners.clear()
|
||||||
|
tempReportListeners.clear()
|
||||||
|
activateListeners.clear()
|
||||||
|
rawListeners.clear()
|
||||||
|
logListeners.clear()
|
||||||
|
activateCode = ""
|
||||||
|
parser.reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 内部命令分发与自动应答
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
private fun dispatch(frame: ScaleFrame, rawHex: String) {
|
||||||
|
when (frame.cmd) {
|
||||||
|
CMD_ACTIVATE -> handleActivate(frame, rawHex)
|
||||||
|
CMD_HEARTBEAT,
|
||||||
|
CMD_HEARTBEAT_STORE -> handleHeartbeat(frame, rawHex)
|
||||||
|
CMD_UNLOCK -> handleLockFeedback(frame, rawHex)
|
||||||
|
CMD_GET_STATUS -> handleStatus(frame, rawHex)
|
||||||
|
CMD_CARD_UPLOAD -> handleCardUpload(frame, rawHex)
|
||||||
|
CMD_OPERATION_RECORD -> handleOperationRecord(frame, rawHex)
|
||||||
|
CMD_TIME_SYNC -> handleTimeSync(frame, rawHex)
|
||||||
|
CMD_POSITION_REPORT -> handlePositionReport(frame, rawHex)
|
||||||
|
CMD_TEMP_REPORT -> handleTempReport(frame, rawHex)
|
||||||
|
else -> {
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到未处理命令:0x%02X,终端ID:${frame.terminalId},原始数据:$rawHex".format(frame.cmd))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理终端激活(CMD=0x00)
|
||||||
|
* 若 activateMap 中存在当前 deviceId 对应的激活码,则自动应答;
|
||||||
|
* 否则仍回调 onActivate,由业务方自行处理
|
||||||
|
*/
|
||||||
|
private fun handleActivate(frame: ScaleFrame, rawHex: String) {
|
||||||
|
log("收到[终端激活]指令,终端ID:${frame.terminalId},固件版本:${frame.firmwareVersion},原始数据:$rawHex")
|
||||||
|
val activeCmd = activateCode
|
||||||
|
if (!activeCmd.isNullOrBlank()) {
|
||||||
|
sendCmd(activeCmd)
|
||||||
|
log("激活码自动应答:$activeCmd")
|
||||||
|
}
|
||||||
|
activateListeners.forEach { it(frame) }
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理心跳(CMD=0x01 / 0x81)
|
||||||
|
* 自动应答:[心跳间隔] [上锁时间] [设备固件版本5字节]
|
||||||
|
*/
|
||||||
|
private fun handleHeartbeat(frame: ScaleFrame, rawHex: String) {
|
||||||
|
val firmwareHex = frame.firmwareVersion.toAsciiHex()
|
||||||
|
val resp = "${HEADER_HEX}0102%02X%02X${firmwareHex}${FOOTER_HEX}".format(
|
||||||
|
heartbeatInterval and 0xFF,
|
||||||
|
lockTimeout and 0xFF
|
||||||
|
)
|
||||||
|
sendCmd(resp)
|
||||||
|
|
||||||
|
val data = parser.parseHeartbeat(frame.rawBody)
|
||||||
|
if (data != null) {
|
||||||
|
heartbeatListeners.forEach { it(frame, data) }
|
||||||
|
}
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到[心跳]指令,终端ID:${frame.terminalId},秤数量:${data?.scaleCount ?: 0},原始数据:$rawHex")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理开锁反馈(CMD=0x02,终端发起,关门后上报)
|
||||||
|
* 自动应答:[锁号00] [终端ID 15字节] [固件版本 5字节]
|
||||||
|
*/
|
||||||
|
private fun handleLockFeedback(frame: ScaleFrame, rawHex: String) {
|
||||||
|
val terminalIdHex = frame.terminalId.toAsciiHex()
|
||||||
|
val firmwareHex = frame.firmwareVersion.toAsciiHex()
|
||||||
|
val resp = "${HEADER_HEX}020200${terminalIdHex}${firmwareHex}${FOOTER_HEX}"
|
||||||
|
sendCmd(resp)
|
||||||
|
lockListeners.forEach { it(frame) }
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到[开锁反馈]指令,终端ID:${frame.terminalId},原始数据:$rawHex")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理获取状态响应(CMD=0x03,终端响应)
|
||||||
|
* 无需应答,直接解析并分发
|
||||||
|
*/
|
||||||
|
private fun handleStatus(frame: ScaleFrame, rawHex: String) {
|
||||||
|
val data = parser.parseStatus(frame.rawBody)
|
||||||
|
if (data != null) {
|
||||||
|
statusListeners.forEach { it(frame, data) }
|
||||||
|
}
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到[获取状态]响应,终端ID:${frame.terminalId},秤数量:${data?.scaleCount ?: 0},原始数据:$rawHex")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理卡号上发(CMD=0x05,终端发起)
|
||||||
|
* 自动应答:成功 0x03
|
||||||
|
*/
|
||||||
|
private fun handleCardUpload(frame: ScaleFrame, rawHex: String) {
|
||||||
|
val resp = "${HEADER_HEX}050203${FOOTER_HEX}"
|
||||||
|
sendCmd(resp)
|
||||||
|
cardListeners.forEach { it(frame) }
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到[卡号上发]指令,终端ID:${frame.terminalId},原始数据:$rawHex")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理操作记录上传(CMD=0x0B,终端发起)
|
||||||
|
* 自动应答:成功 0x03
|
||||||
|
*/
|
||||||
|
private fun handleOperationRecord(frame: ScaleFrame, rawHex: String) {
|
||||||
|
val resp = "${HEADER_HEX}0B0203${FOOTER_HEX}"
|
||||||
|
sendCmd(resp)
|
||||||
|
operationListeners.forEach { it(frame) }
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到[操作记录上传]指令,终端ID:${frame.terminalId},原始数据:$rawHex")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理对时请求(CMD=0x0C,终端发起,仅以太网版本)
|
||||||
|
* 自动应答:当前 Unix 时间戳(含时区偏移),小端序4字节
|
||||||
|
*/
|
||||||
|
private fun handleTimeSync(frame: ScaleFrame, rawHex: String) {
|
||||||
|
val nowMs = System.currentTimeMillis()
|
||||||
|
val timeSec = nowMs / 1000 + TimeZone.getDefault().getOffset(nowMs) / 1000
|
||||||
|
// 取低32位,转为小端序4字节十六进制
|
||||||
|
val timeHex = "%08X".format(timeSec.toInt())
|
||||||
|
.chunked(2).reversed().joinToString("")
|
||||||
|
val resp = "${HEADER_HEX}0C02${timeHex}${FOOTER_HEX}"
|
||||||
|
sendCmd(resp)
|
||||||
|
timeSyncListeners.forEach { it(frame) }
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到[对时]请求,终端ID:${frame.terminalId},时间戳:${timeSec},应答:$resp")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理终端位置上报(CMD=0x0E,终端发起,仅4G版本)
|
||||||
|
* 自动应答:保留字节 0x00
|
||||||
|
*/
|
||||||
|
private fun handlePositionReport(frame: ScaleFrame, rawHex: String) {
|
||||||
|
val resp = "${HEADER_HEX}0E0200${FOOTER_HEX}"
|
||||||
|
sendCmd(resp)
|
||||||
|
positionListeners.forEach { it(frame) }
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到[终端位置上报]指令,终端ID:${frame.terminalId},原始数据:$rawHex")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理温控信息上报(CMD=0x10,终端发起)
|
||||||
|
* 自动应答:保留字节 0x00
|
||||||
|
*/
|
||||||
|
private fun handleTempReport(frame: ScaleFrame, rawHex: String) {
|
||||||
|
val resp = "${HEADER_HEX}100200${FOOTER_HEX}"
|
||||||
|
sendCmd(resp)
|
||||||
|
tempReportListeners.forEach { it(frame) }
|
||||||
|
rawListeners[frame.cmd]?.forEach { it(frame) }
|
||||||
|
log("收到[温控信息上报]指令,终端ID:${frame.terminalId},原始数据:$rawHex")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 私有工具
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
private fun log(message: String) {
|
||||||
|
logListeners.forEach { it(message) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将 ASCII 字符串转为十六进制字符串,用于指令构造
|
||||||
|
* 例:"V2.10" → "56322E3130"
|
||||||
|
*/
|
||||||
|
private fun String.toAsciiHex(): String =
|
||||||
|
toByteArray(Charsets.US_ASCII).joinToString("") { "%02X".format(it) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.serial
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 称重控制板接口协议常量
|
||||||
|
* 统一管理协议头尾、所有命令字节及帧结构偏移量
|
||||||
|
* 设计为独立常量对象,不依赖任何业务类,可复制到其他项目直接使用
|
||||||
|
*/
|
||||||
|
object ScaleProtocolConstants {
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 协议头尾
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 协议头字节数组 */
|
||||||
|
val HEADER: ByteArray = byteArrayOf(0xD6.toByte(), 0xDA.toByte(), 0xDE.toByte(), 0xDB.toByte())
|
||||||
|
|
||||||
|
/** 协议头十六进制字符串 */
|
||||||
|
const val HEADER_HEX: String = "D6DADEDB"
|
||||||
|
|
||||||
|
/** 协议尾字节数组 */
|
||||||
|
val FOOTER: ByteArray = byteArrayOf(0xFF.toByte(), 0xFF.toByte())
|
||||||
|
|
||||||
|
/** 协议尾十六进制字符串 */
|
||||||
|
const val FOOTER_HEX: String = "FFFF"
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 命令字节(cmd 字段,1字节)
|
||||||
|
// 发起方说明:终端=秤控制板主动上报;服务端=Android端主动发送
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 0x00 终端激活(终端发起) */
|
||||||
|
const val CMD_ACTIVATE: Byte = 0x00
|
||||||
|
|
||||||
|
/** 0x01 心跳(终端发起) */
|
||||||
|
const val CMD_HEARTBEAT: Byte = 0x01
|
||||||
|
|
||||||
|
/** 0x81 心跳(终端发起,需存储串口屏显示信息) */
|
||||||
|
const val CMD_HEARTBEAT_STORE: Byte = 0x81.toByte()
|
||||||
|
|
||||||
|
/** 0x02 开锁(服务端发起) */
|
||||||
|
const val CMD_UNLOCK: Byte = 0x02
|
||||||
|
|
||||||
|
/** 0x03 获取状态(服务端发起) */
|
||||||
|
const val CMD_GET_STATUS: Byte = 0x03
|
||||||
|
|
||||||
|
/** 0x04 秤置零(服务端发起) */
|
||||||
|
const val CMD_SCALE_ZERO: Byte = 0x04
|
||||||
|
|
||||||
|
/** 0x05 卡号上发(终端发起) */
|
||||||
|
const val CMD_CARD_UPLOAD: Byte = 0x05
|
||||||
|
|
||||||
|
/** 0x06 秤标定(服务端发起) */
|
||||||
|
const val CMD_SCALE_CALIBRATE: Byte = 0x06
|
||||||
|
|
||||||
|
/** 0x07 价签设置(服务端发起) */
|
||||||
|
const val CMD_PRICE_TAG_SET: Byte = 0x07
|
||||||
|
|
||||||
|
/** 0x08 串口屏(服务端发起) */
|
||||||
|
const val CMD_SERIAL_SCREEN: Byte = 0x08
|
||||||
|
|
||||||
|
/** 0x09 语音播报(服务端发起) */
|
||||||
|
const val CMD_VOICE_BROADCAST: Byte = 0x09
|
||||||
|
|
||||||
|
/** 0x0A 价签(第二块串口屏/透传)设置(服务端发起) */
|
||||||
|
const val CMD_PRICE_TAG_SET2: Byte = 0x0A
|
||||||
|
|
||||||
|
/** 0x0B 操作记录上传(终端发起) */
|
||||||
|
const val CMD_OPERATION_RECORD: Byte = 0x0B
|
||||||
|
|
||||||
|
/** 0x0C 对时(终端发起) */
|
||||||
|
const val CMD_TIME_SYNC: Byte = 0x0C
|
||||||
|
|
||||||
|
/** 0x0E 终端位置上报(终端发起) */
|
||||||
|
const val CMD_POSITION_REPORT: Byte = 0x0E
|
||||||
|
|
||||||
|
/** 0x0F 温控器控制(服务端发起) */
|
||||||
|
const val CMD_TEMP_CTRL: Byte = 0x0F
|
||||||
|
|
||||||
|
/** 0x10 温控信息上报(终端发起) */
|
||||||
|
const val CMD_TEMP_REPORT: Byte = 0x10
|
||||||
|
|
||||||
|
/** 0x11 临时参数设置(服务端发起) */
|
||||||
|
const val CMD_TEMP_PARAM_SET: Byte = 0x11
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
// 帧结构固定偏移量(单位:字节)
|
||||||
|
// ----------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 协议头长度 */
|
||||||
|
const val HEADER_LEN: Int = 4
|
||||||
|
|
||||||
|
/** 命令字段长度 */
|
||||||
|
const val CMD_LEN: Int = 1
|
||||||
|
|
||||||
|
/** 标志字段长度 */
|
||||||
|
const val FLAG_LEN: Int = 1
|
||||||
|
|
||||||
|
/** 数据体起始偏移(协议头 + 命令 + 标志) */
|
||||||
|
const val BODY_OFFSET: Int = HEADER_LEN + CMD_LEN + FLAG_LEN
|
||||||
|
|
||||||
|
/** 协议尾长度 */
|
||||||
|
const val FOOTER_LEN: Int = 2
|
||||||
|
|
||||||
|
/** 单台秤重量字节数 */
|
||||||
|
const val BYTES_PER_WEIGHT: Int = 4
|
||||||
|
|
||||||
|
/** 物联卡号字节数 */
|
||||||
|
const val SIM_CARD_NO_LEN: Int = 20
|
||||||
|
|
||||||
|
/** 固定数据体:终端ID字节数 */
|
||||||
|
const val TERMINAL_ID_LEN: Int = 15
|
||||||
|
|
||||||
|
/** 固定数据体:固件版本字节数 */
|
||||||
|
const val FIRMWARE_VERSION_LEN: Int = 5
|
||||||
|
|
||||||
|
/** 固定数据体:命令次数字节数 */
|
||||||
|
const val CMD_COUNT_LEN: Int = 1
|
||||||
|
|
||||||
|
/** 固定数据体总长度(终端ID + 固件版本 + 命令次数) */
|
||||||
|
const val FIXED_BODY_LEN: Int = TERMINAL_ID_LEN + FIRMWARE_VERSION_LEN + CMD_COUNT_LEN
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.serial
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单台秤的重量数据
|
||||||
|
*
|
||||||
|
* @param index 秤的编号,从1开始
|
||||||
|
* @param grams 重量,单位克,负数表示去皮/负重
|
||||||
|
*/
|
||||||
|
data class ScaleWeight(
|
||||||
|
val index: Int,
|
||||||
|
val grams: Int
|
||||||
|
) {
|
||||||
|
/** 重量转换为千克,保留3位小数 */
|
||||||
|
val kg: Double get() = grams / 1000.0
|
||||||
|
}
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
package com.shuwei.intelligent.shelves.serial
|
|
||||||
|
|
||||||
import com.shuwei.intelligent.shelves.utils.hexToBytes
|
|
||||||
import com.shuwei.intelligent.shelves.utils.toHexString2
|
|
||||||
import io.github.jeadyx.jserialport.AndroidSerialPort
|
|
||||||
import io.github.jeadyx.jserialport.SerialPort
|
|
||||||
import io.github.jeadyx.jserialport.SerialPortFactory
|
|
||||||
import kotlinx.coroutines.*
|
|
||||||
import java.nio.charset.Charset
|
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
object SerialPortManager {
|
|
||||||
private const val portName: String = "/dev/ttyS1"
|
|
||||||
private const val baudRate: Int = 115200
|
|
||||||
private var serialPort: AndroidSerialPort? = null
|
|
||||||
// private var serialPort: SerialPort? = null
|
|
||||||
private val scope = CoroutineScope(Dispatchers.IO)
|
|
||||||
|
|
||||||
// 打开串口
|
|
||||||
suspend fun open(): Boolean {
|
|
||||||
return try {
|
|
||||||
serialPort = SerialPortFactory.create().apply {
|
|
||||||
open(
|
|
||||||
portName = portName,
|
|
||||||
baudRate = baudRate,
|
|
||||||
dataBits = 8,
|
|
||||||
stopBits = 1,
|
|
||||||
parity = SerialPort.PARITY_NONE
|
|
||||||
)
|
|
||||||
} as AndroidSerialPort?
|
|
||||||
true
|
|
||||||
} catch (e: Exception) {
|
|
||||||
e.printStackTrace()
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 发送数据
|
|
||||||
suspend fun send(data: String): Boolean {
|
|
||||||
return try {
|
|
||||||
// serialPort?.write(data.toByteArray())
|
|
||||||
serialPort?.write(data.hexToBytes())
|
|
||||||
true
|
|
||||||
} catch (e: Exception) {
|
|
||||||
e.printStackTrace()
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 启动接收协程
|
|
||||||
fun startReceive(callback: (String) -> Unit) {
|
|
||||||
scope.launch {
|
|
||||||
while (isActive) {
|
|
||||||
serialPort?.read()?.collect { buffer ->
|
|
||||||
// val data = String(buffer)
|
|
||||||
val data = buffer.toHexString2().toUpperCase()
|
|
||||||
callback(data)
|
|
||||||
}
|
|
||||||
delay(50)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 关闭串口
|
|
||||||
suspend fun close() {
|
|
||||||
scope.cancel()
|
|
||||||
serialPort?.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.serial
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取设备状态数据(命令 0x03,服务端发起后终端响应)
|
||||||
|
*
|
||||||
|
* @param lock1Lock 锁1锁状态:0-关 1-开
|
||||||
|
* @param lock1Door 锁1门状态:0-关 1-开
|
||||||
|
* @param lock2Lock 锁2锁状态:0-关 1-开
|
||||||
|
* @param lock2Door 锁2门状态:0-关 1-开
|
||||||
|
* @param scaleCount 秤的数量
|
||||||
|
* @param weights 各台秤的重量列表,索引从1开始
|
||||||
|
* @param temperature 温度值(原始字节,单位由温控器决定)
|
||||||
|
*/
|
||||||
|
data class StatusData(
|
||||||
|
val lock1Lock: Int,
|
||||||
|
val lock1Door: Int,
|
||||||
|
val lock2Lock: Int,
|
||||||
|
val lock2Door: Int,
|
||||||
|
val scaleCount: Int,
|
||||||
|
val weights: List<ScaleWeight>,
|
||||||
|
val temperature: 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.activity.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()
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
//}
|
||||||
@@ -1,40 +1,67 @@
|
|||||||
package com.shuwei.intelligent.shelves.task
|
//package com.shuwei.intelligent.shelves.task
|
||||||
|
//
|
||||||
import android.content.Context
|
//import android.content.Context
|
||||||
import android.util.Log
|
//import android.util.Log
|
||||||
import androidx.work.CoroutineWorker
|
//import androidx.work.CoroutineWorker
|
||||||
import androidx.work.WorkerParameters
|
//import androidx.work.WorkerParameters
|
||||||
import com.shuwei.intelligent.shelves.HomeActivity
|
//import com.shuwei.intelligent.shelves.App
|
||||||
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
|
//import com.shuwei.intelligent.shelves.activity.HomeActivity
|
||||||
import kotlinx.coroutines.Dispatchers
|
//import com.shuwei.intelligent.shelves.model.ShelfBody
|
||||||
import kotlinx.coroutines.withContext
|
//import com.shuwei.intelligent.shelves.net.apiService
|
||||||
|
//import com.shuwei.intelligent.shelves.utils.ext.toJsonString
|
||||||
class SyncTask(appContext: Context, workerParams: WorkerParameters) :
|
//import kotlinx.coroutines.Dispatchers
|
||||||
CoroutineWorker(appContext, workerParams) {
|
//import kotlinx.coroutines.withContext
|
||||||
|
//
|
||||||
companion object {
|
//class SyncTask(appContext: Context, workerParams: WorkerParameters) :
|
||||||
private const val TAG = "SyncTask"
|
// CoroutineWorker(appContext, workerParams) {
|
||||||
}
|
//
|
||||||
|
// companion object {
|
||||||
override suspend fun doWork(): Result {
|
// private const val TAG = "SyncTask"
|
||||||
return try {
|
// }
|
||||||
// 执行后台任务逻辑
|
//
|
||||||
performSync()
|
// override suspend fun doWork(): Result {
|
||||||
|
// return try {
|
||||||
TaskManager.startTask()
|
// // 执行后台任务逻辑
|
||||||
|
// performSync()
|
||||||
Result.success()
|
//
|
||||||
} catch (e: Exception) {
|
// TaskManager.startTask()
|
||||||
e.printStackTrace()
|
//
|
||||||
Result.retry()
|
// Result.success()
|
||||||
}
|
// } catch (e: Exception) {
|
||||||
}
|
// e.printStackTrace()
|
||||||
|
// Result.retry()
|
||||||
private suspend fun performSync() {
|
// }
|
||||||
withContext(Dispatchers.IO) {
|
// }
|
||||||
val list = HomeActivity.list
|
//
|
||||||
Log.d(TAG, "performSync: list:${list.toJsonString()}")
|
// private suspend fun performSync() {
|
||||||
}
|
// withContext(Dispatchers.IO) {
|
||||||
}
|
// val list = HomeActivity.list
|
||||||
|
// Log.d(TAG, "performSync: list:${list.toJsonString()}")
|
||||||
}
|
// val submitList = list.sortedBy { it.deviceNo }
|
||||||
|
// submitList.forEach {
|
||||||
|
// if (it.goodsId.isNullOrBlank()) {
|
||||||
|
// it.weight = it.weightBak
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//// submitList.forEach {
|
||||||
|
//// it.temperature = HomeActivity.showTemperatureC
|
||||||
|
//// it.humidity = HomeActivity.showHumidity
|
||||||
|
//// }
|
||||||
|
// val body = ShelfBody().also {
|
||||||
|
// it.deviceId = App.deviceId
|
||||||
|
// it.canteenId = App.canteenId
|
||||||
|
// it.temperature = HomeActivity.showTemperatureC
|
||||||
|
// it.humidity = HomeActivity.showHumidity
|
||||||
|
// it.goodsList = submitList
|
||||||
|
// }
|
||||||
|
// Log.d(TAG, "performSync: body:${body.toJsonString()}")
|
||||||
|
// try {
|
||||||
|
// val resp = apiService.saveShelfGoodsList(body = body)
|
||||||
|
// Log.d(TAG, "performSync: resp:${resp.toJsonString()}")
|
||||||
|
// } catch (e: Exception) {
|
||||||
|
// e.printStackTrace()
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
//}
|
||||||
@@ -1,44 +1,59 @@
|
|||||||
package com.shuwei.intelligent.shelves.task
|
//package com.shuwei.intelligent.shelves.task
|
||||||
|
//
|
||||||
import androidx.work.ExistingWorkPolicy
|
//import androidx.work.ExistingWorkPolicy
|
||||||
import androidx.work.OneTimeWorkRequestBuilder
|
//import androidx.work.OneTimeWorkRequestBuilder
|
||||||
import androidx.work.WorkManager
|
//import androidx.work.WorkManager
|
||||||
import com.shuwei.intelligent.shelves.App
|
//import com.shuwei.intelligent.shelves.App
|
||||||
import java.util.concurrent.TimeUnit
|
//import java.util.concurrent.TimeUnit
|
||||||
|
//
|
||||||
object TaskManager {
|
//object TaskManager {
|
||||||
const val TASK_NAME = "IntelligentShelvesSyncTask"
|
// const val TASK_NAME = "IntelligentShelvesSyncTask"
|
||||||
|
// const val DEVICE_TASK_NAME = "IntelligentShelvesDeviceTask"
|
||||||
fun startTask() {
|
//
|
||||||
val nextRequest = OneTimeWorkRequestBuilder<SyncTask>()
|
// fun startTask() {
|
||||||
.setInitialDelay(3, TimeUnit.MINUTES)
|
// val nextRequest = OneTimeWorkRequestBuilder<SyncTask>()
|
||||||
// .setInitialDelay(10, TimeUnit.SECONDS)
|
// .setInitialDelay(2, TimeUnit.MINUTES)
|
||||||
// .setInputData(inputData)
|
//// .setInitialDelay(30, TimeUnit.SECONDS)
|
||||||
.build()
|
//// .setInitialDelay(10, TimeUnit.MINUTES)
|
||||||
WorkManager.getInstance(App.get())
|
//// .setInputData(inputData)
|
||||||
.enqueueUniqueWork(TASK_NAME, ExistingWorkPolicy.REPLACE, nextRequest)
|
|
||||||
|
|
||||||
// val constraints = Constraints.Builder()
|
|
||||||
// .setRequiredNetworkType(NetworkType.CONNECTED)
|
|
||||||
// .setRequiresBatteryNotLow(true)
|
|
||||||
// .build()
|
// .build()
|
||||||
// val syncRequest = PeriodicWorkRequestBuilder<SyncTask>(
|
// WorkManager.getInstance(App.getInstance())
|
||||||
// 3L, TimeUnit.MINUTES, // 最小间隔15分钟
|
// .enqueueUniqueWork(TASK_NAME, ExistingWorkPolicy.REPLACE, nextRequest)
|
||||||
// 3L, TimeUnit.MINUTES // 弹性时间窗口
|
//
|
||||||
// )
|
//// val constraints = Constraints.Builder()
|
||||||
// .setConstraints(constraints)
|
//// .setRequiredNetworkType(NetworkType.CONNECTED)
|
||||||
|
//// .setRequiresBatteryNotLow(true)
|
||||||
|
//// .build()
|
||||||
|
//// val syncRequest = PeriodicWorkRequestBuilder<SyncTask>(
|
||||||
|
//// 3L, TimeUnit.MINUTES, // 最小间隔15分钟
|
||||||
|
//// 3L, TimeUnit.MINUTES // 弹性时间窗口
|
||||||
|
//// )
|
||||||
|
//// .setConstraints(constraints)
|
||||||
|
//// .build()
|
||||||
|
//// WorkManager.getInstance(App.get())
|
||||||
|
//// .enqueueUniquePeriodicWork(
|
||||||
|
//// TASK_NAME,
|
||||||
|
//// ExistingPeriodicWorkPolicy.KEEP,
|
||||||
|
//// syncRequest
|
||||||
|
//// )
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// fun cancelTask() {
|
||||||
|
// WorkManager.getInstance(App.getInstance())
|
||||||
|
// .cancelUniqueWork(TASK_NAME)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// fun startDeviceTask() {
|
||||||
|
// val nextRequest = OneTimeWorkRequestBuilder<SyncDeviceTask>()
|
||||||
|
// .setInitialDelay(2, TimeUnit.MINUTES)
|
||||||
// .build()
|
// .build()
|
||||||
// WorkManager.getInstance(App.get())
|
// WorkManager.getInstance(App.getInstance())
|
||||||
// .enqueueUniquePeriodicWork(
|
// .enqueueUniqueWork(DEVICE_TASK_NAME, ExistingWorkPolicy.REPLACE, nextRequest)
|
||||||
// TASK_NAME,
|
// }
|
||||||
// ExistingPeriodicWorkPolicy.KEEP,
|
//
|
||||||
// syncRequest
|
// fun cancelDeviceTask() {
|
||||||
// )
|
// WorkManager.getInstance(App.getInstance())
|
||||||
}
|
// .cancelUniqueWork(DEVICE_TASK_NAME)
|
||||||
|
// }
|
||||||
fun cancelTask() {
|
//
|
||||||
WorkManager.getInstance(App.get())
|
//}
|
||||||
.cancelUniqueWork(TASK_NAME)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,750 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils;
|
||||||
|
|
||||||
|
import static android.content.Context.TELEPHONY_SERVICE;
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint;
|
||||||
|
import android.bluetooth.BluetoothAdapter;
|
||||||
|
import android.content.ActivityNotFoundException;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.content.pm.PackageInfo;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.net.ConnectivityManager;
|
||||||
|
import android.net.NetworkInfo;
|
||||||
|
import android.net.Uri;
|
||||||
|
import android.net.wifi.WifiInfo;
|
||||||
|
import android.net.wifi.WifiManager;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.provider.Settings;
|
||||||
|
import android.telephony.TelephonyManager;
|
||||||
|
import android.text.TextUtils;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
|
import androidx.core.content.FileProvider;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.io.LineNumberReader;
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.net.NetworkInterface;
|
||||||
|
import java.text.DecimalFormat;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class AppUtil {
|
||||||
|
public static String getAppPackageName(Context context) {
|
||||||
|
String packageName = "";
|
||||||
|
try {
|
||||||
|
PackageManager pm = context.getPackageManager();
|
||||||
|
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
|
||||||
|
packageName = pi.packageName;
|
||||||
|
if (AppUtil.isEmpty(packageName)) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return packageName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getAppVersionName(Context context) {
|
||||||
|
String versionName = "";
|
||||||
|
// int versioncode=1;
|
||||||
|
try {
|
||||||
|
PackageManager pm = context.getPackageManager();
|
||||||
|
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
|
||||||
|
versionName = pi.versionName;
|
||||||
|
// versioncode = pi.versionCode;表示更新了多少次
|
||||||
|
if (versionName == null || versionName.length() <= 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return versionName;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static int getAppVersionCode(Context context) {
|
||||||
|
int versioncode = 1;
|
||||||
|
try {
|
||||||
|
PackageManager pm = context.getPackageManager();
|
||||||
|
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
|
||||||
|
versioncode = pi.versionCode;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return versioncode;
|
||||||
|
}
|
||||||
|
|
||||||
|
//判断微信是否安装
|
||||||
|
public static boolean isWeixinInstalled(Context context) {
|
||||||
|
final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
|
||||||
|
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
|
||||||
|
if (pinfo != null) {
|
||||||
|
for (int i = 0; i < pinfo.size(); i++) {
|
||||||
|
String pn = pinfo.get(i).packageName;
|
||||||
|
if (pn.equals("com.tencent.mm")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打电话
|
||||||
|
* <p>
|
||||||
|
* Intent.ACTION_DIAL Intent.ACTION_CALL
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @param mobile
|
||||||
|
*/
|
||||||
|
public static void callUp(Context context, String mobile) {
|
||||||
|
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
|
||||||
|
+ mobile));
|
||||||
|
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||||
|
context.startActivity(intent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取设备ID
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String getDevId(Context context) {
|
||||||
|
TelephonyManager TelephonyMgr = (TelephonyManager) context
|
||||||
|
.getSystemService(Context.TELEPHONY_SERVICE);
|
||||||
|
return TelephonyMgr.getDeviceId();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 姓名脱敏
|
||||||
|
*
|
||||||
|
* @param fullName
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String desensitizedName(String fullName) {
|
||||||
|
if (fullName == null || fullName.length() <= 1) {
|
||||||
|
return fullName;
|
||||||
|
}
|
||||||
|
char[] nameArr = fullName.toCharArray();
|
||||||
|
if (nameArr.length > 2) {
|
||||||
|
for (int i = 1; i < nameArr.length - 1; i++) {
|
||||||
|
nameArr[i] = '*';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
nameArr[1] = '*';
|
||||||
|
}
|
||||||
|
|
||||||
|
return new String(nameArr);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static String formatDateGetFull(String date) {
|
||||||
|
if (isEmpty(date)) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
Date d = new Date(Long.parseLong(date));
|
||||||
|
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||||
|
return dateFormat1.format(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String formatDateGetCurrentTime() {
|
||||||
|
Date d = new Date(System.currentTimeMillis());
|
||||||
|
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//.SSS
|
||||||
|
return dateFormat1.format(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static String formatDateGetFull(long date) {
|
||||||
|
if (date == 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
Date d = new Date(date);
|
||||||
|
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
||||||
|
return dateFormat1.format(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String formatDateGetDay(long date) {
|
||||||
|
if (date == 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
Date d = new Date(date);
|
||||||
|
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
|
||||||
|
return dateFormat1.format(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isEmpty(String s) {
|
||||||
|
if (TextUtils.isEmpty(s) || s.trim().equals("null")) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化浮点型
|
||||||
|
*
|
||||||
|
* @param data
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String formatDouble(double data) {
|
||||||
|
return new DecimalFormat("0.00").format(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化分钟
|
||||||
|
*
|
||||||
|
* @param minutes
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String formatMinutes(int minutes) {
|
||||||
|
int hour = minutes / 60;
|
||||||
|
int minute = minutes % 60;
|
||||||
|
if (hour > 0 && minute > 0) {
|
||||||
|
return hour + "小时" + minute + "分钟";
|
||||||
|
} else if (hour > 0) {
|
||||||
|
return hour + "小时";
|
||||||
|
} else {
|
||||||
|
return minute + "分钟";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//com.fawan.news
|
||||||
|
public static void goToMarket(Context context, String packageName) {
|
||||||
|
Uri uri = Uri.parse("market://details?id=" + packageName);
|
||||||
|
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
|
||||||
|
try {
|
||||||
|
context.startActivity(goToMarket);
|
||||||
|
} catch (ActivityNotFoundException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* true为存在,false为不存在
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @param packageName
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static boolean isInstallApp(Context context, String packageName) {
|
||||||
|
try {
|
||||||
|
context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
|
||||||
|
return true;
|
||||||
|
} catch (PackageManager.NameNotFoundException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化float 保留两位小数
|
||||||
|
*
|
||||||
|
* @param data
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static float formatFloat2(float data) {
|
||||||
|
// DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
|
||||||
|
// return decimalFormat.format(data);//返回字符串
|
||||||
|
|
||||||
|
int scale = 1;//设置位数
|
||||||
|
int roundingMode = 4;//表示四舍五入,可以选择其他舍值方式,例如去尾,等等.
|
||||||
|
BigDecimal bd = new BigDecimal((double) data);
|
||||||
|
bd = bd.setScale(scale, roundingMode);
|
||||||
|
data = bd.floatValue();
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Android 6.0 之前(不包括6.0)获取mac地址
|
||||||
|
* 必须的权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
|
||||||
|
*
|
||||||
|
* @param context * @return
|
||||||
|
*/
|
||||||
|
public static String getMacDefault(Context context) {
|
||||||
|
String mac = "";
|
||||||
|
if (context == null) {
|
||||||
|
return mac;
|
||||||
|
}
|
||||||
|
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
|
||||||
|
WifiInfo info = null;
|
||||||
|
try {
|
||||||
|
info = wifi.getConnectionInfo();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
mac = info.getMacAddress();
|
||||||
|
if (!TextUtils.isEmpty(mac)) {
|
||||||
|
mac = mac.toUpperCase(Locale.ENGLISH);
|
||||||
|
}
|
||||||
|
return mac;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Android 6.0-Android 7.0 获取mac地址
|
||||||
|
*/
|
||||||
|
public static String getMacAddress() {
|
||||||
|
String macSerial = null;
|
||||||
|
String str = "";
|
||||||
|
|
||||||
|
try {
|
||||||
|
Process pp = Runtime.getRuntime().exec("cat/sys/class/net/wlan0/address");
|
||||||
|
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
|
||||||
|
LineNumberReader input = new LineNumberReader(ir);
|
||||||
|
|
||||||
|
while (null != str) {
|
||||||
|
str = input.readLine();
|
||||||
|
if (str != null) {
|
||||||
|
macSerial = str.trim();//去空格
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException ex) {
|
||||||
|
// 赋予默认值
|
||||||
|
ex.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return macSerial;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Android 7.0之后获取Mac地址
|
||||||
|
* 遍历循环所有的网络接口,找到接口是 wlan0
|
||||||
|
* 必须的权限 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String getMacFromHardware() {
|
||||||
|
try {
|
||||||
|
ArrayList<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
|
||||||
|
for (NetworkInterface nif : all) {
|
||||||
|
if (!nif.getName().equals("wlan0"))
|
||||||
|
continue;
|
||||||
|
byte[] macBytes = nif.getHardwareAddress();
|
||||||
|
if (macBytes == null) return "";
|
||||||
|
StringBuilder res1 = new StringBuilder();
|
||||||
|
for (Byte b : macBytes) {
|
||||||
|
res1.append(String.format("%02X:", b));
|
||||||
|
}
|
||||||
|
if (!TextUtils.isEmpty(res1)) {
|
||||||
|
res1.deleteCharAt(res1.length() - 1);
|
||||||
|
}
|
||||||
|
return res1.toString();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取mac地址(适配所有Android版本)
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String getMac(Context context) {
|
||||||
|
String mac = "";
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
||||||
|
mac = getMacDefault(context);
|
||||||
|
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
|
||||||
|
mac = getMacAddress();
|
||||||
|
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||||
|
mac = getMacFromHardware();
|
||||||
|
}
|
||||||
|
return mac;
|
||||||
|
}
|
||||||
|
|
||||||
|
//把String转化为float
|
||||||
|
public static double convertToFloat(String number, double defaultValue) {
|
||||||
|
if (TextUtils.isEmpty(number)) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Double.parseDouble(number);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取AndroidId
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String getAndroidId(Context context) {
|
||||||
|
String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
|
||||||
|
return androidId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取设备唯一 UDID
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@SuppressLint("MissingPermission")
|
||||||
|
public static String getUDID(Context context) {
|
||||||
|
// return "SWZC-HG-001";
|
||||||
|
//// //"test111";
|
||||||
|
String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
|
||||||
|
if (!androidID.equals("")) {
|
||||||
|
try {
|
||||||
|
if (!"9774d56d682e549c".equals(androidID)) {
|
||||||
|
androidID = UUID.nameUUIDFromBytes(androidID.getBytes("utf8")).toString();
|
||||||
|
} else {
|
||||||
|
@SuppressLint("MissingPermission") final String deviceId = ((TelephonyManager) context.getSystemService(TELEPHONY_SERVICE)).getDeviceId();
|
||||||
|
androidID = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")).toString() : UUID.randomUUID().toString();
|
||||||
|
}
|
||||||
|
} catch (UnsupportedEncodingException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
return androidID;
|
||||||
|
}
|
||||||
|
|
||||||
|
//需要权限 android.permission.READ_PHONE_STATE
|
||||||
|
TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
|
||||||
|
String szImei = TelephonyMgr.getDeviceId();
|
||||||
|
if (!szImei.equals("")) {
|
||||||
|
return szImei;
|
||||||
|
}
|
||||||
|
|
||||||
|
//需要权限 android.permission.ACCESS_WIFI_STATE
|
||||||
|
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
|
||||||
|
String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
|
||||||
|
if (!m_szWLANMAC.equals("")) {
|
||||||
|
return m_szWLANMAC;
|
||||||
|
}
|
||||||
|
|
||||||
|
//需要权限 android.permission.BLUETOOTH
|
||||||
|
BluetoothAdapter m_BluetoothAdapter = null;
|
||||||
|
m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||||||
|
String m_szBTMAC = m_BluetoothAdapter.getAddress();
|
||||||
|
if (!m_szBTMAC.equals("")) {
|
||||||
|
return m_szBTMAC;
|
||||||
|
}
|
||||||
|
return getUniquePsuedoID();
|
||||||
|
}
|
||||||
|
|
||||||
|
//获得 Psuedo ID
|
||||||
|
public static String getUniquePsuedoID() {
|
||||||
|
String serial = null;
|
||||||
|
String m_szDevIDShort = "35" +
|
||||||
|
Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +
|
||||||
|
Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +
|
||||||
|
Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
|
||||||
|
Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +
|
||||||
|
Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +
|
||||||
|
Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
|
||||||
|
Build.USER.length() % 10; //13 位
|
||||||
|
try {
|
||||||
|
serial = Build.class.getField("SERIAL").get(null).toString();
|
||||||
|
//API>=9 使用serial号
|
||||||
|
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
|
||||||
|
} catch (Exception exception) {
|
||||||
|
//serial需要一个初始化,随意值
|
||||||
|
serial = "serial";
|
||||||
|
}
|
||||||
|
|
||||||
|
//使用硬件信息拼凑出来的15位号码
|
||||||
|
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getCPUSerial() {
|
||||||
|
String line = "";
|
||||||
|
String TAG = "aaa";
|
||||||
|
Log.e(TAG, " get_quck_Sn() ");
|
||||||
|
Class<?> c = null;
|
||||||
|
try {
|
||||||
|
c = Class.forName("android.os.SystemProperties");
|
||||||
|
|
||||||
|
Method get = c.getMethod("get", String.class);
|
||||||
|
line = (String) get.invoke(c, "ro.serialno");
|
||||||
|
} catch (ClassNotFoundException | NoSuchMethodException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} catch (IllegalAccessException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.e(TAG, " get_quck_Sn() " + line);
|
||||||
|
System.out.println("设备串号" + line);
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断网络连接状态
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static boolean isNetworkConnected(Context context) {
|
||||||
|
if (context != null) {
|
||||||
|
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||||
|
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
|
||||||
|
if (mNetworkInfo != null) {
|
||||||
|
return mNetworkInfo.isAvailable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断WiFi连接状态
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static boolean isWifiConnected(Context context) {
|
||||||
|
if (context != null) {
|
||||||
|
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||||
|
NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
|
||||||
|
if (mWiFiNetworkInfo != null) {
|
||||||
|
return mWiFiNetworkInfo.isAvailable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断移动网络状态
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static boolean isMobileConnected(Context context) {
|
||||||
|
if (context != null) {
|
||||||
|
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||||
|
NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
|
||||||
|
if (mMobileNetworkInfo != null) {
|
||||||
|
return mMobileNetworkInfo.isAvailable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取网络连接类型
|
||||||
|
*
|
||||||
|
* @param context
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static int getConnectedType(Context context) {
|
||||||
|
if (context != null) {
|
||||||
|
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
|
||||||
|
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
|
||||||
|
if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
|
||||||
|
return mNetworkInfo.getType();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据字符的起始和结束索引提取子串
|
||||||
|
*
|
||||||
|
* @param input 原始字符串
|
||||||
|
* @param startIndex 起始索引(包含,从0开始)
|
||||||
|
* @param endIndex 结束索引(不包含)
|
||||||
|
* @return 子串,若输入无效或索引越界则返回空字符串
|
||||||
|
*/
|
||||||
|
public static String getSubstringByIndices(String input, int startIndex, int endIndex) {
|
||||||
|
if (input == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
// 处理索引越界问题
|
||||||
|
int safeStart = Math.max(startIndex, 0);
|
||||||
|
int safeEnd = Math.min(endIndex, input.length());
|
||||||
|
if (safeStart > safeEnd) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return input.substring(safeStart, safeEnd);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getSubstringByIndex(String input, int startIndex, int length) {
|
||||||
|
if (input == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
// 处理索引越界问题
|
||||||
|
int safeStart = Math.max(startIndex, 0);
|
||||||
|
int safeEnd = Math.min(startIndex + length, input.length());
|
||||||
|
if (safeStart > safeEnd) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return input.substring(safeStart, safeEnd);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 十进制转十六进制
|
||||||
|
*
|
||||||
|
* @param decimal
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String decimalToHexWithPadding(int decimal, int padding) {
|
||||||
|
// 将十进制转换为十六进制,并转换为字符串
|
||||||
|
String hex = Integer.toHexString(decimal);
|
||||||
|
|
||||||
|
// 确保字符串长度为至少4位,不足部分前面补0
|
||||||
|
while (hex.length() < padding) {
|
||||||
|
hex = "0" + hex;
|
||||||
|
}
|
||||||
|
|
||||||
|
return hex.toUpperCase(); // 返回大写形式的十六进制字符串
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 十进制转二进制,且返回的二进制为至少7位数
|
||||||
|
*
|
||||||
|
* @param decimal
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static String decimalToBinary(int decimal) {
|
||||||
|
// 如果输入为0,直接返回"0"
|
||||||
|
if (decimal == 0) {
|
||||||
|
return "0";
|
||||||
|
}
|
||||||
|
|
||||||
|
StringBuilder binary = new StringBuilder();
|
||||||
|
|
||||||
|
// 除2取余法,将余数加入二进制字符串
|
||||||
|
while (decimal > 0) {
|
||||||
|
int remainder = decimal % 2;
|
||||||
|
binary.insert(0, remainder);
|
||||||
|
decimal = decimal / 2;
|
||||||
|
}
|
||||||
|
int length = binary.length();
|
||||||
|
if (length < 7) {
|
||||||
|
int padding = 7 - length;
|
||||||
|
for (int i = 0; i < padding; i++) {
|
||||||
|
binary.insert(0, '0');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return binary.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将二进制字符串转换为十六进制字符串,每8位转换为两位十六进制,不足两位前面补零
|
||||||
|
*
|
||||||
|
* @param binaryStr 输入的二进制字符串(仅包含0和1)
|
||||||
|
* @return 转换后的十六进制字符串
|
||||||
|
* @throws IllegalArgumentException 如果输入不是有效的二进制字符串
|
||||||
|
*/
|
||||||
|
public static String binaryToHex(String binaryStr) {
|
||||||
|
// 校验输入合法性
|
||||||
|
if (binaryStr == null || !binaryStr.matches("[01]+")) {
|
||||||
|
throw new IllegalArgumentException("Invalid binary string");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 补前导零使长度成为8的倍数
|
||||||
|
int length = binaryStr.length();
|
||||||
|
int padding = (8 - (length % 8)) % 8; // 计算需要补零的数量
|
||||||
|
StringBuilder paddedBinary = new StringBuilder();
|
||||||
|
for (int i = 0; i < padding; i++) {
|
||||||
|
paddedBinary.append('0');
|
||||||
|
}
|
||||||
|
paddedBinary.append(binaryStr);
|
||||||
|
|
||||||
|
// 每8位转换为两位十六进制
|
||||||
|
StringBuilder hexStr = new StringBuilder();
|
||||||
|
for (int i = 0; i < paddedBinary.length(); i += 8) {
|
||||||
|
String byteStr = paddedBinary.substring(i, i + 8);
|
||||||
|
int decimalValue = Integer.parseInt(byteStr, 2);
|
||||||
|
hexStr.append(String.format("%02X", decimalValue & 0xFF));
|
||||||
|
}
|
||||||
|
|
||||||
|
return hexStr.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据校验 异或处理
|
||||||
|
*/
|
||||||
|
public static String getXor(String content) {
|
||||||
|
int a = 0;
|
||||||
|
for (int i = 0; i < content.length() / 2; i++) {
|
||||||
|
a = a ^ Integer.parseInt(content.substring(i * 2, (i * 2) + 2), 16);
|
||||||
|
}
|
||||||
|
String result = Integer.toHexString(a).toUpperCase();
|
||||||
|
if (result.length() == 1) {
|
||||||
|
return "0" + result;
|
||||||
|
} else {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static double formatPersonInfo(String input, int startIndex, int length) {
|
||||||
|
if (input == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// 处理索引越界问题
|
||||||
|
int safeStart = Math.max(startIndex, 0);
|
||||||
|
int safeEnd = Math.min(startIndex + length, input.length());
|
||||||
|
if (safeStart > safeEnd) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
String result = input.substring(safeStart, safeEnd);
|
||||||
|
double num = Integer.parseInt(result, 16);
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安装apk
|
||||||
|
*
|
||||||
|
* @param activity
|
||||||
|
* @param apkFile
|
||||||
|
*/
|
||||||
|
public static void installApk(Context activity, File apkFile) {
|
||||||
|
//文件有所有者概念,现在是属于当前进程的,需要把这个文件暴露给系统安装程序(其他进程)去安装
|
||||||
|
//因此,可能会存在权限问题,需要做下面的设置
|
||||||
|
//如果文件是sdcard上的,就不需要这个操作了
|
||||||
|
try {
|
||||||
|
apkFile.setExecutable(true, false);
|
||||||
|
apkFile.setReadable(true, false);
|
||||||
|
apkFile.setWritable(true, false);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
Intent intent = new Intent();
|
||||||
|
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||||
|
intent.setAction(Intent.ACTION_VIEW);
|
||||||
|
Uri uri;
|
||||||
|
|
||||||
|
//TODO N FileProvider
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||||
|
uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", apkFile);
|
||||||
|
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||||
|
// intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
|
||||||
|
} else {
|
||||||
|
uri = Uri.fromFile(apkFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
intent.setDataAndType(uri, "application/vnd.android.package-archive");
|
||||||
|
activity.startActivity(intent);
|
||||||
|
|
||||||
|
//TODO 0 INSTALL PERMISSION
|
||||||
|
//在AndroidManifest中加入权限即可
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import com.shuwei.intelligent.shelves.activity.InitActivity
|
||||||
|
import kotlin.jvm.java
|
||||||
|
|
||||||
|
class BootReceiver : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
|
||||||
|
// 启动服务或Activity
|
||||||
|
val launchIntent = Intent(context, InitActivity::class.java)
|
||||||
|
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
context.startActivity(launchIntent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import android.app.ActivityManager
|
||||||
|
import android.app.AlarmManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.os.Process
|
||||||
|
import android.util.Log
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.PrintWriter
|
||||||
|
import java.io.StringWriter
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
import kotlin.system.exitProcess
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 崩溃处理
|
||||||
|
*/
|
||||||
|
class CrashHandler private constructor(private val context: Context) :
|
||||||
|
Thread.UncaughtExceptionHandler {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "CrashHandler"
|
||||||
|
const val CRASH_REPORTS_DIR = "crash_reports"
|
||||||
|
private const val LOG_LINES = 500 // 收集最近500行日志
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var instance: CrashHandler? = null
|
||||||
|
|
||||||
|
fun init(context: Context) {
|
||||||
|
if (instance == null) {
|
||||||
|
synchronized(CrashHandler::class.java) {
|
||||||
|
if (instance == null) {
|
||||||
|
instance = CrashHandler(context.applicationContext)
|
||||||
|
// 初始化时清理过期的崩溃日志(默认保留7天)
|
||||||
|
instance?.cleanupOldCrashReports()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取单例实例
|
||||||
|
* @return 已通过 init() 初始化时返回实例,否则返回 null
|
||||||
|
*/
|
||||||
|
fun getInstance(): CrashHandler? = instance
|
||||||
|
|
||||||
|
//fun getCrashReportFiles(context: Context): Array<File> {
|
||||||
|
// val crashDir = getCrashDir()
|
||||||
|
// return if (crashDir.exists() && crashDir.isDirectory) {
|
||||||
|
// crashDir.listFiles { _, name -> name.endsWith(".log") } ?: emptyArray()
|
||||||
|
// } else {
|
||||||
|
// emptyArray()
|
||||||
|
// }
|
||||||
|
//}
|
||||||
|
//
|
||||||
|
//fun clearCrashReports(context: Context) {
|
||||||
|
// getCrashReportFiles(context).forEach { it.delete() }
|
||||||
|
//}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
|
||||||
|
|
||||||
|
init {
|
||||||
|
Thread.setDefaultUncaughtExceptionHandler(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun uncaughtException(thread: Thread, ex: Throwable) {
|
||||||
|
handleException(thread, ex)
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(3000)
|
||||||
|
} catch (e: InterruptedException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
// 如果系统提供了默认的异常处理器,则交给系统去结束程序
|
||||||
|
// 否则自己结束程序
|
||||||
|
defaultHandler?.uncaughtException(thread, ex) ?: run {
|
||||||
|
Process.killProcess(Process.myPid())
|
||||||
|
exitProcess(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动重启app
|
||||||
|
*/
|
||||||
|
// private fun restartApp() {
|
||||||
|
// // 延迟1秒后重启应用
|
||||||
|
// Handler(Looper.getMainLooper()).postDelayed({
|
||||||
|
// val intent = Intent(context, MainActivity::class.java).apply {
|
||||||
|
// addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// val pendingIntent = PendingIntent.getActivity(
|
||||||
|
// context, 0, intent,
|
||||||
|
// PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
|
||||||
|
// alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent)
|
||||||
|
//
|
||||||
|
// Process.killProcess(Process.myPid())
|
||||||
|
// exitProcess(1)
|
||||||
|
// }, 1000)
|
||||||
|
// }
|
||||||
|
|
||||||
|
private fun handleException(thread: Thread, ex: Throwable) {
|
||||||
|
// 收集设备信息和异常信息
|
||||||
|
val crashInfo = collectCrashInfo(thread, ex)
|
||||||
|
|
||||||
|
// 保存日志文件
|
||||||
|
saveCrashInfoToFile(crashInfo)
|
||||||
|
|
||||||
|
// 这里可以添加其他处理逻辑,比如上传到服务器等
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun collectCrashInfo(thread: Thread, ex: Throwable): String {
|
||||||
|
return buildString {
|
||||||
|
// 收集设备信息
|
||||||
|
collectDeviceInfo(this)
|
||||||
|
|
||||||
|
// 收集应用日志
|
||||||
|
append("\n\n").append(collectLogs())
|
||||||
|
|
||||||
|
// 收集线程和异常信息
|
||||||
|
append("\n\n========== Thread & Exception Info ==========\n")
|
||||||
|
append("Thread: ${thread.name}\n")
|
||||||
|
append("Stack Trace:\n")
|
||||||
|
|
||||||
|
val sw = StringWriter()
|
||||||
|
val pw = PrintWriter(sw)
|
||||||
|
ex.printStackTrace(pw)
|
||||||
|
var cause: Throwable? = ex.cause
|
||||||
|
while (cause != null) {
|
||||||
|
cause.printStackTrace(pw)
|
||||||
|
cause = cause.cause
|
||||||
|
}
|
||||||
|
pw.close()
|
||||||
|
append(sw.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun collectDeviceInfo(sb: StringBuilder) {
|
||||||
|
sb.append("========== Device Info ==========\n")
|
||||||
|
try {
|
||||||
|
// 应用信息
|
||||||
|
val pm = context.packageManager
|
||||||
|
val pi = pm.getPackageInfo(context.packageName, 0)
|
||||||
|
|
||||||
|
sb.append("App Version: ${pi.versionName}_${pi.versionCode}\n")
|
||||||
|
|
||||||
|
// Android 版本信息
|
||||||
|
sb.append("OS Version: ${Build.VERSION.RELEASE}_${Build.VERSION.SDK_INT}\n")
|
||||||
|
|
||||||
|
// 设备信息
|
||||||
|
sb.append("Vendor: ${Build.MANUFACTURER}\n")
|
||||||
|
sb.append("Model: ${Build.MODEL}\n")
|
||||||
|
sb.append("CPU ABI: ${Build.SUPPORTED_ABIS[0]}\n")
|
||||||
|
|
||||||
|
// 其他信息
|
||||||
|
sb.append("Locale: ${Locale.getDefault()}\n")
|
||||||
|
sb.append(
|
||||||
|
"Current Time: ${
|
||||||
|
SimpleDateFormat(
|
||||||
|
"yyyy-MM-dd HH:mm:ss",
|
||||||
|
Locale.getDefault()
|
||||||
|
).format(Date())
|
||||||
|
}\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 内存信息
|
||||||
|
val memoryInfo = ActivityManager.MemoryInfo()
|
||||||
|
val activityManager =
|
||||||
|
context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||||
|
activityManager.getMemoryInfo(memoryInfo)
|
||||||
|
sb.append("Available Memory: ${memoryInfo.availMem / (1024 * 1024)}MB\n")
|
||||||
|
sb.append("Total Memory: ${memoryInfo.totalMem / (1024 * 1024)}MB\n")
|
||||||
|
sb.append("Low Memory: ${memoryInfo.lowMemory}\n")
|
||||||
|
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("","Error while collecting device info")
|
||||||
|
sb.append("Error while collecting device info: ${e.message}\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun collectLogs(): String {
|
||||||
|
return buildString {
|
||||||
|
append("========== Application Logs ==========\n")
|
||||||
|
try {
|
||||||
|
val process = Runtime.getRuntime().exec("logcat -d -v threadtime")
|
||||||
|
val reader = process.inputStream.bufferedReader()
|
||||||
|
|
||||||
|
val logLines = reader.readLines()
|
||||||
|
val start = maxOf(0, logLines.size - LOG_LINES)
|
||||||
|
|
||||||
|
logLines.subList(start, logLines.size).forEach {
|
||||||
|
append(it).append("\n")
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
Log.e(TAG, "Error collecting logs")
|
||||||
|
append("Error collecting logs: ${e.message}\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saveCrashInfoToFile(crashInfo: String) {
|
||||||
|
try {
|
||||||
|
val time = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault()).format(Date())
|
||||||
|
val fileName = "crash_$time.log"
|
||||||
|
|
||||||
|
val crashDir = getCrashDir()
|
||||||
|
|
||||||
|
val crashFile = File(crashDir, fileName)
|
||||||
|
FileOutputStream(crashFile).use { it.write(crashInfo.toByteArray()) }
|
||||||
|
|
||||||
|
Log.d(TAG,"Crash info saved to: ${crashFile.absolutePath}")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "Error saving crash info to file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理旧的崩溃日志
|
||||||
|
*/
|
||||||
|
fun cleanupOldCrashReports(maxAgeDays: Int = 7) {
|
||||||
|
// 该方法会在 Application 启动及定时任务中调用,异常必须内部消化,避免影响主流程
|
||||||
|
try {
|
||||||
|
val crashDir = getCrashDir()
|
||||||
|
if (!crashDir.exists() || !crashDir.isDirectory) return
|
||||||
|
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
val maxAgeMillis = maxAgeDays * 24 * 60 * 60 * 1000L
|
||||||
|
|
||||||
|
crashDir.listFiles()?.forEach { file ->
|
||||||
|
if (file.lastModified() < now - maxAgeMillis) {
|
||||||
|
file.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "清理崩溃日志失败", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getCrashDir():File {
|
||||||
|
//val crashDir = File(context.getExternalFilesDir(null), CRASH_REPORTS_DIR)
|
||||||
|
var crashDir = File(context.filesDir, CRASH_REPORTS_DIR)
|
||||||
|
if (!crashDir.exists()) {
|
||||||
|
crashDir.mkdirs()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(crashDir.exists())) {
|
||||||
|
crashDir = File(context.cacheDir, CRASH_REPORTS_DIR)
|
||||||
|
}
|
||||||
|
return crashDir
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
package com.shuwei.intelligent.shelves.utils
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import androidx.annotation.NonNull
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.time.LocalDateTime
|
import java.time.LocalDateTime
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.util.Calendar
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
@@ -19,6 +21,19 @@ object DateTimeUtil {
|
|||||||
return sdf.format(dateTime)
|
return sdf.format(dateTime)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun stringToDate(dateText: String, pattern: String = YYYY_MM_DD_HH_MM_SS): Date? {
|
||||||
|
val sdf = SimpleDateFormat(pattern, Locale.CHINA)
|
||||||
|
return sdf.parse(dateText)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addDays(date: Date, days: Int): Date {
|
||||||
|
val calendar = Calendar.getInstance().apply {
|
||||||
|
time = date
|
||||||
|
add(Calendar.DAY_OF_MONTH, days)
|
||||||
|
}
|
||||||
|
return calendar.time
|
||||||
|
}
|
||||||
|
|
||||||
// fun convert(dateStr: String, pattern: String = YYYY_MM_DD_HH_MM_SS): Date {
|
// fun convert(dateStr: String, pattern: String = YYYY_MM_DD_HH_MM_SS): Date {
|
||||||
// val formatter = DateTimeFormatter.ofPattern(pattern)
|
// val formatter = DateTimeFormatter.ofPattern(pattern)
|
||||||
// val ldt = LocalDateTime.parse(dateStr, formatter)
|
// val ldt = LocalDateTime.parse(dateStr, formatter)
|
||||||
|
|||||||
@@ -45,3 +45,49 @@ fun byteArrayToHexString(bytes: ByteArray): String {
|
|||||||
fun String.hexToBytes(): ByteArray = hexStringToByteArray(this)
|
fun String.hexToBytes(): ByteArray = hexStringToByteArray(this)
|
||||||
fun ByteArray.toHexString2(): String = byteArrayToHexString(this)
|
fun ByteArray.toHexString2(): String = byteArrayToHexString(this)
|
||||||
|
|
||||||
|
fun hexToBinary(hex: String): String {
|
||||||
|
val hexToBinaryMap = mapOf(
|
||||||
|
'0' to "0000", '1' to "0001", '2' to "0010", '3' to "0011",
|
||||||
|
'4' to "0100", '5' to "0101", '6' to "0110", '7' to "0111",
|
||||||
|
'8' to "1000", '9' to "1001", 'A' to "1010", 'B' to "1011",
|
||||||
|
'C' to "1100", 'D' to "1101", 'E' to "1110", 'F' to "1111"
|
||||||
|
)
|
||||||
|
|
||||||
|
return hex.map { char ->
|
||||||
|
hexToBinaryMap[char] ?: throw IllegalArgumentException("非法十六进制字符: $char")
|
||||||
|
}.joinToString("")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun binaryToHex(binary: String): String {
|
||||||
|
// 补齐到4的倍数长度(方便分组)
|
||||||
|
val paddedBinary = binary.padStart(
|
||||||
|
length = ((binary.length + 3) / 4) * 4,
|
||||||
|
padChar = '0'
|
||||||
|
)
|
||||||
|
|
||||||
|
// 每4位二进制对应1位十六进制
|
||||||
|
return paddedBinary.chunked(4).joinToString("") { nibble ->
|
||||||
|
when (nibble) {
|
||||||
|
"0000" -> "0"
|
||||||
|
"0001" -> "1"
|
||||||
|
"0010" -> "2"
|
||||||
|
"0011" -> "3"
|
||||||
|
"0100" -> "4"
|
||||||
|
"0101" -> "5"
|
||||||
|
"0110" -> "6"
|
||||||
|
"0111" -> "7"
|
||||||
|
"1000" -> "8"
|
||||||
|
"1001" -> "9"
|
||||||
|
"1010" -> "A"
|
||||||
|
"1011" -> "B"
|
||||||
|
"1100" -> "C"
|
||||||
|
"1101" -> "D"
|
||||||
|
"1110" -> "E"
|
||||||
|
"1111" -> "F"
|
||||||
|
else -> throw IllegalArgumentException("无效的二进制段: $nibble")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.trimStart('0') // 去除前导零
|
||||||
|
.ifEmpty { "0" } // 处理全零情况
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
fun f2C(fahrenheit: Double): Double {
|
||||||
|
return (fahrenheit - 32) * 5 / 9
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.shuwei.intelligent.shelves.utils.CrashHandler.Companion.CRASH_REPORTS_DIR
|
||||||
|
import java.io.*
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.*
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件日志记录器
|
||||||
|
* 功能:保存日志到本地文件,每条数据一行,每天生成新文件
|
||||||
|
*/
|
||||||
|
class FileLogger(private val context: Context) {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val LOG_DIR = "logs"
|
||||||
|
private const val FILE_PREFIX = "log_"
|
||||||
|
private const val FILE_EXTENSION = ".txt"
|
||||||
|
|
||||||
|
/** 日志保留天数,超过该天数的日志文件在应用启动时清理 */
|
||||||
|
private const val RETENTION_DAYS = 7L
|
||||||
|
|
||||||
|
/** 单个日志文件大小上限(100MB),超过后当天不再写入,防止异常刷屏撑爆存储 */
|
||||||
|
private const val MAX_LOG_FILE_SIZE = 100L * 1024 * 1024
|
||||||
|
|
||||||
|
private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
|
||||||
|
private val timeFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理过期的日志文件,保留最近 retentionDays 天
|
||||||
|
* 按文件最后修改时间判断,最近仍在写入的文件不会被误删
|
||||||
|
* 建议在 Application 启动时调用一次
|
||||||
|
* @param context 上下文,用于定位 filesDir
|
||||||
|
* @param retentionDays 日志保留天数
|
||||||
|
*/
|
||||||
|
fun cleanupExpiredLogs(context: Context, retentionDays: Long = RETENTION_DAYS) {
|
||||||
|
try {
|
||||||
|
val cutoff = System.currentTimeMillis() - retentionDays * 24 * 60 * 60 * 1000L
|
||||||
|
context.filesDir.listFiles { _, name ->
|
||||||
|
name.startsWith(FILE_PREFIX) && name.endsWith(FILE_EXTENSION)
|
||||||
|
}?.forEach { file ->
|
||||||
|
if (file.lastModified() < cutoff) {
|
||||||
|
file.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录日志
|
||||||
|
* @param message 日志消息
|
||||||
|
* @param level 日志级别
|
||||||
|
*/
|
||||||
|
fun log(message: String, level: LogLevel = LogLevel.INFO) {
|
||||||
|
try {
|
||||||
|
val logEntry = formatLogEntry(message, level)
|
||||||
|
writeToFile(logEntry)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化日志条目
|
||||||
|
*/
|
||||||
|
private fun formatLogEntry(message: String, level: LogLevel): String {
|
||||||
|
val timestamp = timeFormat.format(Date())
|
||||||
|
return "[$timestamp] [$level] $message\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写入文件
|
||||||
|
* 单文件超过大小上限(100MB)时当天不再写入,防止异常刷屏撑爆存储
|
||||||
|
*/
|
||||||
|
private fun writeToFile(logEntry: String) {
|
||||||
|
// val path = File(context.filesDir, LOG_DIR)
|
||||||
|
// if (path.exists().not()) {
|
||||||
|
// path.mkdirs()
|
||||||
|
// }
|
||||||
|
val fileName = getCurrentDateFileName()
|
||||||
|
val file = File(context.filesDir, fileName)
|
||||||
|
if (file.exists() && file.length() > MAX_LOG_FILE_SIZE) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val output = context.openFileOutput(fileName, Context.MODE_APPEND)
|
||||||
|
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(output))
|
||||||
|
writer.use {
|
||||||
|
it.write(logEntry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前日期对应的文件名
|
||||||
|
*/
|
||||||
|
private fun getCurrentDateFileName(): String {
|
||||||
|
val date = dateFormat.format(Date())
|
||||||
|
return "${FILE_PREFIX}${date}${FILE_EXTENSION}"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取指定日期的日志文件
|
||||||
|
* @param date 日期字符串,格式:yyyy-MM-dd
|
||||||
|
*/
|
||||||
|
fun readLogsByDate(date: String): List<String> {
|
||||||
|
val fileName = "${FILE_PREFIX}${date}${FILE_EXTENSION}"
|
||||||
|
return readLogsByName(fileName)
|
||||||
|
}
|
||||||
|
fun readLogsByName(fileName: String): List<String> {
|
||||||
|
try {
|
||||||
|
val input = context.openFileInput(fileName)
|
||||||
|
val reader = BufferedReader(InputStreamReader(input))
|
||||||
|
val list: MutableList<String> = reader.useLines { lines ->
|
||||||
|
lines.toList().toMutableList()
|
||||||
|
}
|
||||||
|
|
||||||
|
// val input2 = FileInputStream(getCrashDir(context))
|
||||||
|
// val reader2 = BufferedReader(InputStreamReader(input2))
|
||||||
|
// val list2: MutableList<String> = reader2.useLines {lines ->
|
||||||
|
// lines.toList().toMutableList()
|
||||||
|
// }
|
||||||
|
// list.addAll(list2)
|
||||||
|
return list
|
||||||
|
} catch (e: FileNotFoundException) {
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public fun getCrashDir(context: Context):File {
|
||||||
|
//val crashDir = File(context.getExternalFilesDir(null), CRASH_REPORTS_DIR)
|
||||||
|
var crashDir = File(context.filesDir, CRASH_REPORTS_DIR)
|
||||||
|
if (!crashDir.exists()) {
|
||||||
|
crashDir.mkdirs()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(crashDir.exists())) {
|
||||||
|
crashDir = File(context.cacheDir, CRASH_REPORTS_DIR)
|
||||||
|
}
|
||||||
|
return crashDir
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有日志文件列表
|
||||||
|
*/
|
||||||
|
fun getLogFiles(): List<String> {
|
||||||
|
return context.fileList()
|
||||||
|
.filter { it.startsWith(FILE_PREFIX) && it.endsWith(FILE_EXTENSION) }
|
||||||
|
//.map { it.replace(FILE_EXTENSION, "") }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 日志级别枚举
|
||||||
|
*/
|
||||||
|
enum class LogLevel {
|
||||||
|
DEBUG, INFO, WARN, ERROR
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfModelV2
|
||||||
|
import com.shuwei.intelligent.shelves.serial.ProtocolConstants
|
||||||
|
|
||||||
|
object GridLayoutTool {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备2列,10格
|
||||||
|
*/
|
||||||
|
private val device2Columns = ProtocolConstants.device2Columns
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备3列,15格,左侧1列竖向编号1、2、3、4、5,右侧2列5行编号为6-7、8-9、10-11、12-13、14-15
|
||||||
|
*/
|
||||||
|
private val device3Columns = ProtocolConstants.device3Columns
|
||||||
|
|
||||||
|
fun getLayoutManager(context: Context): RecyclerView.LayoutManager? {
|
||||||
|
return if (device2Columns.contains(App.deviceId)) {
|
||||||
|
GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false)
|
||||||
|
} else if (device3Columns.contains(App.deviceId)) {
|
||||||
|
GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getLayoutManagerV2(context: Context, columns: Int) = GridLayoutManager(context, columns, GridLayoutManager.VERTICAL, false)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化list显示顺序
|
||||||
|
*/
|
||||||
|
fun initListSort(source: List<ShelfModel>): List<ShelfModel> {
|
||||||
|
val map = source.associateBy { it.deviceNo }
|
||||||
|
return if (device3Columns.contains(App.deviceId)) {
|
||||||
|
// 按全局定义的显示顺序取对应数据,找不到则跳过
|
||||||
|
ProtocolConstants.device3ColumnsOrder.mapNotNull { map[it] }
|
||||||
|
} else if (device2Columns.contains(App.deviceId)) {
|
||||||
|
ProtocolConstants.device2ColumnsOrder.mapNotNull { map[it] }
|
||||||
|
} else {
|
||||||
|
source
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun initListSortV2(rows:Int, columns:Int, source: List<ShelfModelV2>): List<ShelfModelV2> {
|
||||||
|
val map = source.associateBy { it.slotNo?.toIntOrNull()?:0 }
|
||||||
|
if (rows != 5) return source
|
||||||
|
return when (columns) {
|
||||||
|
3 -> {
|
||||||
|
// 3列顺序
|
||||||
|
ProtocolConstants.device3ColumnsOrder.mapNotNull { map[it] }
|
||||||
|
}
|
||||||
|
2 -> {
|
||||||
|
// 2列顺序
|
||||||
|
ProtocolConstants.device2ColumnsOrder.mapNotNull { map[it] }
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
//没有则默认
|
||||||
|
source
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun submitListSortV2(source: List<ShelfModelV2>): List<ShelfModelV2> {
|
||||||
|
return source.sortedBy { it.slotNo?.toIntOrNull()?:0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交接口list顺序
|
||||||
|
*/
|
||||||
|
fun submitListSort(source: List<ShelfModel>): List<ShelfModel> {
|
||||||
|
return source.sortedBy { it.deviceNo }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils;
|
||||||
|
|
||||||
|
|
||||||
|
public class HexUtils {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将有符号十六进制字符串转换为十进制整数
|
||||||
|
* @param hex 十六进制字符串(支持负数补码表示)
|
||||||
|
* @return 对应的十进制整数
|
||||||
|
*/
|
||||||
|
public static int signedHexToDec(String hex) {
|
||||||
|
// 验证输入格式
|
||||||
|
if (hex == null || hex.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("输入不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hex.matches("[0-9A-Fa-f]+")) {
|
||||||
|
throw new IllegalArgumentException("无效的十六进制格式: " + hex);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 转换为无符号长整型
|
||||||
|
long unsignedValue = Long.parseLong(hex, 16);
|
||||||
|
|
||||||
|
// 判断是否为负数(最高位为1)
|
||||||
|
int bitLength = hex.length() * 4; // 每个十六进制字符对应4位
|
||||||
|
long signBitMask = 1L << (bitLength - 1);
|
||||||
|
|
||||||
|
if ((unsignedValue & signBitMask) != 0) {
|
||||||
|
// 负数:计算补码
|
||||||
|
long maxValue = (1L << bitLength) - 1;
|
||||||
|
return (int) (unsignedValue - (maxValue + 1));
|
||||||
|
} else {
|
||||||
|
// 正数:直接转换
|
||||||
|
return (int) unsignedValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试方法
|
||||||
|
*/
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// 测试用例
|
||||||
|
String[] testCases = {
|
||||||
|
"FF", // -1 (8位)
|
||||||
|
"FFFE", // -2 (16位)
|
||||||
|
"FFFFFFFE", // -2 (32位)
|
||||||
|
"7F", // 127
|
||||||
|
"80", // -128
|
||||||
|
"7FFF", // 32767
|
||||||
|
"8000" // -32768
|
||||||
|
};
|
||||||
|
|
||||||
|
System.out.println("有符号十六进制转换测试:");
|
||||||
|
for (String hex : testCases) {
|
||||||
|
try {
|
||||||
|
int result = signedHexToDec(hex);
|
||||||
|
System.out.println(hex + " -> " + result);
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println(hex + " -> 错误: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
|
||||||
|
class IntervalExecutor {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动定时任务
|
||||||
|
* @param delayMillis 延迟时间(毫秒)
|
||||||
|
* @param action 要执行的方法
|
||||||
|
* @return Job 可用于取消任务
|
||||||
|
*/
|
||||||
|
fun startIntervalTask(delayMillis: Long, action: suspend () -> Unit): Job {
|
||||||
|
return CoroutineScope(Dispatchers.Default).launch {
|
||||||
|
while (isActive) {
|
||||||
|
action()
|
||||||
|
delay(delayMillis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动定时任务(带初始延迟)
|
||||||
|
* @param initialDelay 初始延迟时间(毫秒)
|
||||||
|
* @param delayMillis 后续执行间隔(毫秒)
|
||||||
|
* @param action 要执行的方法
|
||||||
|
* @return Job 可用于取消任务
|
||||||
|
*/
|
||||||
|
fun startIntervalTaskWithInitialDelay(
|
||||||
|
initialDelay: Long,
|
||||||
|
delayMillis: Long,
|
||||||
|
action: suspend () -> Unit
|
||||||
|
): Job {
|
||||||
|
return CoroutineScope(Dispatchers.Default).launch {
|
||||||
|
delay(initialDelay)
|
||||||
|
while (isActive) {
|
||||||
|
action()
|
||||||
|
delay(delayMillis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用示例
|
||||||
|
fun main() = runBlocking {
|
||||||
|
val executor = IntervalExecutor()
|
||||||
|
|
||||||
|
// 示例1:每隔10秒执行一次
|
||||||
|
val job1 = executor.startIntervalTask(10000) {
|
||||||
|
println("定时任务执行: ${System.currentTimeMillis()}")
|
||||||
|
// 这里可以执行你的业务逻辑
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例2:先延迟5秒,然后每隔3秒执行一次
|
||||||
|
val job2 = executor.startIntervalTaskWithInitialDelay(5000, 3000) {
|
||||||
|
println("带初始延迟的定时任务: ${System.currentTimeMillis()}")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 运行30秒后取消任务
|
||||||
|
delay(30000)
|
||||||
|
job1.cancel()
|
||||||
|
job2.cancel()
|
||||||
|
println("所有定时任务已取消")
|
||||||
|
}
|
||||||
@@ -13,5 +13,9 @@ object KeyboardUtil {
|
|||||||
view.clearFocus() // 清除焦点避免键盘再次弹出
|
view.clearFocus() // 清除焦点避免键盘再次弹出
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun hideKeyboard(view: View) {
|
||||||
|
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||||
|
imm.hideSoftInputFromWindow(view.windowToken, 0)
|
||||||
|
view.clearFocus() // 清除焦点避免键盘再次弹出
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网络连接检测工具类
|
||||||
|
* 提供检测设备网络连接状态的功能
|
||||||
|
*/
|
||||||
|
object NetworkUtils {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测设备是否连接到网络
|
||||||
|
* @param context 应用上下文
|
||||||
|
* @return true 表示已连接网络,false 表示未连接
|
||||||
|
*/
|
||||||
|
fun isNetworkConnected(context: Context): Boolean {
|
||||||
|
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||||
|
val network = connectivityManager.activeNetwork ?: return false
|
||||||
|
val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
|
||||||
|
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Color
|
||||||
|
import com.google.zxing.BarcodeFormat
|
||||||
|
import com.google.zxing.EncodeHintType
|
||||||
|
import com.google.zxing.WriterException
|
||||||
|
import com.google.zxing.common.BitMatrix
|
||||||
|
import com.google.zxing.qrcode.QRCodeWriter
|
||||||
|
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 二维码生成工具类
|
||||||
|
*/
|
||||||
|
object QRCodeUtil {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成二维码(默认大小)
|
||||||
|
* @param content 二维码内容
|
||||||
|
* @return 生成的二维码Bitmap
|
||||||
|
*/
|
||||||
|
@JvmOverloads
|
||||||
|
fun generateQRCode(content: String, size: Int = 500): Bitmap? {
|
||||||
|
return generateQRCode(content, size, Color.BLACK, Color.WHITE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成二维码(自定义颜色)
|
||||||
|
* @param content 二维码内容
|
||||||
|
* @param size 二维码边长(像素)
|
||||||
|
* @param colorCode 二维码颜色
|
||||||
|
* @param backgroundColor 背景颜色
|
||||||
|
* @return 生成的二维码Bitmap
|
||||||
|
*/
|
||||||
|
fun generateQRCode(
|
||||||
|
content: String,
|
||||||
|
size: Int,
|
||||||
|
colorCode: Int,
|
||||||
|
backgroundColor: Int
|
||||||
|
): Bitmap? {
|
||||||
|
if (content.isEmpty()) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return try {
|
||||||
|
val hints = mutableMapOf<EncodeHintType, Any>().apply {
|
||||||
|
put(EncodeHintType.CHARACTER_SET, "UTF-8")
|
||||||
|
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H) // 纠错级别
|
||||||
|
put(EncodeHintType.MARGIN, 1) // 边距
|
||||||
|
}
|
||||||
|
|
||||||
|
val bitMatrix = QRCodeWriter().encode(
|
||||||
|
content,
|
||||||
|
BarcodeFormat.QR_CODE,
|
||||||
|
size,
|
||||||
|
size,
|
||||||
|
hints
|
||||||
|
)
|
||||||
|
|
||||||
|
val pixels = IntArray(size * size).apply {
|
||||||
|
for (y in 0 until size) {
|
||||||
|
for (x in 0 until size) {
|
||||||
|
this[y * size + x] = if (bitMatrix.get(x, y)) colorCode else backgroundColor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply {
|
||||||
|
setPixels(pixels, 0, size, 0, 0, size, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e: WriterException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成带Logo的二维码
|
||||||
|
* @param content 二维码内容
|
||||||
|
* @param size 二维码边长(像素)
|
||||||
|
* @param logo Logo Bitmap
|
||||||
|
* @return 带Logo的二维码Bitmap
|
||||||
|
*/
|
||||||
|
fun generateQRCodeWithLogo(content: String, size: Int, logo: Bitmap?): Bitmap? {
|
||||||
|
val qrCode = generateQRCode(content, size) ?: return null
|
||||||
|
logo ?: return qrCode
|
||||||
|
|
||||||
|
val logoSize = size / 5 // Logo大小约为二维码的1/5
|
||||||
|
val scaledLogo = Bitmap.createScaledBitmap(logo, logoSize, logoSize, false)
|
||||||
|
|
||||||
|
val offset = (size - logoSize) / 2
|
||||||
|
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply {
|
||||||
|
val canvas = Canvas(this)
|
||||||
|
canvas.drawBitmap(qrCode, 0f, 0f, null)
|
||||||
|
canvas.drawBitmap(scaledLogo, offset.toFloat(), offset.toFloat(), null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import com.shuwei.intelligent.shelves.App
|
||||||
|
import com.shuwei.intelligent.shelves.GlobalKey
|
||||||
|
import com.shuwei.intelligent.shelves.utils.ext.put
|
||||||
|
import kotlin.to
|
||||||
|
|
||||||
|
object SpTool {
|
||||||
|
|
||||||
|
const val DEVICE_CONFIG_CACHE = "deviceConfigCache"
|
||||||
|
const val TOKEN = "token"
|
||||||
|
const val LAUNCH_PAGE_TYPE = "launchPageType"
|
||||||
|
const val DEVICE_ID = "deviceId"
|
||||||
|
|
||||||
|
val pref = App.getSharedPref()!!
|
||||||
|
|
||||||
|
fun put(key: String, value: Any) {
|
||||||
|
pref.put(key to value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getInt(key: String, defValue: Int = 0): Int {
|
||||||
|
return pref.getInt(key, defValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getString(key: String, defValue: String? = ""): String {
|
||||||
|
return pref.getString(key, defValue) ?: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getBoolean(key: String, defValue: Boolean = false): Boolean {
|
||||||
|
return pref.getBoolean(key, defValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
var baseUrl: String
|
||||||
|
get() = getString(GlobalKey.KEY_BASE_URL, "")
|
||||||
|
set(value) {
|
||||||
|
put(GlobalKey.KEY_BASE_URL, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils
|
||||||
|
|
||||||
|
import android.util.SparseArray
|
||||||
|
import androidx.core.util.containsKey
|
||||||
|
import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||||
|
|
||||||
|
object StaleFoodRule {
|
||||||
|
|
||||||
|
private val shelfMap = SparseArray<ShelfModel>()
|
||||||
|
|
||||||
|
// fun load(list: MutableList<ShelfModel>) {
|
||||||
|
// if (list.isEmpty()) {
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// list.forEach {
|
||||||
|
// shelfMap.put(it.deviceNo, it)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
fun judge(item: ShelfModel, block:(Boolean)-> Unit = {}) {
|
||||||
|
val deviceNo = item.deviceNo
|
||||||
|
if (!shelfMap.containsKey(deviceNo)) {
|
||||||
|
//首次设置数据
|
||||||
|
shelfMap.put(deviceNo, item)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val lastItem = shelfMap.get(deviceNo)
|
||||||
|
if (lastItem.goodsId != item.goodsId) {
|
||||||
|
//柜子商品更换
|
||||||
|
shelfMap.put(deviceNo, item)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
//同一产品
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+282
@@ -0,0 +1,282 @@
|
|||||||
|
package com.shuwei.intelligent.shelves.utils;
|
||||||
|
|
||||||
|
//import cn.hutool.core.util.HexUtil;
|
||||||
|
//import cn.hutool.core.util.StrUtil;
|
||||||
|
//import com.chengyi.framework.utils.HexUtils;
|
||||||
|
//import lombok.Data;
|
||||||
|
//import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @Author: NThink
|
||||||
|
* @Date: 2021/12/10
|
||||||
|
* @Description: 鸿科HK70温控器信息消息解包
|
||||||
|
*/
|
||||||
|
public class TemperatureInfoHK70MsgBodyUnpack {
|
||||||
|
|
||||||
|
// 柜温探头温度
|
||||||
|
private Double gwttTemp;
|
||||||
|
|
||||||
|
// 蒸发探头温度
|
||||||
|
private Double zfttTemp;
|
||||||
|
|
||||||
|
// 冷凝探头温度
|
||||||
|
private Double lnttTemp;
|
||||||
|
|
||||||
|
// 停机温度
|
||||||
|
private Double tjTemp;
|
||||||
|
|
||||||
|
// 开机温度回差
|
||||||
|
private Double kjTempRange;
|
||||||
|
|
||||||
|
// 压缩机启动延时
|
||||||
|
private Integer ysjStartDelay;
|
||||||
|
|
||||||
|
// 首次通电压缩机启动延时
|
||||||
|
private Integer ysjStartDelayFirst;
|
||||||
|
|
||||||
|
// 柜温探头补偿
|
||||||
|
private Double gwttbcTemp;
|
||||||
|
|
||||||
|
// 停机温度可设置的最小值
|
||||||
|
private Double tjTempMin;
|
||||||
|
|
||||||
|
// 停机温度可设置的最大值
|
||||||
|
private Double tjTempMax;
|
||||||
|
|
||||||
|
// 压缩机最大待机时间
|
||||||
|
private Integer ysjMaxWait;
|
||||||
|
|
||||||
|
// 压缩机最短运行时间
|
||||||
|
private Integer ysjMinWork;
|
||||||
|
|
||||||
|
// 蒸发器探头状态
|
||||||
|
private Integer zfttStatus;
|
||||||
|
|
||||||
|
// 自动除霜周期
|
||||||
|
private Integer zdcszq;
|
||||||
|
|
||||||
|
// 除霜过程显示
|
||||||
|
private Integer csWorkShow;
|
||||||
|
|
||||||
|
// 除霜最长时间
|
||||||
|
private Integer cszcsj;
|
||||||
|
|
||||||
|
// 除霜中止温度
|
||||||
|
private Double cszzTemp;
|
||||||
|
|
||||||
|
// 除霜类型
|
||||||
|
private Integer csType;
|
||||||
|
|
||||||
|
// 风机运行模式
|
||||||
|
private Integer fanWorkType;
|
||||||
|
|
||||||
|
// 风机首次启动延时
|
||||||
|
private Integer fanFirstStartDelay;
|
||||||
|
|
||||||
|
// 滴水后风机启动延时
|
||||||
|
private Integer fanStartDelayAfterDrip;
|
||||||
|
|
||||||
|
// 开关机状态
|
||||||
|
private String powerStatus;
|
||||||
|
|
||||||
|
// 制冷状态
|
||||||
|
private String coolStatus;
|
||||||
|
|
||||||
|
// 除霜状态
|
||||||
|
private String csStatus;
|
||||||
|
|
||||||
|
// 滴水状态
|
||||||
|
private String dsStatus;
|
||||||
|
|
||||||
|
// 柜温探头报警
|
||||||
|
private String gwttAlarm;
|
||||||
|
|
||||||
|
// 除霜探头报警
|
||||||
|
private String csttAlarm;
|
||||||
|
|
||||||
|
// 冷凝探头报警
|
||||||
|
private String lnttAlarm;
|
||||||
|
|
||||||
|
// 终端ID
|
||||||
|
private String imei;
|
||||||
|
|
||||||
|
// 固件版本
|
||||||
|
private String version;
|
||||||
|
|
||||||
|
// 命令次数
|
||||||
|
private Integer cmdCount;
|
||||||
|
|
||||||
|
public TemperatureInfoHK70MsgBodyUnpack(String body) {
|
||||||
|
// ===================== 寄存器内容:110字节 =====================
|
||||||
|
String jcqContent = body.substring(0, 220);
|
||||||
|
// 柜温探头温度 [0, 4]
|
||||||
|
double gwttTemp = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(0, 4)) * 0.1));
|
||||||
|
// setGwttTemp(gwttTemp);
|
||||||
|
// // 蒸发探头温度 [4, 8]
|
||||||
|
// double zfttTemp = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(4, 8)) * 0.1));
|
||||||
|
// setZfttTemp(zfttTemp);
|
||||||
|
// // 冷凝探头温度 [8, 12]
|
||||||
|
// double lnttTemp = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(8, 12)) * 0.1));
|
||||||
|
// setLnttTemp(lnttTemp);
|
||||||
|
// // 停机温度 [12, 16]
|
||||||
|
// double tjTemp = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(12, 16)) * 1.0));
|
||||||
|
// setTjTemp(tjTemp);
|
||||||
|
// // 开机温度回差 [16, 20]
|
||||||
|
// double kjwdhc = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(16, 20)) * 0.1));
|
||||||
|
// setKjTempRange(kjwdhc);
|
||||||
|
// // 压缩机启动延时 [20, 24]
|
||||||
|
// int ysjqdys = Integer.parseInt(jcqContent.substring(20, 24), 16);
|
||||||
|
// setYsjStartDelay(ysjqdys);
|
||||||
|
// // 首次通电压缩机启动延时 [24, 28]
|
||||||
|
// int ysjqdysFirst = Integer.parseInt(jcqContent.substring(24, 28), 16);
|
||||||
|
// setYsjStartDelayFirst(ysjqdysFirst);
|
||||||
|
// // 柜温探头补偿 [28, 32]
|
||||||
|
// double gwttbc = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(28, 32)) * 0.1));
|
||||||
|
// setGwttbcTemp(gwttbc);
|
||||||
|
// // 停机温度可设置的最小值 [32, 36]
|
||||||
|
// double tjTempMin = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(32, 36)) * 1.0));
|
||||||
|
// setTjTempMin(tjTempMin);
|
||||||
|
// // 停机温度可设置的最大值 [36, 40]
|
||||||
|
// double tjTempMax = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(36, 40)) * 1.0));
|
||||||
|
// setTjTempMin(tjTempMax);
|
||||||
|
// // 压缩机最大待机时间 [40, 44]
|
||||||
|
// int ysjzddjsj = Integer.parseInt(jcqContent.substring(40, 44), 16);
|
||||||
|
// setYsjMaxWait(ysjzddjsj);
|
||||||
|
// // 压缩机最短运行时间 [44, 48]
|
||||||
|
// int ysjzdyxsj = Integer.parseInt(jcqContent.substring(44, 48), 16);
|
||||||
|
// setYsjMinWork(ysjzdyxsj);
|
||||||
|
// // 蒸发器探头选择 [48, 52]
|
||||||
|
// int zfqtt = Integer.parseInt(jcqContent.substring(48, 52), 16);
|
||||||
|
// setZfttStatus(zfqtt);
|
||||||
|
// // TODO 蒸发器探头补偿 [52, 56]
|
||||||
|
// // TODO 自动除霜周期计算方式 [56, 60]
|
||||||
|
// // 自动除霜周期 [60, 64]
|
||||||
|
// int zdcszq = Integer.parseInt(jcqContent.substring(60, 64), 16);
|
||||||
|
// setZdcszq(zdcszq);
|
||||||
|
// // 除霜过程显示选择 [64, 68]
|
||||||
|
// int csgcxx = Integer.parseInt(jcqContent.substring(64, 68), 16);
|
||||||
|
// setCsWorkShow(csgcxx);
|
||||||
|
// // 除霜最长时间 [68, 72]
|
||||||
|
// int cszcsj = Integer.parseInt(jcqContent.substring(68, 72), 16);
|
||||||
|
// setCszcsj(cszcsj);
|
||||||
|
// // 除霜终止温度 [72, 76]
|
||||||
|
// double cszzwd = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(72, 76)) * 1.0));
|
||||||
|
// setCszzTemp(cszzwd);
|
||||||
|
// // TODO 除霜滴水时间 [76, 80]
|
||||||
|
// // TODO 除霜后柜温显示延时 [80, 84]
|
||||||
|
// // TODO 除霜启动延迟 [84, 88]
|
||||||
|
// // 除霜类型选择 [88, 92]
|
||||||
|
// int cslx = Integer.parseInt(jcqContent.substring(88, 92), 16);
|
||||||
|
// setCsType(cslx);
|
||||||
|
// // TODO 辅热提前启动时间 [92, 96]
|
||||||
|
// // TODO 强制除霜温度 [96, 100]
|
||||||
|
// // 风机运行模式 [100, 104]
|
||||||
|
// int fjyxms = Integer.parseInt(jcqContent.substring(100, 104), 16);
|
||||||
|
// setFanWorkType(fjyxms);
|
||||||
|
// // 风机首次启动延时 [104, 108]
|
||||||
|
// int fjscqdys = Integer.parseInt(jcqContent.substring(104, 108), 16);
|
||||||
|
// setFanFirstStartDelay(fjscqdys);
|
||||||
|
// // 滴水后风机启动延时 [108, 112]
|
||||||
|
// int dshfjqdys = Integer.parseInt(jcqContent.substring(108, 112), 16);
|
||||||
|
// setFanStartDelayAfterDrip(dshfjqdys);
|
||||||
|
// // TODO 风机工作最低温度 [112, 116]
|
||||||
|
// // TODO 风机工作最高温度 [116, 120]
|
||||||
|
// // TODO 风机循环开启时间 [120, 124]
|
||||||
|
// // TODO 风机循环关闭时间 [124, 128]
|
||||||
|
// // TODO 比例制冷压缩机停止时间 [128, 132]
|
||||||
|
// // TODO 比例制冷压缩机运行时间 [132, 136]
|
||||||
|
// // TODO 蜂鸣音报警 [136, 140]
|
||||||
|
// // TODO 柜温低温报警(绝对温度) [140, 144]
|
||||||
|
// // TODO 柜温高温报警(绝对温度) [144, 148]
|
||||||
|
// // TODO 柜温报警延时 [148, 152]
|
||||||
|
// // TODO 上电首次柜温报警延时 [152, 156]
|
||||||
|
// // TODO 辅助继电器功能选择 [156, 160]
|
||||||
|
// // TODO 门开关控制输出选择 [160, 164]
|
||||||
|
// // TODO 开门时蜂鸣器响应延时 [164, 168]
|
||||||
|
// // TODO 第三探头功能选择 [168, 172]
|
||||||
|
// // TODO 冷凝器高温报警启动值 [172, 176]
|
||||||
|
// // TODO 冷凝器高温报警下回差 [176, 180]
|
||||||
|
// // TODO 冷凝器高温保护启动值 [180, 184]
|
||||||
|
// // TODO 实时时钟功能开关 [不上报]
|
||||||
|
// // TODO 非营业模式开启时间 [不上报]
|
||||||
|
// // TODO 非营业模式关闭时间 [不上报]
|
||||||
|
// // TODO 非营业模式温度增量 [不上报]
|
||||||
|
// // TODO 非营业模式灯光开启时间 [不上报]
|
||||||
|
// // TODO 节假日设置 [不上报]
|
||||||
|
// // TODO 节假日非营业模式开启时间 [不上报]
|
||||||
|
// // TODO 除雾自动控制模式 [184, 188]
|
||||||
|
// // TODO 除雾自动开启时间 [188, 192]
|
||||||
|
// // TODO 除雾自动关闭时间 [192, 196]
|
||||||
|
// // TODO 开关机自动控制模式 [不上报]
|
||||||
|
// // TODO 自动开机时间 [不上报]
|
||||||
|
// // TODO 自动关机时间 [不上报]
|
||||||
|
// // TODO 单位选择 [196, 200]
|
||||||
|
// // TODO 柜温每升高 1℃显示延时 [204, 208]
|
||||||
|
// // TODO 显示分辨率选择 [208, 212]
|
||||||
|
// // TODO 机器地址 [212, 216]
|
||||||
|
// // TODO 管理员密码设定 [216, 220]
|
||||||
|
//
|
||||||
|
// // ===================== 状态位解析:4字节 =====================
|
||||||
|
// // 1.状态信息
|
||||||
|
// String statusHexStr = body.substring(220, 224);
|
||||||
|
// statusHexStr = HexUtils.reverse(statusHexStr);
|
||||||
|
// String statusBitStr = HexUtils.hexString2binaryString(statusHexStr);
|
||||||
|
// statusBitStr = StrUtil.reverse(statusBitStr);
|
||||||
|
// // 机组运行状态 0:停止 1:运行 [0, 1]
|
||||||
|
// String powerStatus = "0".equals(statusBitStr.substring(0, 1)) ? "close" : "open";
|
||||||
|
// setPowerStatus(powerStatus);
|
||||||
|
// // TODO 自检状态 0:停止 1:运行 [1, 2]
|
||||||
|
// // 压缩机运行状态 0:停止 1:运行 [2, 3]
|
||||||
|
// String coolStatus = "0".equals(statusBitStr.substring(3, 4)) ? "close" : "open";
|
||||||
|
// setCoolStatus(coolStatus);
|
||||||
|
// // 除霜状态 0:停止 1:运行 [3, 4]
|
||||||
|
// String csStatus = "0".equals(statusBitStr.substring(10, 11)) ? "close" : "open";
|
||||||
|
// setCsStatus(csStatus);
|
||||||
|
// // 滴水状态 0:关闭 1:运行中 [4, 5]
|
||||||
|
// String dsStatus = "0".equals(statusBitStr.substring(12, 13)) ? "close" : "open";
|
||||||
|
// setDsStatus(dsStatus);
|
||||||
|
// // TODO 风机状态 0:停止 1:运行 [5, 6]
|
||||||
|
// // TODO 除露状态 0:停止 1:运行 [6, 7]
|
||||||
|
// // TODO 灯光状态 0:停止 1:运行 [7, 8]
|
||||||
|
// // TODO 除霜加热或电磁阀状态 0:停止 1:运行 [8, 9]
|
||||||
|
// // TODO 辅助加热状态 0:停止 1:运行 [9, 10]
|
||||||
|
// // TODO 报警状态 0:停止 1:运行 [10, 11]
|
||||||
|
// // TODO 开门状态 0:停止 1:运行 [11, 12]
|
||||||
|
// // TODO 非营业(节能)状态 0:停止 1:运行 [12, 13]
|
||||||
|
// // TODO 节假日状态 0:停止 1:运行 [13, 14]
|
||||||
|
// // TODO 保留 0:停止 1:运行 [14, 15]
|
||||||
|
// // TODO 保留 0:停止 1:运行 [15, 16]
|
||||||
|
//
|
||||||
|
// // 2.报警信息
|
||||||
|
// String alarmHexStr = body.substring(224, 228);
|
||||||
|
// String alarmBitStr = HexUtils.hexString2binaryString(alarmHexStr);
|
||||||
|
// alarmBitStr = StrUtil.reverse(alarmBitStr);
|
||||||
|
// // 柜温探头故障 0:无报警 1:报警
|
||||||
|
// String gwttAlarm = "0".equals(alarmBitStr.substring(0, 1)) ? "normal" : "alarm";
|
||||||
|
// setGwttAlarm(gwttAlarm);
|
||||||
|
// // 除霜探头故障 0:无报警 1:报警
|
||||||
|
// String csAlarm = "0".equals(alarmBitStr.substring(1, 2)) ? "normal" : "alarm";
|
||||||
|
// setCsttAlarm(csAlarm);
|
||||||
|
// // 冷凝探头故障 0:无报警 1:报警
|
||||||
|
// String lnttAlarm = "0".equals(alarmBitStr.substring(2, 3)) ? "normal" : "alarm";
|
||||||
|
// setLnttAlarm(lnttAlarm);
|
||||||
|
// // TODO 柜温高温报警 0:无报警 1:报警
|
||||||
|
// // TODO 柜温低温报警 0:无报警 1:报警
|
||||||
|
// // TODO 冷凝高温报警 0:无报警 1:报警
|
||||||
|
// // TODO 冷凝保护报警 0:无报警 1:报警
|
||||||
|
// // TODO 门打开报警 0:无报警 1:报警
|
||||||
|
// // TODO 时钟故障报警 0:无报警 1:报警
|
||||||
|
//
|
||||||
|
// // 终端ID 15字节
|
||||||
|
// setImei(HexUtil.decodeHexStr(body.substring(228, 258)));
|
||||||
|
// // 固件版本 5字节
|
||||||
|
// setVersion(HexUtil.decodeHexStr(body.substring(258, 268)));
|
||||||
|
// // 命令次数
|
||||||
|
// setCmdCount(Integer.parseInt(body.substring(268, 270), 16));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// String reverse = HexUtils.reverse("8000");
|
||||||
|
// System.out.println(reverse);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package com.shuwei.intelligent.shelves.utils
|
|
||||||
|
|
||||||
import android.widget.Toast
|
|
||||||
import com.shuwei.intelligent.shelves.App
|
|
||||||
//D6DADEDB0302000001000C06
|
|
||||||
object UIUtils {
|
|
||||||
fun toast(strRes: Int) {
|
|
||||||
Toast.makeText(App.get(), strRes, Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun toast(str: String) {
|
|
||||||
Toast.makeText(App.get(), str, Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,6 +10,7 @@ import android.os.Bundle
|
|||||||
import android.util.TypedValue
|
import android.util.TypedValue
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.inputmethod.EditorInfo
|
import android.view.inputmethod.EditorInfo
|
||||||
|
import android.view.inputmethod.InputMethodManager
|
||||||
import android.widget.EditText
|
import android.widget.EditText
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.core.app.ActivityOptionsCompat
|
import androidx.core.app.ActivityOptionsCompat
|
||||||
@@ -22,6 +23,9 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.os.SystemClock
|
||||||
|
|
||||||
fun Context.toast(
|
fun Context.toast(
|
||||||
message: String?,
|
message: String?,
|
||||||
@@ -151,3 +155,43 @@ fun View.clickWithDebounce(delay: Long = 500, action: () -> Unit) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun View.hideKeyboard() {
|
||||||
|
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||||
|
imm.hideSoftInputFromWindow(this.windowToken, 0)
|
||||||
|
this.clearFocus() // 清除焦点避免键盘再次弹出
|
||||||
|
}
|
||||||
|
|
||||||
|
fun String.copyTextToClipboard(context: Context) {
|
||||||
|
// 获取系统服务中的ClipboardManager
|
||||||
|
val clipboard: ClipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
|
||||||
|
// 创建一个ClipData对象,包含要复制的文本
|
||||||
|
val clip = ClipData.newPlainText("label", this)
|
||||||
|
|
||||||
|
// 将ClipData对象设置到剪贴板
|
||||||
|
clipboard.setPrimaryClip(clip)
|
||||||
|
|
||||||
|
// 显示一个简单的Toast提示用户文本已复制
|
||||||
|
Toast.makeText(context, "文本已复制到剪贴板", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为View添加双击点击事件的扩展函数
|
||||||
|
*/
|
||||||
|
fun View.setOnDoubleClickListener(onDoubleClickListener: (View) -> Unit) {
|
||||||
|
var lastClickTime = 0L
|
||||||
|
var lastClickView: View? = null
|
||||||
|
|
||||||
|
this.setOnClickListener { view ->
|
||||||
|
val currentTime = SystemClock.elapsedRealtime()
|
||||||
|
if (lastClickView === view && currentTime - lastClickTime < 500) {
|
||||||
|
// 双击事件触发
|
||||||
|
onDoubleClickListener(view)
|
||||||
|
lastClickTime = 0
|
||||||
|
} else {
|
||||||
|
lastClickTime = currentTime
|
||||||
|
lastClickView = view
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
//package com.shuwei.intelligent.shelves.viewmodel
|
|
||||||
//
|
|
||||||
//import androidx.lifecycle.LiveData
|
|
||||||
//import androidx.lifecycle.MutableLiveData
|
|
||||||
//import androidx.lifecycle.ViewModel
|
|
||||||
//import com.shuwei.intelligent.shelves.model.ShelfModel
|
|
||||||
//
|
|
||||||
//class ShelfDataViewModel : ViewModel() {
|
|
||||||
//
|
|
||||||
// private val _shelfItems = MutableLiveData<MutableList<ShelfModel>>()
|
|
||||||
// val shelfItems: LiveData<MutableList<ShelfModel>> = _shelfItems
|
|
||||||
//
|
|
||||||
// fun updateItems(newItems: MutableList<ShelfModel>) {
|
|
||||||
// _shelfItems.value = newItems
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// fun getCurrentItems(): MutableList<ShelfModel> = _shelfItems.value ?: mutableListOf()
|
|
||||||
//
|
|
||||||
//}
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
|
<!-- android:width="800dp"-->
|
||||||
|
<!-- android:height="1280dp"-->
|
||||||
|
<item>
|
||||||
|
<shape android:shape="rectangle">
|
||||||
|
<solid android:color="@color/bg_page" />
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
<item
|
||||||
|
android:width="450dp"
|
||||||
|
android:height="430dp"
|
||||||
|
android:gravity="top|center_horizontal"
|
||||||
|
android:top="150dp">
|
||||||
|
<bitmap android:src="@drawable/img_init" android:scaleType="fitCenter"/>
|
||||||
|
</item>
|
||||||
|
|
||||||
|
</layer-list>
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 4.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:color="#30000000">
|
||||||
|
<item>
|
||||||
|
<shape android:shape="rectangle">
|
||||||
|
|
||||||
|
<solid android:color="@color/white" />
|
||||||
|
<corners android:radius="8dp" />
|
||||||
|
<stroke
|
||||||
|
android:width="1dp"
|
||||||
|
android:color="@color/bg_card_blue" />
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
</ripple>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:color="#30000000">
|
||||||
|
<item>
|
||||||
|
<shape android:shape="rectangle">
|
||||||
|
|
||||||
|
<solid android:color="@color/bg_card_blue" />
|
||||||
|
<corners android:radius="8dp" />
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
</ripple>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:color="#30000000">
|
||||||
|
<item>
|
||||||
|
<shape android:shape="rectangle">
|
||||||
|
|
||||||
|
<solid android:color="#ff08C6DC" />
|
||||||
|
<corners android:radius="8dp" />
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
</ripple>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
|
<!-- android:width="800dp"-->
|
||||||
|
<!-- android:height="1280dp"-->
|
||||||
|
<item>
|
||||||
|
<shape android:shape="rectangle">
|
||||||
|
<solid android:color="@color/bg_page" />
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
<item
|
||||||
|
android:width="225dp"
|
||||||
|
android:height="215dp"
|
||||||
|
android:gravity="top|center_horizontal"
|
||||||
|
android:top="75dp">
|
||||||
|
<bitmap android:src="@drawable/img_init" android:scaleType="fitCenter"/>
|
||||||
|
</item>
|
||||||
|
|
||||||
|
</layer-list>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:shape="rectangle">
|
||||||
|
<solid android:color="@color/white"/>
|
||||||
|
<corners android:radius="12dp"/>
|
||||||
|
</shape>
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:shape="rectangle">
|
||||||
|
<solid android:color="#4ECDC4" />
|
||||||
|
<corners android:radius="12dp" />
|
||||||
|
<stroke
|
||||||
|
android:width="2dp"
|
||||||
|
android:color="#2BA39F" />
|
||||||
|
</shape>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="80dp"
|
||||||
|
android:height="80dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<!-- 网络断开的图标 -->
|
||||||
|
<path
|
||||||
|
android:fillColor="#FF6B6B"
|
||||||
|
android:pathData="M1,9l2,2c4.97,-4.97 13.03,-4.97 18,0l2,-2C16.93,2.93 7.08,2.93 1,9zM5,13l2,2c2.76,-2.76 7.24,-2.76 10,0l2,-2c-4.42,-4.42 -11.58,-4.42 -16,0zM9,17h6v2h-6z" />
|
||||||
|
</vector>
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 999 KiB |
@@ -0,0 +1,52 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="240dp"
|
||||||
|
android:height="240dp"
|
||||||
|
android:viewportWidth="1024"
|
||||||
|
android:viewportHeight="1024">
|
||||||
|
|
||||||
|
<!-- 由小到大排列的圆点,构成旋转加载指示器 -->
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M876.864,782.592c3.264,0 6.272,-3.2 6.272,-6.656c0,-3.456 -3.008,-6.592 -6.272,-6.592c-3.264,0 -6.272,3.2 -6.272,6.592c0,3.456 3.008,6.656 6.272,6.656z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M736.32,935.936c2.304,2.432 5.568,3.84 8.768,3.84a12.16,12.16 0,0 0,8.832 -3.84a13.76,13.76 0,0 0,0 -18.56a12.224,12.224 0,0 0,-8.832 -3.84a12.16,12.16 0,0 0,-8.768 3.84a13.696,13.696 0,0 0,0 18.56z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M552.32,1018.24c3.456,3.648 8.32,5.76 13.184,5.76a18.368,18.368 0,0 0,13.184 -5.76a20.608,20.608 0,0 0,0 -27.968a18.368,18.368 0,0 0,-13.184 -5.824a18.368,18.368 0,0 0,-13.184 5.76a20.608,20.608 0,0 0,0 28.032z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M353.984,1012.48c4.608,4.8 11.072,7.68 17.6,7.68a24.448,24.448 0,0 0,17.536 -7.68a27.456,27.456 0,0 0,0 -37.248a24.448,24.448 0,0 0,-17.536 -7.68a24.448,24.448 0,0 0,-17.6 7.68a27.52,27.52 0,0 0,0 37.184z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M178.304,920.64c5.76,6.08 13.824,9.6 21.952,9.6a30.592,30.592 0,0 0,22.016 -9.6a34.368,34.368 0,0 0,0 -46.592a30.592,30.592 0,0 0,-22.016 -9.6a30.592,30.592 0,0 0,-21.952 9.6a34.368,34.368 0,0 0,0 46.592z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M57.152,761.28c6.912,7.36 16.64,11.648 26.368,11.648a36.736,36.736 0,0 0,26.432 -11.584a41.28,41.28 0,0 0,0 -55.936a36.736,36.736 0,0 0,-26.432 -11.584a36.8,36.8 0,0 0,-26.368 11.52a41.28,41.28 0,0 0,0 56z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M12.736,564.672a42.88,42.88 0,0 0,30.784 13.44a42.88,42.88 0,0 0,30.784 -13.44a48.128,48.128 0,0 0,0 -65.216a42.88,42.88 0,0 0,-30.72 -13.44a42.88,42.88 0,0 0,-30.848 13.44a48.128,48.128 0,0 0,0 65.216z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M52.544,369.28a48.96,48.96 0,0 0,35.2 15.36a48.96,48.96 0,0 0,35.2 -15.36a54.976,54.976 0,0 0,0 -74.56a48.96,48.96 0,0 0,-35.2 -15.424a48.96,48.96 0,0 0,-35.2 15.424a54.976,54.976 0,0 0,0 74.56z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M168.32,212.48c10.368,11.008 24.96,17.408 39.68,17.408c14.592,0 29.184,-6.4 39.552,-17.408a61.888,61.888 0,0 0,0 -83.84a55.104,55.104 0,0 0,-39.616 -17.408c-14.656,0 -29.248,6.4 -39.616,17.408a61.888,61.888 0,0 0,0 83.84z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M337.344,124.8c11.52,12.16 27.712,19.264 43.968,19.264c16.256,0 32.448,-7.04 43.968,-19.264a68.672,68.672 0,0 0,0 -93.184a61.248,61.248 0,0 0,-43.968 -19.264a61.248,61.248 0,0 0,-43.968 19.264a68.736,68.736 0,0 0,0 93.184z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M526.976,123.712c12.672,13.44 30.528,21.248 48.448,21.248s35.712,-7.808 48.384,-21.248a75.584,75.584 0,0 0,0 -102.464A67.392,67.392 0,0 0,575.36 0c-17.92,0 -35.776,7.808 -48.448,21.248a75.584,75.584 0,0 0,0 102.464z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M700.8,210.304c13.824,14.592 33.28,23.104 52.736,23.104c19.584,0 39.04,-8.512 52.8,-23.104a82.432,82.432 0,0 0,0 -111.744a73.472,73.472 0,0 0,-52.8 -23.168c-19.52,0 -38.912,8.512 -52.736,23.168a82.432,82.432 0,0 0,0 111.744z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M824.832,368.832c14.976,15.872 36.032,25.088 57.216,25.088c21.12,0 42.24,-9.216 57.152,-25.088a89.344,89.344 0,0 0,0 -121.088a79.616,79.616 0,0 0,-57.152 -25.088c-21.184,0 -42.24,9.216 -57.216,25.088a89.344,89.344 0,0 0,0 121.088z" />
|
||||||
|
<path
|
||||||
|
android:fillColor="#ffffff"
|
||||||
|
android:pathData="M875.264,572.864c16.128,17.088 38.784,27.008 61.632,27.008c22.784,0 45.44,-9.92 61.568,-27.008a96.256,96.256 0,0 0,0 -130.432a85.76,85.76 0,0 0,-61.568 -27.072c-22.848,0 -45.44,9.984 -61.632,27.072a96.192,96.192 0,0 0,0 130.432z" />
|
||||||
|
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:shape="ring"
|
||||||
|
android:innerRadiusRatio="3"
|
||||||
|
android:thicknessRatio="8"
|
||||||
|
android:useLevel="false">
|
||||||
|
<gradient
|
||||||
|
android:type="sweep"
|
||||||
|
android:startColor="#FF6B6B"
|
||||||
|
android:centerColor="#4ECDC4"
|
||||||
|
android:endColor="#FF6B6B"
|
||||||
|
android:angle="0" />
|
||||||
|
</shape>
|
||||||
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
|
||||||
|
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:color="?android:attr/colorControlHighlight">
|
||||||
|
<item android:id="@android:id/mask">
|
||||||
|
<color android:color="@android:color/white" />
|
||||||
|
</item>
|
||||||
|
</ripple>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:shape="rectangle">
|
||||||
|
<solid android:color="#90000000"/>
|
||||||
|
<corners android:radius="5dp"/>
|
||||||
|
</shape>
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="match_parent"
|
android:layout_height="match_parent"
|
||||||
android:orientation="vertical"
|
android:orientation="vertical"
|
||||||
android:background="@color/bg_page">
|
tools:background="@color/bg_page">
|
||||||
|
|
||||||
<FrameLayout
|
<FrameLayout
|
||||||
android:id="@+id/flStatusBar"
|
android:id="@+id/flStatusBar"
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
android:layout_gravity="start"
|
android:layout_gravity="start"
|
||||||
android:textSize="24sp"
|
android:textSize="24sp"
|
||||||
android:fontFamily="sans-serif-medium"
|
android:fontFamily="sans-serif-medium"
|
||||||
tools:text="1-1冷藏柜 -2°C / 87%" />
|
android:text=" " />
|
||||||
|
|
||||||
<TextView
|
<TextView
|
||||||
android:id="@+id/tv_right_status"
|
android:id="@+id/tv_right_status"
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?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_width="match_parent"
|
||||||
android:layout_height="match_parent"
|
android:layout_height="match_parent"
|
||||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||||
@@ -17,4 +17,11 @@
|
|||||||
android:layout_marginEnd="12dp"
|
android:layout_marginEnd="12dp"
|
||||||
tools:listitem="@layout/list_item_shelf"/>
|
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>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user