Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
428852a07e | ||
|
|
96863e2078 | ||
|
|
41036cdbf9 | ||
|
|
0d0fcd24b7 | ||
|
|
bb32ed84fe | ||
|
|
6a1a1f3c5c | ||
|
|
9311d13b90 | ||
|
|
143d24923b | ||
|
|
9a77733d24 | ||
|
|
c72d30e88a | ||
|
|
904ccdbb06 | ||
|
|
9ae0d709f2 | ||
|
|
34adc0fe56 | ||
|
|
29228b069b | ||
|
|
d6a9c3562d | ||
|
|
28c7628321 | ||
|
|
3cf9818dad | ||
|
|
c8eb2b8f24 |
@@ -1,15 +1,15 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/caches
|
||||
/.idea/libraries
|
||||
/.idea/modules.xml
|
||||
/.idea/workspace.xml
|
||||
/.idea/navEditor.xml
|
||||
/.idea/assetWizardSettings.xml
|
||||
/.idea/
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
local.properties
|
||||
.claude/
|
||||
app/debug/
|
||||
app/release/
|
||||
# 临时忽略 assets 下的 .pt 模型文件,正式文件就绪后取消此行
|
||||
app/src/main/assets/*.pt
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="AndroidProjectSystem">
|
||||
<option name="providerId" value="com.android.tools.idea.GradleProjectSystem" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="21" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="deploymentTargetSelector">
|
||||
<selectionStates>
|
||||
<SelectionState runConfigName="app">
|
||||
<option name="selectionMode" value="DROPDOWN" />
|
||||
<DropdownSelection timestamp="2026-01-28T08:24:39.059017600Z">
|
||||
<Target type="DEFAULT_BOOT">
|
||||
<handle>
|
||||
<DeviceId pluginId="Default" identifier="serial=192.168.1.80:5555;connection=d6ad651e" />
|
||||
</handle>
|
||||
</Target>
|
||||
</DropdownSelection>
|
||||
<DialogSelection />
|
||||
</SelectionState>
|
||||
</selectionStates>
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DeviceTable">
|
||||
<option name="columnSorters">
|
||||
<list>
|
||||
<ColumnSorterState>
|
||||
<option name="column" value="Name" />
|
||||
<option name="order" value="ASCENDING" />
|
||||
</ColumnSorterState>
|
||||
</list>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="testRunner" value="CHOOSE_PER_TEST" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
<option value="$PROJECT_DIR$/app" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectMigrations">
|
||||
<option name="MigrateToGradleLocalJavaHome">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
</set>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,9 +0,0 @@
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||
</component>
|
||||
<component name="ProjectType">
|
||||
<option name="id" value="Android" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,17 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RunConfigurationProducerService">
|
||||
<option name="ignoredProducers">
|
||||
<set>
|
||||
<option value="com.intellij.execution.junit.AbstractAllInDirectoryConfigurationProducer" />
|
||||
<option value="com.intellij.execution.junit.AllInPackageConfigurationProducer" />
|
||||
<option value="com.intellij.execution.junit.PatternConfigurationProducer" />
|
||||
<option value="com.intellij.execution.junit.TestInClassConfigurationProducer" />
|
||||
<option value="com.intellij.execution.junit.UniqueIdConfigurationProducer" />
|
||||
<option value="com.intellij.execution.junit.testDiscovery.JUnitTestDiscoveryConfigurationProducer" />
|
||||
<option value="org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer" />
|
||||
<option value="org.jetbrains.kotlin.idea.junit.KotlinPatternConfigurationProducer" />
|
||||
</set>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,4 @@
|
||||
kotlin version: 2.0.21
|
||||
error message: The daemon has terminated unexpectedly on startup attempt #1 with error code: 0. The daemon process output:
|
||||
1. Kotlin compile daemon is ready
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
id("com.google.devtools.ksp") version "2.0.21-1.0.27"
|
||||
// alias(libs.plugins.android.application)
|
||||
// alias(libs.plugins.kotlin.android)
|
||||
// id("com.google.devtools.ksp") version "2.0.21-1.0.27"
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
// id("com.google.dagger.hilt.android")
|
||||
id("com.google.devtools.ksp")
|
||||
id("kotlin-parcelize")
|
||||
kotlin("kapt")
|
||||
}
|
||||
|
||||
android {
|
||||
@@ -24,7 +30,7 @@ android {
|
||||
}
|
||||
|
||||
// 设置输出APK文件名格式
|
||||
setProperty("archivesBaseName", "菜品配比终端v${versionName}")
|
||||
setProperty("archivesBaseName", "pbc_v${versionName}")
|
||||
}
|
||||
signingConfigs {
|
||||
create("debug_507") {
|
||||
@@ -42,10 +48,12 @@ android {
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
signingConfig = signingConfigs.getByName("debug_507")
|
||||
// buildConfigField("boolean", "DEBUG", "false")
|
||||
}
|
||||
debug {
|
||||
//507扫码秤主板在android.buildTypes{}内增加
|
||||
signingConfig = signingConfigs.getByName("debug_507")
|
||||
// buildConfigField("boolean", "DEBUG", "true")
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
@@ -57,6 +65,7 @@ android {
|
||||
}
|
||||
buildFeatures {
|
||||
viewBinding = true
|
||||
buildConfig = true
|
||||
}
|
||||
packagingOptions {
|
||||
pickFirst("lib/armeabi-v7a/libserial_port.so")
|
||||
@@ -74,7 +83,9 @@ android {
|
||||
}
|
||||
// li
|
||||
}
|
||||
|
||||
val isDebug = gradle.startParameter.taskNames.any {
|
||||
it.contains("debug", ignoreCase = true)
|
||||
}
|
||||
dependencies {
|
||||
implementation(fileTree("libs") { include("*.jar", "*.aar") })
|
||||
implementation(libs.androidx.core.ktx)
|
||||
@@ -86,32 +97,55 @@ dependencies {
|
||||
testImplementation(libs.junit)
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
implementation(libs.androidx.activity.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.ktx)
|
||||
|
||||
implementation("com.google.code.gson:gson:2.10.1")
|
||||
implementation("com.squareup.okhttp3:okhttp:4.9.1")
|
||||
implementation("com.squareup.okhttp3:logging-interceptor:4.9.1")
|
||||
implementation("com.squareup.retrofit2:retrofit:2.9.0")
|
||||
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
|
||||
implementation(libs.gson)
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.logging.interceptor)
|
||||
implementation(libs.retrofit)
|
||||
implementation(libs.java.websocket)
|
||||
implementation(libs.converter.gson)
|
||||
|
||||
implementation("io.github.cymchad:BaseRecyclerViewAdapterHelper4:4.1.2")
|
||||
implementation(libs.baserecyclerviewadapterhelper4)
|
||||
|
||||
implementation("androidx.room:room-runtime:2.5.2")
|
||||
ksp("androidx.room:room-compiler:2.5.2")
|
||||
implementation("androidx.room:room-ktx:2.5.2") // Kotlin扩展
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
|
||||
implementation("androidx.activity:activity-ktx:1.8.0")
|
||||
// room
|
||||
implementation(libs.androidx.room.runtime)
|
||||
ksp(libs.androidx.room.compiler)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
|
||||
// implementation("biz.laenger.android:vpbs:0.0.6")
|
||||
|
||||
//必须 1.0.0 以上
|
||||
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-header-radar:3.0.0-alpha")
|
||||
implementation("io.github.scwang90:refresh-footer-classics:3.0.0-alpha")
|
||||
//经典加载
|
||||
// refresh-layout
|
||||
implementation(libs.refresh.layout.kernel)
|
||||
implementation(libs.refresh.header.classics)
|
||||
implementation(libs.refresh.header.radar)
|
||||
implementation(libs.refresh.footer.classics)
|
||||
|
||||
//implementation("com.geyifeng.immersionbar:immersionbar:3.2.2")
|
||||
}
|
||||
|
||||
// glide
|
||||
implementation(libs.glide)
|
||||
annotationProcessor(libs.compiler)
|
||||
|
||||
// camerax
|
||||
implementation(libs.androidx.camera.core)
|
||||
implementation(libs.androidx.camera.camera2)
|
||||
implementation(libs.androidx.camera.lifecycle)
|
||||
implementation(libs.androidx.camera.view)
|
||||
implementation(libs.androidx.camera.extensions)
|
||||
|
||||
//pytorch
|
||||
implementation (libs.pytorch.android)
|
||||
implementation (libs.pytorch.android.torchvision)
|
||||
|
||||
// objectbox
|
||||
if (isDebug) {
|
||||
debugImplementation(libs.objectbox.android.objectbrowser)
|
||||
} else {
|
||||
releaseImplementation(libs.objectbox.android)
|
||||
}
|
||||
}
|
||||
|
||||
apply(plugin = "io.objectbox")
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"_note1": "KEEP THIS FILE! Check it into a version control system (VCS) like git.",
|
||||
"_note2": "ObjectBox manages crucial IDs for your object model. See docs for details.",
|
||||
"_note3": "If you have VCS merge conflicts, you must resolve them according to ObjectBox docs.",
|
||||
"entities": [
|
||||
{
|
||||
"id": "1:6465153867413579585",
|
||||
"lastPropertyId": "4:3660727688686055762",
|
||||
"name": "Food",
|
||||
"properties": [
|
||||
{
|
||||
"id": "1:3688350375714699356",
|
||||
"name": "id",
|
||||
"type": 6,
|
||||
"flags": 1
|
||||
},
|
||||
{
|
||||
"id": "2:6503828433160216329",
|
||||
"name": "name",
|
||||
"type": 9
|
||||
},
|
||||
{
|
||||
"id": "3:1726525909323356793",
|
||||
"name": "foodIdx",
|
||||
"type": 5
|
||||
},
|
||||
{
|
||||
"id": "4:3660727688686055762",
|
||||
"name": "foodVector",
|
||||
"indexId": "1:5497952887792054610",
|
||||
"type": 28,
|
||||
"flags": 8
|
||||
}
|
||||
],
|
||||
"relations": []
|
||||
}
|
||||
],
|
||||
"lastEntityId": "1:6465153867413579585",
|
||||
"lastIndexId": "1:5497952887792054610",
|
||||
"lastRelationId": "0:0",
|
||||
"lastSequenceId": "0:0",
|
||||
"modelVersion": 5,
|
||||
"modelVersionParserMinimum": 5,
|
||||
"retiredEntityUids": [],
|
||||
"retiredIndexUids": [],
|
||||
"retiredPropertyUids": [],
|
||||
"retiredRelationUids": [],
|
||||
"version": 1
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:sharedUserId="android.uid.system">
|
||||
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- android:sharedUserId="android.uid.system" -->
|
||||
<uses-feature android:name="android.hardware.usb.host" />
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera"
|
||||
android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
@@ -41,7 +45,6 @@
|
||||
<activity
|
||||
android:name=".ui.InitActivity"
|
||||
android:exported="true"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -50,24 +53,29 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".ui.HomeActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.SelectDishActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity
|
||||
android:name=".ui.PrepareCookActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity
|
||||
android:name=".ui.DishSamplingActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity
|
||||
android:name=".ui.SamplingListActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
@@ -82,10 +90,28 @@
|
||||
<!-- tools:ignore="DiscouragedApi,LockedOrientationActivity" />-->
|
||||
<activity
|
||||
android:name=".ui.FoodSearchActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity android:name="com.shuwei.dish.match.ui.DeviceConfigActivity" />
|
||||
<activity android:name="com.shuwei.dish.match.ui.SubmitFoodActivity" />
|
||||
<activity android:name="com.shuwei.dish.match.ui.DeviceConfigActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash" />
|
||||
<activity android:name="com.shuwei.dish.match.ui.SettingActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity android:name="com.shuwei.dish.match.ui.SubmitFoodActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash" />
|
||||
<activity
|
||||
android:name="com.shuwei.dish.match.ui.MasterScaleActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity
|
||||
android:name="com.shuwei.dish.match.ui.SlaveActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="landscape"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
|
||||
<receiver
|
||||
android:name=".utils.BootReceiver"
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
{
|
||||
"class_names": [
|
||||
"三黄鸡",
|
||||
"上海青WP2026020200041",
|
||||
"冰草WP2026020900054",
|
||||
"刀豆",
|
||||
"北豆腐WP2025111900007",
|
||||
"味精WP2026013000034",
|
||||
"圆生菜WP2026020900053",
|
||||
"圆白菜[卷心菜,包菜]WP2025111000063",
|
||||
"基围虾WP2025110700019",
|
||||
"多宝鱼WP2025112600011",
|
||||
"大白菜(代表值)WP2026022800638",
|
||||
"大葱WP2026013000025",
|
||||
"姜[黄姜]WP2026022800956",
|
||||
"娃娃菜WP2026020200005",
|
||||
"小白菜WP2026022800031",
|
||||
"小米辣椒WP2026013000027",
|
||||
"小葱WP2026013000029",
|
||||
"山药(带皮)WP2026020200008",
|
||||
"巨人笋",
|
||||
"广东菜心WP2025120100014",
|
||||
"木耳(干)[黑木耳,云耳]WP2026022801182",
|
||||
"杏鲍菇WP2026022700030",
|
||||
"松花蛋",
|
||||
"松茸菌WP2025120100016",
|
||||
"沙葱",
|
||||
"海带(浸)[江白菜,昆布]WP2026022800035",
|
||||
"牛腩WP2025110700043",
|
||||
"猪五花肉WP2026020300048",
|
||||
"猪腿肉WP2025110700040",
|
||||
"玉米WP2025120100017",
|
||||
"玉米糁(黄)WP2026022800038",
|
||||
"番茄[西红柿]WP2026021000028",
|
||||
"白吉饼WP2026013000024",
|
||||
"笋",
|
||||
"粉丝",
|
||||
"紫甘蓝",
|
||||
"红心萝卜[心里美]WP2026022800368",
|
||||
"红提子WP2025111900006",
|
||||
"红椒WP2026030300055",
|
||||
"红洋葱WP2026030600054",
|
||||
"红美人椒WP2026020300049",
|
||||
"红薯",
|
||||
"红薯粉条(袋)",
|
||||
"羊排WP2025120300021",
|
||||
"羊血WP2026013000038",
|
||||
"胡萝卜WP2025110600008",
|
||||
"芋头",
|
||||
"花卷",
|
||||
"芹菜WP2025111000065",
|
||||
"苦菊",
|
||||
"茄子(紫皮,长)WP2025110700024",
|
||||
"茼蒿WP2026020200045",
|
||||
"莲藕(带皮)",
|
||||
"莴笋(鲜)[莴苣]WP2026020200009",
|
||||
"菜花(白色)[花椰菜]",
|
||||
"菠菜(鲜)[赤根菜]WP2026022800700",
|
||||
"蒜WP2025111400003",
|
||||
"蒜苗WP2026013000028",
|
||||
"蒜薹(圆)",
|
||||
"蒸鱼豉油WP2026013000032",
|
||||
"薏米[薏仁米,苡米]WP2026022800037",
|
||||
"西兰花[绿菜花]WP2025110700029",
|
||||
"西葫芦",
|
||||
"豆腐皮WP2025111000059",
|
||||
"豆角",
|
||||
"辣椒(红,小)WP2025111000066",
|
||||
"辣椒(青,尖)WP2026022800504",
|
||||
"醪糟",
|
||||
"金针菇[(鲜)[智力菇]WP2026030600051",
|
||||
"青线椒WP2026013000031",
|
||||
"韭菜WP2026020200044",
|
||||
"韭黄",
|
||||
"馒头(代表值)WP2026030600056",
|
||||
"香椿[香椿芽]WP2026022801086",
|
||||
"香菇(鲜)[香蕈,冬菇]WP2026030600050",
|
||||
"香菜WP2026013000030",
|
||||
"马铃薯[土豆、洋芋]WP2026012900001",
|
||||
"鸡全腿(带骨)",
|
||||
"鸡翅(带骨)",
|
||||
"鸡腿肉WP2025110700048",
|
||||
"鸡腿(带骨)",
|
||||
"鸡蛋WP2026013000039",
|
||||
"麦芹",
|
||||
"黄瓜(鲜)[胡瓜]WP2025110700031",
|
||||
"黄豆芽WP2026020200042",
|
||||
"黑袋子",
|
||||
"黑鱼(整条鱼)WP2025110600012"
|
||||
],
|
||||
"class_to_idx": {
|
||||
"三黄鸡": 0,
|
||||
"上海青WP2026020200041": 1,
|
||||
"冰草WP2026020900054": 2,
|
||||
"刀豆": 3,
|
||||
"北豆腐WP2025111900007": 4,
|
||||
"味精WP2026013000034": 5,
|
||||
"圆生菜WP2026020900053": 6,
|
||||
"圆白菜[卷心菜,包菜]WP2025111000063": 7,
|
||||
"基围虾WP2025110700019": 8,
|
||||
"多宝鱼WP2025112600011": 9,
|
||||
"大白菜(代表值)WP2026022800638": 10,
|
||||
"大葱WP2026013000025": 11,
|
||||
"姜[黄姜]WP2026022800956": 12,
|
||||
"娃娃菜WP2026020200005": 13,
|
||||
"小白菜WP2026022800031": 14,
|
||||
"小米辣椒WP2026013000027": 15,
|
||||
"小葱WP2026013000029": 16,
|
||||
"山药(带皮)WP2026020200008": 17,
|
||||
"巨人笋": 18,
|
||||
"广东菜心WP2025120100014": 19,
|
||||
"木耳(干)[黑木耳,云耳]WP2026022801182": 20,
|
||||
"杏鲍菇WP2026022700030": 21,
|
||||
"松花蛋": 22,
|
||||
"松茸菌WP2025120100016": 23,
|
||||
"沙葱": 24,
|
||||
"海带(浸)[江白菜,昆布]WP2026022800035": 25,
|
||||
"牛腩WP2025110700043": 26,
|
||||
"猪五花肉WP2026020300048": 27,
|
||||
"猪腿肉WP2025110700040": 28,
|
||||
"玉米WP2025120100017": 29,
|
||||
"玉米糁(黄)WP2026022800038": 30,
|
||||
"番茄[西红柿]WP2026021000028": 31,
|
||||
"白吉饼WP2026013000024": 32,
|
||||
"笋": 33,
|
||||
"粉丝": 34,
|
||||
"紫甘蓝": 35,
|
||||
"红心萝卜[心里美]WP2026022800368": 36,
|
||||
"红提子WP2025111900006": 37,
|
||||
"红椒WP2026030300055": 38,
|
||||
"红洋葱WP2026030600054": 39,
|
||||
"红美人椒WP2026020300049": 40,
|
||||
"红薯": 41,
|
||||
"红薯粉条(袋)": 42,
|
||||
"羊排WP2025120300021": 43,
|
||||
"羊血WP2026013000038": 44,
|
||||
"胡萝卜WP2025110600008": 45,
|
||||
"芋头": 46,
|
||||
"花卷": 47,
|
||||
"芹菜WP2025111000065": 48,
|
||||
"苦菊": 49,
|
||||
"茄子(紫皮,长)WP2025110700024": 50,
|
||||
"茼蒿WP2026020200045": 51,
|
||||
"莲藕(带皮)": 52,
|
||||
"莴笋(鲜)[莴苣]WP2026020200009": 53,
|
||||
"菜花(白色)[花椰菜]": 54,
|
||||
"菠菜(鲜)[赤根菜]WP2026022800700": 55,
|
||||
"蒜WP2025111400003": 56,
|
||||
"蒜苗WP2026013000028": 57,
|
||||
"蒜薹(圆)": 58,
|
||||
"蒸鱼豉油WP2026013000032": 59,
|
||||
"薏米[薏仁米,苡米]WP2026022800037": 60,
|
||||
"西兰花[绿菜花]WP2025110700029": 61,
|
||||
"西葫芦": 62,
|
||||
"豆腐皮WP2025111000059": 63,
|
||||
"豆角": 64,
|
||||
"辣椒(红,小)WP2025111000066": 65,
|
||||
"辣椒(青,尖)WP2026022800504": 66,
|
||||
"醪糟": 67,
|
||||
"金针菇[(鲜)[智力菇]WP2026030600051": 68,
|
||||
"青线椒WP2026013000031": 69,
|
||||
"韭菜WP2026020200044": 70,
|
||||
"韭黄": 71,
|
||||
"馒头(代表值)WP2026030600056": 72,
|
||||
"香椿[香椿芽]WP2026022801086": 73,
|
||||
"香菇(鲜)[香蕈,冬菇]WP2026030600050": 74,
|
||||
"香菜WP2026013000030": 75,
|
||||
"马铃薯[土豆、洋芋]WP2026012900001": 76,
|
||||
"鸡全腿(带骨)": 77,
|
||||
"鸡翅(带骨)": 78,
|
||||
"鸡腿肉WP2025110700048": 79,
|
||||
"鸡腿(带骨)": 80,
|
||||
"鸡蛋WP2026013000039": 81,
|
||||
"麦芹": 82,
|
||||
"黄瓜(鲜)[胡瓜]WP2025110700031": 83,
|
||||
"黄豆芽WP2026020200042": 84,
|
||||
"黑袋子": 85,
|
||||
"黑鱼(整条鱼)WP2025110600012": 86
|
||||
},
|
||||
"idx_to_class": {
|
||||
"0": "三黄鸡",
|
||||
"1": "上海青WP2026020200041",
|
||||
"2": "冰草WP2026020900054",
|
||||
"3": "刀豆",
|
||||
"4": "北豆腐WP2025111900007",
|
||||
"5": "味精WP2026013000034",
|
||||
"6": "圆生菜WP2026020900053",
|
||||
"7": "圆白菜[卷心菜,包菜]WP2025111000063",
|
||||
"8": "基围虾WP2025110700019",
|
||||
"9": "多宝鱼WP2025112600011",
|
||||
"10": "大白菜(代表值)WP2026022800638",
|
||||
"11": "大葱WP2026013000025",
|
||||
"12": "姜[黄姜]WP2026022800956",
|
||||
"13": "娃娃菜WP2026020200005",
|
||||
"14": "小白菜WP2026022800031",
|
||||
"15": "小米辣椒WP2026013000027",
|
||||
"16": "小葱WP2026013000029",
|
||||
"17": "山药(带皮)WP2026020200008",
|
||||
"18": "巨人笋",
|
||||
"19": "广东菜心WP2025120100014",
|
||||
"20": "木耳(干)[黑木耳,云耳]WP2026022801182",
|
||||
"21": "杏鲍菇WP2026022700030",
|
||||
"22": "松花蛋",
|
||||
"23": "松茸菌WP2025120100016",
|
||||
"24": "沙葱",
|
||||
"25": "海带(浸)[江白菜,昆布]WP2026022800035",
|
||||
"26": "牛腩WP2025110700043",
|
||||
"27": "猪五花肉WP2026020300048",
|
||||
"28": "猪腿肉WP2025110700040",
|
||||
"29": "玉米WP2025120100017",
|
||||
"30": "玉米糁(黄)WP2026022800038",
|
||||
"31": "番茄[西红柿]WP2026021000028",
|
||||
"32": "白吉饼WP2026013000024",
|
||||
"33": "笋",
|
||||
"34": "粉丝",
|
||||
"35": "紫甘蓝",
|
||||
"36": "红心萝卜[心里美]WP2026022800368",
|
||||
"37": "红提子WP2025111900006",
|
||||
"38": "红椒WP2026030300055",
|
||||
"39": "红洋葱WP2026030600054",
|
||||
"40": "红美人椒WP2026020300049",
|
||||
"41": "红薯",
|
||||
"42": "红薯粉条(袋)",
|
||||
"43": "羊排WP2025120300021",
|
||||
"44": "羊血WP2026013000038",
|
||||
"45": "胡萝卜WP2025110600008",
|
||||
"46": "芋头",
|
||||
"47": "花卷",
|
||||
"48": "芹菜WP2025111000065",
|
||||
"49": "苦菊",
|
||||
"50": "茄子(紫皮,长)WP2025110700024",
|
||||
"51": "茼蒿WP2026020200045",
|
||||
"52": "莲藕(带皮)",
|
||||
"53": "莴笋(鲜)[莴苣]WP2026020200009",
|
||||
"54": "菜花(白色)[花椰菜]",
|
||||
"55": "菠菜(鲜)[赤根菜]WP2026022800700",
|
||||
"56": "蒜WP2025111400003",
|
||||
"57": "蒜苗WP2026013000028",
|
||||
"58": "蒜薹(圆)",
|
||||
"59": "蒸鱼豉油WP2026013000032",
|
||||
"60": "薏米[薏仁米,苡米]WP2026022800037",
|
||||
"61": "西兰花[绿菜花]WP2025110700029",
|
||||
"62": "西葫芦",
|
||||
"63": "豆腐皮WP2025111000059",
|
||||
"64": "豆角",
|
||||
"65": "辣椒(红,小)WP2025111000066",
|
||||
"66": "辣椒(青,尖)WP2026022800504",
|
||||
"67": "醪糟",
|
||||
"68": "金针菇[(鲜)[智力菇]WP2026030600051",
|
||||
"69": "青线椒WP2026013000031",
|
||||
"70": "韭菜WP2026020200044",
|
||||
"71": "韭黄",
|
||||
"72": "馒头(代表值)WP2026030600056",
|
||||
"73": "香椿[香椿芽]WP2026022801086",
|
||||
"74": "香菇(鲜)[香蕈,冬菇]WP2026030600050",
|
||||
"75": "香菜WP2026013000030",
|
||||
"76": "马铃薯[土豆、洋芋]WP2026012900001",
|
||||
"77": "鸡全腿(带骨)",
|
||||
"78": "鸡翅(带骨)",
|
||||
"79": "鸡腿肉WP2025110700048",
|
||||
"80": "鸡腿(带骨)",
|
||||
"81": "鸡蛋WP2026013000039",
|
||||
"82": "麦芹",
|
||||
"83": "黄瓜(鲜)[胡瓜]WP2025110700031",
|
||||
"84": "黄豆芽WP2026020200042",
|
||||
"85": "黑袋子",
|
||||
"86": "黑鱼(整条鱼)WP2025110600012"
|
||||
},
|
||||
"embedding_dim": 512,
|
||||
"total_images": 2093,
|
||||
"build_time": "2026-03-10T10:33:47.104848"
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.ImageView
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemFoodCollectionBinding
|
||||
import com.shuwei.dish.match.objbox.FoodCollectionBean
|
||||
import com.shuwei.dish.match.utils.ext.load
|
||||
|
||||
class FoodCollectionAdapter (var list: MutableList<FoodCollectionBean>) :
|
||||
BaseQuickAdapter<FoodCollectionBean, FoodCollectionAdapter.VH>(list) {
|
||||
|
||||
inner class VH(var binding: ListItemFoodCollectionBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||
val inflater = LayoutInflater.from(context)
|
||||
val binding = ListItemFoodCollectionBinding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: FoodCollectionBean?) {
|
||||
val binding = holder.binding
|
||||
item?.let {
|
||||
binding.ivFinish.visibility = if (it.isFinish) View.VISIBLE else View.GONE
|
||||
binding.ivDelete.visibility = if (it.isShowCamera) View.GONE else View.VISIBLE
|
||||
binding.imageView.run {
|
||||
if (it.isShowCamera) {
|
||||
scaleType = ImageView.ScaleType.CENTER
|
||||
setImageResource(R.drawable.ic_camera_default)
|
||||
} else {
|
||||
//scaleType = ImageView.ScaleType.FIT_CENTER
|
||||
scaleType = ImageView.ScaleType.CENTER_CROP
|
||||
//setImageURI(it.imageUri)
|
||||
//setImageBitmap(it.bitmap)
|
||||
if (it.imageUri!=null) {
|
||||
setImageURI(it.imageUri)
|
||||
} else {
|
||||
load(it.imageFile)
|
||||
}
|
||||
// it.bitmap?.let { bitmap ->
|
||||
// GlideUtils.loadRoundCornerWitBitmap(
|
||||
// context,
|
||||
// url = bitmap,
|
||||
// imageView = this,
|
||||
// radius = 8.dp
|
||||
// )
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -41,6 +41,7 @@ class GoodsInfoSearchAdapter(private var list: MutableList<CookFoodGoodsEntity>)
|
||||
): VH {
|
||||
val binding =
|
||||
ListItemSearchGoodsInfoBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.shuwei.dish.match.base
|
||||
|
||||
import android.content.Intent
|
||||
import android.content.pm.ActivityInfo
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
@@ -14,6 +15,9 @@ import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.activity.viewModels
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ActivityBaseBinding
|
||||
import com.shuwei.dish.match.dialog.Loading
|
||||
@@ -35,34 +39,25 @@ import kotlin.getValue
|
||||
open class BaseActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var binding: ActivityBaseBinding
|
||||
private var launcher: ActivityResultLauncher<Intent>? = null
|
||||
private var launchCallback: ((Intent?) -> Unit)? = null
|
||||
|
||||
public fun launch(cls: Class<*>, launchCallback: (Intent?) -> Unit) {
|
||||
this.launchCallback = launchCallback
|
||||
launcher?.launch(Intent(this, cls))
|
||||
}
|
||||
|
||||
public fun launch(intent: Intent, launchCallback: (Intent?) -> Unit) {
|
||||
this.launchCallback = launchCallback
|
||||
launcher?.launch(intent)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// 提前隐藏系统栏,避免窗口创建时导航栏闪烁
|
||||
hideSystemBars()
|
||||
// 主设备竖屏,子设备横屏
|
||||
requestedOrientation = if (GlobalData.deviceRole == DeviceRole.MASTER)
|
||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
||||
else
|
||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
|
||||
ActivityManager.addActivity(this)
|
||||
binding = ActivityBaseBinding.inflate(layoutInflater)
|
||||
if (this !is InitActivity) {
|
||||
if (this !is InitActivity || GlobalData.deviceRole == DeviceRole.SLAVE) {
|
||||
binding.root.setBackgroundColor(ContextCompat.getColor(this, R.color.bg_color))
|
||||
}
|
||||
setContentView(binding.root)
|
||||
statusBarDarkFont(enable = false)
|
||||
launcher =
|
||||
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
if (result.resultCode == RESULT_OK) {
|
||||
launchCallback?.invoke(result.data)
|
||||
}
|
||||
}
|
||||
|
||||
// window.setDecorFitsSystemWindows(false) // 启用 Edge-to-Edge
|
||||
// window.insetsController?.apply {
|
||||
@@ -86,17 +81,17 @@ open class BaseActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
fun hideStatusBar() {
|
||||
enableEdgeToEdge()
|
||||
// val uiOptions = (View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
|
||||
// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) // 隐藏导航栏(可选)
|
||||
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
// enableEdgeToEdge()
|
||||
//// val uiOptions = (View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
|
||||
//// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) // 隐藏导航栏(可选)
|
||||
// window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
hideSystemBars()
|
||||
}
|
||||
|
||||
fun statusBarDarkFont(enable: Boolean) {
|
||||
//window.decorView.systemUiVisibility = if (enable) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
|
||||
val color = ContextCompat.getColor(
|
||||
this,
|
||||
if (enable) R.color.black else R.color.white
|
||||
this, if (enable) R.color.black else R.color.white
|
||||
)
|
||||
binding.tvLeftTime.setTextColor(color)
|
||||
binding.tvRightTime.setTextColor(color)
|
||||
@@ -142,7 +137,7 @@ open class BaseActivity : AppCompatActivity() {
|
||||
binding.tvLeftTime.text = arr[1]
|
||||
}
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
val handler = Handler(Looper.getMainLooper())
|
||||
private val updateTask = object : Runnable {
|
||||
override fun run() {
|
||||
updateDateTime()
|
||||
@@ -161,8 +156,11 @@ open class BaseActivity : AppCompatActivity() {
|
||||
handler.removeCallbacks(updateTask)
|
||||
}
|
||||
|
||||
fun showLoading() {
|
||||
Loading.show(this)
|
||||
fun showLoading(msg: String = "加载中……") {
|
||||
Loading.show(
|
||||
context = this,
|
||||
message = msg
|
||||
)
|
||||
}
|
||||
|
||||
fun dismissLoading() {
|
||||
@@ -193,4 +191,86 @@ open class BaseActivity : AppCompatActivity() {
|
||||
netViewModel.querySeasoningList(param, onSuccess, onFailure)
|
||||
}
|
||||
|
||||
|
||||
private var permissionCallback: ((isGranted: Boolean) -> Unit)? = null
|
||||
private var activityCallback: ((intent: Intent?) -> Unit)? = null
|
||||
|
||||
fun requestMultiplePermissions(
|
||||
permissions: Array<String>,
|
||||
callback: (isGranted: Boolean) -> Unit
|
||||
) {
|
||||
this.permissionCallback = callback
|
||||
requestMultiplePermissionsLauncher.launch(permissions)
|
||||
}
|
||||
|
||||
fun requestPermission(permission: String, callback: (isGranted: Boolean) -> Unit) {
|
||||
this.permissionCallback = callback
|
||||
requestPermissionLauncher.launch(permission)
|
||||
}
|
||||
|
||||
val requestMultiplePermissionsLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { permissions ->
|
||||
var isGranted = true
|
||||
permissions.entries.forEach {
|
||||
if (!it.value) {
|
||||
isGranted = false
|
||||
}
|
||||
}
|
||||
permissionCallback?.invoke(isGranted)
|
||||
}
|
||||
|
||||
// 权限请求回调
|
||||
val requestPermissionLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { isGranted ->
|
||||
permissionCallback?.invoke(isGranted)
|
||||
}
|
||||
|
||||
fun startActivity(intent: Intent, callback: (Intent?) -> Unit) {
|
||||
this.activityCallback = callback
|
||||
startActivityLauncher.launch(intent)
|
||||
}
|
||||
|
||||
// activity页面返回的回调
|
||||
private val startActivityLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) {
|
||||
activityCallback?.invoke(it.data)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 窗口焦点变化时回调
|
||||
* 场景:弹出 Dialog 后焦点丢失,Dialog 消失后焦点恢复,此时需重新隐藏系统栏,
|
||||
* 避免系统栏在 Dialog 关闭后意外"复活"
|
||||
*/
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) {
|
||||
hideSystemBars()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐藏状态栏和导航栏
|
||||
* 使用 WindowInsetsControllerCompat(Androidx 推荐方式,向下兼容性好)
|
||||
* - setDecorFitsSystemWindows 只在首次调用时设置,避免反复触发布局重绘
|
||||
* (重绘会导致 RecyclerView 滑动时抛出 "view is not a child, cannot hide" 异常)
|
||||
* - 每次调用仍重新执行 hide(),保证系统栏在滑出后能被重新隐藏
|
||||
*/
|
||||
private var systemBarsConfigured = false
|
||||
private fun hideSystemBars() {
|
||||
if (!systemBarsConfigured) {
|
||||
// 只执行一次:允许布局延伸到系统栏区域
|
||||
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||
systemBarsConfigured = true
|
||||
}
|
||||
WindowInsetsControllerCompat(window, window.decorView).apply {
|
||||
hide(WindowInsetsCompat.Type.systemBars())
|
||||
systemBarsBehavior =
|
||||
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -8,9 +8,13 @@ import android.content.SharedPreferences
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.db.DatabaseProvider
|
||||
import com.shuwei.dish.match.objbox.ObjectBox
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.ui.InitActivity.Companion.TAG
|
||||
import com.shuwei.dish.match.utils.AppUtil
|
||||
import com.shuwei.dish.match.utils.BootReceiver
|
||||
import com.shuwei.dish.match.utils.CrashHandler
|
||||
import com.shuwei.dish.match.utils.Weigher2
|
||||
|
||||
|
||||
class BaseApp : Application() {
|
||||
@@ -20,12 +24,33 @@ class BaseApp : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instance = this
|
||||
CrashHandler.init(this)
|
||||
val deviceId = AppUtil.getUDID(this)
|
||||
Log.d(TAG, "onCreate: deviceId=$deviceId")
|
||||
GlobalData.deviceId = deviceId
|
||||
|
||||
// 根据设备 ID 判断角色:指定 ID 为主设备,其余为子设备
|
||||
// 主设备是/dev/ttyS7,子设备是/dev/ttyS4
|
||||
if (deviceId == "8fc2ab34-2137-3112-acca-f884ea8736d4") {
|
||||
GlobalData.deviceRole = DeviceRole.MASTER
|
||||
Weigher2.setDevicePort("/dev/ttyS7")
|
||||
} else {
|
||||
GlobalData.deviceRole = DeviceRole.SLAVE
|
||||
Weigher2.setDevicePort("/dev/ttyS4")
|
||||
}
|
||||
Log.d(TAG, "设备角色: ${GlobalData.deviceRole}")
|
||||
|
||||
// 启动秤服务(主设备多启动发现+聚合,子设备只启动服务端+注册)
|
||||
ScaleServiceManager.start(this)
|
||||
// GlobalData.deviceId = "39a7abdd06b3c7ab"
|
||||
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
|
||||
registerReceiver(BootReceiver(), filter)
|
||||
ObjectBox.init(this)
|
||||
}
|
||||
|
||||
override fun onTerminate() {
|
||||
ScaleServiceManager.stop()
|
||||
super.onTerminate()
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -18,8 +18,16 @@ abstract class BaseFragment<VB : ViewBinding> : Fragment() {
|
||||
|
||||
abstract fun inflateBinding(inflater: LayoutInflater, container: ViewGroup?): VB
|
||||
|
||||
abstract fun initialize()
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
_binding = null
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
initialize()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +1,30 @@
|
||||
package com.shuwei.dish.match.base
|
||||
|
||||
object GlobalData {
|
||||
var appBaseUrl: String = "https://dev.yixiong-tech.com:8081"
|
||||
/**
|
||||
* 设备角色枚举
|
||||
* MASTER:主设备,负责汇聚所有设备的秤数据并展示大屏界面
|
||||
* SLAVE:子设备,负责推送本机秤数据给主设备
|
||||
*/
|
||||
enum class DeviceRole { MASTER, SLAVE }
|
||||
|
||||
object GlobalData {
|
||||
var appBaseUrl: String = TEST_BASE_URL
|
||||
|
||||
/**
|
||||
* 具体业务 BaseUrl
|
||||
*/
|
||||
const val TEST_BASE_URL = "http://192.168.1.201:14801"
|
||||
const val UAT_BASE_URL = "https://dev.yixiong-tech.com:8081"
|
||||
const val PROD_BASE_URL = "https://api.dm.yixiong-tech.com:8443"
|
||||
/**
|
||||
* 设备id
|
||||
*/
|
||||
var deviceId: String = ""
|
||||
|
||||
/**
|
||||
* 当前设备角色,启动时从 SpTool 读取,默认为 SLAVE
|
||||
*/
|
||||
var deviceRole: DeviceRole = DeviceRole.SLAVE
|
||||
var appId = "Hkz1rBk6PZXbS8KwKr67K2eZtsz8bRoMHLg64bUdgCZj"
|
||||
var sdkKey = "AabXs3sHM8UhhE7oCGf4LVMLrdkGb1nJNksbjjTdVt7k"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.LayoutInflater
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.DialogFoodRecognizeBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
|
||||
/**
|
||||
* 菜品识别结果弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
* @param activity 宿主 Activity
|
||||
* @param onItemSelected 用户点击某一菜品时的回调
|
||||
*/
|
||||
class FoodRecognizeDialog(
|
||||
private val activity: BaseActivity,
|
||||
private val onItemSelected: (item: CookFoodGoodsEntity) -> Unit
|
||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
|
||||
private val binding = DialogFoodRecognizeBinding.inflate(LayoutInflater.from(activity))
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>()
|
||||
private val adapter = GoodsInfoSearchAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
list[position].isClicked = true
|
||||
notifyItemChanged(position)
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
onItemSelected(list[position])
|
||||
dismiss()
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
setCancelable(true)
|
||||
behavior.skipCollapsed = false
|
||||
setOnDismissListener { activity.hideStatusBar() }
|
||||
binding.recyclerView.run {
|
||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
adapter = this@FoodRecognizeDialog.adapter
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载识别结果数据并显示弹窗
|
||||
* @param items 识别到的菜品列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun loadData(items: List<CookFoodGoodsEntity>) {
|
||||
list.clear()
|
||||
list.addAll(items)
|
||||
adapter.notifyDataSetChanged()
|
||||
if (!isShowing) show()
|
||||
}
|
||||
}
|
||||
@@ -13,14 +13,22 @@ object Loading {
|
||||
|
||||
private var dialog: LoadingDialog? = null
|
||||
|
||||
fun show(context: Context) {
|
||||
fun isShowing(): Boolean {
|
||||
return dialog != null && dialog!!.isShowing
|
||||
}
|
||||
|
||||
fun updateContent(content: String) {
|
||||
if (isShowing().not()) return
|
||||
dialog!!.updateContent(content)
|
||||
}
|
||||
|
||||
fun show(context: Context, message: String = "加载中……", onDismiss: () -> Unit = {}) {
|
||||
try {
|
||||
if (dialog?.isShowing == true) {
|
||||
dialog?.dismiss()
|
||||
}
|
||||
|
||||
if (dialog == null) {
|
||||
dialog = LoadingDialog(context)
|
||||
dialog = LoadingDialog(context = context, message = message, onDismiss = onDismiss)
|
||||
}
|
||||
dialog?.show()
|
||||
} catch (e: Exception) {
|
||||
@@ -45,11 +53,14 @@ object Loading {
|
||||
|
||||
class LoadingDialog(
|
||||
context: Context,
|
||||
message: String = "加载中……",
|
||||
private var onDismiss: () -> Unit = {}
|
||||
message: String,
|
||||
private var onDismiss: () -> Unit
|
||||
) : Dialog(context, R.style.LoadingDialog) {
|
||||
private val binding: DialogLoadingBinding by lazy {
|
||||
DialogLoadingBinding.inflate(LayoutInflater.from(context))
|
||||
}
|
||||
|
||||
init {
|
||||
val binding = DialogLoadingBinding.inflate(LayoutInflater.from(context))
|
||||
binding.tvMessage.text = message
|
||||
setContentView(binding.root)
|
||||
setCancelable(true)
|
||||
@@ -64,6 +75,10 @@ class LoadingDialog(
|
||||
onDismiss()
|
||||
}
|
||||
}
|
||||
|
||||
fun updateContent(content: String) {
|
||||
binding.tvMessage.text = content
|
||||
}
|
||||
}
|
||||
|
||||
//class LoadingDialog3(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.shuwei.dish.match.net
|
||||
|
||||
import com.google.gson.JsonSyntaxException
|
||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
||||
import com.shuwei.dish.match.utils.ext.toObject
|
||||
import com.shuwei.dish.match.utils.ext.toType
|
||||
@@ -60,10 +61,10 @@ suspend fun <T> request(
|
||||
onFailure("-1", apiException.errorMsg)
|
||||
return
|
||||
}
|
||||
if (response?.isSuccess() == true) {
|
||||
if (response.isSuccess()) {
|
||||
onSuccess(response.data as T)
|
||||
} else {
|
||||
onFailure(response?.code ?: "-1", response?.msg ?: "")
|
||||
onFailure(response.code, response.msg ?: "")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +78,11 @@ fun getApiException(e: Exception): ApiException {
|
||||
return when (e) {
|
||||
is HttpException -> httpException2ApiException(e)
|
||||
|
||||
is JsonSyntaxException -> ApiException(
|
||||
ErrorType.NETWORK_ERROR,
|
||||
errorMsg = "服务器响应异常,请稍后重试"
|
||||
)
|
||||
|
||||
is UnknownHostException -> ApiException(
|
||||
ErrorType.NETWORK_ERROR,
|
||||
errorMsg = "网络未连接,请检查网络"
|
||||
@@ -108,10 +114,15 @@ fun getApiException(e: Exception): ApiException {
|
||||
|
||||
fun httpException2ApiException(e: HttpException): ApiException {
|
||||
val body = e.response()?.errorBody()?.string()
|
||||
val codeMsg: CodeMsg? = body?.toObject<CodeMsg>()
|
||||
val codeMsg: CodeMsg? = try {
|
||||
body?.toObject<CodeMsg>()
|
||||
} catch (ex: Exception) {
|
||||
null
|
||||
}
|
||||
return ApiException(
|
||||
ErrorType.NETWORK_ERROR,
|
||||
errorMsg = codeMsg?.msg ?: ""
|
||||
errorMsg = if (codeMsg == null) "数据解析异常(${e.code()})"
|
||||
else codeMsg.msg ?: "服务器错误(${e.code()})"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.shuwei.dish.match.objbox
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import java.io.File
|
||||
|
||||
data class FoodClassInfo(
|
||||
var class_names: List<String>,
|
||||
var class_to_idx: Map<String, Int>,
|
||||
var idx_to_class: Map<String, String>
|
||||
)
|
||||
|
||||
data class FoodCollectionBean(
|
||||
var imageUri: Uri? = null,
|
||||
var bitmap: Bitmap? = null,
|
||||
var imageFile: File? = null,
|
||||
var imageVector: FloatArray? = null,
|
||||
var isShowCamera: Boolean = false,
|
||||
var isFinish:Boolean = false,
|
||||
var uploadSuccess:Boolean = false
|
||||
)
|
||||
|
||||
data class ReceiptGoodsInfo(
|
||||
var goodsId: String? = "",
|
||||
var goodsName: String? = "",
|
||||
var procurementUnit: String? = "",
|
||||
var procurementCount: Int? = 0,
|
||||
var procurementPrice: Double? = 0.0,
|
||||
var procurementAmount: Double? = 0.0,
|
||||
var receiptCount: Int? = 0,
|
||||
var goodsWeight: Int? = 0,
|
||||
var goodsState: String? = "",
|
||||
var isSelected: Boolean = false,
|
||||
var isLocalGoods: Boolean = false
|
||||
)
|
||||
|
||||
//data class DropdownInfo(
|
||||
// var id: String,
|
||||
// var name: String
|
||||
//)
|
||||
|
||||
//data class RecognizeResult(
|
||||
// var name: String? = null,
|
||||
// var image: String? = null,
|
||||
// var isSelected: Boolean = false
|
||||
//)
|
||||
|
||||
//data class GoodsSearchInfo(
|
||||
// var id: String? = null,
|
||||
// var name: String? = null,
|
||||
// var isSelected: Boolean = false
|
||||
//)
|
||||
|
||||
data class OperateBean(
|
||||
var obj: Any? = null,
|
||||
var typeList: MutableList<OperateType> = mutableListOf(),
|
||||
var isSelected: Boolean = false,
|
||||
var isLocalGoods: Boolean = false,
|
||||
var isReceiptPage: Boolean = true
|
||||
)
|
||||
|
||||
data class OperateType(
|
||||
var value: String = "",
|
||||
var width: Int = 0,
|
||||
var textColor: String = "#FF999999",
|
||||
var isBoldFont: Boolean = false,
|
||||
var isShowIcon: Boolean = false
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.shuwei.dish.match.objbox
|
||||
|
||||
import io.objectbox.annotation.Entity
|
||||
import io.objectbox.annotation.HnswIndex
|
||||
import io.objectbox.annotation.Id
|
||||
import io.objectbox.annotation.VectorDistanceType
|
||||
|
||||
@Entity
|
||||
data class Food(
|
||||
@Id var id: Long = 0,
|
||||
var name: String? = null,
|
||||
var foodIdx: Int = 0,
|
||||
@HnswIndex(dimensions = 512, distanceType = VectorDistanceType.DOT_PRODUCT)
|
||||
var foodVector: FloatArray? = null
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (javaClass != other?.javaClass) return false
|
||||
|
||||
other as Food
|
||||
|
||||
if (id != other.id) return false
|
||||
if (foodIdx != other.foodIdx) return false
|
||||
if (name != other.name) return false
|
||||
if (!foodVector.contentEquals(other.foodVector)) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = id.hashCode()
|
||||
result = 31 * result + foodIdx
|
||||
result = 31 * result + (name?.hashCode() ?: 0)
|
||||
result = 31 * result + (foodVector?.contentHashCode() ?: 0)
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package com.shuwei.dish.match.objbox
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import androidx.core.graphics.scale
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.shuwei.dish.match.utils.AssetsTool
|
||||
import com.shuwei.dish.match.utils.LogSaveUtil
|
||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.pytorch.IValue
|
||||
import org.pytorch.Module
|
||||
import org.pytorch.torchvision.TensorImageUtils
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
|
||||
|
||||
object FoodModule {
|
||||
|
||||
private lateinit var module_mobile: Module
|
||||
|
||||
private val NO_MEAN_RGB = floatArrayOf(0.0f, 0.0f, 0.0f)
|
||||
private val NO_STD_RGB = floatArrayOf(1.0f, 1.0f, 1.0f)
|
||||
|
||||
// 1. 定义你的模型固定输入尺寸 (根据你的tflite模型修改,比如224x224)
|
||||
private const val MODEL_INPUT_WIDTH = 300
|
||||
private const val MODEL_INPUT_HEIGHT = 300
|
||||
const val DEFAULT_FOOD_INDEX = -1
|
||||
const val DEFAULT_QUERY_COUNT = 50
|
||||
|
||||
const val BAG_RATE = 0.05
|
||||
|
||||
suspend fun init(context: Context) {
|
||||
withContext(Dispatchers.IO) {
|
||||
module_mobile = Module.load(copyAssetToCache(context, "best_embedding_model_mobile.pt"))
|
||||
initDefFoodData(context)
|
||||
}
|
||||
}
|
||||
|
||||
// fun uri2FloatArray(uri: Uri): FloatArray? {
|
||||
// return MyApp.instance?.let { context ->
|
||||
// ImageUtil.uriToBitmap(context, uri)?.let {
|
||||
// bitmap2FloatArray(it)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
fun bitmap2FloatArray(originBitmap: Bitmap, isRecycle: Boolean): FloatArray? {
|
||||
var rgb565Bitmap: Bitmap? = null
|
||||
try {
|
||||
val scaledBitmap = originBitmap.scale(MODEL_INPUT_WIDTH, MODEL_INPUT_HEIGHT)
|
||||
if (isRecycle) {
|
||||
originBitmap.recycle()
|
||||
}
|
||||
rgb565Bitmap = scaledBitmap.copy(Bitmap.Config.RGB_565, false)
|
||||
scaledBitmap.recycle()
|
||||
val inputTensor = TensorImageUtils.bitmapToFloat32Tensor(
|
||||
rgb565Bitmap,
|
||||
NO_MEAN_RGB, // [0.485, 0.456, 0.406] TORCHVISION_NORM_MEAN_RGB
|
||||
NO_STD_RGB // [0.229, 0.224, 0.225] TORCHVISION_NORM_STD_RGB
|
||||
)
|
||||
val outputTensor = module_mobile.forward(IValue.from(inputTensor)).toTensor()
|
||||
return outputTensor.dataAsFloatArray
|
||||
} catch (e: OutOfMemoryError) {
|
||||
e.printStackTrace()
|
||||
logInfo("bitmap2FloatArray异常:${e.message}")
|
||||
} finally {
|
||||
if (rgb565Bitmap != null && rgb565Bitmap.isRecycled.not()) {
|
||||
rgb565Bitmap.recycle()
|
||||
}
|
||||
//System.gc()
|
||||
//System.runFinalization()
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// fun queryFood(uri: Uri, queryCount: Int = DEFAULT_QUERY_COUNT): List<String>? {
|
||||
// return uri2FloatArray(uri)?.let {
|
||||
// queryFood(it, queryCount)
|
||||
// }
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 返回识别物品名称列表
|
||||
// */
|
||||
// fun queryFood(bitmap: Bitmap, queryCount: Int = DEFAULT_QUERY_COUNT): List<String> {
|
||||
// val floatArray = bitmap2FloatArray(bitmap)
|
||||
// return queryFood(floatArray, queryCount)
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * 返回识别物品IdNameScore对象列表
|
||||
// */
|
||||
// fun queryFoodNameScore(bitmap: Bitmap, queryCount: Int = DEFAULT_QUERY_COUNT): List<IdNameScore> {
|
||||
// val floatArray = bitmap2FloatArray(bitmap)
|
||||
// return queryFoodNameScore(floatArray, queryCount)
|
||||
// }
|
||||
|
||||
suspend fun queryFoodNameScore(
|
||||
floatArray: FloatArray?,
|
||||
queryCount: Int = DEFAULT_QUERY_COUNT
|
||||
): List<IdNameScore> {
|
||||
if (floatArray == null) return emptyList()
|
||||
// val query: Query<Food> = box.query(Food_.foodVector.nearestNeighbors(floatArray, queryCount)).build()
|
||||
// //查询比较分数
|
||||
//// val tempList = query.findWithScores().sortedBy { it.score }.map { "${it.get().name}|${it.get().foodIdx}|${it.score}" }
|
||||
// var idScoreList: List<IdWithScore>
|
||||
// try {
|
||||
// idScoreList = query.findIdsWithScores();
|
||||
// } finally {
|
||||
// // 先关闭Query,释放Cursor
|
||||
// query.close()
|
||||
// }
|
||||
|
||||
logInfo("queryFood向量:${floatArray.slice(0 until 50).toJsonString()}")
|
||||
val idScoreList = ObjectBox.query(floatArray, queryCount)
|
||||
// 批量加载所有实体,一次DB操作替代循环单条查询
|
||||
val foodMap = ObjectBox.getByIds(idScoreList.map { it.id }).associateBy { it.id }
|
||||
val nameScoreList = mutableListOf<IdNameScore>()
|
||||
idScoreList.forEach {
|
||||
val name = foodMap[it.id]?.name ?: ""
|
||||
nameScoreList.add(IdNameScore(id = it.id, name = name, score = it.score))
|
||||
}
|
||||
logInfo("queryFood数据:${nameScoreList.toJsonString()}")
|
||||
return nameScoreList
|
||||
}
|
||||
|
||||
suspend fun getFoodScoreList(bitmap: Bitmap, queryCount: Int = DEFAULT_QUERY_COUNT): List<IdNameScore> {
|
||||
val floatArray = bitmap2FloatArray(bitmap, false) ?: return emptyList()
|
||||
logInfo("getFoodScoreList向量:${floatArray.toJsonString()}")
|
||||
val nameScoreList = queryFoodNameScore(floatArray, queryCount)
|
||||
if (nameScoreList.isEmpty()) {
|
||||
return emptyList()
|
||||
}
|
||||
//暂时不过滤
|
||||
val maxScoreList = nameScoreList
|
||||
//.filter { it.score < 0.15 }
|
||||
.groupBy { it.name }
|
||||
.map { (_, value) -> value.minByOrNull { it.score }!! }
|
||||
.toMutableList()
|
||||
// val map = mutableMapOf<String, Int>()
|
||||
// nameScoreList.forEach {
|
||||
// val key = it.name
|
||||
// val count = map[key] ?: 0
|
||||
// map[key] = count + 1
|
||||
// }
|
||||
// val orderList = map.entries.sortedByDescending { it.value }.map { it.key }.toMutableList()
|
||||
// val firstFood = nameScoreList[0].name
|
||||
// orderList.remove(firstFood)
|
||||
// orderList.add(0, firstFood)
|
||||
//
|
||||
// val sortedScoreList = maxScoreList.sortedWith(compareBy {
|
||||
// orderList.indexOf(it.name)
|
||||
// })
|
||||
val sortedScoreList = maxScoreList.sortedBy { it.score }
|
||||
logInfo("getFoodScoreList数据:${sortedScoreList.toJsonString()}")
|
||||
return sortedScoreList
|
||||
}
|
||||
|
||||
// suspend fun queryFood(floatArray: FloatArray, queryCount: Int = DEFAULT_QUERY_COUNT): List<String> {
|
||||
// val map = mutableMapOf<String, Int>()
|
||||
// val nameScoreList = queryFoodNameScore(floatArray, queryCount)
|
||||
// nameScoreList.filter { it.score < 0.05 }.forEach {
|
||||
// val count = map[it.name] ?: 0
|
||||
// map[it.name] = count + 1
|
||||
// }
|
||||
// val list = map.entries.sortedByDescending { it.value }.map { it.key }
|
||||
// return list
|
||||
// }
|
||||
|
||||
data class IdNameScore(
|
||||
val id: Long,
|
||||
var name: String,
|
||||
val score: Double
|
||||
)
|
||||
|
||||
suspend fun initDefFoodData(context: Context, action: () -> Unit = {}) {
|
||||
try {
|
||||
val count = ObjectBox.countIndexField(DEFAULT_FOOD_INDEX)
|
||||
if (count > 0) {
|
||||
return
|
||||
}
|
||||
val embeddingsJson = AssetsTool.readAssetsFile(context, "data/embeddings.json")
|
||||
val labelsJson = AssetsTool.readAssetsFile(context, "data/labels.json")
|
||||
val classInfoJson = AssetsTool.readAssetsFile(context, "data/class_info.json")
|
||||
|
||||
val embeddingsList: List<List<Float>> =
|
||||
Gson().fromJson(embeddingsJson, object : TypeToken<List<List<Float>>>() {}.type)
|
||||
val labelsList: IntArray = Gson().fromJson(labelsJson, IntArray::class.java)
|
||||
val classInfo: FoodClassInfo =
|
||||
Gson().fromJson(classInfoJson, FoodClassInfo::class.java)
|
||||
|
||||
val foodMap = classInfo.idx_to_class
|
||||
val list = mutableListOf<Food>()
|
||||
val size = embeddingsList.size
|
||||
val size2 = labelsList.size
|
||||
val size3 = foodMap.size
|
||||
logInfo("initDefFoodData: $size,$size2,$size3")
|
||||
embeddingsList.forEachIndexed { index, floatList ->
|
||||
val classIdx = labelsList[index]
|
||||
val foodName = foodMap["$classIdx"]
|
||||
val array = floatList.toFloatArray()
|
||||
// ObjectBox.boxStore.runInTx {
|
||||
// box.put(Food(name = foodName, foodVector = array, foodIdx = DEFAULT_FOOD_INDEX))
|
||||
// }
|
||||
val food = Food(name = foodName, foodVector = array, foodIdx = DEFAULT_FOOD_INDEX)
|
||||
list.add(food)
|
||||
}
|
||||
// val tempList = list.chunked(10)
|
||||
ObjectBox.putAll(list)
|
||||
action()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
logInfo("initDefFoodData: ---${e.message}--")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* ,此方法的主要目的是:从assets 拷贝到 app的cache目录
|
||||
* @param context
|
||||
* @param fileName
|
||||
* @return 例如是这样:/data/user/0/com.frizzle.pluginhookandroid9/cache/plugin-debug.apk
|
||||
*
|
||||
* 不可能反正SD
|
||||
*/
|
||||
// fun copyAssetToCache(context: Context, fileName: String): String? {
|
||||
// // 此app的缓存目录 --> 会默认在 cache目录...,可以自己去看看哦
|
||||
// val cacheDir = context.getCacheDir()
|
||||
// if (!cacheDir.exists()) {
|
||||
// cacheDir.mkdirs() // TODO 如果没有缓存目录,就创建
|
||||
// }
|
||||
// val outPath = File(cacheDir, fileName) // TODO 创建输出的文件位置
|
||||
// if (outPath.exists()) {
|
||||
// outPath.delete() // TODO 如果该文件已经存在,就删掉
|
||||
// }
|
||||
// var `is`: InputStream? = null // 读取
|
||||
// var fos: FileOutputStream? = null // 写入
|
||||
// try {
|
||||
// // 创建文件,如果创建成功,就返回true
|
||||
// val res = outPath.createNewFile()
|
||||
// if (res) {
|
||||
// `is` = context.getAssets().open(fileName) // 拿到main/assets目录的输入流,用于读取字节
|
||||
// fos = FileOutputStream(outPath) // 读取出来的字节最终写到outPath
|
||||
// val buf = ByteArray(`is`.available()) // 缓存区
|
||||
// var byteCount: Int
|
||||
//
|
||||
// // 开始循环读取
|
||||
// while ((`is`.read(buf).also { byteCount = it }) != -1) {
|
||||
// fos.write(buf, 0, byteCount)
|
||||
// }
|
||||
// return outPath.getAbsolutePath()
|
||||
// }
|
||||
// } catch (e: IOException) {
|
||||
// e.printStackTrace()
|
||||
// } finally {
|
||||
// try {
|
||||
// // TODO 一定要记得关闭资源,为了不去性能的磨损
|
||||
// fos?.flush()
|
||||
// `is`?.close()
|
||||
// fos?.close()
|
||||
// } catch (e: IOException) {
|
||||
// e.printStackTrace()
|
||||
// }
|
||||
// }
|
||||
// return null
|
||||
// }
|
||||
|
||||
fun copyAssetToCache(context: Context, fileName: String): String? {
|
||||
val cacheFile = File(context.cacheDir, fileName)
|
||||
val buffer = ByteArray(8 * 1024)
|
||||
var inputStream: InputStream? = null
|
||||
var outputStream: FileOutputStream? = null
|
||||
|
||||
try {
|
||||
inputStream = context.assets.open(fileName)
|
||||
outputStream = FileOutputStream(cacheFile)
|
||||
var byteCount: Int
|
||||
while (inputStream.read(buffer).also { byteCount = it } != -1) {
|
||||
outputStream.write(buffer, 0, byteCount)
|
||||
}
|
||||
outputStream.channel.force(true) // 强制物理落盘,比flush更彻底
|
||||
return cacheFile.absolutePath
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
logInfo("文件拷贝失败 fileName=$fileName, error=${e.message}")
|
||||
// 拷贝失败时删除残缺文件,避免下次读取到损坏文件
|
||||
if (cacheFile.exists()) {
|
||||
cacheFile.delete()
|
||||
}
|
||||
} finally {
|
||||
outputStream?.close()
|
||||
inputStream?.close()
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun logInfo(msg:String) {
|
||||
Log.d("FoodModule", msg)
|
||||
LogSaveUtil.saveLogFile(msg)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
/*
|
||||
* Copyright 2024 ObjectBox Ltd. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.shuwei.dish.match.objbox
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.utils.LogSaveUtil
|
||||
import io.objectbox.Box
|
||||
import io.objectbox.BoxStore
|
||||
import io.objectbox.BoxStoreBuilder
|
||||
import io.objectbox.exception.DbException
|
||||
import io.objectbox.exception.FileCorruptException
|
||||
import io.objectbox.kotlin.boxFor
|
||||
import io.objectbox.query.Query
|
||||
import io.objectbox.sync.Sync
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.util.zip.GZIPOutputStream
|
||||
import com.shuwei.dish.match.BuildConfig
|
||||
|
||||
/**
|
||||
* Singleton to keep BoxStore reference and provide current list of Notes Objects.
|
||||
* Inserts demo data if no Objects are stored.
|
||||
*/
|
||||
object ObjectBox {
|
||||
|
||||
// 确保所有设备/版本使用相同的objectbox-models/default.json
|
||||
// 避免直接修改自动生成的MyObjectBox类
|
||||
// 跨版本升级时使用boxStore.runInTx执行数据迁移
|
||||
|
||||
private const val TAG = "ObjectBox"
|
||||
|
||||
// 添加 @Volatile 保证多线程下的可见性
|
||||
@Volatile
|
||||
var boxStore: BoxStore? = null
|
||||
|
||||
/**
|
||||
* If building the [boxStore] failed, contains the thrown error message.
|
||||
*/
|
||||
var dbExceptionMessage: String? = null
|
||||
private set
|
||||
|
||||
fun init(context: Context) {
|
||||
if (boxStore != null && boxStore!!.isClosed.not()) return
|
||||
// 优化:调大事务回收超时时间
|
||||
System.setProperty("objectbox.finalizerTimeout", "30000");
|
||||
// On Android make sure to pass a Context when building the Store.
|
||||
boxStore = try {
|
||||
MyObjectBox.builder()
|
||||
.androidContext(context.applicationContext)
|
||||
//.disableMultiProcess() // 开启多进程支持(按需关闭,单进程可删)
|
||||
//.disableFileCompression() // 禁用文件压缩,避免存储异常
|
||||
.build()
|
||||
} catch (e: DbException) {
|
||||
if (e.javaClass == DbException::class.java || e is FileCorruptException) {
|
||||
// Failed to build BoxStore due to database file issue, store message;
|
||||
// checked in NoteListActivity to notify user.
|
||||
dbExceptionMessage = e.toString()
|
||||
LogSaveUtil.saveLogFile("ObjectBox.init异常1:$dbExceptionMessage")
|
||||
return
|
||||
} else {
|
||||
LogSaveUtil.saveLogFile("ObjectBox.init异常2:${e.message}")
|
||||
// Failed to build BoxStore due to developer error.
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
if (BuildConfig.DEBUG) {
|
||||
var syncAvailable = if (Sync.isAvailable()) "available" else "unavailable"
|
||||
Log.d(
|
||||
TAG,
|
||||
"Using ObjectBox ${BoxStore.getVersion()} (${BoxStore.getVersionNative()}, sync $syncAvailable)"
|
||||
)
|
||||
// Enable ObjectBox Admin on debug builds.
|
||||
// https://docs.objectbox.io/data-browser
|
||||
io.objectbox.android.Admin(boxStore).start(context.applicationContext)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* If the database file is not in use, compresses (GZIP) and copies it to the given [target].
|
||||
* 增加 IOException 捕获,避免文件异常导致崩溃。
|
||||
*/
|
||||
fun copyAndGzipDatabaseFileTo(target: File, context: Context): Boolean {
|
||||
if (BoxStore.isDatabaseOpen(context, null)) {
|
||||
// Do not copy if database file is still in use.
|
||||
// If it would be open, the copy will likely get corrupted
|
||||
// as BoxStore may currently write data to the file.
|
||||
Log.e(TAG, "Database file is still in use, can not copy.")
|
||||
return false
|
||||
}
|
||||
|
||||
// If a name was given when building BoxStore use that instead of the default below.
|
||||
val dbName = BoxStoreBuilder.DEFAULT_NAME
|
||||
return try {
|
||||
File(context.filesDir, "objectbox/$dbName/data.mdb").inputStream().use { input ->
|
||||
target.parentFile?.mkdirs()
|
||||
GZIPOutputStream(target.outputStream()).use { output ->
|
||||
input.copyTo(output, DEFAULT_BUFFER_SIZE)
|
||||
}
|
||||
}
|
||||
true
|
||||
} catch (e: IOException) {
|
||||
Log.e(TAG, "备份数据库文件失败", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 获取指定实体的Box,自动关联BoxStore
|
||||
inline fun <reified T> getBox(): Box<T>? = boxStore?.boxFor()
|
||||
|
||||
// 协程安全执行数据库操作(推荐所有操作使用此方法)
|
||||
suspend fun <T> safeDbOp(operation: suspend () -> T): T? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
dbMutex.withLock { operation() }
|
||||
} catch (e: FileCorruptException) {
|
||||
// 操作中触发损坏,尝试重建数据库
|
||||
e.printStackTrace()
|
||||
LogSaveUtil.saveLogFile("safeDbOp出现FileCorruptException异常:${e.message},${e.errorCode}")
|
||||
// 使用安全调用替代 !! 断言,避免 NPE
|
||||
val app = BaseApp.instance ?: return@withContext null
|
||||
init(app)
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
LogSaveUtil.saveLogFile("safeDbOp出现其它异常:${e.message}")
|
||||
null
|
||||
} finally {
|
||||
// 线程资源清理
|
||||
boxStore?.closeThreadResources()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun query(floatArray: FloatArray, queryCount: Int) = safeDbOp {
|
||||
val query: Query<Food>? = getBox<Food>()?.query(
|
||||
Food_.foodVector
|
||||
.nearestNeighbors(floatArray, queryCount)
|
||||
)?.build()
|
||||
try {
|
||||
query?.findIdsWithScores()
|
||||
} finally {
|
||||
// 先关闭Query,释放Cursor
|
||||
query?.close()
|
||||
}
|
||||
} ?: emptyList()
|
||||
|
||||
suspend fun get(id: Long) = safeDbOp {
|
||||
getBox<Food>()?.get(id)
|
||||
}
|
||||
|
||||
// 批量按ID加载,一次DB事务替代循环单条查询
|
||||
suspend fun getByIds(ids: List<Long>): List<Food> = safeDbOp {
|
||||
if (ids.isEmpty()) return@safeDbOp emptyList<Food>()
|
||||
getBox<Food>()?.get(ids.toLongArray()) ?: emptyList<Food>()
|
||||
} ?: emptyList()
|
||||
|
||||
suspend fun put(entity: Food) = safeDbOp {
|
||||
getBox<Food>()?.put(entity)
|
||||
}
|
||||
|
||||
suspend fun putAll(entities: List<Food>) = safeDbOp {
|
||||
val box = getBox<Food>()
|
||||
box?.put(entities)
|
||||
}
|
||||
|
||||
// 使用 QueryBuilder 在数据库层计数,避免全量加载到内存
|
||||
suspend fun countNameField(name: String) = safeDbOp {
|
||||
getBox<Food>()?.query(Food_.name.equal(name))?.build()?.count()
|
||||
} ?: 0L
|
||||
|
||||
suspend fun countIndexField(idx: Int) = safeDbOp {
|
||||
getBox<Food>()?.query(Food_.foodIdx.equal(idx))?.build()?.count()
|
||||
} ?: 0L
|
||||
|
||||
// 使用 QueryBuilder 在数据库层过滤,避免全量加载到内存
|
||||
suspend fun filter(name: String?) = safeDbOp {
|
||||
if (!name.isNullOrBlank()) {
|
||||
getBox<Food>()?.query(Food_.name.contains(name))?.build()?.find()
|
||||
?.distinctBy { it.name }
|
||||
} else {
|
||||
getBox<Food>()?.all?.distinctBy { it.name }
|
||||
} ?: emptyList()
|
||||
}
|
||||
|
||||
// 使用 QueryBuilder 在数据库层删除,避免全量加载到内存
|
||||
suspend fun remove(name: String) = safeDbOp {
|
||||
getBox<Food>()?.query(Food_.name.equal(name))?.build()?.remove()
|
||||
}
|
||||
|
||||
private val dbMutex = Mutex() // 协程并发锁,保证写入操作原子性
|
||||
private const val DB_DIR_NAME = "objectbox" // ObjectBox 默认数据库目录
|
||||
private const val BACKUP_DIR_NAME = "objectbox_backup" // 备份目录
|
||||
|
||||
// 检查内部存储是否可读写(操作数据库前调用)
|
||||
// 修复:原逻辑错误地检查外部存储状态,数据库存于内部存储,与外部存储无关
|
||||
fun isStorageAvailable(context: Context): Boolean {
|
||||
return try {
|
||||
context.filesDir.canRead() && context.filesDir.canWrite()
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// 备份数据库到应用私有目录(无权限要求,推荐)
|
||||
suspend fun backupDb(context: Context): Boolean = withContext(Dispatchers.IO) {
|
||||
if (!isStorageAvailable(context)) return@withContext false
|
||||
val dbDir = File(context.filesDir, DB_DIR_NAME)
|
||||
val backupDir = File(context.filesDir, BACKUP_DIR_NAME)
|
||||
return@withContext copyDir(dbDir, backupDir)
|
||||
}
|
||||
|
||||
// 从备份恢复数据库(恢复后会重建BoxStore)
|
||||
suspend fun restoreDb(context: Context): Boolean = withContext(Dispatchers.IO) {
|
||||
if (!isStorageAvailable(context)) return@withContext false
|
||||
val dbDir = File(context.filesDir, DB_DIR_NAME)
|
||||
val backupDir = File(context.filesDir, BACKUP_DIR_NAME)
|
||||
if (!backupDir.exists()) return@withContext false
|
||||
// 先关闭旧的BoxStore,删除损坏文件,再恢复备份
|
||||
boxStore?.close()
|
||||
deleteDbFiles(context)
|
||||
val isSuccess = copyDir(backupDir, dbDir)
|
||||
// 重新初始化
|
||||
init(context)
|
||||
return@withContext isSuccess
|
||||
}
|
||||
|
||||
// 递归删除数据库文件
|
||||
private fun deleteDbFiles(context: Context) {
|
||||
val dbDir = File(context.filesDir, DB_DIR_NAME)
|
||||
if (dbDir.exists()) deleteDirRecursively(dbDir)
|
||||
}
|
||||
|
||||
// 递归删除目录
|
||||
private fun deleteDirRecursively(file: File) {
|
||||
if (file.isDirectory) {
|
||||
file.listFiles()?.forEach { deleteDirRecursively(it) }
|
||||
}
|
||||
file.delete()
|
||||
}
|
||||
|
||||
// 递归复制目录(核心备份/恢复逻辑)
|
||||
private fun copyDir(srcDir: File, destDir: File): Boolean {
|
||||
return try {
|
||||
if (!srcDir.exists()) return false
|
||||
if (!destDir.exists()) destDir.mkdirs()
|
||||
srcDir.listFiles()?.forEach { srcFile ->
|
||||
val destFile = File(destDir, srcFile.name)
|
||||
if (srcFile.isDirectory) {
|
||||
copyDir(srcFile, destFile)
|
||||
} else {
|
||||
copyFile(srcFile, destFile)
|
||||
}
|
||||
}
|
||||
true
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// 复制单个文件(使用NIO,高效稳定)
|
||||
private fun copyFile(srcFile: File, destFile: File) {
|
||||
FileInputStream(srcFile).channel.use { srcChannel ->
|
||||
FileOutputStream(destFile).channel.use { destChannel ->
|
||||
destChannel.transferFrom(srcChannel, 0, srcChannel.size())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭BoxStore(应用退出时调用,可选)
|
||||
fun close() {
|
||||
boxStore?.close()
|
||||
boxStore = null
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
import android.content.Context
|
||||
import android.net.nsd.NsdManager
|
||||
import android.net.nsd.NsdServiceInfo
|
||||
import android.util.Log
|
||||
import java.util.LinkedList
|
||||
|
||||
/**
|
||||
* mDNS 设备发现管理器(仅主设备运行)
|
||||
* 持续扫描局域网,发现或丢失 DishMatch 子设备时通过回调通知连接管理器
|
||||
*
|
||||
* 注意:Android NsdManager.resolveService 不支持并发调用,多台子设备同时被发现时
|
||||
* 会报 FAILURE_ALREADY_ACTIVE(3) 导致解析失败。此处使用串行队列逐一解析。
|
||||
*/
|
||||
class MdnsDiscoveryManager(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MdnsDiscoveryManager"
|
||||
}
|
||||
|
||||
private val nsdManager: NsdManager by lazy {
|
||||
context.getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||
}
|
||||
|
||||
private var discoveryListener: NsdManager.DiscoveryListener? = null
|
||||
private var isDiscovering = false
|
||||
|
||||
/** 待解析队列,串行处理避免并发解析失败 */
|
||||
private val resolveQueue = LinkedList<NsdServiceInfo>()
|
||||
@Volatile
|
||||
private var isResolving = false
|
||||
|
||||
/**
|
||||
* 发现新设备时的回调:(deviceId, host, port)
|
||||
*/
|
||||
var onDeviceFound: ((deviceId: String, host: String, port: Int) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 设备离线时的回调:(deviceId)
|
||||
*/
|
||||
var onDeviceLost: ((deviceId: String) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 开始扫描局域网中的 DishMatch 设备
|
||||
*/
|
||||
fun startDiscovery() {
|
||||
if (isDiscovering) return
|
||||
|
||||
discoveryListener = object : NsdManager.DiscoveryListener {
|
||||
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
|
||||
Log.e(TAG, "开始扫描失败: errorCode=$errorCode")
|
||||
isDiscovering = false
|
||||
}
|
||||
|
||||
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {
|
||||
Log.e(TAG, "停止扫描失败: errorCode=$errorCode")
|
||||
}
|
||||
|
||||
override fun onDiscoveryStarted(serviceType: String) {
|
||||
Log.d(TAG, "mDNS 扫描已启动")
|
||||
isDiscovering = true
|
||||
}
|
||||
|
||||
override fun onDiscoveryStopped(serviceType: String) {
|
||||
Log.d(TAG, "mDNS 扫描已停止")
|
||||
isDiscovering = false
|
||||
}
|
||||
|
||||
override fun onServiceFound(service: NsdServiceInfo) {
|
||||
// 只处理 DishMatch 服务
|
||||
if (!service.serviceName.startsWith("DishMatch-")) return
|
||||
Log.d(TAG, "发现设备: ${service.serviceName}")
|
||||
enqueueResolve(service)
|
||||
}
|
||||
|
||||
override fun onServiceLost(service: NsdServiceInfo) {
|
||||
if (!service.serviceName.startsWith("DishMatch-")) return
|
||||
val deviceId = service.serviceName.removePrefix("DishMatch-")
|
||||
Log.d(TAG, "设备离线: $deviceId")
|
||||
onDeviceLost?.invoke(deviceId)
|
||||
}
|
||||
}
|
||||
|
||||
nsdManager.discoverServices(
|
||||
MdnsRegisterManager.SERVICE_TYPE,
|
||||
NsdManager.PROTOCOL_DNS_SD,
|
||||
discoveryListener
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析服务获取 IP 和端口
|
||||
*/
|
||||
private fun resolveService(service: NsdServiceInfo) {
|
||||
nsdManager.resolveService(service, object : NsdManager.ResolveListener {
|
||||
override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {
|
||||
Log.e(TAG, "解析设备地址失败: ${info.serviceName}, errorCode=$errorCode")
|
||||
// 解析结束(失败),继续处理队列中下一个
|
||||
processNextResolve()
|
||||
}
|
||||
|
||||
override fun onServiceResolved(info: NsdServiceInfo) {
|
||||
val deviceId = info.serviceName.removePrefix("DishMatch-")
|
||||
val host = info.host?.hostAddress ?: run {
|
||||
processNextResolve()
|
||||
return
|
||||
}
|
||||
val port = info.port
|
||||
Log.d(TAG, "设备地址已解析: $deviceId -> $host:$port")
|
||||
onDeviceFound?.invoke(deviceId, host, port)
|
||||
// 解析结束(成功),继续处理队列中下一个
|
||||
processNextResolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 将待解析服务加入队列,若当前无解析任务则立即开始 */
|
||||
@Synchronized
|
||||
private fun enqueueResolve(service: NsdServiceInfo) {
|
||||
resolveQueue.add(service)
|
||||
if (!isResolving) {
|
||||
processNextResolve()
|
||||
}
|
||||
}
|
||||
|
||||
/** 从队列取出下一个服务进行解析 */
|
||||
@Synchronized
|
||||
private fun processNextResolve() {
|
||||
val next = resolveQueue.poll() ?: run {
|
||||
isResolving = false
|
||||
return
|
||||
}
|
||||
isResolving = true
|
||||
resolveService(next)
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止扫描,在应用退出时调用
|
||||
*/
|
||||
fun stopDiscovery() {
|
||||
if (!isDiscovering) return
|
||||
discoveryListener?.let {
|
||||
try {
|
||||
nsdManager.stopServiceDiscovery(it)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "停止扫描异常: ${e.message}")
|
||||
}
|
||||
}
|
||||
discoveryListener = null
|
||||
synchronized(this) {
|
||||
resolveQueue.clear()
|
||||
isResolving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
import android.content.Context
|
||||
import android.net.nsd.NsdManager
|
||||
import android.net.nsd.NsdServiceInfo
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* mDNS 服务注册管理器(主设备和子设备均运行)
|
||||
* 将本机 WebSocket 服务以 mDNS 形式广播到局域网,让主设备能发现本机 IP:PORT
|
||||
*/
|
||||
class MdnsRegisterManager(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MdnsRegisterManager"
|
||||
/** mDNS 服务类型,所有 DishMatch 设备使用统一类型 */
|
||||
const val SERVICE_TYPE = "_dishmatch._tcp."
|
||||
/** WebSocket 服务监听端口 */
|
||||
const val WS_PORT = 8765
|
||||
}
|
||||
|
||||
private val nsdManager: NsdManager by lazy {
|
||||
context.getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||
}
|
||||
|
||||
private var registrationListener: NsdManager.RegistrationListener? = null
|
||||
private var isRegistered = false
|
||||
|
||||
/**
|
||||
* 向局域网注册 mDNS 服务
|
||||
* @param deviceId 当前设备 ID,作为服务名称后缀,便于主设备识别
|
||||
*/
|
||||
fun register(deviceId: String) {
|
||||
if (isRegistered) return
|
||||
|
||||
val serviceInfo = NsdServiceInfo().apply {
|
||||
serviceName = "DishMatch-$deviceId"
|
||||
serviceType = SERVICE_TYPE
|
||||
port = WS_PORT
|
||||
}
|
||||
|
||||
registrationListener = object : NsdManager.RegistrationListener {
|
||||
override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {
|
||||
Log.e(TAG, "mDNS 注册失败, errorCode=$errorCode")
|
||||
isRegistered = false
|
||||
}
|
||||
|
||||
override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) {
|
||||
Log.e(TAG, "mDNS 注销失败, errorCode=$errorCode")
|
||||
}
|
||||
|
||||
override fun onServiceRegistered(info: NsdServiceInfo) {
|
||||
Log.d(TAG, "mDNS 注册成功: ${info.serviceName}")
|
||||
isRegistered = true
|
||||
}
|
||||
|
||||
override fun onServiceUnregistered(info: NsdServiceInfo) {
|
||||
Log.d(TAG, "mDNS 已注销: ${info.serviceName}")
|
||||
isRegistered = false
|
||||
}
|
||||
}
|
||||
|
||||
nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registrationListener)
|
||||
}
|
||||
|
||||
/**
|
||||
* 注销 mDNS 服务,在应用退出时调用
|
||||
*/
|
||||
fun unregister() {
|
||||
if (!isRegistered) return
|
||||
registrationListener?.let {
|
||||
try {
|
||||
nsdManager.unregisterService(it)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "注销 mDNS 异常: ${e.message}")
|
||||
}
|
||||
}
|
||||
registrationListener = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
/**
|
||||
* 单个秤的数据快照
|
||||
* @param deviceId 所属设备 ID
|
||||
* @param address 秤地址编号(硬件 address,对应 WeightUtil 回调的 address 参数)
|
||||
* @param weight 重量,单位克
|
||||
* @param state 秤状态:1=稳定,0=不稳定,2=量程溢出(对应 WeightUtil 中的 STATE_* 常量)
|
||||
* @param ts 数据时间戳(毫秒)
|
||||
* @param ip 所属设备的 IP 地址,用于 UI 展示;网络传输数据中可能为空
|
||||
*/
|
||||
data class ScaleData(
|
||||
val deviceId: String,
|
||||
val address: Int,
|
||||
val weight: Double,
|
||||
val state: Int,
|
||||
val ts: Long,
|
||||
val ip: String = ""
|
||||
)
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* 秤数据聚合器(仅主设备运行)
|
||||
* 统一管理本机秤(直接读取 WeightUtil)和远端子设备秤(通过 WebSocket 接收)的数据
|
||||
* 通过 StateFlow 将所有秤的最新快照暴露给 UI 层
|
||||
*
|
||||
* 数据 Map 的 key 格式:"{deviceId}#{address}",便于 UI 按设备分组展示
|
||||
*/
|
||||
class ScaleDataAggregator(private val localDeviceId: String) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ScaleDataAggregator"
|
||||
/** 本机秤监听器的 key,防止与其他监听器冲突 */
|
||||
private const val LOCAL_LISTENER_KEY = "ScaleDataAggregator_local"
|
||||
}
|
||||
|
||||
/** 所有秤的最新数据,UI 层通过此 Flow 订阅更新 */
|
||||
private val _allScales = MutableStateFlow<Map<String, ScaleData>>(emptyMap())
|
||||
val allScales: StateFlow<Map<String, ScaleData>> = _allScales.asStateFlow()
|
||||
|
||||
/** 内部缓存,并发安全 */
|
||||
private val cache = ConcurrentHashMap<String, ScaleData>()
|
||||
|
||||
/** deviceId → IP 地址映射,用于写入 ScaleData.ip 字段 */
|
||||
private val deviceIpMap = ConcurrentHashMap<String, String>()
|
||||
|
||||
/**
|
||||
* 设置指定设备的 IP 地址
|
||||
* 若缓存中已有该设备的数据且 ip 为空,立即回填并触发 StateFlow 更新,
|
||||
* 解决早期数据包在 IP 到达前入缓存导致一直显示"未知"的问题
|
||||
* @param deviceId 设备 ID
|
||||
* @param ip IP 地址字符串
|
||||
*/
|
||||
fun setDeviceIp(deviceId: String, ip: String) {
|
||||
if (ip.isEmpty()) return
|
||||
deviceIpMap[deviceId] = ip
|
||||
// 回填该设备所有 ip 为空的缓存条目
|
||||
val keys = cache.keys.filter { it.startsWith("$deviceId#") }
|
||||
if (keys.isEmpty()) return
|
||||
var updated = false
|
||||
keys.forEach { key ->
|
||||
val old = cache[key] ?: return@forEach
|
||||
if (old.ip.isEmpty()) {
|
||||
cache[key] = old.copy(ip = ip)
|
||||
updated = true
|
||||
}
|
||||
}
|
||||
if (updated) {
|
||||
_allScales.value = HashMap(cache)
|
||||
Log.d(TAG, "已回填设备IP: $deviceId -> $ip, 共 ${keys.size} 条")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动本机秤数据监听
|
||||
* 主设备本机秤直接读取 WeightUtil,无需经过网络
|
||||
*/
|
||||
fun startLocalCollection() {
|
||||
WeightUtil.addWeightListener(LOCAL_LISTENER_KEY) { address, state, weight ->
|
||||
val data = ScaleData(
|
||||
deviceId = localDeviceId,
|
||||
address = address,
|
||||
weight = weight,
|
||||
state = state,
|
||||
ts = System.currentTimeMillis(),
|
||||
ip = deviceIpMap[localDeviceId] ?: ""
|
||||
)
|
||||
updateCache(data)
|
||||
}
|
||||
Log.d(TAG, "本机秤监听已启动, deviceId=$localDeviceId")
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理来自 WebSocket 客户端的远端秤数据
|
||||
* 由 ScaleWebSocketClient.onScaleData 回调触发
|
||||
* 自动补充该设备已记录的 IP 信息
|
||||
*/
|
||||
fun onRemoteScaleData(data: ScaleData) {
|
||||
val ip = deviceIpMap[data.deviceId] ?: data.ip
|
||||
updateCache(if (ip.isNotEmpty() && data.ip.isEmpty()) data.copy(ip = ip) else data)
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除指定设备的所有秤数据(设备离线时调用)
|
||||
*/
|
||||
fun removeDevice(deviceId: String) {
|
||||
val keysToRemove = cache.keys.filter { it.startsWith("$deviceId#") }
|
||||
if (keysToRemove.isEmpty()) return
|
||||
keysToRemove.forEach { cache.remove(it) }
|
||||
deviceIpMap.remove(deviceId)
|
||||
_allScales.value = HashMap(cache)
|
||||
Log.d(TAG, "已移除设备数据: $deviceId, 共 ${keysToRemove.size} 个秤")
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止本机秤监听并清空所有数据
|
||||
*/
|
||||
fun stop() {
|
||||
WeightUtil.removeWeightListener(LOCAL_LISTENER_KEY)
|
||||
cache.clear()
|
||||
deviceIpMap.clear()
|
||||
_allScales.value = emptyMap()
|
||||
Log.d(TAG, "ScaleDataAggregator 已停止")
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新缓存并发布新快照到 StateFlow
|
||||
*/
|
||||
private fun updateCache(data: ScaleData) {
|
||||
val key = "${data.deviceId}#${data.address}"
|
||||
cache[key] = data
|
||||
_allScales.value = HashMap(cache)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.base.DeviceRole
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
/**
|
||||
* 秤服务统一门面(单例)
|
||||
* 根据当前设备角色(MASTER/SLAVE)启动对应的服务组合:
|
||||
*
|
||||
* 所有设备均运行:
|
||||
* - MdnsRegisterManager:将本机 WebSocket 服务广播到局域网
|
||||
* - ScaleWebSocketServer:对外提供本机秤数据推送服务
|
||||
*
|
||||
* 仅主设备(MASTER)额外运行:
|
||||
* - MdnsDiscoveryManager:发现局域网内子设备
|
||||
* - ScaleWebSocketClient:连接子设备 WebSocket
|
||||
* - ScaleDataAggregator:聚合本机 + 远端所有秤数据
|
||||
*
|
||||
* 使用方式:
|
||||
* 在 Application.onCreate() 中调用 ScaleServiceManager.start(context)
|
||||
* 在 Application.onTerminate() 中调用 ScaleServiceManager.stop()
|
||||
* 主设备 UI 通过 ScaleServiceManager.allScales 订阅全量秤数据
|
||||
*/
|
||||
object ScaleServiceManager {
|
||||
|
||||
private const val TAG = "ScaleServiceManager"
|
||||
|
||||
private var mdnsRegister: MdnsRegisterManager? = null
|
||||
private var wsServer: ScaleWebSocketServer? = null
|
||||
private var udpSender: UdpBroadcastSender? = null
|
||||
|
||||
// 以下仅主设备使用
|
||||
private var mdnsDiscovery: MdnsDiscoveryManager? = null
|
||||
private var udpReceiver: UdpBroadcastReceiver? = null
|
||||
private var wsClient: ScaleWebSocketClient? = null
|
||||
private var aggregator: ScaleDataAggregator? = null
|
||||
|
||||
/**
|
||||
* 所有秤数据的实时流,仅主设备有效;子设备返回 null
|
||||
* UI 层通过 lifecycleScope.launch { allScales?.collect { ... } } 订阅
|
||||
*/
|
||||
val allScales: StateFlow<Map<String, ScaleData>>?
|
||||
get() = aggregator?.allScales
|
||||
|
||||
/**
|
||||
* 主设备连接状态回调(仅子设备使用)
|
||||
* 设置后会立即转发给 wsServer;需在 start() 之后设置才能生效
|
||||
*/
|
||||
var onMasterConnectionChanged: ((connected: Boolean) -> Unit)?
|
||||
get() = wsServer?.onConnectionChanged
|
||||
set(value) { wsServer?.onConnectionChanged = value }
|
||||
|
||||
/** 当前是否有主设备连接(仅子设备使用) */
|
||||
val isMasterConnected: Boolean
|
||||
get() = wsServer?.isConnected == true
|
||||
|
||||
/**
|
||||
* 启动所有秤服务,在 Application.onCreate() 中调用
|
||||
*/
|
||||
fun start(context: Context) {
|
||||
val deviceId = GlobalData.deviceId
|
||||
val role = GlobalData.deviceRole
|
||||
Log.d(TAG, "启动秤服务, deviceId=$deviceId, role=$role")
|
||||
|
||||
// 所有设备:启动 WebSocket 服务端 + mDNS 注册
|
||||
wsServer = ScaleWebSocketServer(deviceId, context).also { it.start() }
|
||||
mdnsRegister = MdnsRegisterManager(context).also { it.register(deviceId) }
|
||||
|
||||
if (role == DeviceRole.MASTER) {
|
||||
startMasterServices(context, deviceId)
|
||||
} else {
|
||||
// 子设备:启动 UDP 广播,作为 mDNS 的兜底发现机制
|
||||
val localIp = getLocalIp(context)
|
||||
udpSender = UdpBroadcastSender(deviceId, localIp).also { it.start() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本机局域网 IP,委托给 NetworkUtil 统一处理版本兼容
|
||||
*/
|
||||
private fun getLocalIp(context: Context): String {
|
||||
return NetworkUtil.getLocalIpAddress(context)
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动主设备专属服务
|
||||
*/
|
||||
private fun startMasterServices(context: Context, deviceId: String) {
|
||||
// 聚合器:统一管理本机 + 远端秤数据
|
||||
aggregator = ScaleDataAggregator(deviceId).also {
|
||||
// 记录本机 IP,供本机秤数据展示使用
|
||||
it.setDeviceIp(deviceId, getLocalIp(context))
|
||||
it.startLocalCollection()
|
||||
}
|
||||
|
||||
// WebSocket 客户端
|
||||
val client = ScaleWebSocketClient().also {
|
||||
it.onScaleData = { data -> aggregator?.onRemoteScaleData(data) }
|
||||
}
|
||||
wsClient = client
|
||||
|
||||
// 统一的设备发现处理:mDNS 和 UDP 共用同一逻辑
|
||||
fun onDeviceFound(remoteId: String, host: String, port: Int) {
|
||||
if (remoteId == deviceId) return
|
||||
Log.d(TAG, "发现子设备 $remoteId ($host:$port), 建立连接")
|
||||
aggregator?.setDeviceIp(remoteId, host)
|
||||
client.connect(remoteId, host, port)
|
||||
}
|
||||
|
||||
// mDNS 发现:发现子设备 → 建立 WebSocket 连接;设备离线 → 断开连接并清除数据
|
||||
mdnsDiscovery = MdnsDiscoveryManager(context).also { discovery ->
|
||||
discovery.onDeviceFound = { remoteId, host, port ->
|
||||
onDeviceFound(remoteId, host, port)
|
||||
}
|
||||
discovery.onDeviceLost = { remoteId ->
|
||||
Log.d(TAG, "子设备离线 $remoteId, 断开连接并清除数据")
|
||||
client.disconnect(remoteId)
|
||||
aggregator?.removeDevice(remoteId)
|
||||
udpReceiver?.removeDevice(remoteId)
|
||||
}
|
||||
discovery.startDiscovery()
|
||||
}
|
||||
|
||||
// UDP 广播接收:作为 mDNS 的兜底,发现 mDNS 未能触发的子设备
|
||||
udpReceiver = UdpBroadcastReceiver().also { receiver ->
|
||||
receiver.onDeviceFound = { remoteId, host, port ->
|
||||
onDeviceFound(remoteId, host, port)
|
||||
}
|
||||
receiver.start()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止所有秤服务,在 Application.onTerminate() 或退出时调用
|
||||
*/
|
||||
fun stop() {
|
||||
mdnsDiscovery?.stopDiscovery()
|
||||
udpReceiver?.stop()
|
||||
udpSender?.stop()
|
||||
wsClient?.shutdown()
|
||||
aggregator?.stop()
|
||||
wsServer?.stop()
|
||||
mdnsRegister?.unregister()
|
||||
|
||||
mdnsDiscovery = null
|
||||
udpReceiver = null
|
||||
udpSender = null
|
||||
wsClient = null
|
||||
aggregator = null
|
||||
wsServer = null
|
||||
mdnsRegister = null
|
||||
Log.d(TAG, "所有秤服务已停止")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
import android.util.Log
|
||||
import com.google.gson.Gson
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.ScheduledExecutorService
|
||||
import java.util.concurrent.ScheduledFuture
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 秤数据 WebSocket 客户端连接管理器(仅主设备运行)
|
||||
* 管理与多台子设备的 WebSocket 长连接,支持断线自动重连(指数退避)
|
||||
*/
|
||||
class ScaleWebSocketClient {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ScaleWebSocketClient"
|
||||
/** 初始重连间隔(毫秒) */
|
||||
private const val RECONNECT_BASE_MS = 2_000L
|
||||
/** 最大重连间隔(毫秒) */
|
||||
private const val RECONNECT_MAX_MS = 30_000L
|
||||
}
|
||||
|
||||
private val gson = Gson()
|
||||
|
||||
private val httpClient = OkHttpClient.Builder()
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.readTimeout(0, TimeUnit.SECONDS) // WebSocket 长连接不设置读取超时
|
||||
.pingInterval(20, TimeUnit.SECONDS) // 心跳保活
|
||||
.build()
|
||||
|
||||
/** 各设备当前 WebSocket 连接,key = deviceId */
|
||||
private val connections = ConcurrentHashMap<String, WebSocket>()
|
||||
/** 各设备当前重连任务,key = deviceId */
|
||||
private val reconnectTasks = ConcurrentHashMap<String, ScheduledFuture<*>>()
|
||||
/** 各设备当前重连延迟,key = deviceId */
|
||||
private val reconnectDelays = ConcurrentHashMap<String, Long>()
|
||||
/** 已主动移除的设备集合,不对其触发重连 */
|
||||
private val removedDevices = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
private val scheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
|
||||
|
||||
/** 收到秤数据时的回调,在子线程调用 */
|
||||
var onScaleData: ((data: ScaleData) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 连接到指定子设备
|
||||
* @param deviceId 子设备 ID
|
||||
* @param host 子设备 IP
|
||||
* @param port 子设备 WebSocket 端口
|
||||
*/
|
||||
fun connect(deviceId: String, host: String, port: Int) {
|
||||
removedDevices.remove(deviceId)
|
||||
reconnectDelays[deviceId] = RECONNECT_BASE_MS
|
||||
doConnect(deviceId, host, port)
|
||||
}
|
||||
|
||||
private fun doConnect(deviceId: String, host: String, port: Int) {
|
||||
val url = "ws://$host:$port"
|
||||
val request = Request.Builder().url(url).build()
|
||||
|
||||
val ws = httpClient.newWebSocket(request, object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
Log.d(TAG, "已连接子设备: $deviceId ($url)")
|
||||
connections[deviceId] = webSocket
|
||||
reconnectDelays[deviceId] = RECONNECT_BASE_MS
|
||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
try {
|
||||
val data = gson.fromJson(text, ScaleData::class.java)
|
||||
onScaleData?.invoke(data)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "解析秤数据失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
Log.w(TAG, "连接子设备失败: $deviceId, ${t.message}")
|
||||
connections.remove(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
Log.d(TAG, "子设备连接已关闭: $deviceId, reason=$reason")
|
||||
connections.remove(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
}
|
||||
})
|
||||
|
||||
connections[deviceId] = ws
|
||||
}
|
||||
|
||||
/**
|
||||
* 指数退避重连
|
||||
*/
|
||||
private fun scheduleReconnect(deviceId: String, host: String, port: Int) {
|
||||
if (removedDevices.contains(deviceId)) return
|
||||
|
||||
val delay = reconnectDelays[deviceId] ?: RECONNECT_BASE_MS
|
||||
Log.d(TAG, "将在 ${delay}ms 后重连子设备: $deviceId")
|
||||
|
||||
val future = scheduler.schedule({
|
||||
if (!removedDevices.contains(deviceId)) {
|
||||
doConnect(deviceId, host, port)
|
||||
}
|
||||
}, delay, TimeUnit.MILLISECONDS)
|
||||
|
||||
reconnectTasks[deviceId]?.cancel(false)
|
||||
reconnectTasks[deviceId] = future
|
||||
|
||||
// 下次重连延迟翻倍,上限 30s
|
||||
reconnectDelays[deviceId] = minOf(delay * 2, RECONNECT_MAX_MS)
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开指定子设备连接(不再重连)
|
||||
* @param deviceId 子设备 ID
|
||||
*/
|
||||
fun disconnect(deviceId: String) {
|
||||
removedDevices.add(deviceId)
|
||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
||||
connections.remove(deviceId)?.close(1000, "设备离线")
|
||||
reconnectDelays.remove(deviceId)
|
||||
Log.d(TAG, "已断开子设备: $deviceId")
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭所有连接并释放资源,在应用退出时调用
|
||||
*/
|
||||
fun shutdown() {
|
||||
val ids = connections.keys.toList()
|
||||
ids.forEach { disconnect(it) }
|
||||
scheduler.shutdownNow()
|
||||
httpClient.dispatcher.executorService.shutdown()
|
||||
Log.d(TAG, "ScaleWebSocketClient 已关闭")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.google.gson.Gson
|
||||
import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import org.java_websocket.WebSocket
|
||||
import org.java_websocket.handshake.ClientHandshake
|
||||
import org.java_websocket.server.WebSocketServer
|
||||
import java.net.InetSocketAddress
|
||||
|
||||
/**
|
||||
* 秤数据 WebSocket 服务端(主设备和子设备均运行)
|
||||
* 监听 WeightUtil 回调,将本机秤数据实时推送给所有已连接的主设备客户端
|
||||
*/
|
||||
class ScaleWebSocketServer(private val deviceId: String, private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ScaleWebSocketServer"
|
||||
/** 节流间隔:两次推送之间的最小间隔(毫秒) */
|
||||
private const val THROTTLE_MS = 100L
|
||||
}
|
||||
|
||||
private val gson = Gson()
|
||||
private var server: InternalServer? = null
|
||||
|
||||
/** 主设备连接状态变化回调:true=已连接,false=已断开;在主线程外调用,需自行切换线程 */
|
||||
var onConnectionChanged: ((connected: Boolean) -> Unit)? = null
|
||||
|
||||
/** 当前是否有主设备连接 */
|
||||
val isConnected: Boolean
|
||||
get() = server?.connections?.isNotEmpty() == true
|
||||
|
||||
/** 每个秤地址的最近一次推送时间,用于节流 */
|
||||
private val lastPushTime = mutableMapOf<Int, Long>()
|
||||
|
||||
/** 缓存各秤最新数据,新客户端连接时立即同步当前状态 */
|
||||
private val latestData = mutableMapOf<Int, ScaleData>()
|
||||
|
||||
/**
|
||||
* 启动 WebSocket 服务器,并注册 WeightUtil 回调
|
||||
*/
|
||||
fun start() {
|
||||
server = InternalServer(MdnsRegisterManager.WS_PORT)
|
||||
server?.isReuseAddr = true
|
||||
server?.start()
|
||||
Log.d(TAG, "WebSocket 服务端已启动,端口 ${MdnsRegisterManager.WS_PORT}")
|
||||
|
||||
// 注册本机秤数据监听
|
||||
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||
val now = System.currentTimeMillis()
|
||||
// 节流:同一地址 100ms 内只推送一次
|
||||
if (now - (lastPushTime[address] ?: 0L) < THROTTLE_MS) return@addWeightListener
|
||||
|
||||
lastPushTime[address] = now
|
||||
val data = ScaleData(
|
||||
deviceId = deviceId,
|
||||
address = address,
|
||||
weight = weight,
|
||||
state = state,
|
||||
ts = now,
|
||||
ip = NetworkUtil.getLocalIpAddress(context)
|
||||
)
|
||||
latestData[address] = data
|
||||
broadcast(gson.toJson(data))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止 WebSocket 服务器,移除秤监听
|
||||
*/
|
||||
fun stop() {
|
||||
WeightUtil.removeWeightListener(TAG)
|
||||
try {
|
||||
server?.stop(1000)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "停止服务端异常: ${e.message}")
|
||||
}
|
||||
server = null
|
||||
latestData.clear()
|
||||
lastPushTime.clear()
|
||||
Log.d(TAG, "WebSocket 服务端已停止")
|
||||
}
|
||||
|
||||
/**
|
||||
* 向所有已连接客户端广播消息
|
||||
*/
|
||||
private fun broadcast(json: String) {
|
||||
server?.connections?.forEach { conn ->
|
||||
if (conn.isOpen) {
|
||||
try {
|
||||
conn.send(json)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "推送失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 内部 WebSocket 服务器实现
|
||||
*/
|
||||
private inner class InternalServer(port: Int) :
|
||||
WebSocketServer(InetSocketAddress(port)) {
|
||||
|
||||
override fun onOpen(conn: WebSocket, handshake: ClientHandshake) {
|
||||
Log.d(TAG, "主设备已连接: ${conn.remoteSocketAddress}")
|
||||
onConnectionChanged?.invoke(true)
|
||||
// 新客户端连接后,立即推送所有秤的最新数据
|
||||
latestData.values.forEach { data ->
|
||||
try {
|
||||
conn.send(gson.toJson(data))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "初始推送失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) {
|
||||
Log.d(TAG, "主设备已断开: ${conn.remoteSocketAddress}, reason=$reason")
|
||||
// 若已无任何连接,通知子设备 UI 更新为未连接状态
|
||||
if (server?.connections.isNullOrEmpty()) {
|
||||
onConnectionChanged?.invoke(false)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(conn: WebSocket, message: String) {
|
||||
// 服务端无需处理来自主设备的消息
|
||||
}
|
||||
|
||||
override fun onError(conn: WebSocket?, ex: Exception) {
|
||||
Log.e(TAG, "WebSocket 服务端错误: ${ex.message}")
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
Log.d(TAG, "WebSocket 服务端 onStart")
|
||||
connectionLostTimeout = 60
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
import android.util.Log
|
||||
import com.google.gson.Gson
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* UDP 广播接收器(主设备运行)
|
||||
* 监听子设备发来的 UDP 广播包,解析后通过回调通知连接管理器
|
||||
* 与 mDNS 互为备份,任意一条路发现子设备均可建立 WebSocket 连接
|
||||
*/
|
||||
class UdpBroadcastReceiver {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "UdpBroadcastReceiver"
|
||||
private const val BUFFER_SIZE = 1024
|
||||
}
|
||||
|
||||
private val gson = Gson()
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
|
||||
/** 已发现的设备集合,避免重复触发回调,key=deviceId, value="host:port" */
|
||||
private val knownDevices = ConcurrentHashMap<String, String>()
|
||||
|
||||
@Volatile
|
||||
private var running = false
|
||||
private var socket: DatagramSocket? = null
|
||||
|
||||
/**
|
||||
* 发现新设备时的回调:(deviceId, host, port)
|
||||
* 与 MdnsDiscoveryManager.onDeviceFound 签名一致,可共用同一处理逻辑
|
||||
*/
|
||||
var onDeviceFound: ((deviceId: String, host: String, port: Int) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 开始监听 UDP 广播
|
||||
*/
|
||||
fun start() {
|
||||
if (running) return
|
||||
running = true
|
||||
executor.execute { listenLoop() }
|
||||
Log.d(TAG, "UDP 广播接收已启动, 监听端口=${UdpBroadcastSender.BROADCAST_PORT}")
|
||||
}
|
||||
|
||||
private fun listenLoop() {
|
||||
try {
|
||||
socket = DatagramSocket(UdpBroadcastSender.BROADCAST_PORT).also { it.broadcast = true }
|
||||
val buf = ByteArray(BUFFER_SIZE)
|
||||
while (running) {
|
||||
val packet = DatagramPacket(buf, buf.size)
|
||||
socket?.receive(packet) ?: break
|
||||
val json = String(packet.data, 0, packet.length, Charsets.UTF_8)
|
||||
handlePacket(json)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (running) Log.w(TAG, "UDP 接收异常: ${e.message}")
|
||||
} finally {
|
||||
socket?.close()
|
||||
socket = null
|
||||
}
|
||||
}
|
||||
|
||||
private fun handlePacket(json: String) {
|
||||
try {
|
||||
val payload = gson.fromJson(json, UdpBroadcastSender.Payload::class.java)
|
||||
val key = "${payload.ip}:${payload.port}"
|
||||
// 同一设备已通知过则跳过,避免每5秒重复触发连接
|
||||
if (knownDevices.put(payload.deviceId, key) == key) return
|
||||
Log.d(TAG, "UDP 发现设备: ${payload.deviceId} -> ${payload.ip}:${payload.port}")
|
||||
onDeviceFound?.invoke(payload.deviceId, payload.ip, payload.port)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "解析 UDP 广播包失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除已知设备记录,设备离线时调用,确保设备重新上线后能再次触发回调
|
||||
*/
|
||||
fun removeDevice(deviceId: String) {
|
||||
knownDevices.remove(deviceId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止监听,释放资源
|
||||
*/
|
||||
fun stop() {
|
||||
running = false
|
||||
socket?.close()
|
||||
executor.shutdownNow()
|
||||
Log.d(TAG, "UDP 广播接收已停止")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.shuwei.dish.match.scale
|
||||
|
||||
import android.util.Log
|
||||
import com.google.gson.Gson
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.InetAddress
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.ScheduledFuture
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* UDP 广播发送器(子设备运行)
|
||||
* 每隔固定间隔向局域网广播本机的 deviceId、IP、WebSocket 端口
|
||||
* 作为 mDNS 的兜底发现机制,确保主设备能可靠发现子设备
|
||||
*/
|
||||
class UdpBroadcastSender(
|
||||
private val deviceId: String,
|
||||
private val localIp: String,
|
||||
private val wsPort: Int = MdnsRegisterManager.WS_PORT
|
||||
) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "UdpBroadcastSender"
|
||||
/** UDP 广播目标端口,与 UdpBroadcastReceiver 保持一致 */
|
||||
const val BROADCAST_PORT = 8766
|
||||
/** 广播间隔(秒) */
|
||||
private const val INTERVAL_SEC = 5L
|
||||
}
|
||||
|
||||
private val gson = Gson()
|
||||
private val scheduler = Executors.newSingleThreadScheduledExecutor()
|
||||
private var task: ScheduledFuture<*>? = null
|
||||
|
||||
/** 广播数据包结构 */
|
||||
data class Payload(val deviceId: String, val ip: String, val port: Int)
|
||||
|
||||
/**
|
||||
* 开始定时广播
|
||||
*/
|
||||
fun start() {
|
||||
if (task != null) return
|
||||
task = scheduler.scheduleWithFixedDelay({
|
||||
sendBroadcast()
|
||||
}, 0, INTERVAL_SEC, TimeUnit.SECONDS)
|
||||
Log.d(TAG, "UDP 广播已启动, deviceId=$deviceId, ip=$localIp, port=$wsPort")
|
||||
}
|
||||
|
||||
private fun sendBroadcast() {
|
||||
try {
|
||||
val payload = gson.toJson(Payload(deviceId, localIp, wsPort))
|
||||
val data = payload.toByteArray(Charsets.UTF_8)
|
||||
DatagramSocket().use { socket ->
|
||||
socket.broadcast = true
|
||||
val packet = DatagramPacket(
|
||||
data, data.size,
|
||||
InetAddress.getByName("255.255.255.255"),
|
||||
BROADCAST_PORT
|
||||
)
|
||||
socket.send(packet)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "UDP 广播发送失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止广播,释放资源
|
||||
*/
|
||||
fun stop() {
|
||||
task?.cancel(false)
|
||||
task = null
|
||||
scheduler.shutdownNow()
|
||||
Log.d(TAG, "UDP 广播已停止")
|
||||
}
|
||||
}
|
||||
@@ -238,8 +238,8 @@ class DishSamplingActivity : BaseActivity() {
|
||||
}
|
||||
val food = FoodRecord()
|
||||
binding.etInputDish.let {
|
||||
if (it.tag!=null && it.tag.toString() == it.text.toString()) {
|
||||
food.foodId = foodId
|
||||
if (it.tag != null && it.tag.toString() == it.text.toString()) {
|
||||
food.foodId = foodId
|
||||
}
|
||||
}
|
||||
food.foodName = showFoodName
|
||||
@@ -259,17 +259,16 @@ class DishSamplingActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
private fun jumpSearch(v: View) {
|
||||
launch(Intent(this, FoodSearchActivity::class.java).apply {
|
||||
val intent = Intent(this, FoodSearchActivity::class.java).apply {
|
||||
putExtra(FoodSearchActivity.FOOD_NAME, binding.etInputDish.text.toString().trim())
|
||||
}) { intent ->
|
||||
intent?.let {
|
||||
foodId = it.getStringExtra(FoodSearchActivity.FOOD_ID)
|
||||
foodName = it.getStringExtra(FoodSearchActivity.FOOD_NAME)
|
||||
binding.etInputDish.run {
|
||||
setText(foodName)
|
||||
tag = foodName
|
||||
setSelection(text.length)
|
||||
}
|
||||
}
|
||||
startActivity(intent) {
|
||||
foodId = it?.getStringExtra(FoodSearchActivity.FOOD_ID)
|
||||
foodName = it?.getStringExtra(FoodSearchActivity.FOOD_NAME)
|
||||
binding.etInputDish.run {
|
||||
setText(foodName)
|
||||
tag = foodName
|
||||
setSelection(text.length)
|
||||
}
|
||||
}
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
|
||||
@@ -1,26 +1,34 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import android.os.SystemClock
|
||||
import android.view.KeyEvent
|
||||
import android.view.animation.RotateAnimation
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.base.DeviceRole
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.ActivityInitBinding
|
||||
import com.shuwei.dish.match.db.AppRepository
|
||||
import com.shuwei.dish.match.http.UrlConfig
|
||||
import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.utils.AppUtil
|
||||
import com.shuwei.dish.match.utils.QRCodeUtil
|
||||
import com.shuwei.dish.match.utils.NetworkUtils
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.Weigher2
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toObject
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import com.shuwei.dish.match.viewmodel.AppViewModel
|
||||
import com.shuwei.dish.match.viewmodel.factory.AppFactory
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class InitActivity : BaseActivity() {
|
||||
@@ -30,58 +38,33 @@ class InitActivity : BaseActivity() {
|
||||
|
||||
private lateinit var binding: ActivityInitBinding
|
||||
private lateinit var appViewModel: AppViewModel
|
||||
private var startTime = 0L // 倒计时开始时间
|
||||
private var lastNetworkCheckTime = 0L // 上次检测网络的时间
|
||||
|
||||
@SuppressLint("HardwareIds")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
addBackKeyListener()
|
||||
statusBarDarkFont(enable = true)
|
||||
// useBackground(false)
|
||||
binding = ActivityInitBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
|
||||
lifecycleScope.launch {
|
||||
FoodModule.init(this@InitActivity)
|
||||
}
|
||||
// setHeaderBackground(isHomePage = true)
|
||||
setHeaderBgVisible(false)
|
||||
BaseApp.appVersion = AppUtil.getAppVersionCode(this).toString()
|
||||
|
||||
// 获取 ANDROID_ID
|
||||
// var androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
|
||||
// androidId = "39a7abdd06b3c7ab"
|
||||
// BaseApp.deviceId = androidId
|
||||
// SpTool.put(SpTool.DEVICE_ID, androidId)
|
||||
// BaseApp.configUrl = UrlConfig.BASE_URL
|
||||
BaseApp.canteenId = "0"
|
||||
// // TODO: 以上保存deviceId用于临时使用,后续改为下面注释方式
|
||||
|
||||
// var deviceId = AppUtil.getUDID(this)
|
||||
// Log.d(TAG, "onCreate: deviceId=$deviceId")
|
||||
//// deviceId = "39a7abdd06b3c7ab"
|
||||
// deviceId = "3ea47dc0-3cf0-3c2f-909c-265a9a65572e"
|
||||
//// deviceId = "6ce7cd59-b875-38b2-b73d-88a570be3212"
|
||||
//
|
||||
// BaseApp.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()
|
||||
|
||||
initViewModel()
|
||||
|
||||
WeightUtil.init()
|
||||
WeightUtil.getWeight()
|
||||
WeightUtil.startContinuousRead()
|
||||
// HttpUtil.getAppToken()
|
||||
|
||||
// HttpUtil.loopGetToken = true
|
||||
countDown()
|
||||
initViews()
|
||||
}
|
||||
|
||||
private fun initViewModel() {
|
||||
@@ -90,19 +73,28 @@ class InitActivity : BaseActivity() {
|
||||
appViewModel = ViewModelProvider(this, factory)[AppViewModel::class.java]
|
||||
}
|
||||
|
||||
private fun startNextPage() {
|
||||
val launchPageType = SpTool.getInt(SpTool.LAUNCH_PAGE_TYPE, -1)
|
||||
when (launchPageType) {
|
||||
0 -> {
|
||||
startActivity<SelectDishActivity>()
|
||||
private fun startNextPage(withDelay: Boolean = false) {
|
||||
lifecycleScope.launch {
|
||||
if (withDelay) delay(2000)
|
||||
// 子设备:直接进入小屏专属页面,不走原有大屏业务流程
|
||||
if (GlobalData.deviceRole == DeviceRole.SLAVE) {
|
||||
startActivity<SlaveActivity>()
|
||||
return@launch
|
||||
}
|
||||
// 主设备:走原有路由逻辑
|
||||
val launchPageType = SpTool.getInt(SpTool.LAUNCH_PAGE_TYPE, -1)
|
||||
when (launchPageType) {
|
||||
0 -> {
|
||||
startActivity<SelectDishActivity>()
|
||||
}
|
||||
|
||||
1 -> {
|
||||
goSampling()
|
||||
}
|
||||
1 -> {
|
||||
goSampling()
|
||||
}
|
||||
|
||||
else -> {
|
||||
startActivity<HomeActivity>()
|
||||
else -> {
|
||||
startActivity<HomeActivity>()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,112 +104,154 @@ class InitActivity : BaseActivity() {
|
||||
if (it.isEmpty()) {
|
||||
//无调料信息打开采样历史列表页面,点击设置配置调料信息
|
||||
startActivity<SamplingListActivity>()
|
||||
// finish()
|
||||
return@loadSeasoning
|
||||
}
|
||||
appViewModel.countCookFood(cookMode = 1) { count ->
|
||||
if (count > 0) {
|
||||
//有烹饪中数据打开采样历史列表页面
|
||||
startActivity<SamplingListActivity>()
|
||||
// finish()
|
||||
return@countCookFood
|
||||
}
|
||||
//无烹饪数据打开新增采样页面
|
||||
startActivity<DishSamplingActivity> {
|
||||
putExtra(DishSamplingActivity.PAGE_FROM, DishSamplingActivity.HOME)
|
||||
}
|
||||
// finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun countDown() {
|
||||
lifecycleScope.launch {
|
||||
flow {
|
||||
(2 downTo 1).forEach {
|
||||
delay(1000)
|
||||
emit(it)
|
||||
}
|
||||
}.collect {
|
||||
// 倒计时结束执行跳转
|
||||
if (it == 1) {
|
||||
startNextPage()
|
||||
//保留初始化页面,不关闭
|
||||
// finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// private fun initConfig() {
|
||||
// binding.ivQrCode.setImageBitmap(
|
||||
// QRCodeUtil.generateQRCode(
|
||||
// content = BaseApp.deviceId ?: "",
|
||||
// size = 200.dp
|
||||
// )
|
||||
// )
|
||||
// binding.btnInit.setOnClickListener {
|
||||
//// HttpUtil.loopGetToken = false
|
||||
//// getDeviceConfig()
|
||||
// }
|
||||
// }
|
||||
|
||||
// private fun getDeviceConfig() {
|
||||
// val tokenUrl =
|
||||
// "${UrlConfig.DEVICE_TOKEN}?qrcodeId=${BaseApp.deviceId}&appVersion=${BaseApp.appVersion}"
|
||||
// HttpUtil.get(url = tokenUrl, doSuccess = { token ->
|
||||
// Log.d(TAG, "initConfig: $token")
|
||||
// getConfig(token.toString())
|
||||
// }, doFailure = { code, msg ->
|
||||
// Log.d(TAG, "initConfig: $code,$msg")
|
||||
// })
|
||||
// }
|
||||
|
||||
// private fun getConfig(token: String) {
|
||||
// val deviceConfigUrl =
|
||||
// "${UrlConfig.DEVICE_CONFIG}?equipmentCode=${BaseApp.deviceId}&&appVersion=${BaseApp.appVersion}"
|
||||
// HttpUtil.get(
|
||||
// url = deviceConfigUrl, header = mutableMapOf(
|
||||
// "X-Access-Token" to token
|
||||
// ), doSuccess = {
|
||||
// Log.d(TAG, "getDeviceConfig: $it")
|
||||
// val data = it.toJsonString()
|
||||
// val checkResult = checkConfigData(data)
|
||||
// if (checkResult.not()) {
|
||||
// toast("初始化设备失败,请稍后重试")
|
||||
// return@get
|
||||
// }
|
||||
// HttpUtil.loopGetToken = true
|
||||
// SpTool.put(SpTool.DEVICE_CONFIG_CACHE, data)
|
||||
// startActivity<HomeActivity>()
|
||||
//// finish()
|
||||
// }, doFailure = { code, msg ->
|
||||
// Log.d(TAG, "getDeviceConfig: $code,$msg")
|
||||
// toast("初始化设备失败,请稍后重试,code=${code},msg=${msg}")
|
||||
// })
|
||||
// }
|
||||
|
||||
data class DeviceConfigBean(
|
||||
var appPackageUrl: String? = null,
|
||||
var canteenId: String? = null
|
||||
)
|
||||
|
||||
// private fun checkConfigData(data: String): Boolean {
|
||||
// if (data.isBlank()) {
|
||||
// return false
|
||||
// }
|
||||
// val config = data.toObject<DeviceConfigBean?>()
|
||||
// if (config == null) {
|
||||
// return false
|
||||
// }
|
||||
// BaseApp.configUrl = config.appPackageUrl ?: ""
|
||||
// BaseApp.canteenId = config.canteenId ?: ""
|
||||
// return true
|
||||
// }
|
||||
|
||||
override fun onDestroy() {
|
||||
WeightUtil.stopContinuousRead()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 初始化控件事件
|
||||
*/
|
||||
private fun initViews() {
|
||||
// 连接网络按钮点击事件
|
||||
binding.btnConnectNetwork.setOnClickListener {
|
||||
openNetworkSettings()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动加载动画 - 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)) {
|
||||
// 有网络时隐藏网络检测区域,直接跳转
|
||||
binding.llNetwork.gone()
|
||||
startNextPage(withDelay = false)
|
||||
return
|
||||
}
|
||||
binding.llNetwork.visible()
|
||||
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.visible()
|
||||
binding.llNetworkButton.gone()
|
||||
binding.tvCountdown.text = "60秒"
|
||||
// 无网络时才启动加载动画
|
||||
startLoadingAnimation()
|
||||
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)) {
|
||||
startNextPage()
|
||||
} else {
|
||||
// 网络未连接,显示"连接网络"按钮
|
||||
showNetworkButton()
|
||||
}
|
||||
}
|
||||
}, 100) // 每 100ms 检查一次,确保精确性
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测网络连接
|
||||
*/
|
||||
private fun checkNetworkConnection() {
|
||||
if (NetworkUtils.isNetworkConnected(this)) {
|
||||
// 网络连接成功,停止倒计时并跳转到 HomeActivity
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
startNextPage()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 显示"连接网络"按钮
|
||||
*/
|
||||
private fun showNetworkButton() {
|
||||
// binding.llNetwork.setBackgroundColor("#5C77F7".toColorInt())
|
||||
binding.llLoading.gone()
|
||||
binding.llNetworkButton.visible()
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开系统网络设置页面
|
||||
*/
|
||||
private fun openNetworkSettings() {
|
||||
val intent = Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)
|
||||
startActivity(intent) {}
|
||||
}
|
||||
|
||||
private fun addBackKeyListener() {
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
// 禁用返回键,不执行任何操作
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityMasterScaleBinding
|
||||
import com.shuwei.dish.match.databinding.ListItemScaleDataBinding
|
||||
import com.shuwei.dish.match.scale.ScaleData
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 主设备秤数据总览页面(仅 MASTER 角色显示)
|
||||
* 聚合展示所有设备(本机 + 远端子设备)的实时秤数据
|
||||
* 数据按设备分组展示:设备号 + IP + 该设备下所有秤数据
|
||||
* 数据来源:ScaleServiceManager.allScales(StateFlow)
|
||||
*/
|
||||
class MasterScaleActivity : BaseActivity() {
|
||||
|
||||
private lateinit var binding: ActivityMasterScaleBinding
|
||||
|
||||
/**
|
||||
* 按设备分组后的数据模型
|
||||
* @param deviceId 设备 ID
|
||||
* @param ip 设备 IP 地址
|
||||
* @param scales 该设备下所有秤数据,按 address 排序
|
||||
*/
|
||||
private data class DeviceGroup(
|
||||
val deviceId: String,
|
||||
val ip: String,
|
||||
val scales: List<ScaleData>
|
||||
)
|
||||
|
||||
private val groupList = mutableListOf<DeviceGroup>()
|
||||
private val adapter = DeviceGroupAdapter(groupList)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityMasterScaleBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground()
|
||||
|
||||
binding.ivMasterBack.setOnClickListener { finish() }
|
||||
binding.rvScaleList.layoutManager = LinearLayoutManager(this)
|
||||
binding.rvScaleList.itemAnimator = null // 关闭默认动画,避免数据频繁更新时出现闪烁错乱
|
||||
binding.rvScaleList.adapter = adapter
|
||||
|
||||
observeScaleData()
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅 ScaleServiceManager 的全量秤数据 StateFlow
|
||||
* 每次有任一秤数据更新时,重新按设备分组并刷新列表
|
||||
*/
|
||||
private fun observeScaleData() {
|
||||
val flow = ScaleServiceManager.allScales ?: return
|
||||
|
||||
lifecycleScope.launch {
|
||||
flow.collectLatest { scaleMap ->
|
||||
// 按 deviceId 分组,本机设备排最前,其余按 deviceId 排序
|
||||
val localId = com.shuwei.dish.match.base.GlobalData.deviceId
|
||||
// 本机 IP 实时读取,避免 App 启动时网络未就绪导致缓存为空
|
||||
val localIp = NetworkUtil.getLocalIpAddress(this@MasterScaleActivity)
|
||||
val groups = scaleMap.values
|
||||
.groupBy { it.deviceId }
|
||||
.entries
|
||||
.sortedWith(compareBy({ if (it.key == localId) 0 else 1 }, { it.key }))
|
||||
.map { (deviceId, scales) ->
|
||||
DeviceGroup(
|
||||
deviceId = deviceId,
|
||||
ip = if (deviceId == localId) localIp
|
||||
else scales.firstOrNull { it.ip.isNotEmpty() }?.ip ?: "",
|
||||
scales = scales.sortedBy { it.address }
|
||||
)
|
||||
}
|
||||
updateList(groups)
|
||||
updateStatusBar(scaleMap)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun updateList(groups: List<DeviceGroup>) {
|
||||
groupList.clear()
|
||||
groupList.addAll(groups)
|
||||
adapter.notifyDataSetChanged()
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
private fun updateStatusBar(scaleMap: Map<String, ScaleData>) {
|
||||
val deviceCount = scaleMap.values.map { it.deviceId }.distinct().size
|
||||
val scaleCount = scaleMap.size
|
||||
binding.tvConnectionStatus.text = "已发现设备:$deviceCount 台 / 共 $scaleCount 个秤"
|
||||
}
|
||||
|
||||
/** 设备分组适配器,每项展示一台设备及其所有秤数据 */
|
||||
private inner class DeviceGroupAdapter(private val data: List<DeviceGroup>) :
|
||||
RecyclerView.Adapter<DeviceGroupAdapter.VH>() {
|
||||
|
||||
inner class VH(val binding: ListItemScaleDataBinding) :
|
||||
RecyclerView.ViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = VH(
|
||||
ListItemScaleDataBinding.inflate(LayoutInflater.from(parent.context), parent, false)
|
||||
)
|
||||
|
||||
override fun getItemCount() = data.size
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
val group = data[position]
|
||||
holder.binding.tvDeviceLabel.text = "设备:${group.deviceId}"
|
||||
holder.binding.tvDeviceIp.text = "IP:${group.ip.ifEmpty { "未知" }}"
|
||||
|
||||
// 清空旧秤行,重新填充
|
||||
val container: LinearLayout = holder.binding.llScaleContainer
|
||||
container.removeAllViews()
|
||||
|
||||
group.scales.forEach { scale ->
|
||||
val stateStr = when (scale.state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
else -> "${scale.state}"
|
||||
}
|
||||
// 每行:秤编号 重量 状态
|
||||
val row = LinearLayout(holder.itemView.context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT
|
||||
).also { it.topMargin = 4.dp }
|
||||
}
|
||||
row.addView(makeTextView("秤 ${scale.address}", 22, weight = 1f))
|
||||
row.addView(makeTextView("${scale.weight} g", 26, bold = true, weight = 2f))
|
||||
row.addView(makeTextView(stateStr, 18, weight = 1f))
|
||||
container.addView(row)
|
||||
}
|
||||
}
|
||||
|
||||
/** 创建秤行内的 TextView */
|
||||
private fun makeTextView(
|
||||
text: String,
|
||||
spSize: Int,
|
||||
bold: Boolean = false,
|
||||
weight: Float = 1f
|
||||
): TextView = TextView(this@MasterScaleActivity).apply {
|
||||
this.text = text
|
||||
textSize = spSize.toFloat()
|
||||
if (bold) setTypeface(null, android.graphics.Typeface.BOLD)
|
||||
setTextColor(
|
||||
if (bold) getColor(R.color.home_title)
|
||||
else getColor(R.color.home_sub_title)
|
||||
)
|
||||
layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, weight)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Typeface
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import androidx.activity.viewModels
|
||||
import androidx.recyclerview.widget.ItemTouchHelper
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
@@ -12,23 +13,34 @@ import com.shuwei.dish.match.adapter.DishPartAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityPrepareCookBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutFoodRemindBinding
|
||||
import com.shuwei.dish.match.dialog.FoodSearchDialog
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.dialog.FoodRecognizeDialog
|
||||
import com.shuwei.dish.match.dialog.FoodSearchDialog
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.net.NetViewModel
|
||||
import android.view.ViewGroup
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
||||
import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.CameraUtils
|
||||
import com.shuwei.dish.match.utils.ImageUtil
|
||||
import com.shuwei.dish.match.utils.SwipeCallback
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.Serializable
|
||||
import kotlin.getValue
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
class PrepareCookActivity : BaseActivity() {
|
||||
@@ -40,6 +52,8 @@ class PrepareCookActivity : BaseActivity() {
|
||||
|
||||
private lateinit var binding: ActivityPrepareCookBinding
|
||||
|
||||
private val cameraUtils: CameraUtils by lazy { CameraUtils(this) }
|
||||
|
||||
private var food: FoodRecord? = null
|
||||
|
||||
private var goodsList: MutableList<CookFoodGoodsEntity>? = null
|
||||
@@ -69,6 +83,7 @@ class PrepareCookActivity : BaseActivity() {
|
||||
binding.tvDishName.text = food?.foodName ?: ""
|
||||
addViewClickListener()
|
||||
|
||||
initCamera(binding.flCameraContainer)
|
||||
initRecyclerView()
|
||||
|
||||
getDishDetail()
|
||||
@@ -81,6 +96,9 @@ class PrepareCookActivity : BaseActivity() {
|
||||
//Log.d(TAG, "addViewClickListener: address=$address,state=$state,weight=$weight")
|
||||
if (address == AddressUtil.ONE) {
|
||||
binding.tvDishPartWeight.text = "${weight}"
|
||||
if (state == WeightUtil.STATE_STABLE) {
|
||||
recognizeFood(weight)
|
||||
}
|
||||
}
|
||||
})
|
||||
binding.ivWeightClear.setOnClickListener {
|
||||
@@ -134,6 +152,25 @@ class PrepareCookActivity : BaseActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private val isTakingPhoto = AtomicBoolean(false)
|
||||
|
||||
/**
|
||||
* 重量稳定时触发菜品识别
|
||||
* @param weight 当前稳定重量
|
||||
*/
|
||||
private fun recognizeFood(weight: Double) {
|
||||
if (weight < 10) {
|
||||
if (recognizeDialog.isShowing) recognizeDialog.dismiss()
|
||||
return
|
||||
}
|
||||
if (isTakingPhoto.get() || recognizeDialog.isShowing) return
|
||||
isTakingPhoto.set(true)
|
||||
cameraUtils.takePhoto(
|
||||
succCallback = cameraSuccessCallback,
|
||||
failCallback = cameraFailureCallback
|
||||
)
|
||||
}
|
||||
|
||||
private fun addFood() {
|
||||
FoodSearchDialog().show(this) { item ->
|
||||
val filterResult = list.firstOrNull { it.goodsId == item.goodsId }
|
||||
@@ -251,6 +288,16 @@ class PrepareCookActivity : BaseActivity() {
|
||||
|
||||
private var firstReqSize = 0
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>()
|
||||
private val recognizeDialog by lazy {
|
||||
FoodRecognizeDialog(this) { item ->
|
||||
// TODO: 处理识别结果选中
|
||||
}
|
||||
.apply {
|
||||
setOnDismissListener {
|
||||
isTakingPhoto.set(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
private val dishPartAdapter by lazy {
|
||||
DishPartAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, positon ->
|
||||
@@ -326,6 +373,26 @@ class PrepareCookActivity : BaseActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
cameraUtils.bind()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
cameraUtils.unbind()
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化相机并绑定预览容器
|
||||
* @param container 相机预览容器
|
||||
*/
|
||||
fun initCamera(container: ViewGroup) {
|
||||
cameraUtils.initCamera()
|
||||
val previewBinding = LayoutCameraPreviewBinding.inflate(layoutInflater, container)
|
||||
cameraUtils.setPreviewController(previewBinding.previewView)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
@SuppressLint("GestureBackNavigation")
|
||||
@Deprecated("Deprecated in Java")
|
||||
@@ -367,4 +434,49 @@ class PrepareCookActivity : BaseActivity() {
|
||||
}.show()
|
||||
}
|
||||
|
||||
private val cameraSuccessCallback: (Uri) -> Unit = { uri ->
|
||||
Log.d(TAG, "takePhoto success")
|
||||
lifecycleScope.launch {
|
||||
withContext(Dispatchers.IO) {
|
||||
val bitmap = ImageUtil.uriToBitmap(this@PrepareCookActivity, uri)
|
||||
if (bitmap == null) {
|
||||
Log.d(TAG, "takePhoto bitmap is null")
|
||||
isTakingPhoto.set(false)
|
||||
return@withContext
|
||||
}
|
||||
val foodScoreList = FoodModule.getFoodScoreList(bitmap)
|
||||
if (foodScoreList.isEmpty()) {
|
||||
Log.d(TAG, "takePhoto foodScoreList is empty")
|
||||
isTakingPhoto.set(false)
|
||||
return@withContext
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
queryFood(foodScoreList)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val cameraFailureCallback: (String) -> Unit = { errMsg ->
|
||||
Log.d(TAG, "takePhoto failure")
|
||||
isTakingPhoto.set(false)
|
||||
}
|
||||
|
||||
private fun queryFood(list: List<FoodModule.IdNameScore>) {
|
||||
Log.d(TAG, "takePhoto queryFood, list=${list.toString()}")
|
||||
//调用接口成功,返回食材列表设置isTakingPhoto.set(false),暂时写死数据
|
||||
val foodList = mutableListOf<CookFoodGoodsEntity>()
|
||||
list.forEachIndexed { index, food ->
|
||||
val foodName = food.name.split("WP").first()
|
||||
val foodScore = ((1-food.score) * 100).roundedDecimalPlace(2)
|
||||
foodList.add(CookFoodGoodsEntity(
|
||||
goodsId = index.toString(),
|
||||
goodsName = "${foodName}-${foodScore}%",
|
||||
foodId = index.toString()
|
||||
))
|
||||
}
|
||||
recognizeDialog.loadData(foodList)
|
||||
isTakingPhoto.set(false)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -59,9 +59,7 @@ class SamplingListActivity : BaseActivity() {
|
||||
it.visible()
|
||||
it.setImageResource(R.drawable.ic_setting)
|
||||
it.setOnClickListener {
|
||||
startActivity<DeviceConfigActivity> {
|
||||
putExtra(DeviceConfigActivity.COOK_MODE, 2)
|
||||
}
|
||||
startActivity<SettingActivity>()
|
||||
}
|
||||
}, backAction = {
|
||||
it.gone()
|
||||
@@ -86,7 +84,7 @@ class SamplingListActivity : BaseActivity() {
|
||||
appViewModel.deleteCookFoodAndGoods(cookMode = 1, foodId = foodId, onFinish = action)
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent?) {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
val isConfigPage = intent?.getBooleanExtra(IS_CONFIG_PAGE, false) ?: false
|
||||
if (isConfigPage) {
|
||||
@@ -394,9 +392,7 @@ class SamplingListActivity : BaseActivity() {
|
||||
rightBtnText = "去设置",
|
||||
leftBtnClick = {},
|
||||
rightBtnClick = {
|
||||
startActivity<DeviceConfigActivity> {
|
||||
putExtra(DeviceConfigActivity.COOK_MODE, 2)
|
||||
}
|
||||
startActivity<SettingActivity>()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -59,9 +59,7 @@ class SelectDishActivity : BaseActivity() {
|
||||
it.visible()
|
||||
it.setImageResource(R.drawable.ic_setting)
|
||||
it.setOnClickListener {
|
||||
startActivity<DeviceConfigActivity> {
|
||||
putExtra(DeviceConfigActivity.COOK_MODE, 1)
|
||||
}
|
||||
startActivity<SettingActivity>()
|
||||
}
|
||||
}, backAction = {
|
||||
it.gone()
|
||||
@@ -84,18 +82,19 @@ class SelectDishActivity : BaseActivity() {
|
||||
private var configFinished = false
|
||||
|
||||
fun judgeDeviceConfig(block: () -> Unit) {
|
||||
if (configFinished) {
|
||||
block()
|
||||
return
|
||||
}
|
||||
appViewModel.loadSeasoning {
|
||||
if (it.isEmpty()) {
|
||||
showDeviceConfigDialog()
|
||||
return@loadSeasoning
|
||||
}
|
||||
configFinished = true
|
||||
block()
|
||||
}
|
||||
// if (configFinished) {
|
||||
// block()
|
||||
// return
|
||||
// }
|
||||
// appViewModel.loadSeasoning {
|
||||
// if (it.isEmpty()) {
|
||||
// showDeviceConfigDialog()
|
||||
// return@loadSeasoning
|
||||
// }
|
||||
// configFinished = true
|
||||
// block()
|
||||
// }
|
||||
block()
|
||||
}
|
||||
|
||||
private fun showDeviceConfigDialog() {
|
||||
@@ -107,9 +106,7 @@ class SelectDishActivity : BaseActivity() {
|
||||
rightBtnText = "去设置",
|
||||
leftBtnClick = {},
|
||||
rightBtnClick = {
|
||||
startActivity<DeviceConfigActivity> {
|
||||
putExtra(DeviceConfigActivity.COOK_MODE, 1)
|
||||
}
|
||||
startActivity<SettingActivity>()
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -167,7 +164,7 @@ class SelectDishActivity : BaseActivity() {
|
||||
appViewModel.deleteCookFoodAndGoods(cookMode = 0, foodId = foodId, onFinish = action)
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent?) {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
runCatching {
|
||||
val isConfigPage = intent?.getBooleanExtra(IS_CONFIG_PAGE, false) ?: false
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.DeviceRole
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.ActivitySettingBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
||||
import com.shuwei.dish.match.ui.fragment.CollectFragment
|
||||
import com.shuwei.dish.match.ui.fragment.DeviceConfigFragment
|
||||
import com.shuwei.dish.match.utils.CameraUtils
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
/**
|
||||
* 设置Activity
|
||||
* 功能:管理多个设置相关的Fragment,支持Fragment切换
|
||||
*/
|
||||
class SettingActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "SettingActivity"
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivitySettingBinding
|
||||
private val cameraUtils: CameraUtils by lazy {
|
||||
CameraUtils(this)
|
||||
}
|
||||
private lateinit var previewView: PreviewView
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivitySettingBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground()
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "设置"
|
||||
}, rightIconActon = {
|
||||
it.gone()
|
||||
})
|
||||
|
||||
// 默认显示设备配置Fragment
|
||||
if (savedInstanceState == null) {
|
||||
showDeviceConfigFragment()
|
||||
}
|
||||
|
||||
initUI()
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化UI和事件监听
|
||||
*/
|
||||
private fun initUI() {
|
||||
// 设备配置按钮点击事件
|
||||
binding.btnDeviceConfig.setOnClickListener {
|
||||
showDeviceConfigFragment()
|
||||
updateButtonColors(isDeviceConfigSelected = true)
|
||||
}
|
||||
|
||||
// 菜品采集按钮点击事件
|
||||
binding.btnFoodCollect.setOnClickListener {
|
||||
checkCameraPermissionAndShowFragment()
|
||||
updateButtonColors(isDeviceConfigSelected = false)
|
||||
}
|
||||
|
||||
// // 设备角色只读展示,角色由设备 ID 决定,不可手动切换
|
||||
// updateRoleButtonText()
|
||||
// binding.btnDeviceRole.isEnabled = false
|
||||
|
||||
// 主设备显示「秤数据监控」入口
|
||||
if (GlobalData.deviceRole == DeviceRole.MASTER) {
|
||||
binding.btnScaleMonitor.visible()
|
||||
binding.btnScaleMonitor.setOnClickListener {
|
||||
startActivity<MasterScaleActivity>()
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化按钮颜色(默认设备配置为选中状态)
|
||||
updateButtonColors(isDeviceConfigSelected = true)
|
||||
}
|
||||
|
||||
// /** 刷新角色按钮文字 */
|
||||
// private fun updateRoleButtonText() {
|
||||
// val roleLabel = if (GlobalData.deviceRole == DeviceRole.MASTER) "主设备" else "子设备"
|
||||
// binding.btnDeviceRole.text = "设备角色:$roleLabel"
|
||||
// }
|
||||
|
||||
/**
|
||||
* 更新底部菜单按钮的颜色状态
|
||||
* @param isDeviceConfigSelected 设备配置按钮是否被选中
|
||||
*/
|
||||
private fun updateButtonColors(isDeviceConfigSelected: Boolean) {
|
||||
val selectedColor = "#FFFFFF".toColorInt() // 选中颜色(白色)
|
||||
val unselectedColor = "#5E7585".toColorInt() // 未选中颜色(灰色)
|
||||
|
||||
if (isDeviceConfigSelected) {
|
||||
// 设备配置按钮:选中状态
|
||||
binding.btnDeviceConfig.apply {
|
||||
setTextColor(selectedColor)
|
||||
textSize = 28f
|
||||
setTypeface(null, android.graphics.Typeface.BOLD)
|
||||
background = ContextCompat.getDrawable(this@SettingActivity, R.drawable.bg_btn_underline)
|
||||
}
|
||||
// 采集食材按钮:未选中状态
|
||||
binding.btnFoodCollect.apply {
|
||||
setTextColor(unselectedColor)
|
||||
textSize = 26f
|
||||
setTypeface(null, android.graphics.Typeface.NORMAL)
|
||||
background = null
|
||||
}
|
||||
} else {
|
||||
// 设备配置按钮:未选中状态
|
||||
binding.btnDeviceConfig.apply {
|
||||
setTextColor(unselectedColor)
|
||||
textSize = 26f
|
||||
setTypeface(null, android.graphics.Typeface.NORMAL)
|
||||
background = null
|
||||
}
|
||||
// 采集食材按钮:选中状态
|
||||
binding.btnFoodCollect.apply {
|
||||
setTextColor(selectedColor)
|
||||
textSize = 28f
|
||||
setTypeface(null, android.graphics.Typeface.BOLD)
|
||||
background = ContextCompat.getDrawable(this@SettingActivity, R.drawable.bg_btn_underline)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查相机权限并显示 CollectFragment
|
||||
*/
|
||||
@SuppressLint("ObsoleteSdkInt")
|
||||
private fun checkCameraPermissionAndShowFragment() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
||||
// Android 6.0 以下,直接显示 Fragment
|
||||
showFragment(fragmentList[1])
|
||||
return
|
||||
}
|
||||
if (ContextCompat.checkSelfPermission(
|
||||
this,
|
||||
Manifest.permission.CAMERA
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
// 权限已授予,直接显示 Fragment
|
||||
showFragment(fragmentList[1])
|
||||
} else {
|
||||
// 权限未授予,申请权限
|
||||
requestPermission(Manifest.permission.CAMERA) { isGranted ->
|
||||
if (isGranted) {
|
||||
// 权限已授予,显示 CollectFragment
|
||||
showFragment(fragmentList[1])
|
||||
} else {
|
||||
// 权限被拒绝
|
||||
toast("暂无相机权限,无法使用菜品采集功能")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化相机
|
||||
* @param container 相机预览容器
|
||||
*/
|
||||
fun initCamera(container: ViewGroup) {
|
||||
cameraUtils.initCamera()
|
||||
val previewBinding =
|
||||
LayoutCameraPreviewBinding.inflate(layoutInflater, container)
|
||||
previewView = previewBinding.previewView.also {
|
||||
it.updateLayoutParams {
|
||||
width = 456.dp
|
||||
height = 342.dp
|
||||
}
|
||||
}
|
||||
cameraUtils.setPreviewController(previewView)
|
||||
}
|
||||
|
||||
/**
|
||||
* Activity 恢复时绑定相机
|
||||
*/
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
cameraUtils.bind()
|
||||
}
|
||||
|
||||
/**
|
||||
* Activity 暂停时解绑相机
|
||||
*/
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
cameraUtils.unbind()
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供给 Fragment 调用的拍照方法
|
||||
*/
|
||||
fun takePhoto(succCallback: (Uri) -> Unit, failCallback: (msg: String) -> Unit = {}) {
|
||||
cameraUtils.takePhoto(succCallback = succCallback, failCallback = failCallback)
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示设备配置Fragment
|
||||
*/
|
||||
private fun showDeviceConfigFragment() {
|
||||
// val fragment = DeviceConfigFragment.newInstance()
|
||||
// supportFragmentManager.beginTransaction()
|
||||
// .replace(binding.fragmentContainer.id, fragment)
|
||||
// .addToBackStack(null)
|
||||
// .commit()
|
||||
showFragment(fragmentList[0])
|
||||
}
|
||||
|
||||
private val fragmentList = mutableListOf<Fragment>().apply {
|
||||
add(DeviceConfigFragment.newInstance())
|
||||
add(CollectFragment())
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示指定的 Fragment
|
||||
* 使用 add/show/hide 方式管理 Fragment,避免重复创建
|
||||
* 已添加的 Fragment 直接显示,未添加的 Fragment 先添加再显示
|
||||
*/
|
||||
private fun showFragment(fragment: Fragment) {
|
||||
runCatching {
|
||||
supportFragmentManager.beginTransaction().apply {
|
||||
// 如果 Fragment 还未添加到容器中,则添加
|
||||
if (!fragment.isAdded) {
|
||||
add(binding.fragmentContainer.id, fragment)
|
||||
} else {
|
||||
// 已添加过,直接显示
|
||||
show(fragment)
|
||||
}
|
||||
|
||||
// 隐藏其他 Fragment
|
||||
fragmentList.forEach { otherFragment ->
|
||||
if (otherFragment != fragment && otherFragment.isAdded) {
|
||||
hide(otherFragment)
|
||||
}
|
||||
}
|
||||
|
||||
commit()
|
||||
}
|
||||
}.onFailure {
|
||||
it.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.ActivitySlaveBinding
|
||||
import com.shuwei.dish.match.databinding.ListItemScaleRowBinding
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
|
||||
/**
|
||||
* 子设备专属页面(小屏幕设备使用)
|
||||
* 仅展示本机秤的实时数据和主设备连接状态
|
||||
* 布局简洁,适配小屏幕
|
||||
*/
|
||||
class SlaveActivity : BaseActivity() {
|
||||
|
||||
private lateinit var binding: ActivitySlaveBinding
|
||||
|
||||
/** 本机秤数据列表:address → (weight, state) */
|
||||
private data class ScaleItem(val address: Int, val weight: Double, val state: Int)
|
||||
|
||||
private val scaleList = mutableListOf<ScaleItem>()
|
||||
private val adapter = ScaleAdapter(scaleList)
|
||||
|
||||
/** 已连接的主设备数量(有连接即代表主设备在线) */
|
||||
private var masterConnected = false
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivitySlaveBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground()
|
||||
|
||||
binding.tvDeviceId.text = "设备:${GlobalData.deviceId}"
|
||||
binding.tvDeviceIp.text = "IP:${getLocalIpAddress()}"
|
||||
binding.rvScaleList.layoutManager = LinearLayoutManager(this)
|
||||
binding.rvScaleList.itemAnimator = null // 关闭默认动画,避免数据频繁更新时出现闪烁错乱
|
||||
binding.rvScaleList.adapter = adapter
|
||||
|
||||
updateMasterStatus(ScaleServiceManager.isMasterConnected)
|
||||
listenLocalScales()
|
||||
listenMasterConnection()
|
||||
addBackKeyListener()
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用返回键,防止退回 InitActivity 后重复打开本页
|
||||
*/
|
||||
private fun addBackKeyListener() {
|
||||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
// 禁用返回键,不执行任何操作
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅主设备连接状态,回调在非主线程,切换到主线程更新 UI
|
||||
*/
|
||||
private fun listenMasterConnection() {
|
||||
ScaleServiceManager.onMasterConnectionChanged = { connected ->
|
||||
runOnUiThread { updateMasterStatus(connected) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听本机 WeightUtil 回调,实时刷新秤列表
|
||||
*/
|
||||
private fun listenLocalScales() {
|
||||
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||
runOnUiThread {
|
||||
val idx = scaleList.indexOfFirst { it.address == address }
|
||||
val item = ScaleItem(address, weight, state)
|
||||
if (idx >= 0) {
|
||||
scaleList[idx] = item
|
||||
adapter.notifyItemChanged(idx)
|
||||
} else {
|
||||
scaleList.add(item)
|
||||
scaleList.sortBy { it.address }
|
||||
adapter.notifyDataSetChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新主设备连接状态文字
|
||||
* 由 ScaleWebSocketServer 的 onOpen/onClose 回调驱动(可在后续扩展中接入)
|
||||
*/
|
||||
@SuppressLint("SetTextI18n")
|
||||
fun updateMasterStatus(connected: Boolean) {
|
||||
masterConnected = connected
|
||||
binding.tvMasterStatus.text = if (connected) "主设备:已连接 ✓" else "主设备:未连接"
|
||||
binding.tvMasterStatus.setTextColor(
|
||||
getColor(if (connected) android.R.color.holo_green_dark else android.R.color.holo_red_light)
|
||||
)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
ScaleServiceManager.onMasterConnectionChanged = null
|
||||
WeightUtil.removeWeightListener(TAG)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TAG = "SlaveActivity"
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本机局域网 IP,委托给 NetworkUtil 统一处理版本兼容
|
||||
* 获取失败时返回"未知"
|
||||
*/
|
||||
private fun getLocalIpAddress(): String {
|
||||
return NetworkUtil.getLocalIpAddress(this).ifEmpty { "未知" }
|
||||
}
|
||||
|
||||
private class ScaleAdapter(private val data: List<ScaleItem>) :
|
||||
RecyclerView.Adapter<ScaleAdapter.VH>() {
|
||||
|
||||
inner class VH(val binding: ListItemScaleRowBinding) :
|
||||
RecyclerView.ViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = VH(
|
||||
ListItemScaleRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
|
||||
)
|
||||
|
||||
override fun getItemCount() = data.size
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
val item = data[position]
|
||||
val stateStr = when (item.state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
else -> "${item.state}"
|
||||
}
|
||||
holder.binding.tvScaleLabel.text = "秤 ${item.address}"
|
||||
holder.binding.tvWeight.text = "${item.weight} g"
|
||||
holder.binding.tvState.text = stateStr
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package com.shuwei.dish.match.ui.fragment
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.FoodCollectionAdapter
|
||||
import com.shuwei.dish.match.base.BaseFragment
|
||||
import com.shuwei.dish.match.databinding.FragmentCollectBinding
|
||||
import com.shuwei.dish.match.dialog.Loading
|
||||
import com.shuwei.dish.match.objbox.FoodCollectionBean
|
||||
import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.ui.SettingActivity
|
||||
import com.shuwei.dish.match.utils.BitmapSaver
|
||||
import com.shuwei.dish.match.utils.Debouncer
|
||||
import com.shuwei.dish.match.utils.ImageUtil
|
||||
import com.shuwei.dish.match.utils.LogSaveUtil
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
class CollectFragment : BaseFragment<FragmentCollectBinding>() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "CollectFragment"
|
||||
const val MAX_COUNT = 9
|
||||
}
|
||||
|
||||
private var selectedFoodId: String? = ""
|
||||
private var selectedFoodName: String? = ""
|
||||
|
||||
private val foodCollectionList = mutableListOf<FoodCollectionBean>().apply {
|
||||
repeat(MAX_COUNT) {
|
||||
add(FoodCollectionBean(isShowCamera = true))
|
||||
}
|
||||
}
|
||||
|
||||
// private val searchFoodList = mutableListOf<FoodInfo>()
|
||||
// private var settingActivity: SettingActivity? = null
|
||||
// private var checkedItem: FoodInfo? = null
|
||||
// private val searchFoodAdapter by lazy {
|
||||
// CollectFoodListAdapter(searchFoodList).apply {
|
||||
// setOnItemClickListener { adapter, view, position ->
|
||||
// searchFoodList.forEachIndexed { index, item -> item.isChecked = index == position }
|
||||
// checkedItem = searchFoodList[position]
|
||||
// notifyDataSetChanged()
|
||||
// selectedFoodId = checkedItem!!.foodId
|
||||
// selectedFoodName = checkedItem!!.foodName
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
private val debouncer = Debouncer(2000)
|
||||
private lateinit var settingActivity: SettingActivity
|
||||
|
||||
private val collectionAdapter: FoodCollectionAdapter by lazy {
|
||||
FoodCollectionAdapter(foodCollectionList).apply {
|
||||
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
|
||||
foodCollectionList[position].let {
|
||||
it.bitmap = null
|
||||
it.imageVector = null
|
||||
it.imageFile = null
|
||||
it.imageUri = null
|
||||
it.isShowCamera = true
|
||||
it.isFinish = false
|
||||
it.uploadSuccess = false
|
||||
}
|
||||
notifyItemChanged(position)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
override fun inflateBinding(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?
|
||||
): FragmentCollectBinding {
|
||||
return FragmentCollectBinding.inflate(LayoutInflater.from(context))
|
||||
}
|
||||
|
||||
//typealias CameraCallback = (Uri) -> Unit
|
||||
|
||||
private val cameraCallback: (Uri) -> Unit = { uri ->
|
||||
try {
|
||||
val index = foodCollectionList.indexOfFirst { it.imageFile == null }
|
||||
if (index == -1) {
|
||||
toast("每次只允许保存${MAX_COUNT}条数据")
|
||||
hideWaitingDialog()
|
||||
rerurn@ cameraCallback
|
||||
}
|
||||
activity?.runOnUiThread {
|
||||
foodCollectionList[index].let {
|
||||
it.imageVector = null
|
||||
it.bitmap = null
|
||||
it.isShowCamera = false
|
||||
it.imageFile = null
|
||||
it.imageUri = uri
|
||||
}
|
||||
collectionAdapter.notifyItemChanged(index)
|
||||
}
|
||||
// hideWaitingDialog()
|
||||
Thread {
|
||||
ImageUtil.uriToBitmap(requireActivity(), uri)?.let { bitmap ->
|
||||
getImageVector(index, bitmap)
|
||||
}
|
||||
}.start()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
hideWaitingDialog()
|
||||
toast("程序异常${e.message}")
|
||||
log("程序异常${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun getImageVector(index: Int, bitmap: Bitmap) {
|
||||
// val bitmap = BitmapCropper.cropCenter(
|
||||
// original = srcBmp,
|
||||
// targetWidth = 900, targetHeight = 900,
|
||||
//// offsetX = 30, offsetY = 100
|
||||
// )
|
||||
val imageVector = try {
|
||||
FoodModule.bitmap2FloatArray(bitmap, false)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
toast("操作失败")
|
||||
log("操作失败:${e.message}")
|
||||
hideWaitingDialog()
|
||||
return
|
||||
}
|
||||
val file = BitmapSaver.saveToAppFilesDir(
|
||||
bitmap, requireActivity(), "IMG_CROP_${System.currentTimeMillis()}.jpg"
|
||||
)
|
||||
log("${this.javaClass.simpleName}-cameraCallback-裁剪bitmap保存文件路径:${file?.absolutePath}")
|
||||
|
||||
activity?.runOnUiThread {
|
||||
foodCollectionList[index].let {
|
||||
it.imageVector = imageVector
|
||||
it.bitmap = null
|
||||
it.isShowCamera = false
|
||||
it.imageFile = file
|
||||
}
|
||||
collectionAdapter.notifyItemChanged(index)
|
||||
}
|
||||
if (bitmap.isRecycled.not()) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
hideWaitingDialog()
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun takePhoto() {
|
||||
val count = foodCollectionList.count { it.bitmap != null }
|
||||
if (count >= MAX_COUNT) {
|
||||
toast("每次只允许保存${MAX_COUNT}条数据")
|
||||
return
|
||||
}
|
||||
val index = foodCollectionList.indexOfFirst { it.imageFile == null }
|
||||
if (index == -1) {
|
||||
toast("每次只允许保存${MAX_COUNT}条数据")
|
||||
hideWaitingDialog()
|
||||
return
|
||||
}
|
||||
showWaitingDialog("采集中……")
|
||||
settingActivity.takePhoto(succCallback = cameraCallback, failCallback = { errMsg ->
|
||||
hideWaitingDialog()
|
||||
// toast("拍照异常,请重新操作")
|
||||
// if (cameraErrorCount >= 10) {
|
||||
// toast("拍照异常,请重新操作")
|
||||
// log("拍照异常,请重新操作:$errMsg")
|
||||
// cameraErrorCount = 0
|
||||
// return@takePhoto
|
||||
// }
|
||||
// cameraErrorCount++
|
||||
// takePhoto()
|
||||
})
|
||||
}
|
||||
|
||||
override fun initialize() {
|
||||
settingActivity = activity as SettingActivity
|
||||
// 首次显示 CollectFragment 时初始化相机
|
||||
settingActivity.initCamera(binding.flCameraPreview)
|
||||
|
||||
binding.rvFoodList.let {
|
||||
it.layoutManager =
|
||||
GridLayoutManager(requireActivity(), 3, GridLayoutManager.VERTICAL, false)
|
||||
it.adapter = collectionAdapter
|
||||
}
|
||||
|
||||
binding.btnFoodSearch.setOnClickListener {
|
||||
searchFood()
|
||||
}
|
||||
|
||||
binding.btnSave.setOnClickListener {
|
||||
// if (checkedItem == null || checkedItem!!.isChecked.not()) {
|
||||
// toast("请选择菜品名称")
|
||||
// return@setOnClickListener
|
||||
// }
|
||||
// val count = foodCollectionList.count { it.imageFile != null }
|
||||
// if (count == 0) {
|
||||
// toast("请拍摄菜品照片")
|
||||
// return@setOnClickListener
|
||||
// }
|
||||
// upload()
|
||||
}
|
||||
|
||||
binding.editFoodName.setOnEditorActionListener { v, actionId, event ->
|
||||
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
|
||||
searchFood()
|
||||
val imm =
|
||||
v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
imm.hideSoftInputFromWindow(v.windowToken, 0)
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
binding.btnCollectedFood.setOnClickListener {
|
||||
// startActivity(Intent(requireActivity(), CollectedFoodActivity::class.java))
|
||||
}
|
||||
binding.btnTakePhoto.clickWithDebounce {
|
||||
val count = foodCollectionList.count { it.bitmap != null }
|
||||
if (count >= MAX_COUNT) {
|
||||
toast("每次只允许保存${MAX_COUNT}条数据")
|
||||
return@clickWithDebounce
|
||||
}
|
||||
takePhoto()
|
||||
}
|
||||
binding.btnClearData.setOnClickListener { clearData() }
|
||||
// binding.rvSearchFood.let {
|
||||
// it.layoutManager = GridLayoutManager(context, 2)
|
||||
// it.adapter = searchFoodAdapter
|
||||
// }
|
||||
|
||||
searchFood()
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun upload() {
|
||||
// lifecycleScope.launch {
|
||||
// val totalFileCount = foodCollectionList.count { it.imageFile != null }
|
||||
// showWaitingDialog2("图片上传中0/$totalFileCount")
|
||||
// val params = HashMap<String, RequestBody>()
|
||||
// //params["placeId"] = restId.toRequestBody()
|
||||
// params["foodId"] = checkedItem!!.foodId.toRequestBody()
|
||||
// params["foodName"] = checkedItem!!.foodName!!.toRequestBody()
|
||||
// params["version"] = GlobalData.foodModelVersion.toRequestBody()
|
||||
//
|
||||
// ImageUploader(totalList = foodCollectionList, uploadImage = { batch ->
|
||||
// val files = batch.map { it.imageFile }
|
||||
// val foodVectorList = batch.filter { it.imageVector != null }.map {
|
||||
// it.imageVector!!.joinToString(
|
||||
// separator = ",", prefix = "[", postfix = "]"
|
||||
// )
|
||||
// }
|
||||
// val foodVectorJson =
|
||||
// foodVectorList.joinToString(separator = ",", prefix = "[", postfix = "]")
|
||||
// log("json=$foodVectorJson")
|
||||
// params["foodVector"] = foodVectorJson.toRequestBody()
|
||||
// viewModel?.uploadCollectFoodPics(files, params)
|
||||
// }, onProgress = { count, batch, idList ->
|
||||
// //batch.forEach {
|
||||
// // it.uploadSuccess = true
|
||||
// //}
|
||||
// runBlocking {
|
||||
// activity?.runOnUiThread {
|
||||
// showWaitingDialog("图片上传中$count/$totalFileCount")
|
||||
// }
|
||||
// val foodList = batch.mapIndexed { index, it ->
|
||||
// Food(
|
||||
// collectId = if (index < idList.size) idList[index] else null,
|
||||
// foodId = checkedItem!!.foodId,
|
||||
// foodName = checkedItem!!.foodName,
|
||||
// foodVector = it.imageVector,
|
||||
// version = GlobalData.foodModelVersion
|
||||
// )
|
||||
// }
|
||||
// ObjectBox.putAll(foodList)
|
||||
// activity?.runOnUiThread {
|
||||
// batch.forEach { it.isFinish = true }
|
||||
// collectionAdapter.notifyDataSetChanged()
|
||||
// }
|
||||
// }
|
||||
// }, onError = {
|
||||
// activity?.runOnUiThread {
|
||||
// binding.root.postDelayed({
|
||||
// hideWaitingDialog()
|
||||
// toast("上传失败,请稍后重试")
|
||||
// }, 1000)
|
||||
// }
|
||||
// }, onComplete = {
|
||||
// //vectorThread()
|
||||
// binding.root.postDelayed({
|
||||
// hideWaitingDialog()
|
||||
// toast("上传成功")
|
||||
// }, 1000)
|
||||
// }).processUploads()
|
||||
// }
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun searchFood() {
|
||||
debouncer.debounce {
|
||||
searchByFoodName(binding.editFoodName.text.toString()) {
|
||||
// searchFoodList.clear()
|
||||
// searchFoodList.addAll(it)
|
||||
// searchFoodAdapter.notifyDataSetChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var clickIndex = -1
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun clearData() {
|
||||
foodCollectionList.forEach {
|
||||
it.bitmap = null
|
||||
it.imageVector = null
|
||||
it.imageFile = null
|
||||
it.imageUri = null
|
||||
it.isShowCamera = true
|
||||
it.isFinish = false
|
||||
it.uploadSuccess = false
|
||||
}
|
||||
collectionAdapter.notifyDataSetChanged()
|
||||
|
||||
clickIndex = -1
|
||||
binding.editFoodName.setText("")
|
||||
searchFood()
|
||||
}
|
||||
|
||||
private var isFirstOpen = true
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (isVisible.not()) return
|
||||
binding.llCameraFlag.run {
|
||||
visibility = View.VISIBLE
|
||||
postDelayed({
|
||||
visibility = View.GONE
|
||||
}, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
binding.llCameraFlag.visibility = View.VISIBLE
|
||||
}
|
||||
|
||||
private fun log(msg: String) {
|
||||
Log.d(TAG, "log: $msg")
|
||||
LogSaveUtil.saveLogFile(msg)
|
||||
}
|
||||
|
||||
private fun searchByFoodName(name: String, block: (String) -> Unit) {}
|
||||
private fun hideWaitingDialog() {
|
||||
settingActivity.dismissLoading()
|
||||
}
|
||||
|
||||
private fun showWaitingDialog(msg: String) {
|
||||
if (Loading.isShowing()) {
|
||||
Loading.updateContent(msg)
|
||||
return
|
||||
}
|
||||
settingActivity.showLoading(msg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package com.shuwei.dish.match.ui.fragment
|
||||
|
||||
import android.graphics.Typeface
|
||||
import android.os.Bundle
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.text.style.AbsoluteSizeSpan
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.LineHeightSpan
|
||||
import android.text.style.StyleSpan
|
||||
import android.util.Log
|
||||
import android.util.SparseArray
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.core.view.forEach
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.base.BaseFragment
|
||||
import com.shuwei.dish.match.databinding.FragmentDeviceConfigBinding
|
||||
import com.shuwei.dish.match.db.AppRepository
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.dialog.SeasoningSearchDialog
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.entity.ResetReasoningRecord
|
||||
import com.shuwei.dish.match.adapter.TextCellAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.JsonAssetsLoader
|
||||
import com.shuwei.dish.match.utils.MultiClickDetector
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.appendText
|
||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import com.shuwei.dish.match.viewmodel.AppViewModel
|
||||
import com.shuwei.dish.match.viewmodel.factory.AppFactory
|
||||
import com.shuwei.dish.match.databinding.LayoutFoodRemindBinding
|
||||
import com.shuwei.dish.match.ui.SamplingListActivity
|
||||
import com.shuwei.dish.match.ui.SelectDishActivity
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
|
||||
/**
|
||||
* 设备配置Fragment
|
||||
* 功能:支持三种模式选择(制作、采样、品控),调料网格配置管理
|
||||
*/
|
||||
class DeviceConfigFragment : BaseFragment<FragmentDeviceConfigBinding>() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "DeviceConfigFragment"
|
||||
const val COOK_MODE = "cookMode"
|
||||
|
||||
val modeList = listOf<ModeBean>(
|
||||
ModeBean("制作模式", "菜品快速制作,记录熟重"),
|
||||
ModeBean("采样模式", "菜品快速制作,记录熟重"),
|
||||
ModeBean("品控模式", "菜品快速制作,记录熟重")
|
||||
)
|
||||
|
||||
fun newInstance(cookMode: Int = 0): DeviceConfigFragment {
|
||||
return DeviceConfigFragment().apply {
|
||||
arguments = Bundle().apply {
|
||||
putInt(COOK_MODE, cookMode)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ModeBean(
|
||||
var modeName: String,
|
||||
var modeDesc: String
|
||||
)
|
||||
|
||||
private lateinit var appViewModel: AppViewModel
|
||||
|
||||
private var cookMode: Int = 0
|
||||
private val weightArray = SparseArray<Double>()
|
||||
private val addressArray = AddressUtil.getWeighAddressArray()
|
||||
private var seasoningItems = mutableListOf<SeasoningEntity>()
|
||||
private val detector = MultiClickDetector(targetCount = 10, intervalMs = 800)
|
||||
|
||||
override fun inflateBinding(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?
|
||||
): FragmentDeviceConfigBinding {
|
||||
return FragmentDeviceConfigBinding.inflate(inflater, container, false)
|
||||
}
|
||||
|
||||
override fun initialize(){
|
||||
cookMode = arguments?.getInt(COOK_MODE, 0) ?: 0
|
||||
initViewModel()
|
||||
initUI()
|
||||
addWeighListener()
|
||||
addGridItemListener()
|
||||
loadSeasoning()
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化ViewModel
|
||||
*/
|
||||
private fun initViewModel() {
|
||||
val db = BaseApp.instance!!.database
|
||||
val factory = AppFactory(AppRepository(db.appDao()))
|
||||
appViewModel = ViewModelProvider(this, factory)[AppViewModel::class.java]
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化UI
|
||||
*/
|
||||
private fun initUI() {
|
||||
loadQualitySpan(isEnable = false)
|
||||
when (cookMode) {
|
||||
1 -> {
|
||||
binding.rbModeCook.isChecked = true
|
||||
binding.rbModeSampling.isChecked = false
|
||||
loadCookSpan(isClicked = true)
|
||||
loadSamplingSpan()
|
||||
}
|
||||
|
||||
2 -> {
|
||||
binding.rbModeCook.isChecked = false
|
||||
binding.rbModeSampling.isChecked = true
|
||||
loadCookSpan()
|
||||
loadSamplingSpan(isClicked = true)
|
||||
}
|
||||
|
||||
else -> {
|
||||
binding.rbModeCook.isChecked = true
|
||||
binding.rbModeSampling.isChecked = false
|
||||
loadCookSpan(isClicked = true)
|
||||
loadSamplingSpan()
|
||||
}
|
||||
}
|
||||
|
||||
binding.rbModeCook.setOnClickListener {
|
||||
SpTool.put(SpTool.LAUNCH_PAGE_TYPE, 0)
|
||||
binding.rbModeCook.isChecked = true
|
||||
binding.rbModeSampling.isChecked = false
|
||||
loadCookSpan(isClicked = true)
|
||||
loadSamplingSpan()
|
||||
activity?.startActivity<SelectDishActivity> {
|
||||
putExtra(SelectDishActivity.IS_CONFIG_PAGE, true)
|
||||
}
|
||||
activity?.finish()
|
||||
}
|
||||
binding.rbModeSampling.setOnClickListener {
|
||||
SpTool.put(SpTool.LAUNCH_PAGE_TYPE, 1)
|
||||
binding.rbModeCook.isChecked = false
|
||||
binding.rbModeSampling.isChecked = true
|
||||
loadCookSpan()
|
||||
loadSamplingSpan(isClicked = true)
|
||||
activity?.startActivity<SamplingListActivity> {
|
||||
putExtra(SamplingListActivity.IS_CONFIG_PAGE, true) }
|
||||
activity?.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加称重监听
|
||||
*/
|
||||
private fun addWeighListener() {
|
||||
WeightUtil.addWeightListener(
|
||||
weightKey = TAG,
|
||||
getWeight = { address, state, weight ->
|
||||
Log.d(TAG, "addWeighListener: address=$address,stat=$state,weight=$weight")
|
||||
weightArray.put(address, weight)
|
||||
val item = seasoningItems.firstOrNull { address == addressArray[it.sort] }
|
||||
item?.let {
|
||||
it.useWeight = weight.toDouble()
|
||||
updateGridData(it)
|
||||
}
|
||||
Log.d(TAG, "addWeighListener: update-----------------------")
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加网格项点击监听
|
||||
*/
|
||||
private fun addGridItemListener() {
|
||||
binding.include.root.forEach { child ->
|
||||
child.clickWithDebounce {
|
||||
val sort = child.tag.toString().toInt()
|
||||
val entity = seasoningItems.firstOrNull { it.sort == sort } ?: SeasoningEntity()
|
||||
clickGridItem(sort, entity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载调料数据
|
||||
*/
|
||||
private fun loadSeasoning() {
|
||||
appViewModel.loadSeasoning {
|
||||
seasoningItems.clear()
|
||||
seasoningItems.addAll(it)
|
||||
initConfigData()
|
||||
setGridData(seasoningItems)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化配置数据,确保有12个调料位置
|
||||
*/
|
||||
private fun initConfigData() {
|
||||
repeat(12) { num ->
|
||||
val firstOne = seasoningItems.firstOrNull { it.sort == num }
|
||||
if (firstOne == null) {
|
||||
seasoningItems.add(SeasoningEntity().also { it.sort = num })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置网格数据
|
||||
*/
|
||||
private fun setGridData(list: MutableList<SeasoningEntity>) {
|
||||
val gridLayout = binding.include.root
|
||||
list.forEach { entity ->
|
||||
val tag = entity.sort.toString()
|
||||
val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新网格数据
|
||||
*/
|
||||
private fun updateGridData(entity: SeasoningEntity) {
|
||||
val gridLayout = binding.include.root
|
||||
val tag = entity.sort.toString()
|
||||
val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
}
|
||||
|
||||
/**
|
||||
* 点击网格项,打开调料搜索对话框
|
||||
*/
|
||||
private fun clickGridItem(sort: Int, entity: SeasoningEntity) {
|
||||
val currentAddress = AddressUtil.getWeighAddressArray().get(sort)
|
||||
SeasoningSearchDialog(
|
||||
weighIndex = sort,
|
||||
weighAddress = currentAddress,
|
||||
clickName = entity.goodsName
|
||||
).show(requireActivity() as BaseActivity) { item ->
|
||||
syncItem(entity, item)
|
||||
// 3-调料
|
||||
entity.materialType = 3
|
||||
entity.sort = sort
|
||||
saveSeasoning(entity) {
|
||||
val tag = sort.toString()
|
||||
val gridLayout = binding.include.root
|
||||
val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步调料项数据
|
||||
*/
|
||||
private fun syncItem(oldItem: SeasoningEntity, newItem: SeasoningEntity) {
|
||||
oldItem.run {
|
||||
goodsId = newItem.goodsId
|
||||
goodsName = newItem.goodsName
|
||||
goodsOrRelationCode = newItem.goodsOrRelationCode
|
||||
relateionType = newItem.relateionType
|
||||
materialType = newItem.materialType
|
||||
allEdible = newItem.allEdible
|
||||
useWeight = newItem.useWeight
|
||||
popularName = newItem.popularName
|
||||
canteenId = newItem.canteenId
|
||||
relateionType_dictText = newItem.relateionType_dictText
|
||||
|
||||
foodId = newItem.foodId
|
||||
sort = newItem.sort
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存调料数据
|
||||
*/
|
||||
fun saveSeasoning(entity: SeasoningEntity, action: () -> Unit = {}) {
|
||||
appViewModel.saveSeasoning(entity) {
|
||||
action()
|
||||
toast("保存成功")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载品控模式文本样式
|
||||
*/
|
||||
private fun loadQualitySpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
binding.rbModeQuality.text =
|
||||
getModeTextSpan(
|
||||
topText = modeList[2].modeName,
|
||||
bottomText = modeList[2].modeDesc,
|
||||
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载采样模式文本样式
|
||||
*/
|
||||
private fun loadSamplingSpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
binding.rbModeSampling.text =
|
||||
getModeTextSpan(
|
||||
topText = modeList[1].modeName,
|
||||
bottomText = modeList[1].modeDesc,
|
||||
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载制作模式文本样式
|
||||
*/
|
||||
private fun loadCookSpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
binding.rbModeCook.text =
|
||||
getModeTextSpan(
|
||||
topText = modeList[0].modeName,
|
||||
bottomText = modeList[0].modeDesc,
|
||||
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成模式文本样式
|
||||
*/
|
||||
private fun getModeTextSpan(
|
||||
topText: String,
|
||||
topColor: String,
|
||||
bottomText: String,
|
||||
bottomColor: String
|
||||
): SpannableStringBuilder {
|
||||
return buildSpannableString {
|
||||
appendText(
|
||||
topText,
|
||||
ForegroundColorSpan(topColor.toColorInt()),
|
||||
StyleSpan(Typeface.BOLD),
|
||||
AbsoluteSizeSpan(36, true),
|
||||
LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
fm.descent += 10.dp // 增加行间距
|
||||
}
|
||||
)
|
||||
append("\n")
|
||||
appendText(
|
||||
bottomText,
|
||||
ForegroundColorSpan(bottomColor.toColorInt()),
|
||||
AbsoluteSizeSpan(26, true)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
// 移除称重监听
|
||||
WeightUtil.removeWeightListener(TAG)
|
||||
}
|
||||
}
|
||||
@@ -87,8 +87,7 @@ class DishListFragment : BaseFragment<FragmentDishListBinding>() {
|
||||
return FragmentDishListBinding.inflate(inflater, container, false)
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
override fun initialize() {
|
||||
activity = requireActivity() as SelectDishActivity
|
||||
dinnerType = arguments?.getString(DINNER_TYPE, "0") ?: "0"
|
||||
binding.rvDishList.run {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import java.io.BufferedReader
|
||||
import java.io.IOException
|
||||
import java.io.InputStreamReader
|
||||
|
||||
|
||||
object AssetsTool {
|
||||
|
||||
// fun readJson(context: Context, fileName: String): List<String> {
|
||||
// val json = readAssetsFile(context, fileName)
|
||||
// val json2 = json.replace("[[", "[").replaceAfterLast("]]", "]")
|
||||
// val list = json2.split("],")
|
||||
// val resultList = mutableListOf<String>()
|
||||
// var count = 0
|
||||
// val tempList = mutableListOf<String>()
|
||||
// list.forEachIndexed { index, text ->
|
||||
// if (count >= 500) {
|
||||
// val tempJson = "[${tempList.joinToString (",")}]"
|
||||
// resultList.add(tempJson)
|
||||
// tempList.clear()
|
||||
// count = 0
|
||||
// }
|
||||
// val newText = if (index == list.size - 1) text else "${text}]"
|
||||
// tempList.add(newText)
|
||||
// count++
|
||||
// }
|
||||
// if (count < 500) {
|
||||
// val tempJson = "[${tempList.joinToString(",")}]"
|
||||
// resultList.add(tempJson)
|
||||
// }
|
||||
// return resultList
|
||||
// }
|
||||
|
||||
fun readAssetsFile(context: Context, fileName: String): String {
|
||||
val stringBuilder = StringBuilder()
|
||||
try {
|
||||
val bf = BufferedReader(InputStreamReader(context.assets.open(fileName)))
|
||||
bf.useLines { lines -> lines.forEach { stringBuilder.append(it) } }
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
return stringBuilder.toString()
|
||||
}
|
||||
|
||||
fun loadImagesFromAssets(context: Context, subPath: String): MutableList<Bitmap> {
|
||||
val bitmaps: MutableList<Bitmap> = mutableListOf()
|
||||
val assetManager = context.assets
|
||||
|
||||
try {
|
||||
val files = assetManager.list(subPath)
|
||||
files?.forEach { file ->
|
||||
assetManager.open("$subPath/$file").use { `is` ->
|
||||
val bitmap = BitmapFactory.decodeStream(`is`)
|
||||
if (bitmap != null) {
|
||||
bitmaps.add(bitmap)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
return bitmaps
|
||||
}
|
||||
|
||||
fun loadImageBitmapFromAssets(context: Context, imagePath:String, action:(bmp: Bitmap)-> Unit) {
|
||||
context.assets.open(imagePath).use { `is` ->
|
||||
val bitmap = BitmapFactory.decodeStream(`is`)
|
||||
action(bitmap)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Environment
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
|
||||
object BitmapSaver {
|
||||
// 保存到公共目录(需WRITE_EXTERNAL_STORAGE权限)
|
||||
fun saveToPublicDirectory(
|
||||
bitmap: Bitmap,
|
||||
folderName: String = Environment.DIRECTORY_PICTURES,
|
||||
fileName: String,
|
||||
format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG,
|
||||
quality: Int = 100
|
||||
): File? {
|
||||
val dir = Environment.getExternalStoragePublicDirectory(folderName)
|
||||
if (!dir.exists()) dir.mkdirs()
|
||||
|
||||
return saveBitmap(bitmap, File(dir, fileName), format, quality)
|
||||
}
|
||||
|
||||
// 保存到应用私有目录(无需权限)
|
||||
fun saveToAppFilesDir(
|
||||
bitmap: Bitmap,
|
||||
context: Context,
|
||||
fileName: String,
|
||||
format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG,
|
||||
quality: Int = 100
|
||||
): File? {
|
||||
//val dir = context.getExternalFilesDir(null)
|
||||
val dir = File(context.cacheDir, "crop")
|
||||
if (dir.exists().not()) {
|
||||
dir.mkdirs()
|
||||
}
|
||||
return saveBitmap(bitmap, File(dir, fileName), format, quality)
|
||||
}
|
||||
|
||||
private fun saveBitmap(
|
||||
bitmap: Bitmap,
|
||||
outputFile: File,
|
||||
format: Bitmap.CompressFormat,
|
||||
quality: Int
|
||||
): File? {
|
||||
return try {
|
||||
FileOutputStream(outputFile).use { fos ->
|
||||
bitmap.compress(format, quality, fos)
|
||||
fos.flush()
|
||||
}
|
||||
outputFile
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.view.CameraController
|
||||
import androidx.camera.view.LifecycleCameraController
|
||||
import androidx.camera.view.PreviewView
|
||||
|
||||
class CameraUtils(private var activity: ComponentActivity) {
|
||||
|
||||
private var cameraController: LifecycleCameraController? = null
|
||||
private var photoCaptureHelper: PhotoCaptureHelper? = null
|
||||
private var failCallback: ((msg: String) -> Unit)? = null
|
||||
|
||||
// private var isCameraReady = false
|
||||
fun takePhoto(succCallback: (Uri) -> Unit, failCallback: (msg: String) -> Unit = { }) {
|
||||
this.failCallback = failCallback
|
||||
cameraController?.let {
|
||||
if (photoCaptureHelper == null) {
|
||||
initCaptureHelper()
|
||||
}
|
||||
}
|
||||
photoCaptureHelper?.let {
|
||||
it.addSuccessCallback(succCallback)
|
||||
it.bindCameraCallback {
|
||||
bind()
|
||||
}
|
||||
it.takePhoto()
|
||||
}
|
||||
}
|
||||
|
||||
private fun initCaptureHelper() {
|
||||
photoCaptureHelper = PhotoCaptureHelper(
|
||||
context = activity,
|
||||
cameraController = cameraController!!,
|
||||
onSuccess = {},
|
||||
onError = { msg ->
|
||||
//toast(msg)
|
||||
failCallback?.invoke(msg)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fun setPreviewController(previewView: PreviewView?) {
|
||||
if (previewView?.controller == null) {
|
||||
previewView?.controller = cameraController
|
||||
}
|
||||
}
|
||||
|
||||
fun initCamera() {
|
||||
if (cameraController == null) {
|
||||
cameraController = LifecycleCameraController(activity).apply {
|
||||
// 必须设置有效的用例
|
||||
setEnabledUseCases(
|
||||
CameraController.IMAGE_CAPTURE
|
||||
// or CameraController.VIDEO_CAPTURE
|
||||
)
|
||||
cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
|
||||
}
|
||||
bind()
|
||||
}
|
||||
|
||||
// if (isCameraReady.not()) {
|
||||
// try {
|
||||
// cameraController!!.initializationFuture.addListener({
|
||||
// isCameraReady = true
|
||||
// Timber.d("Camera initialized successfully")
|
||||
// }, ContextCompat.getMainExecutor(this))
|
||||
// } catch (e: Exception) {
|
||||
// Timber.d("Camera initialized error = ${e.message}")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
fun bind() {
|
||||
cameraController?.bindToLifecycle(activity)
|
||||
}
|
||||
|
||||
fun unbind() {
|
||||
cameraController?.unbind()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package com.shuwei.dish.match.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 com.shuwei.dish.match.ui.HomeActivity
|
||||
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"
|
||||
private 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getCrashReportFiles(context: Context): Array<File> {
|
||||
val crashDir = File(context.getExternalFilesDir(null), CRASH_REPORTS_DIR)
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动重启app
|
||||
*/
|
||||
private fun restartApp() {
|
||||
// 延迟1秒后重启应用
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
val intent = Intent(context, HomeActivity::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)
|
||||
|
||||
// 这里可以添加其他处理逻辑,比如上传到服务器等
|
||||
restartApp()
|
||||
}
|
||||
|
||||
private fun collectCrashInfo(thread: Thread, ex: Throwable): String {
|
||||
return buildString {
|
||||
// 收集设备信息
|
||||
collectDeviceInfo(this)
|
||||
|
||||
// 收集应用日志
|
||||
try {
|
||||
append("\n\n").append(collectLogs())
|
||||
} catch (e: OutOfMemoryError) {
|
||||
append("collectLogs发生OutOfMemoryError:${e.message}")
|
||||
}
|
||||
|
||||
// 收集线程和异常信息
|
||||
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.firstOrNull() ?: "unknown"}\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(TAG, "Error while collecting device info", e)
|
||||
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 = kotlin.comparisons.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", e)
|
||||
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 = File(context.getExternalFilesDir(null), CRASH_REPORTS_DIR)
|
||||
if (!crashDir.exists() && !crashDir.mkdirs()) {
|
||||
Log.d(TAG,"Failed to create crash report directory")
|
||||
return
|
||||
}
|
||||
|
||||
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", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理旧的崩溃日志
|
||||
*/
|
||||
fun cleanupOldCrashReports(maxAgeDays: Int = 7) {
|
||||
val crashDir = File(context.getExternalFilesDir(null), CRASH_REPORTS_DIR)
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
/**
|
||||
* 防抖工具
|
||||
*/
|
||||
class Debouncer(private val delayMillis: Long = 2000) {
|
||||
private var lastActionTime = 0L
|
||||
|
||||
/**
|
||||
* 执行防抖操作
|
||||
* @param action 要执行的操作
|
||||
* @return Boolean 是否执行了操作 (true=已执行, false=被防抖)
|
||||
*/
|
||||
fun debounce(action: () -> Unit): Boolean {
|
||||
val currentTime = System.currentTimeMillis()
|
||||
if (currentTime - lastActionTime >= delayMillis) {
|
||||
lastActionTime = currentTime
|
||||
action()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 重置防抖计时
|
||||
fun reset() {
|
||||
lastActionTime = 0L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.widget.ImageView
|
||||
import androidx.annotation.DrawableRes
|
||||
import com.bumptech.glide.Glide
|
||||
import com.bumptech.glide.RequestBuilder
|
||||
import com.bumptech.glide.load.DataSource
|
||||
import com.bumptech.glide.load.engine.DiskCacheStrategy
|
||||
import com.bumptech.glide.load.engine.GlideException
|
||||
import com.bumptech.glide.load.resource.bitmap.CircleCrop
|
||||
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
|
||||
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
|
||||
import com.bumptech.glide.request.RequestListener
|
||||
import com.bumptech.glide.request.RequestOptions
|
||||
import com.bumptech.glide.request.target.Target
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Glide图片加载工具类
|
||||
*/
|
||||
object GlideUtils {
|
||||
|
||||
// 默认配置
|
||||
private val defaultOptions = RequestOptions()
|
||||
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
|
||||
.skipMemoryCache(false)
|
||||
|
||||
/**
|
||||
* 普通加载图片
|
||||
* @param context 上下文
|
||||
* @param url 图片地址
|
||||
* @param imageView 目标ImageView
|
||||
* @param placeholderResId 占位图资源ID
|
||||
* @param errorResId 错误图资源ID
|
||||
*/
|
||||
fun loadImage(
|
||||
context: Context,
|
||||
url: Any?,
|
||||
imageView: ImageView,
|
||||
@DrawableRes placeholderResId: Int = 0,
|
||||
@DrawableRes errorResId: Int = 0
|
||||
) {
|
||||
val requestBuilder = Glide.with(context)
|
||||
.load(url)
|
||||
.apply(defaultOptions)
|
||||
|
||||
applyPlaceholder(requestBuilder, placeholderResId, errorResId)
|
||||
.transition(DrawableTransitionOptions.withCrossFade())
|
||||
.into(imageView)
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载圆形图片
|
||||
* @param context 上下文
|
||||
* @param url 图片地址
|
||||
* @param imageView 目标ImageView
|
||||
* @param placeholderResId 占位图资源ID
|
||||
* @param errorResId 错误图资源ID
|
||||
*/
|
||||
fun loadCircleImage(
|
||||
context: Context,
|
||||
url: Any?,
|
||||
imageView: ImageView,
|
||||
@DrawableRes placeholderResId: Int = 0,
|
||||
@DrawableRes errorResId: Int = 0
|
||||
) {
|
||||
val requestBuilder = Glide.with(context)
|
||||
.load(url)
|
||||
.apply(defaultOptions)
|
||||
.transform(CircleCrop())
|
||||
|
||||
applyPlaceholder(requestBuilder, placeholderResId, errorResId)
|
||||
.into(imageView)
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载圆角图片
|
||||
* @param context 上下文
|
||||
* @param url 图片地址
|
||||
* @param imageView 目标ImageView
|
||||
* @param radius 圆角半径(px)
|
||||
* @param placeholderResId 占位图资源ID
|
||||
* @param errorResId 错误图资源ID
|
||||
*/
|
||||
fun loadRoundCornerImage(
|
||||
context: Context,
|
||||
url: Any?,
|
||||
imageView: ImageView,
|
||||
radius: Int,
|
||||
@DrawableRes placeholderResId: Int = 0,
|
||||
@DrawableRes errorResId: Int = 0
|
||||
) {
|
||||
val requestBuilder = Glide.with(context)
|
||||
.load(url)
|
||||
.apply(defaultOptions)
|
||||
.transform(RoundedCorners(radius))
|
||||
|
||||
applyPlaceholder(requestBuilder, placeholderResId, errorResId)
|
||||
.into(imageView)
|
||||
}
|
||||
|
||||
fun loadRoundCornerWitBitmap(
|
||||
context: Context,
|
||||
url: Bitmap,
|
||||
imageView: ImageView,
|
||||
radius: Int,
|
||||
@DrawableRes placeholderResId: Int = 0,
|
||||
@DrawableRes errorResId: Int = 0
|
||||
) {
|
||||
val requestBuilder = Glide.with(context)
|
||||
.load(url)
|
||||
.apply(RequestOptions.bitmapTransform(RoundedCorners(radius)))
|
||||
|
||||
applyPlaceholder(requestBuilder, placeholderResId, errorResId)
|
||||
.into(imageView)
|
||||
}
|
||||
/**
|
||||
* 加载图片并获取Bitmap
|
||||
* @param context 上下文
|
||||
* @param url 图片地址
|
||||
* @param callback 加载回调
|
||||
*/
|
||||
fun loadImageAsBitmap(
|
||||
context: Context,
|
||||
url: Any?,
|
||||
callback: (Bitmap?) -> Unit
|
||||
) {
|
||||
Glide.with(context)
|
||||
.asBitmap()
|
||||
.load(url)
|
||||
.apply(defaultOptions)
|
||||
.addListener(object : RequestListener<Bitmap> {
|
||||
|
||||
override fun onLoadFailed(
|
||||
e: GlideException?,
|
||||
model: Any?,
|
||||
target: Target<Bitmap?>,
|
||||
isFirstResource: Boolean
|
||||
): Boolean {
|
||||
callback(null)
|
||||
return false
|
||||
}
|
||||
|
||||
override fun onResourceReady(
|
||||
resource: Bitmap,
|
||||
model: Any,
|
||||
target: Target<Bitmap?>?,
|
||||
dataSource: DataSource,
|
||||
isFirstResource: Boolean
|
||||
): Boolean {
|
||||
callback(resource)
|
||||
return false
|
||||
}
|
||||
})
|
||||
.submit()
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除内存缓存
|
||||
* @param context 上下文
|
||||
*/
|
||||
fun clearMemoryCache(context: Context) {
|
||||
Glide.get(context).clearMemory()
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除磁盘缓存
|
||||
* @param context 上下文
|
||||
*/
|
||||
fun clearDiskCache(context: Context) {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
Glide.get(context).clearDiskCache()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存文件
|
||||
* @param context 上下文
|
||||
* @param url 图片地址
|
||||
* @param callback 回调
|
||||
*/
|
||||
fun getImageCacheFile(
|
||||
context: Context,
|
||||
url: String,
|
||||
callback: (File?) -> Unit
|
||||
) {
|
||||
Glide.with(context)
|
||||
.downloadOnly()
|
||||
.load(url)
|
||||
.addListener(object : RequestListener<File> {
|
||||
override fun onLoadFailed(
|
||||
e: GlideException?,
|
||||
model: Any?,
|
||||
target: Target<File?>,
|
||||
isFirstResource: Boolean
|
||||
): Boolean {
|
||||
callback(null)
|
||||
return false
|
||||
}
|
||||
|
||||
override fun onResourceReady(
|
||||
resource: File,
|
||||
model: Any,
|
||||
target: Target<File?>?,
|
||||
dataSource: DataSource,
|
||||
isFirstResource: Boolean
|
||||
): Boolean {
|
||||
callback(resource)
|
||||
return false
|
||||
}
|
||||
})
|
||||
.submit()
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停请求
|
||||
* @param context 上下文
|
||||
*/
|
||||
fun pauseRequests(context: Context) {
|
||||
Glide.with(context).pauseRequests()
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复请求
|
||||
* @param context 上下文
|
||||
*/
|
||||
fun resumeRequests(context: Context) {
|
||||
Glide.with(context).resumeRequests()
|
||||
}
|
||||
|
||||
// 私有方法:应用占位图和错误图
|
||||
private fun <T> applyPlaceholder(
|
||||
requestBuilder: RequestBuilder<T>,
|
||||
@DrawableRes placeholderResId: Int,
|
||||
@DrawableRes errorResId: Int
|
||||
): RequestBuilder<T> {
|
||||
return requestBuilder.apply {
|
||||
if (placeholderResId != 0) {
|
||||
placeholder(placeholderResId)
|
||||
}
|
||||
if (errorResId != 0) {
|
||||
error(errorResId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package com.shuwei.dish.match.utils;
|
||||
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Created by Administrator on 2018/11/9.
|
||||
*/
|
||||
public class GpioUtils {
|
||||
|
||||
private static final String TAG = "GpioUtils";
|
||||
|
||||
/*
|
||||
给export申请权限
|
||||
*/
|
||||
public static void upgradeRootPermissionForExport() {
|
||||
upgradeRootPermission("/sys/class/gpio/export");
|
||||
}
|
||||
|
||||
/*
|
||||
配置一个gpio路径
|
||||
*/
|
||||
public static boolean exportGpio(int gpio) {
|
||||
return writeNode("/sys/class/gpio/export", "" + gpio);
|
||||
}
|
||||
|
||||
/*
|
||||
给获取io口的状态的路径申请权限,该方法需要在exportGpio后调用
|
||||
*/
|
||||
public static void upgradeRootPermissionForGpio(int gpio) {
|
||||
upgradeRootPermission("/sys/class/gpio/gpio" + gpio + "/direction");
|
||||
upgradeRootPermission("/sys/class/gpio/gpio" + gpio + "/value");
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
设置io口为输入或输出
|
||||
*/
|
||||
public static boolean setGpioDirection(int gpio, int arg) {
|
||||
String gpioDirection = "";
|
||||
if (arg == 0) gpioDirection = "out";
|
||||
else if (arg == 1) gpioDirection = "in";
|
||||
else return false;
|
||||
return writeNode("/sys/class/gpio/gpio" + gpio + "/direction", gpioDirection);
|
||||
}
|
||||
|
||||
/*
|
||||
获取io口的状态为输出还是输入
|
||||
*/
|
||||
public static String getGpioDirection(int gpio) {
|
||||
String gpioDirection = "";
|
||||
gpioDirection = readNode("/sys/class/gpio/gpio" + gpio + "/direction");
|
||||
return gpioDirection;
|
||||
}
|
||||
|
||||
/*
|
||||
给输出io口写值,高电平或低电平
|
||||
*/
|
||||
public static boolean writeGpioValue(int gpio, String arg) {
|
||||
return writeNode("/sys/class/gpio/gpio" + gpio + "/value", arg);
|
||||
}
|
||||
|
||||
//获取当前gpio是高还是低
|
||||
public static String getGpioValue(int gpio) {
|
||||
return readNode("/sys/class/gpio/gpio" + gpio + "/value");
|
||||
}
|
||||
|
||||
|
||||
private static boolean upgradeRootPermission(String path) {
|
||||
Process process = null;
|
||||
DataOutputStream os = null;
|
||||
try {
|
||||
String cmd = "chmod 777 " + path;
|
||||
process = Runtime.getRuntime().exec("su"); //切换到root帐号
|
||||
os = new DataOutputStream(process.getOutputStream());
|
||||
os.writeBytes(cmd + "\n");
|
||||
os.writeBytes("exit\n");
|
||||
os.flush();
|
||||
process.waitFor();
|
||||
} catch (Exception e) {
|
||||
} finally {
|
||||
try {
|
||||
if (os != null) {
|
||||
os.close();
|
||||
}
|
||||
process.destroy();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
return process.waitFor() == 0;
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean writeNode(String path, String arg) {
|
||||
Log.d(TAG, "Gpio_test set node path: " + path + " arg: " + arg);
|
||||
if (path == null || arg == null) {
|
||||
Log.e(TAG, "set node error");
|
||||
return false;
|
||||
}
|
||||
FileWriter fileWriter = null;
|
||||
BufferedWriter bufferedWriter = null;
|
||||
try {
|
||||
fileWriter = new FileWriter(path);
|
||||
fileWriter.write(arg);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Gpio_test write node error!! path" + path + " arg: " + arg);
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
} finally {
|
||||
try {
|
||||
if (fileWriter != null) {
|
||||
fileWriter.close();
|
||||
}
|
||||
if (bufferedWriter != null) {
|
||||
bufferedWriter.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static long mTime = 0;
|
||||
private static int mFailTimes = 0;
|
||||
|
||||
private static String readNode(String path) {
|
||||
String result = "";
|
||||
|
||||
FileReader fread = null;
|
||||
BufferedReader buffer = null;
|
||||
try {
|
||||
fread = new FileReader(path);
|
||||
buffer = new BufferedReader(fread);
|
||||
String str = null;
|
||||
while ((str = buffer.readLine()) != null) {
|
||||
result = str;
|
||||
break;
|
||||
}
|
||||
mFailTimes = 0;
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "IO Exception");
|
||||
e.printStackTrace();
|
||||
if (mTime == 0 || SystemClock.uptimeMillis() - mTime < 1000) {
|
||||
mFailTimes++;
|
||||
}
|
||||
if (mFailTimes >= 3) {
|
||||
Log.d(TAG, "read format node continuous failed three times, exist thread");
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (buffer != null) {
|
||||
buffer.close();
|
||||
}
|
||||
if (fread != null) {
|
||||
fread.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.InputStream
|
||||
|
||||
object ImageUtil {
|
||||
|
||||
fun uriToBitmap(context: Context, uri: Uri): Bitmap? {
|
||||
return try {
|
||||
val options = BitmapFactory.Options()
|
||||
//options.inSampleSize = 2; // 这会将图片的尺寸缩小到原来的1/2
|
||||
options.inJustDecodeBounds = false
|
||||
// options.inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
options.inPreferredConfig = Bitmap.Config.RGB_565
|
||||
context.contentResolver.openInputStream(uri)?.use { stream ->
|
||||
BitmapFactory.decodeStream(stream, null, options)
|
||||
// BitmapFactory.decodeStream(stream)
|
||||
}
|
||||
context.contentResolver.openInputStream(uri)?.use { stream ->
|
||||
BitmapFactory.decodeStream(stream)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun uriToMultipart(context: Context, uri: Uri, partName: String): MultipartBody.Part? {
|
||||
try {
|
||||
val contentResolver = context.contentResolver
|
||||
val inputStream: InputStream = contentResolver.openInputStream(uri) ?: return null
|
||||
|
||||
// 临时文件(避免直接访问SAF文件)
|
||||
val tempFile = File.createTempFile("upload_", ".jpg", context.cacheDir)
|
||||
|
||||
val outputStream = FileOutputStream(tempFile)
|
||||
inputStream.copyTo(outputStream)
|
||||
inputStream.close()
|
||||
outputStream.close()
|
||||
|
||||
val requestFile = RequestBody.create("image/*".toMediaTypeOrNull(), tempFile)
|
||||
return MultipartBody.Part.createFormData(partName, tempFile.name, requestFile)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.shuwei.dish.match.utils;
|
||||
|
||||
/**
|
||||
* Log统一管理类
|
||||
*/
|
||||
public class L {
|
||||
|
||||
private L() {
|
||||
/* cannot be instantiated */
|
||||
throw new UnsupportedOperationException("cannot be instantiated");
|
||||
}
|
||||
|
||||
public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化
|
||||
private static final String TAG = "mzf";
|
||||
|
||||
// 下面四个是默认tag的函数
|
||||
public static void i(String msg) {
|
||||
if (isDebug)
|
||||
android.util.Log.i(TAG, msg);
|
||||
}
|
||||
|
||||
public static void d(String msg) {
|
||||
if (isDebug)
|
||||
android.util.Log.d(TAG, msg);
|
||||
}
|
||||
|
||||
public static void e(String msg) {
|
||||
if (isDebug)
|
||||
android.util.Log.e(TAG, msg);
|
||||
}
|
||||
|
||||
public static void v(String msg) {
|
||||
if (isDebug)
|
||||
android.util.Log.v(TAG, msg);
|
||||
}
|
||||
|
||||
// 下面是传入自定义tag的函数
|
||||
public static void i(String tag, String msg) {
|
||||
if (isDebug)
|
||||
android.util.Log.i(tag, msg);
|
||||
}
|
||||
|
||||
public static void d(String tag, String msg) {
|
||||
if (isDebug)
|
||||
android.util.Log.d(tag, msg);
|
||||
}
|
||||
|
||||
public static void e(String tag, String msg) {
|
||||
if (isDebug)
|
||||
android.util.Log.e(tag, msg);
|
||||
}
|
||||
|
||||
public static void v(String tag, String msg) {
|
||||
if (isDebug)
|
||||
android.util.Log.v(tag, msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.shuwei.dish.match.utils;
|
||||
|
||||
public class LightManager {
|
||||
private static final String TAG = "LightManager";
|
||||
|
||||
public static void openGreenLight() {
|
||||
L.e(TAG, "openGreenLight");
|
||||
GpioUtils.writeGpioValue(41, "1");
|
||||
}
|
||||
|
||||
public static void closeGreenLight() {
|
||||
L.e(TAG, "closeGreenLight");
|
||||
GpioUtils.writeGpioValue(41, "0");
|
||||
}
|
||||
|
||||
public static void openRedLight() {
|
||||
L.e(TAG, "openRedLight");
|
||||
GpioUtils.writeGpioValue(40, "1");
|
||||
}
|
||||
|
||||
public static void closeRedLight() {
|
||||
L.e(TAG, "closeRedLight");
|
||||
GpioUtils.writeGpioValue(40, "0");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
object LogSaveUtil {
|
||||
|
||||
private const val TAG = "LogSaveUtil"
|
||||
private const val CRASH_REPORTS_DIR = "crash_reports"
|
||||
|
||||
public fun saveLogFile(msg: String) {
|
||||
saveLogFile("yyyy-MM-dd", msg)
|
||||
}
|
||||
|
||||
public fun saveLogFile(pattern: String, msg: String) {
|
||||
try {
|
||||
saveLog(pattern, msg)
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "Error saving crash info to file:${e.message}")
|
||||
try {
|
||||
saveLog(pattern, "Error saving crash info to file:${e.message}")
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "save exception:${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun saveLog(pattern: String, logInfo: String) {
|
||||
val time = SimpleDateFormat(pattern, Locale.getDefault()).format(Date())
|
||||
val fileName = "crash_$time.log"
|
||||
|
||||
val crashDir = getCrashDir()
|
||||
|
||||
val crashFile = File(crashDir, fileName)
|
||||
|
||||
val saveTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
|
||||
FileOutputStream(crashFile, true).use { it.write("$saveTime||$logInfo\n".toByteArray()) }
|
||||
|
||||
Log.d(TAG,"Crash info saved to: ${crashFile.absolutePath}")
|
||||
}
|
||||
|
||||
fun getCrashDir(): File {
|
||||
//val crashDir = File(context.getExternalFilesDir(null), CRASH_REPORTS_DIR)
|
||||
var crashDir = File(BaseApp.instance!!.filesDir, CRASH_REPORTS_DIR)
|
||||
if (!crashDir.exists()) {
|
||||
crashDir.mkdirs()
|
||||
}
|
||||
|
||||
if (!(crashDir.exists())) {
|
||||
crashDir = File(BaseApp.instance!!.cacheDir, CRASH_REPORTS_DIR)
|
||||
}
|
||||
return crashDir
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import java.net.Inet4Address
|
||||
|
||||
/**
|
||||
* 网络工具类
|
||||
*/
|
||||
object NetworkUtil {
|
||||
|
||||
/**
|
||||
* 获取本机局域网 IPv4 地址
|
||||
* - Android 12+(API 31+):使用 ConnectivityManager + LinkProperties,避免废弃 API
|
||||
* - Android 12 以下:回退到 WifiManager.connectionInfo.ipAddress
|
||||
* @return IP 字符串,获取失败返回空字符串
|
||||
*/
|
||||
fun getLocalIpAddress(context: Context): String {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
getIpViaConnectivityManager(context)
|
||||
} else {
|
||||
getIpViaWifiManager(context)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Android 12+ 方式:通过 ConnectivityManager 获取活跃网络的 LinkProperties
|
||||
*/
|
||||
private fun getIpViaConnectivityManager(context: Context): String {
|
||||
return try {
|
||||
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val network = cm.activeNetwork ?: return ""
|
||||
val props: LinkProperties = cm.getLinkProperties(network) ?: return ""
|
||||
props.linkAddresses
|
||||
.map { it.address }
|
||||
.filterIsInstance<Inet4Address>()
|
||||
.firstOrNull { !it.isLoopbackAddress }
|
||||
?.hostAddress ?: ""
|
||||
} catch (e: Exception) {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Android 12 以下方式:通过 WifiManager 获取 IP(仅 WiFi 有效)
|
||||
*/
|
||||
@Suppress("DEPRECATION")
|
||||
private fun getIpViaWifiManager(context: Context): String {
|
||||
return try {
|
||||
val wm = context.applicationContext
|
||||
.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
val ip = wm.connectionInfo.ipAddress
|
||||
if (ip == 0) ""
|
||||
else "${ip and 0xFF}.${ip shr 8 and 0xFF}.${ip shr 16 and 0xFF}.${ip shr 24 and 0xFF}"
|
||||
} catch (e: Exception) {
|
||||
""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.shuwei.dish.match.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,91 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.camera.core.ImageCapture
|
||||
import androidx.camera.core.ImageCaptureException
|
||||
import androidx.camera.view.CameraController
|
||||
import androidx.core.content.ContextCompat
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 拍照工具类
|
||||
* @param context Context 上下文
|
||||
* @param cameraController CameraController 相机控制器
|
||||
* @param onSuccess (Uri) -> Unit 拍照成功回调
|
||||
* @param onError (String) -> Unit 拍照失败回调
|
||||
*/
|
||||
class PhotoCaptureHelper(
|
||||
private val context: Context,
|
||||
private val cameraController: CameraController,
|
||||
private val onSuccess: (Uri) -> Unit = {},
|
||||
private val onError: (String) -> Unit = {}
|
||||
) {
|
||||
private val callbackList: MutableList<(Uri) -> Unit> = mutableListOf()
|
||||
fun addSuccessCallback(callback:(Uri) -> Unit) {
|
||||
if (callbackList.contains(callback).not()) {
|
||||
callbackList.add(callback)
|
||||
}
|
||||
}
|
||||
|
||||
private var bindCamera:(()->Unit)?=null
|
||||
fun bindCameraCallback(callback:()->Unit) {
|
||||
this.bindCamera = callback
|
||||
}
|
||||
|
||||
/**
|
||||
* 拍照方法
|
||||
* @param fileNamePrefix 文件名前缀,默认为"IMG_"
|
||||
* @param fileExtension 文件扩展名,默认为".jpg"
|
||||
*/
|
||||
fun takePhoto(
|
||||
fileNamePrefix: String = "IMG_",
|
||||
fileExtension: String = ".jpg"
|
||||
) {
|
||||
// Timber.d("开始拍照采集")
|
||||
|
||||
try {
|
||||
val executor = ContextCompat.getMainExecutor(context)
|
||||
val cacheDir = context.cacheDir
|
||||
val photoFile = File.createTempFile(
|
||||
"${fileNamePrefix}${System.currentTimeMillis()}",
|
||||
fileExtension,
|
||||
cacheDir
|
||||
)
|
||||
|
||||
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
|
||||
|
||||
cameraController.takePicture(
|
||||
outputOptions,
|
||||
executor,
|
||||
object : ImageCapture.OnImageSavedCallback {
|
||||
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
|
||||
val photoUri = outputFileResults.savedUri ?: Uri.fromFile(photoFile)
|
||||
// Timber.d("照片保存成功: $photoUri")
|
||||
onSuccess(photoUri)
|
||||
callbackList.forEach {
|
||||
it(photoUri)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(exception: ImageCaptureException) {
|
||||
val errorMsg = "拍照失败: ${exception.message}"
|
||||
if (errorMsg.contains("Not bound to a valid Camera")) {
|
||||
if (bindCamera != null) {
|
||||
bindCamera?.invoke()
|
||||
//takePhoto()
|
||||
}
|
||||
|
||||
}
|
||||
// Timber.e(exception, errorMsg)
|
||||
onError(errorMsg)
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
val errorMsg = "创建临时文件失败: ${e.message}"
|
||||
// Timber.e(e, errorMsg)
|
||||
onError(errorMsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,10 @@ object SpTool {
|
||||
const val TOKEN = "token"
|
||||
const val LAUNCH_PAGE_TYPE = "launchPageType"
|
||||
const val DEVICE_ID = "deviceId"
|
||||
/** 设备角色:存储值为 "MASTER" 或 "SLAVE",默认 "SLAVE" */
|
||||
const val DEVICE_ROLE = "deviceRole"
|
||||
/** 秤串口路径,默认 /dev/ttyS7,子设备可能需要配置为其他值 */
|
||||
const val SCALE_DEVICE_PORT = "scaleDevicePort"
|
||||
|
||||
val pref = BaseApp.getSharedPref()!!
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.Gravity
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
@@ -11,7 +13,20 @@ import com.shuwei.dish.match.R
|
||||
|
||||
object ToastUtil {
|
||||
|
||||
fun show(context: Context, message: String, duration:Int = Toast.LENGTH_SHORT) {
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
fun show(context: Context, message: String, duration: Int = Toast.LENGTH_SHORT) {
|
||||
// 确保在主线程中执行
|
||||
if (Thread.currentThread() == Looper.getMainLooper().thread) {
|
||||
showToast(context, message, duration)
|
||||
} else {
|
||||
mainHandler.post {
|
||||
showToast(context, message, duration)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun showToast(context: Context, message: String, duration: Int) {
|
||||
val inflater = LayoutInflater.from(context)
|
||||
val layout: View = inflater.inflate(R.layout.custom_toast, null)
|
||||
val textView = layout.findViewById<TextView>(R.id.tvMessage)
|
||||
@@ -22,7 +37,6 @@ object ToastUtil {
|
||||
toast.setGravity(Gravity.CENTER, 0, 0) // 调整位置居中显示
|
||||
toast.setDuration(duration)
|
||||
toast.show()
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -24,10 +24,21 @@ public class Weigher2 {
|
||||
public static final int ERR_004 = 1004;
|
||||
public static final int ERR_PCB_NOT_SUPPORT = 2000;
|
||||
private static SensorScale mSensorScale;
|
||||
private static String mDevicePort = "/dev/ttyS4";
|
||||
// private static String mDevicePort = "/dev/ttyS4";
|
||||
private static String mDevicePort = "/dev/ttyS7";
|
||||
private static boolean mConnect = false;
|
||||
private static Listener mListener;
|
||||
|
||||
/** 允许外部在 init() 前设置串口路径,用于不同硬件型号的子设备 */
|
||||
public static void setDevicePort(String port) {
|
||||
mDevicePort = port;
|
||||
Log.d(TAG, "串口已设置为: " + port);
|
||||
}
|
||||
|
||||
public static String getDevicePort() {
|
||||
return mDevicePort;
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
String var0;
|
||||
if ((var0 = Build.MODEL) == "pcb_941") {
|
||||
@@ -41,7 +52,8 @@ public class Weigher2 {
|
||||
System.init();
|
||||
initScale();
|
||||
if (var0 == "pcb_908") {
|
||||
mDevicePort = "/dev/ttyS4";
|
||||
// mDevicePort = "/dev/ttyS4";
|
||||
mDevicePort = "/dev/ttyS7";
|
||||
}
|
||||
|
||||
mSensorScale.openScale(mDevicePort, 115200, (open) -> {
|
||||
|
||||
@@ -7,6 +7,7 @@ import android.util.Log
|
||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
//import com.aithings.Weigher
|
||||
import com.wabon.wbintelligenthardwaresdk.api.SensorScale
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
typealias WeightCallback = (address: Int, state: Int, weight: Double) -> Unit
|
||||
|
||||
@@ -17,8 +18,7 @@ object WeightUtil {
|
||||
const val STATE_OVER_WEIGHT = SensorScale.STATE_OVER_WEIGHT
|
||||
|
||||
var isConnected = false
|
||||
var weightFuncMap: MutableMap<String, WeightCallback?>? =
|
||||
null
|
||||
val weightFuncMap: ConcurrentHashMap<String, WeightCallback?> = ConcurrentHashMap()
|
||||
|
||||
fun init() {
|
||||
Weigher2.init()
|
||||
@@ -38,7 +38,7 @@ object WeightUtil {
|
||||
}
|
||||
val useWeight = (weight*1000).roundedOneDecimalPlace()
|
||||
Log.d(TAG, "readWeight, address=$address,state=$stateStr, weight=$useWeight")
|
||||
weightFuncMap?.forEach { (key, value) ->
|
||||
weightFuncMap.forEach { (key, value) ->
|
||||
value?.invoke(address, state, useWeight)
|
||||
}
|
||||
|
||||
@@ -82,14 +82,15 @@ object WeightUtil {
|
||||
}
|
||||
}
|
||||
|
||||
fun removeWeightListener(weightKey: String) {
|
||||
weightFuncMap.remove(weightKey)
|
||||
}
|
||||
|
||||
fun addWeightListener(
|
||||
weightKey: String,
|
||||
getWeight: WeightCallback = { _, _, _ -> }
|
||||
) {
|
||||
if (weightFuncMap == null) {
|
||||
weightFuncMap = mutableMapOf()
|
||||
}
|
||||
weightFuncMap?.put(weightKey, getWeight)
|
||||
weightFuncMap[weightKey] = getWeight
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,11 +11,13 @@ import android.util.TypedValue
|
||||
import android.view.View
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.EditText
|
||||
import android.widget.ImageView
|
||||
import android.widget.Toast
|
||||
import androidx.core.app.ActivityOptionsCompat
|
||||
import androidx.fragment.app.Fragment
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.shuwei.dish.match.utils.GlideUtils
|
||||
import com.shuwei.dish.match.utils.ToastUtil
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -181,3 +183,6 @@ fun Double.roundedDecimalPlace(num: Int): Double {
|
||||
fun Double.roundedOneDecimalPlace(): Double {
|
||||
return this.roundedDecimalPlace(1)
|
||||
}
|
||||
fun ImageView.load(url: Any?) {
|
||||
GlideUtils.loadImage(context, url, this)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:color="#FF0A1428" android:state_pressed="false"/>
|
||||
<item android:color="#FFFF3232" android:state_pressed="true"/>
|
||||
</selector>
|
||||
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 横屏专用启动背景,适配子设备 800×480 屏幕 -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- 背景色铺满全屏 -->
|
||||
<item>
|
||||
<shape android:shape="rectangle">
|
||||
<solid android:color="@color/bg_color"/>
|
||||
</shape>
|
||||
</item>
|
||||
|
||||
<!-- 图片居中显示,适配横屏比例 -->
|
||||
<item
|
||||
android:width="200dp"
|
||||
android:height="190dp"
|
||||
android:gravity="center">
|
||||
<bitmap android:src="@drawable/img_init" android:scaleType="fitCenter"/>
|
||||
</item>
|
||||
|
||||
</layer-list>
|
||||
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 5.4 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 25 KiB |
@@ -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="#FFFF3232"/>
|
||||
<corners android:radius="12dp"/>
|
||||
</shape>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- 浅红色背景 -->
|
||||
<item>
|
||||
<shape android:shape="rectangle">
|
||||
<solid android:color="#FFE8E8" />
|
||||
</shape>
|
||||
</item>
|
||||
|
||||
<!-- 底部红色下划线(固定宽度100dp,高度3dp,距离底部5dp) -->
|
||||
<item android:bottom="5dp" android:top="62dp" android:gravity="center">
|
||||
<shape android:shape="rectangle">
|
||||
<size android:width="100dp" android:height="3dp" />
|
||||
<solid android:color="#FF3232" />
|
||||
</shape>
|
||||
</item>
|
||||
</layer-list>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- 底部白色下划线(固定宽度100dp,高度5dp,距离底部5dp,圆角5dp) -->
|
||||
<item android:bottom="5dp" android:top="60dp" android:gravity="center">
|
||||
<shape android:shape="rectangle">
|
||||
<size android:width="100dp" android:height="5dp" />
|
||||
<solid android:color="#FFFFFF" />
|
||||
<corners android:radius="5dp" />
|
||||
</shape>
|
||||
</item>
|
||||
</layer-list>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- 白色背景 -->
|
||||
<item android:drawable="@color/white" />
|
||||
|
||||
<!-- 底部浅灰色下划线 -->
|
||||
<item android:bottom="0dp">
|
||||
<shape android:shape="rectangle">
|
||||
<solid android:color="#E8E8E8" />
|
||||
<size android:height="1dp" />
|
||||
</shape>
|
||||
</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="#FFE7EFF8"/>
|
||||
<corners android:radius="8dp"/>
|
||||
</shape>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:state_pressed="false">
|
||||
<shape android:shape="rectangle">
|
||||
<corners android:radius="50dp"/>
|
||||
<solid android:color="@color/white"/>
|
||||
<stroke android:color="#FFF5F6F8" android:width="2dp"/>
|
||||
</shape>
|
||||
</item>
|
||||
<item android:state_pressed="true">
|
||||
<shape android:shape="rectangle">
|
||||
<corners android:radius="50dp"/>
|
||||
<solid android:color="#FFFFF0F0"/>
|
||||
<stroke android:color="#FFFF3232" android:width="2dp"/>
|
||||
</shape>
|
||||
</item>
|
||||
</selector>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:state_checked="false">
|
||||
<shape android:shape="rectangle">
|
||||
<corners android:radius="50dp"/>
|
||||
<solid android:color="@color/white"/>
|
||||
<!-- <stroke android:color="#FFC4CFDA" android:width="2dp"/>-->
|
||||
</shape>
|
||||
</item>
|
||||
<item android:state_checked="true">
|
||||
<shape android:shape="rectangle">
|
||||
<corners android:radius="50dp"/>
|
||||
<solid android:color="#FFFFF0F0"/>
|
||||
<stroke android:color="#FFFF3232" android:width="2dp"/>
|
||||
</shape>
|
||||
</item>
|
||||
</selector>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<solid android:color="#FFFF3232"/>
|
||||
<size android:width="10dp" android:height="40dp"/>
|
||||
<corners android:radius="5dp"/>
|
||||
</shape>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:id="@+id/tvFoodName"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="100dp"
|
||||
android:background="@drawable/bg_text_dialog"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center"
|
||||
android:maxLines="1"
|
||||
android:layout_marginHorizontal="14dp"
|
||||
android:layout_marginVertical="14dp"
|
||||
android:paddingHorizontal="15dp"
|
||||
android:textAlignment="center"
|
||||
android:textColor="@color/color_text_dialog"
|
||||
android:textSize="30sp"
|
||||
android:textStyle="bold"
|
||||
tools:text="肉沫干拌面" />
|
||||
@@ -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="#FFF4FAFF"/>
|
||||
<stroke android:width="2dp" android:color="@color/white"/>
|
||||
</shape>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?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"/>
|
||||
<stroke android:width="2dp" android:color="#FFC4CFDA"/>
|
||||
<corners android:radius="45dp"/>
|
||||
</shape>
|
||||
@@ -0,0 +1,115 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 横屏 800×480 专用布局,View ID 与 activity_init.xml 完全一致,供子设备使用 -->
|
||||
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/bg_color">
|
||||
|
||||
<!-- 主内容区:水平居中排列加载区和网络错误区 -->
|
||||
<LinearLayout
|
||||
android:id="@+id/llNetwork"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="horizontal"
|
||||
android:gravity="center">
|
||||
|
||||
<!-- 加载动画容器 -->
|
||||
<LinearLayout
|
||||
android:id="@+id/llLoading"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:gravity="center"
|
||||
android:visibility="visible">
|
||||
|
||||
<!-- 加载动画 -->
|
||||
<ImageView
|
||||
android:id="@+id/ivLoading"
|
||||
android:layout_width="100dp"
|
||||
android:layout_height="100dp"
|
||||
android:src="@drawable/loading_spinner"
|
||||
android:contentDescription="加载中" />
|
||||
|
||||
<!-- 倒计时文字 -->
|
||||
<TextView
|
||||
android:id="@+id/tvCountdown"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="60秒"
|
||||
android:textSize="32sp"
|
||||
android:textColor="@color/black"
|
||||
android:textStyle="bold"
|
||||
android:layout_marginTop="16dp" />
|
||||
|
||||
<!-- 提示文字 -->
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="网络连接检测中,请稍后……"
|
||||
android:textSize="16sp"
|
||||
android:textColor="#555555"
|
||||
android:layout_marginTop="10dp"
|
||||
tools:ignore="HardcodedText" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<!-- 连接网络按钮容器 -->
|
||||
<LinearLayout
|
||||
android:id="@+id/llNetworkButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:gravity="center"
|
||||
android:visibility="gone">
|
||||
|
||||
<!-- 网络错误图标 -->
|
||||
<ImageView
|
||||
android:layout_width="100dp"
|
||||
android:layout_height="100dp"
|
||||
android:src="@drawable/ic_network_error"
|
||||
android:contentDescription="网络连接失败"
|
||||
android:layout_marginBottom="16dp" />
|
||||
|
||||
<!-- 连接失败提示 -->
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="网络连接失败"
|
||||
android:textSize="28sp"
|
||||
android:textColor="@color/black"
|
||||
android:textStyle="bold"
|
||||
android:layout_marginBottom="20dp"
|
||||
tools:ignore="HardcodedText" />
|
||||
|
||||
<!-- 连接网络按钮 -->
|
||||
<Button
|
||||
android:id="@+id/btnConnectNetwork"
|
||||
android:layout_width="260dp"
|
||||
android:layout_height="56dp"
|
||||
android:text="连接网络"
|
||||
android:textSize="20sp"
|
||||
android:textStyle="bold"
|
||||
android:textColor="@android:color/white"
|
||||
android:background="@drawable/btn_connect_network"
|
||||
tools:ignore="HardcodedText" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<!-- 以下 View 在此布局中不使用,保留 ID 确保 ActivityInitBinding.bind() 不崩溃 -->
|
||||
<TextView
|
||||
android:id="@+id/btnInit"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="0dp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/ivQrCode"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="0dp"
|
||||
android:visibility="gone"
|
||||
tools:ignore="ContentDescription" />
|
||||
|
||||
</FrameLayout>
|
||||
@@ -62,7 +62,7 @@
|
||||
android:layout_marginStart="30dp"
|
||||
android:layout_marginTop="40dp"
|
||||
android:layout_marginBottom="40dp"
|
||||
android:text="@string/dish_composition"
|
||||
android:text="@string/dish_list"
|
||||
android:textColor="@color/black666"
|
||||
android:textSize="28sp" />
|
||||
|
||||
|
||||
@@ -1,51 +1,146 @@
|
||||
<?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"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical">
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<ImageView
|
||||
android:layout_width="450dp"
|
||||
android:layout_height="430dp"
|
||||
android:layout_marginStart="50dp"
|
||||
android:layout_marginTop="250dp"
|
||||
android:layout_marginEnd="50dp"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:src="@drawable/img_init"
|
||||
tools:ignore="ContentDescription"
|
||||
android:visibility="invisible"/>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/btnInit"
|
||||
android:layout_width="300dp"
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginTop="160dp"
|
||||
android:background="@drawable/bg_init_button"
|
||||
android:orientation="vertical">
|
||||
|
||||
<ImageView
|
||||
android:layout_width="450dp"
|
||||
android:layout_height="430dp"
|
||||
android:layout_marginStart="50dp"
|
||||
android:layout_marginTop="250dp"
|
||||
android:layout_marginEnd="50dp"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:src="@drawable/img_init"
|
||||
tools:ignore="ContentDescription"
|
||||
android:visibility="invisible"/>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/btnInit"
|
||||
android:layout_width="300dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginTop="160dp"
|
||||
android:background="@drawable/bg_init_button"
|
||||
android:gravity="center"
|
||||
android:padding="10dp"
|
||||
android:text="设备初始化"
|
||||
android:textColor="@color/white"
|
||||
android:textSize="30sp"
|
||||
android:textStyle="bold"
|
||||
tools:ignore="HardcodedText"
|
||||
android:visibility="invisible"/>
|
||||
|
||||
<Space
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"/>
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/ivQrCode"
|
||||
android:layout_width="200dp"
|
||||
android:layout_height="200dp"
|
||||
android:layout_gravity="center_horizontal|bottom"
|
||||
android:layout_marginBottom="50dp"
|
||||
tools:src="@mipmap/ic_logo1024"
|
||||
tools:ignore="ContentDescription"
|
||||
android:visibility="invisible"/>
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/llNetwork"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:orientation="vertical"
|
||||
android:gravity="center"
|
||||
android:padding="10dp"
|
||||
android:text="设备初始化"
|
||||
android:textColor="@color/white"
|
||||
android:textSize="30sp"
|
||||
android:textStyle="bold"
|
||||
tools:ignore="HardcodedText"
|
||||
android:visibility="invisible"/>
|
||||
android:visibility="gone">
|
||||
|
||||
<Space
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"/>
|
||||
<!-- Loading 动画容器 -->
|
||||
<LinearLayout
|
||||
android:id="@+id/llLoading"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:gravity="center"
|
||||
android:visibility="visible"
|
||||
android:layout_marginTop="260dp">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/ivQrCode"
|
||||
android:layout_width="200dp"
|
||||
android:layout_height="200dp"
|
||||
android:layout_gravity="center_horizontal|bottom"
|
||||
android:layout_marginBottom="50dp"
|
||||
tools:src="@mipmap/ic_logo1024"
|
||||
tools:ignore="ContentDescription"
|
||||
android:visibility="invisible"/>
|
||||
<!-- 加载动画 -->
|
||||
<ImageView
|
||||
android:id="@+id/ivLoading"
|
||||
android:layout_width="160dp"
|
||||
android:layout_height="160dp"
|
||||
android:src="@drawable/loading_spinner"
|
||||
android:contentDescription="加载中" />
|
||||
|
||||
</LinearLayout>
|
||||
<!-- 倒计时文字 -->
|
||||
<TextView
|
||||
android:id="@+id/tvCountdown"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="60秒"
|
||||
android:textSize="40sp"
|
||||
android:textColor="@color/black"
|
||||
android:textStyle="bold"
|
||||
android:layout_marginTop="50dp" />
|
||||
|
||||
<!-- 提示文字 -->
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="网络连接检测中,请稍后……"
|
||||
android:textSize="22sp"
|
||||
android:textColor="#555555"
|
||||
android:layout_marginTop="20dp" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<!-- 连接网络按钮容器 -->
|
||||
<LinearLayout
|
||||
android:id="@+id/llNetworkButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:gravity="center"
|
||||
android:visibility="gone">
|
||||
|
||||
<!-- 网络错误图标 -->
|
||||
<ImageView
|
||||
android:layout_width="140dp"
|
||||
android:layout_height="140dp"
|
||||
android:src="@drawable/ic_network_error"
|
||||
android:contentDescription="网络连接失败"
|
||||
android:layout_marginBottom="30dp" />
|
||||
|
||||
<!-- 连接失败提示 -->
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="网络连接失败"
|
||||
android:textSize="36sp"
|
||||
android:textColor="@color/black"
|
||||
android:textStyle="bold"
|
||||
android:layout_marginBottom="40dp" />
|
||||
|
||||
<!-- 连接网络按钮 -->
|
||||
<Button
|
||||
android:id="@+id/btnConnectNetwork"
|
||||
android:layout_width="350dp"
|
||||
android:layout_height="70dp"
|
||||
android:text="连接网络"
|
||||
android:textSize="24sp"
|
||||
android:textStyle="bold"
|
||||
android:textColor="@android:color/white"
|
||||
android:background="@drawable/btn_connect_network" />
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
</LinearLayout>
|
||||
</FrameLayout>
|
||||
@@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
tools:background="@color/bg_color">
|
||||
|
||||
<!-- 顶部标题 -->
|
||||
<TextView
|
||||
android:id="@+id/tvMasterTitle"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center_horizontal"
|
||||
android:layout_marginTop="10dp"
|
||||
android:layout_marginBottom="10dp"
|
||||
android:text="全设备秤数据监控"
|
||||
app:layout_constraintTop_toTopOf="parent"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
android:textColor="@color/home_title"
|
||||
android:textSize="36sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<!-- 主设备连接状态栏 -->
|
||||
<TextView
|
||||
android:id="@+id/tvConnectionStatus"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
app:layout_constraintTop_toBottomOf="@id/tvMasterTitle"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
android:layout_marginBottom="16dp"
|
||||
android:textColor="@color/home_sub_title"
|
||||
android:textSize="24sp"
|
||||
tools:text="已发现设备:3 台" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/ivMasterBack"
|
||||
android:layout_width="70dp"
|
||||
android:layout_height="60dp"
|
||||
android:layout_gravity="start"
|
||||
android:paddingStart="30dp"
|
||||
android:paddingEnd="10dp"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toTopOf="@id/tvMasterTitle"
|
||||
app:layout_constraintBottom_toBottomOf="@id/tvMasterTitle"
|
||||
android:src="@drawable/ic_back"
|
||||
tools:ignore="ContentDescription" />
|
||||
|
||||
<!-- 秤数据列表 -->
|
||||
<androidx.recyclerview.widget.RecyclerView
|
||||
android:id="@+id/rvScaleList"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
app:layout_constraintTop_toBottomOf="@id/tvConnectionStatus"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
android:overScrollMode="never"
|
||||
android:padding="16dp"
|
||||
tools:listitem="@layout/list_item_scale_data"/>
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
@@ -262,6 +262,11 @@
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
<FrameLayout
|
||||
android:id="@+id/flCameraContainer"
|
||||
android:layout_width="1dp"
|
||||
android:layout_height="1dp" />
|
||||
|
||||
<androidx.appcompat.widget.AppCompatButton
|
||||
android:id="@+id/btnCook"
|
||||
android:layout_width="match_parent"
|
||||
|
||||