Author SHA1 Message Date
lvmeng a6d2441704 优化:修复眼睛图标显示效果 2026-03-18 16:14:47 +08:00
lvmeng e7d11530a6 优化:修改消费码输入框为密码模式,添加显示/隐藏密码切换功能 2026-03-18 15:55:06 +08:00
lvmeng c56769769b 优化:修改消费码输入框为密��模式,添加显示/隐藏密码切换功能 2026-03-18 15:42:50 +08:00
lvmeng 8673cec545 优化:修改人脸识别任务延迟参数和添加相机权限检查 2026-03-18 14:06:42 +08:00
lvmeng 8ec7ea6a79 优化 2026-03-13 15:42:37 +08:00
lvmeng a80e3d1ba6 ObjectBox数据库操作增加线程资源清理 2026-03-12 17:25:36 +08:00
mazengfei 6d825d7235 扫码支付增加会员id字段 2026-03-12 12:39:35 +08:00
lvmeng 4f1860eb37 存在待支付订单时停止识别 2026-03-12 11:43:20 +08:00
mazengfei 45a7bf8369 优化非支付页面扫码点击问题 2026-03-11 18:34:49 +08:00
lvmengandClaude Sonnet 4.6 f0b50ef82f 修复MainActivity中扫码枪按键事件触发页面按钮点击问题
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 14:54:52 +08:00
lvmeng 824dc5f867 优化扫码支付结果会员非会员显示 2026-03-11 13:55:29 +08:00
lvmengandClaude Sonnet 4.6 7232735073 修复MainActivity停止时CameraX NPE崩溃
1. 升级CameraX版本 1.3.0 → 1.4.1,从根本修复RequestWithCallback.abort() NPE
2. 跳转PayActivity前调用shutdownCamera(),防止in-flight拍照请求触发生命周期异常
3. onResume()顶部增加相机恢复逻辑,通过cameraProviderFuture==null判断是否需要重新初始化
4. shutdownCamera()中将cameraProviderFuture置null,作为相机已停止的可靠标志

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-10 19:05:28 +08:00
mazengfei 8a1630f2a4 优化扫码枪支付 2026-03-10 14:44:34 +08:00
lvmeng 39c0ca7d72 优化人脸识别区域效果 2026-03-10 11:10:23 +08:00
lvmeng dfde8c0fad 人脸全量接口只首次请求 2026-03-10 10:53:18 +08:00
lvmeng aca84f1e94 Rename .java to .kt 2026-03-10 10:53:18 +08:00
lvmeng 7bcb74d9e0 增加支付成功语音提示;增加扫码支付; 2026-03-10 09:41:34 +08:00
mazengfei 6c857dd1f7 优化 2026-03-09 21:59:04 +08:00
mazengfei fd0f9977b1 使用人脸接口中的member字段判断是否会员;逻辑优化; 2026-03-09 21:26:02 +08:00
lvmeng ec4a5801c2 支付页面统一副屏逻辑 2026-03-09 19:56:09 +08:00
lvmeng 59b3ad72fe 优化人脸识别显示形状 2026-02-11 17:00:08 +08:00
lvmeng 462755824d 优化 2026-02-11 15:00:27 +08:00
lvmeng 0c990ea7ee 打开增加检查网络情况 2026-02-11 14:48:30 +08:00
lvmeng ac30d95812 优化人脸识别区域 2026-02-10 09:48:26 +08:00
lvmeng 23546a967b 首页人脸识别区域改为圆形 2026-02-09 18:47:53 +08:00
lvmeng f227d15108 菜品信息查询接口增加deviceType字段 2026-02-06 11:20:58 +08:00
lvmeng e2c0ed35ec 优化识别及增加扫码枪逻辑 2026-02-04 18:00:46 +08:00
lvmeng 7596924d75 优化 2026-02-03 15:00:19 +08:00
lvmeng 6e7eb80715 优化 2026-01-26 15:53:43 +08:00
lvmeng 50d12de534 优化 2026-01-14 10:38:09 +08:00
lvmeng e86db688e1 优化 2026-01-13 14:26:18 +08:00
lvmeng c38bead8a3 优化 2026-01-13 09:30:12 +08:00
lvmeng ebc3d856d6 优化 2026-01-09 18:38:55 +08:00
lvmeng a6fa5f153a 优化 2026-01-09 16:10:57 +08:00
lvmeng a0452e985a 优化不足一份的识别问题 2026-01-09 11:59:24 +08:00
lvmeng a79f7db867 优化 2026-01-08 19:36:31 +08:00
马增飞 fce721bfc3 优化 2026-01-08 17:31:13 +08:00
马增飞 3cccba4f08 优化 2026-01-08 17:30:03 +08:00
lvmeng 2a55ddb617 采集向量优化调试 2026-01-08 15:02:44 +08:00
lvmeng 378e6088e7 采集向量数据接口调试 2026-01-06 18:49:33 +08:00
lvmeng fc04db9268 增量人脸查询优化 2025-12-31 11:54:17 +08:00
lvmeng 0d2a38391c 增量分页优化 2025-12-29 14:17:57 +08:00
lvmeng 7374f279b4 增量分页优化 2025-12-29 14:08:04 +08:00
lvmeng bb4230419a 增量接口时间戳来源于全量查询时间 2025-12-26 14:12:18 +08:00
lvmeng 5c7f222a0a 修改接口地址 2025-12-26 13:50:28 +08:00
lvmeng dfb734e25d 营养数据计算优化;人脸增加数据处理;其它优化; 2025-12-25 18:57:26 +08:00
lvmeng f080a8b73c 优化识别后未离开多次切换模式导致的不再识别问题 2025-12-22 14:18:46 +08:00
lvmeng 960b429e69 优化 2025-12-19 17:34:31 +08:00
lvmeng af56fb4aeb 优化 2025-12-19 11:10:56 +08:00
lvmeng ab3109f36a 支付完成倒计时3秒返回首页;秤默认置零取消,打开直接识别物品;人脸识别图片显示拉伸优化;设置页面切换是否收费模式首页逻辑处理; 2025-12-18 18:25:15 +08:00
lvmeng 1d0e1a62e2 增加消费码支付功能、支付逻辑优化、金额问题优化、订单绑定优化 2025-12-12 17:50:51 +08:00
lvmeng a0847d21b7 调试优化 2025-12-11 18:54:57 +08:00
lvmeng 6e318f8c82 支付调试优化 2025-12-10 17:56:24 +08:00
lvmeng 88d7530568 t调试 2025-12-09 18:38:26 +08:00
lvmeng 086845dd16 营养接口调试、支付接口联调 2025-12-08 18:06:48 +08:00
lvmeng 04e318f47b 增加支付接口相关逻辑 2025-12-05 18:03:31 +08:00
lvmeng 8899cae323 接口调试、增加人脸识别后主副屏支付金额逻辑、其它优化 2025-12-03 18:40:47 +08:00
lvmeng 29188c5944 接口联调 2025-11-28 18:46:41 +08:00
lvmeng 9bcd7c9983 人脸识别支付流程 2025-11-28 09:13:29 +08:00
lvmeng 88179e27b7 首页、支付功能 2025-11-26 18:57:53 +08:00
lvmeng 60b712f216 结算页面、设置页面 2025-11-19 18:35:53 +08:00
马增飞 9818dfc438 结算 2025-11-19 12:05:12 +08:00
mazengfei cb9d68d2e3 功能优化 2025-11-17 16:09:01 +08:00
mazengfei b4087e435e 修改模式切换流程 2025-11-10 18:55:21 +08:00
lvmeng 4abc855b36 功能优化 2025-11-07 14:23:53 +08:00
mazengfei c898cbb3e2 修改模式切换流程 2025-11-06 19:19:45 +08:00
mazengfei 0a09814a61 修改菜品识别逻辑 2025-11-06 17:49:47 +08:00
mazengfei cc2fd2d743 修改菜品识别逻辑 2025-11-06 14:18:48 +08:00
mazengfei cd883af92f 修改菜品识别逻辑 2025-11-04 15:46:40 +08:00
mazengfei 9c60049843 修改菜品识别逻辑 2025-10-31 23:19:42 +08:00
mazengfei e47b362883 添加菜品采集 2025-10-31 09:53:51 +08:00
马增飞 ed6c5e83be 新增菜品采集 2025-10-18 15:06:07 +08:00
lvmeng a27cc5f7ee 识别图片处理、查询菜品数据 2025-10-17 14:47:28 +08:00
lvmeng dd51448aea 处理gradle冲突 2025-10-16 19:44:28 +08:00
lvmeng b62738aa15 Merge branch 'dev_lvmeng_1016'
# Conflicts:
#	app/build.gradle.kts
#	build.gradle.kts
#	settings.gradle.kts
2025-10-16 19:30:22 +08:00
lvmeng 7a60f4b34d Merge remote-tracking branch 'origin/master' 2025-10-16 19:23:58 +08:00
lvmeng c23aedf464 支持菜品识别 2025-10-16 19:20:59 +08:00
mazengfei 795e685a3a 修改配置参数 2025-10-16 16:40:43 +08:00
lvmeng d9b725cb63 Merge remote-tracking branch 'origin/master' 2025-10-16 13:35:06 +08:00
mazengfei bb63b47b97 导入pytorch 2025-10-16 13:32:59 +08:00
lvmeng caefbd0944 优化 2025-09-26 16:02:18 +08:00
zxj d48f41e917 添加注释 2025-08-22 16:36:17 +08:00
zxj 18fbdc9875 添加开机自启功能 2025-08-21 15:45:35 +08:00
zxj f055441340 添加了模拟识别菜品功能 2025-08-13 11:29:08 +08:00
zxj e93550a24b 处理副屏加载失败导致的崩溃问题 2025-08-11 17:53:20 +08:00
zxj fde2cd0544 调整了人脸识别背景及提示位置 2025-08-11 17:13:48 +08:00
zxj fc326a8f42 修复了柱状图显示问题,修复了菜品图片显示问题,处理了人脸采集框变形问题 2025-08-11 15:38:06 +08:00
zxj 4086f9c0b7 修复了识别窗口追踪功能 2025-08-08 10:25:54 +08:00
270 changed files with 19760 additions and 2816 deletions
Generated
+1
View File
@@ -0,0 +1 @@
DualScreen
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="17" />
</component>
</project>
+2 -2
View File
@@ -4,10 +4,10 @@
<selectionStates> <selectionStates>
<SelectionState runConfigName="app"> <SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" /> <option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2025-08-05T03:50:06.075639Z"> <DropdownSelection timestamp="2026-03-10T03:02:12.156794100Z">
<Target type="DEFAULT_BOOT"> <Target type="DEFAULT_BOOT">
<handle> <handle>
<DeviceId pluginId="PhysicalDevice" identifier="serial=2FD2511004054749" /> <DeviceId pluginId="Default" identifier="serial=192.168.1.211:5555;connection=7435869e" />
</handle> </handle>
</Target> </Target>
</DropdownSelection> </DropdownSelection>
+13
View File
@@ -0,0 +1,13 @@
<?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 -1
View File
@@ -6,7 +6,7 @@
<GradleProjectSettings> <GradleProjectSettings>
<option name="testRunner" value="CHOOSE_PER_TEST" /> <option name="testRunner" value="CHOOSE_PER_TEST" />
<option name="externalProjectPath" value="$PROJECT_DIR$" /> <option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" /> <option name="gradleJvm" value="azul-17" />
<option name="modules"> <option name="modules">
<set> <set>
<option value="$PROJECT_DIR$" /> <option value="$PROJECT_DIR$" />
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="UsePropertyAccessSyntax" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
</profile>
</component>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MaterialThemeProjectNewConfig">
<option name="metadata">
<MTProjectMetadataState>
<option name="userId" value="29face46:19ce5e8d9d0:-7fe0" />
</MTProjectMetadataState>
</option>
</component>
</project>
+1 -1
View File
@@ -1,6 +1,6 @@
<project version="4"> <project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" /> <component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="zulu-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">
+4
View File
@@ -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
+26 -14
View File
@@ -1,11 +1,12 @@
import org.gradle.kotlin.dsl.implementation
plugins { plugins {
alias(libs.plugins.android.application) // alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android) // alias(libs.plugins.kotlin.android)
id("com.google.devtools.ksp") id("com.android.application")
id("org.jetbrains.kotlin.android")
id("com.google.dagger.hilt.android") id("com.google.dagger.hilt.android")
id("com.google.devtools.ksp")
id("kotlin-parcelize") id("kotlin-parcelize")
kotlin("kapt")
} }
android { android {
@@ -31,6 +32,7 @@ android {
ndk { ndk {
abiFilters.addAll(listOf("armeabi-v7a"/*, "arm64-v8a"*/)) abiFilters.addAll(listOf("armeabi-v7a"/*, "arm64-v8a"*/))
} }
setProperty("archivesBaseName", "档口双屏_${versionName}")
} }
buildTypes { buildTypes {
@@ -55,14 +57,7 @@ android {
} }
dependencies { dependencies {
// implementation( implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.aar", "*.jar"))))
// fileTree(
// mapOf(
// "dir" to "libs",
// "include" to listOf("*.aar", "*.jar")
// )
// )
// )
implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat) implementation(libs.androidx.appcompat)
implementation(libs.material) implementation(libs.material)
@@ -109,4 +104,21 @@ dependencies {
implementation(libs.core) implementation(libs.core)
implementation(libs.android.core) implementation(libs.android.core)
}
implementation(libs.pytorch.android)
implementation(libs.pytorch.android.torchvision)
implementation("io.github.scwang90:refresh-layout-kernel:3.0.0-alpha")
implementation("io.github.scwang90:refresh-header-classics:3.0.0-alpha")
val objectboxVersion = "5.0.1"
debugImplementation("io.objectbox:objectbox-android-objectbrowser:$objectboxVersion")
// releaseImplementation("io.objectbox:objectbox-android:$objectboxVersion")
// implementation("io.objectbox:objectbox-fulltext:5.0.1")
implementation(libs.androidx.recyclerview)
implementation("org.greenrobot:eventbus:3.2.0")
}
apply(plugin = "io.objectbox")
+21
View File
@@ -0,0 +1,21 @@
{
"version": 3,
"artifactType": {
"type": "APK",
"kind": "Directory"
},
"applicationId": "com.sw.dualscreen",
"variantName": "debug",
"elements": [
{
"type": "SINGLE",
"filters": [],
"attributes": [],
"versionCode": 1,
"versionName": "1.0",
"outputFile": "档口双屏_1.0-debug.apk"
}
],
"elementType": "File",
"minSdkVersionForDexing": 29
}
Binary file not shown.
Binary file not shown.
+77
View File
@@ -0,0 +1,77 @@
{
"_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:594331511073099531",
"lastPropertyId": "11:7949771231314213889",
"name": "Food",
"properties": [
{
"id": "1:2317727855243736226",
"name": "id",
"type": 6,
"flags": 1
},
{
"id": "4:1528837175750321569",
"name": "foodVector",
"indexId": "1:6010838397086628487",
"type": 28,
"flags": 8
},
{
"id": "5:5561277398349179032",
"name": "collectId",
"type": 9
},
{
"id": "6:8313847979709019172",
"name": "foodId",
"type": 9
},
{
"id": "7:1375536603452792462",
"name": "foodName",
"type": 9
},
{
"id": "8:7942065542192169896",
"name": "version",
"type": 9
},
{
"id": "9:4394472487596452023",
"name": "otherField",
"type": 9
},
{
"id": "10:5704890122356491756",
"name": "createTime",
"type": 9
},
{
"id": "11:7949771231314213889",
"name": "isDel",
"type": 1
}
],
"relations": []
}
],
"lastEntityId": "1:594331511073099531",
"lastIndexId": "1:6010838397086628487",
"lastRelationId": "0:0",
"lastSequenceId": "0:0",
"modelVersion": 5,
"modelVersionParserMinimum": 5,
"retiredEntityUids": [],
"retiredIndexUids": [],
"retiredPropertyUids": [
340951913928211738,
5484846939472684412
],
"retiredRelationUids": [],
"version": 1
}
+77
View File
@@ -0,0 +1,77 @@
{
"_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:594331511073099531",
"lastPropertyId": "11:7949771231314213889",
"name": "Food",
"properties": [
{
"id": "1:2317727855243736226",
"name": "id",
"type": 6,
"flags": 1
},
{
"id": "4:1528837175750321569",
"name": "foodVector",
"indexId": "1:6010838397086628487",
"type": 28,
"flags": 8
},
{
"id": "5:5561277398349179032",
"name": "collectId",
"type": 9
},
{
"id": "6:8313847979709019172",
"name": "foodId",
"type": 9
},
{
"id": "7:1375536603452792462",
"name": "foodName",
"type": 9
},
{
"id": "8:7942065542192169896",
"name": "version",
"type": 9
},
{
"id": "9:4394472487596452023",
"name": "otherField",
"type": 9
},
{
"id": "10:5704890122356491756",
"name": "createTime",
"type": 9
},
{
"id": "11:7949771231314213889",
"name": "isDel",
"type": 5
}
],
"relations": []
}
],
"lastEntityId": "1:594331511073099531",
"lastIndexId": "1:6010838397086628487",
"lastRelationId": "0:0",
"lastSequenceId": "0:0",
"modelVersion": 5,
"modelVersionParserMinimum": 5,
"retiredEntityUids": [],
"retiredIndexUids": [],
"retiredPropertyUids": [
340951913928211738,
5484846939472684412
],
"retiredRelationUids": [],
"version": 1
}
+37
View File
@@ -0,0 +1,37 @@
{
"version": 3,
"artifactType": {
"type": "APK",
"kind": "Directory"
},
"applicationId": "com.sw.dualscreen",
"variantName": "release",
"elements": [
{
"type": "SINGLE",
"filters": [],
"attributes": [],
"versionCode": 1,
"versionName": "1.0",
"outputFile": "档口双屏_1.0-release.apk"
}
],
"elementType": "File",
"baselineProfiles": [
{
"minApi": 28,
"maxApi": 30,
"baselineProfiles": [
"baselineProfiles/1/档口双屏_1.0-release.dm"
]
},
{
"minApi": 31,
"maxApi": 2147483647,
"baselineProfiles": [
"baselineProfiles/0/档口双屏_1.0-release.dm"
]
}
],
"minSdkVersionForDexing": 29
}
+39 -2
View File
@@ -8,12 +8,14 @@
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission <uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="32" /> android:maxSdkVersion="32" />
<uses-permission <uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" /> android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application <application
android:name=".MyApp" android:name=".MyApp"
@@ -25,11 +27,22 @@
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.DualScreen" android:theme="@style/Theme.DualScreen"
android:networkSecurityConfig="@xml/network_security_config"
android:usesCleartextTraffic="true" android:usesCleartextTraffic="true"
tools:targetApi="31"> tools:targetApi="31">
<!-- 注册BootReceiver,监听开机完成广播 -->
<receiver
android:name=".receiver.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity <activity
android:name=".activity.InitActivity" android:name=".activity.InitActivity"
android:exported="true"> android:exported="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
@@ -38,8 +51,32 @@
</activity> </activity>
<activity <activity
android:name=".activity.MainActivity" android:name=".activity.MainActivity"
android:exported="true"> android:exported="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity> </activity>
<!-- <activity-->
<!-- android:name=".activity.FoodCollectionActivity"-->
<!-- android:exported="true">-->
<!-- </activity>-->
<!-- <activity android:name="com.sw.dualscreen.activity.CollectedDataActivity" />-->
<activity android:name="com.sw.dualscreen.activity.SettingActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
<activity android:name="com.sw.dualscreen.activity.CollectedFoodActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
<activity android:name="com.sw.dualscreen.activity.PayActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
android:launchMode="singleTask"/>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application> </application>
</manifest> </manifest>
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 515 KiB

+41
View File
@@ -0,0 +1,41 @@
{
"class_names": [
"回锅肉",
"手撕包菜",
"炒细面",
"红烧肉",
"肉沫酸豆角",
"蒜苔炒肉",
"西红柿鸡蛋",
"豆角茄子",
"麻婆豆腐",
"麻辣小面"
],
"class_to_idx": {
"回锅肉": 0,
"手撕包菜": 1,
"炒细面": 2,
"红烧肉": 3,
"肉沫酸豆角": 4,
"蒜苔炒肉": 5,
"西红柿鸡蛋": 6,
"豆角茄子": 7,
"麻婆豆腐": 8,
"麻辣小面": 9
},
"idx_to_class": {
"0": "回锅肉",
"1": "手撕包菜",
"2": "炒细面",
"3": "红烧肉",
"4": "肉沫酸豆角",
"5": "蒜苔炒肉",
"6": "西红柿鸡蛋",
"7": "豆角茄子",
"8": "麻婆豆腐",
"9": "麻辣小面"
},
"embedding_dim": 512,
"total_images": 500,
"build_time": "2025-10-16T17:51:06.285784"
}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
@@ -11,6 +11,7 @@ object GlobalData {
* 设备id * 设备id
*/ */
var deviceId: String = "" var deviceId: String = ""
/** /**
* app版本号 * app版本号
*/ */
@@ -19,7 +20,13 @@ object GlobalData {
/** /**
* 具体业务baseurl * 具体业务baseurl
*/ */
var appBaseUrl: String = "" var appBaseUrl2: String = "http://192.168.1.201:14801"
var appBaseUrl: String = "https://dev.yixiong-tech.com:8081"
/**
* 菜品识别模型版本号,后边以接口返回为准
*/
var foodModelVersion: String = "1.0.0"
/** /**
* 横排数量 * 横排数量
@@ -38,7 +45,7 @@ object GlobalData {
var appId = "Hkz1rBk6PZXbS8KwKr67K2eZtsz8bRoMHLg64bUdgCZj" var appId = "Hkz1rBk6PZXbS8KwKr67K2eZtsz8bRoMHLg64bUdgCZj"
var sdkKey = "AabXs3sHM8UhhE7oCGf4LVMLrdkGb1nJNksbjjTdVt7k" var sdkKey = "AabXs3sHM8UhhE7oCGf4LVMLrdkGb1nJNksbjjTdVt7k"
var activeKey = "085F-118G-Q3AB-1WVJ" var activeKey = "085F-118G-Q3NU-134V"//2号楼"085F-118G-Q3AB-1WVJ" 5号楼"085F-118G-Q3LH-HPGZ"
} }
/** /**
@@ -59,4 +66,6 @@ object GlobalKey {
const val KEY_TOKEN = "tokenKey" const val KEY_TOKEN = "tokenKey"
const val KEY_FIRST_RUN = "firstRun" const val KEY_FIRST_RUN = "firstRun"
const val KEY_USER_INFO = "userInfoKey" const val KEY_USER_INFO = "userInfoKey"
const val KEY_PICKUP_MODE = "pickupMode"
const val KEY_CHARGE_MODE = "chargeMode"
} }
+50 -3
View File
@@ -1,5 +1,10 @@
package com.sw.dualscreen package com.sw.dualscreen
import android.app.Activity
import android.os.Bundle
import com.sw.dualscreen.objbox.ObjectBox
import com.sw.dualscreen.sdk.SensorScaleUtils
import com.sw.dualscreen.utils.ActivityManager
import com.sw.dualscreen.utils.CrashHandler import com.sw.dualscreen.utils.CrashHandler
import com.sw.plate.App import com.sw.plate.App
import com.sw.plate.utils.AppUtil import com.sw.plate.utils.AppUtil
@@ -8,17 +13,59 @@ import timber.log.Timber
class MyApp : App() { class MyApp : App() {
companion object { companion object {
const val DEBUG: Boolean = true const val DEBUG: Boolean = true
var instance: MyApp?=null
} }
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
instance = this
Timber.plant(Timber.DebugTree()) Timber.plant(Timber.DebugTree())
var deviceId = AppUtil.getUDID(this) var deviceId = AppUtil.getUDID(this)
Timber.d("UDID = ${AppUtil.getUDID(this)}") Timber.d("deviceId = $deviceId")
deviceId = "3ea47dc0-3cf0-3c2f-909c-265a9a65572e" // deviceId = "3ea47dc0-3cf0-3c2f-909c-265a9a65572e"
GlobalData.deviceId = deviceId GlobalData.deviceId = deviceId
GlobalData.appBaseUrl = if ("2987f0c5-5754-33e9-b00a-251db5e2e55f" == deviceId) GlobalData.appBaseUrl2 else GlobalData.appBaseUrl
ObjectBox.init(this)
// 初始化崩溃处理器 // 初始化崩溃处理器
CrashHandler.init(this) CrashHandler.init(this)
SensorScaleUtils.startScale()
addActivityLifecycleListener()
}
private fun addActivityLifecycleListener() {
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(
activity: Activity,
savedInstanceState: Bundle?
) {
ActivityManager.addActivity(activity)
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityResumed(activity: Activity) {
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(
activity: Activity,
outState: Bundle
) {
}
override fun onActivityDestroyed(activity: Activity) {
ActivityManager.removeActivity(activity)
if (ActivityManager.isEmpty()) {
SensorScaleUtils.closeScale()
}
}
})
} }
} }
@@ -0,0 +1,42 @@
package com.sw.dualscreen
class Test {
private var lastWeight = 0
// private var currentWeight = 0
data class WeightRecord(
var eatWeight: Int = 0,
var deviceWeight: Int = 0,
var lastWeight: Int = 0,
var state: Boolean = false
)
private val weightRecord by lazy { WeightRecord() }
fun main() {
readWeight { weight ->
if (weightRecord.state) {
//数据已记录
return@readWeight
}
if (weight == 0 || lastWeight == 0) {
return@readWeight
}
if (weight < lastWeight) {
weightRecord.let {
it.deviceWeight = weight
it.eatWeight = it.deviceWeight - it.lastWeight
it.state = true
}
}
lastWeight = weight
}
}
fun readWeight(block: (Int) -> Unit) {
}
}
@@ -1,25 +1,42 @@
package com.sw.dualscreen.activity package com.sw.dualscreen.activity
import android.app.Dialog
import android.content.Context import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.hardware.display.DisplayManager
import android.os.Bundle import android.os.Bundle
import android.text.TextUtils import android.util.Log
import android.view.Display
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup
import android.view.WindowManager import android.view.WindowManager
import android.widget.TextView import android.widget.TextView
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding import androidx.viewbinding.ViewBinding
import com.sw.dualscreen.R import com.sw.dualscreen.R
import com.sw.dualscreen.databinding.DialogWaitingBinding
import com.sw.dualscreen.model.IActivityResult
import com.sw.dualscreen.model.response.PostEvent
import com.sw.dualscreen.utils.FileUtil
import com.sw.dualscreen.view.CustomDialog import com.sw.dualscreen.view.CustomDialog
import com.sw.dualscreen.viewmodel.BaseViewModel import com.sw.dualscreen.viewmodel.BaseViewModel
import kotlinx.coroutines.Job import com.sw.plate.utils.ScanGunKeyEventHelper
import kotlinx.coroutines.launch import com.sw.plate.utils.ToastUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber import timber.log.Timber
abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() { abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {
val displays: Array<Display> by lazy {
val displayManager = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
displayManager.displays
}
protected lateinit var binding: VB protected lateinit var binding: VB
protected lateinit var context: Context protected lateinit var context: Context
private var mDialogWaiting: CustomDialog? = null private var mDialogWaiting: CustomDialog? = null
@@ -27,6 +44,7 @@ abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
EventBus.getDefault().register(this)
enableEdgeToEdge() enableEdgeToEdge()
context = this context = this
@@ -40,6 +58,12 @@ abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {
registerDataChange() registerDataChange()
} }
override fun onDestroy() {
keyEventHelper?.release()
EventBus.getDefault().unregister(this)
super.onDestroy()
}
abstract fun getViewModel(): BaseViewModel abstract fun getViewModel(): BaseViewModel
protected abstract fun inflateViewBinding(): VB protected abstract fun inflateViewBinding(): VB
@@ -49,36 +73,113 @@ abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {
} }
open fun registerDataChange() { open fun registerDataChange() {
lifecycleScope.launch { // lifecycleScope.launch {
viewModel.showLoading.collect { // viewModel.showLoading.collect {
Timber.d("registerDataChange 用户 showLoading = $it") // Timber.d("registerDataChange 用户 showLoading = $it")
if (it) { // if (it) {
showWaitingDialog("") // showWaitingDialog("")
} else { // } else {
hideWaitingDialog() // hideWaitingDialog()
} // }
} // }
} // }
} }
/** /**
* 显示等待提示框 * 显示等待提示框
*/ */
fun showWaitingDialog(tip: String?): Dialog? { fun showWaitingDialog(tip: String?) {
hideWaitingDialog() runOnUiThread {
val view = View.inflate(this, R.layout.dialog_waiting, null) hideWaitingDialog()
if (!TextUtils.isEmpty(tip)) (view.findViewById<View?>(R.id.tvTip) as TextView).text = tip //val view = View.inflate(this, R.layout.dialog_waiting, null)
mDialogWaiting = CustomDialog(this, view, R.style.MyDialog) val dialogBinding = DialogWaitingBinding.inflate(LayoutInflater.from(this))
mDialogWaiting!!.show() dialogBinding.tvTip.text = tip
mDialogWaiting!!.setCancelable(true) mDialogWaiting = CustomDialog(this, dialogBinding.root)
return mDialogWaiting mDialogWaiting?.show()
}
} }
/** /**
* 隐藏等待提示框 * 隐藏等待提示框
*/ */
fun hideWaitingDialog() { fun hideWaitingDialog() {
mDialogWaiting?.dismiss() runOnUiThread {
mDialogWaiting = null mDialogWaiting?.dismiss()
mDialogWaiting = null
}
}
fun showWaitingDialog2(tip: String?) {
if (mDialogWaiting == null) {
hideWaitingDialog()
val view = View.inflate(this, R.layout.dialog_waiting, null)
mDialogWaiting = CustomDialog(this, view, R.style.MyDialog)
mDialogWaiting?.show()
}
val contentView = mDialogWaiting?.findViewById<ViewGroup>(android.R.id.content)
val tvTip = contentView?.findViewById<TextView>(R.id.tvTip)
tvTip?.text = tip
}
private var launchPermissionCallback: IActivityResult.RequestPermissionCallback? = null
fun requestSinglePermissionResult(
permission: String,
permissionCallback: IActivityResult.RequestPermissionCallback?
) {
this.launchPermissionCallback = permissionCallback
permissionLauncher.launch(permission)
}
private val permissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { result: Boolean ->
launchPermissionCallback?.callback(result)
}
fun log(msg: String) {
Timber.d(msg)
FileUtil.saveLog(msg)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onPostEvent(event: PostEvent) {
}
/**
* 监听扫描枪扫描事件
*/
fun registerKeyEvent() {
keyEventHelper =
ScanGunKeyEventHelper( object : ScanGunKeyEventHelper.OnScanSuccessListener {
override fun onScanSuccess(barcode: String?) {
Timber.d("onScanSuccess barcode = $barcode")
if (barcode == null) return
scanGunKeyEventCallback(barcode)
}
})
}
protected var keyEventHelper: ScanGunKeyEventHelper? = null
/**
* 处理扫描枪数据
*/
fun scanGunKeyEventCallback(scanInfo: String){
if (this is PayActivity) {
qrCodePay(scanInfo)
}
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (keyEventHelper != null) {
if (keyEventHelper!!.isScanGunEvent(event)) {
keyEventHelper!!.analysisKeyEvent(event)
return true
}
}
return super.dispatchKeyEvent(event)
} }
} }
@@ -0,0 +1,228 @@
package com.sw.dualscreen.activity
import android.annotation.SuppressLint
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.sw.dualscreen.GlobalData
import com.sw.dualscreen.R
import com.sw.dualscreen.adapter.CollectedFoodNewAdapter
import com.sw.dualscreen.databinding.ActivityCollectedFoodBinding
import com.sw.dualscreen.dialog.RemindDialog
import com.sw.dualscreen.ext.addOnActionSearchListener
import com.sw.dualscreen.ext.gone
import com.sw.dualscreen.ext.hideKeyboard
import com.sw.dualscreen.ext.visible
import com.sw.dualscreen.objbox.CollectedFoodInfo
import com.sw.dualscreen.objbox.ObjectBox
import com.sw.dualscreen.viewmodel.BaseViewModel
import com.sw.dualscreen.viewmodel.UserViewModel
import com.sw.plate.utils.ToastUtils
import kotlinx.coroutines.launch
class CollectedFoodActivity : BaseActivity<ActivityCollectedFoodBinding>() {
companion object {
private const val PAGE_SIZE = 100
}
private val viewModel by viewModels<UserViewModel>()
override fun getViewModel(): BaseViewModel {
return viewModel
}
override fun inflateViewBinding(): ActivityCollectedFoodBinding {
return ActivityCollectedFoodBinding.inflate(layoutInflater)
}
private val list: MutableList<CollectedFoodInfo> = mutableListOf()
private val adapter by lazy {
CollectedFoodNewAdapter(list).apply {
// isStateViewEnable = true
addOnItemChildClickListener(R.id.ivDeleteFood) { _, _, position ->
loadDeleteDialog(position)
}
}
}
override fun initialize() {
super.initialize()
registerKeyEvent()
binding.root.setOnClickListener { it.hideKeyboard() }
binding.rvFoodList.let {
it.layoutManager = LinearLayoutManager(this)
it.adapter = adapter
}
binding.include.let {
it.tvPageTitle.text = "已采集餐品"
it.ivPageBack.setOnClickListener { finish() }
}
binding.ivFoodSearch.setOnClickListener {
val searchName = binding.etInputFood.text.toString().trim()
if (searchName.isBlank()) {
ToastUtils.showToast("请输入物品名称")
return@setOnClickListener
}
getCollectGoods(searchName)
}
binding.etInputFood.let { v ->
v.addOnActionSearchListener {
val searchName = binding.etInputFood.text.toString().trim()
if (searchName.isBlank()) {
ToastUtils.showToast("请输入物品名称")
return@addOnActionSearchListener
}
pageNo = 1
getCollectGoods(searchName)
}
v.addTextChangedListener {
if (it.isNullOrBlank()) {
pageNo = 1
getCollectGoods()
}
}
}
binding.refreshLayout.let {
it.setEnableRefresh(true)
it.setEnableLoadMore(false)
it.setOnRefreshListener {
pageNo = 1
getCollectGoods()
}
it.setOnLoadMoreListener {
getCollectGoods()
}
}
binding.emptyInclude.root.setOnClickListener {
it.hideKeyboard()
}
getCollectGoods()
}
@SuppressLint("NotifyDataSetChanged")
private fun getCollectGoods(searchName: String? = null) {
// if (box == null) {
// box = ObjectBox.boxStore.boxFor(Food::class)
// }
// list.clear()
// val totalList = box?.all
// ?.filter { it.name!=null }
// ?.groupBy { it.name!! }
// ?.map { CollectedFoodInfo(foodName = it.key, foodCount = it.value.size) }
// //var queryMap:Map<String, List<Food>> ?= null
// if (searchName.isNullOrBlank().not()) {
// //queryMap = totalMap?.filter { it.key.contains(searchName) }
// val temp = totalList?.filter { it.foodName?.contains(searchName) == true}
// if (temp.isNullOrEmpty().not()) {
// list.addAll(temp)
// }
// } else {
// if (totalList.isNullOrEmpty().not()) {
// list.addAll(totalList)
// }
// }
// adapter.notifyDataSetChanged()
// if (list.isEmpty()) {
// loadEmptyView()
// }
viewModel.getCollectedFoodList(
pageNo = pageNo,
pageSize = PAGE_SIZE,
foodName = searchName ?: ""
) { items ->
runOnUiThread {
loadFoodList(items)
}
}
}
@SuppressLint("NotifyDataSetChanged")
private fun loadFoodList(items: List<CollectedFoodInfo>) {
finishRefresh()
if (pageNo == 1 && items.isEmpty()) {
list.clear()
adapter.notifyDataSetChanged()
loadEmptyView()
binding.refreshLayout.setEnableLoadMore(false)
return
}
binding.refreshLayout.visible()
binding.emptyInclude.root.gone()
if (pageNo == 1) {
list.clear()
}
list.addAll(items)
val isEnableLoadMore = items.size >= PAGE_SIZE
if (isEnableLoadMore) {
pageNo++
}
binding.refreshLayout.setEnableLoadMore(isEnableLoadMore)
adapter.notifyDataSetChanged()
binding.root.hideKeyboard()
}
private var pageNo = 1
// private var emptyBinding: LayoutEmptySearchBinding? = null
private fun loadEmptyView() {
binding.refreshLayout.gone()
binding.emptyInclude.root.visible()
//if (emptyBinding == null) {
// emptyBinding =
// LayoutEmptySearchBinding.inflate(layoutInflater, binding.rvFoodList, false)
//}
//emptyBinding?.root?.let { layout ->
// layout.setOnClickListener { layout.hideKeyboard() }
// adapter.stateView = layout
//}
}
private fun loadDeleteDialog(position: Int) {
RemindDialog(
context = context,
content = "请确认是否删除菜品:${list[position].foodName}",
confirmBlock = {
deleteGoods(position)
}).show()
}
private fun deleteGoods(position: Int) {
val food = list[position]
showWaitingDialog("加载中……")
viewModel.deleteCollectFood(food.foodId, GlobalData.foodModelVersion) { deleteSuccess ->
if (deleteSuccess) {
// Thread {}.start()
lifecycleScope.launch {
val filterFoodList = ObjectBox.filter(food.foodName)
filterFoodList.forEach { it.isDel = true }
if (filterFoodList.isNotEmpty()) {
ObjectBox.putAll(filterFoodList)
}
runOnUiThread {
hideWaitingDialog()
adapter.removeAt(position)
ToastUtils.showToast("删除成功")
if (list.isEmpty()) {
loadEmptyView()
}
}
}
}
}
}
private fun finishRefresh() {
binding.refreshLayout.let {
if (pageNo == 1) {
it.finishRefresh(500)
} else {
it.finishLoadMore(500)
}
}
}
}
@@ -1,56 +1,162 @@
package com.sw.dualscreen.activity package com.sw.dualscreen.activity
import android.Manifest
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.CountDownTimer
import androidx.activity.enableEdgeToEdge import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.sw.dualscreen.GlobalData import com.sw.dualscreen.GlobalData
import com.sw.dualscreen.databinding.ActivityInitBinding import com.sw.dualscreen.databinding.ActivityInitBinding
import com.sw.dualscreen.utils.QRCodeUtil import com.sw.dualscreen.dialog.RemindDialog
import com.sw.dualscreen.ext.clickWithDebounce
import com.sw.dualscreen.ext.visible
import com.sw.dualscreen.model.response.FoodVector
import com.sw.dualscreen.objbox.Food
import com.sw.dualscreen.objbox.FoodModule
import com.sw.dualscreen.objbox.ObjectBox
import com.sw.dualscreen.utils.L
import com.sw.dualscreen.viewmodel.BaseViewModel import com.sw.dualscreen.viewmodel.BaseViewModel
import com.sw.dualscreen.viewmodel.DeviceViewModel import com.sw.dualscreen.viewmodel.UserViewModel
import com.sw.plate.utils.AppUtil import com.sw.plate.utils.AppUtil
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
class InitActivity : BaseActivity<ActivityInitBinding>() { class InitActivity : BaseActivity<ActivityInitBinding>() {
private val viewModel by viewModels<DeviceViewModel>() companion object {
private const val PAGE_SIZE = 100
}
private val userViewModel by viewModels<UserViewModel>()
private var pageNum = 1
// 相机权限请求回调
private val requestCameraPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
// 权限请求成功,打开 MainActivity
goMainActivity()
} else {
// 权限请求失败,显示弹窗
showPermissionDeniedDialog()
}
}
// 设置页面返回的回调
private val startSettingsLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
// 从设置页面返回,重新检查权限
checkCameraPermissionAfterSettings()
}
override fun getViewModel(): BaseViewModel { override fun getViewModel(): BaseViewModel {
return viewModel return userViewModel
} }
override fun inflateViewBinding(): ActivityInitBinding { override fun inflateViewBinding(): ActivityInitBinding {
return ActivityInitBinding.inflate(layoutInflater) return ActivityInitBinding.inflate(layoutInflater)
} }
private fun getCollectedFoodVector(block: () -> Unit) {
userViewModel.getCollectedFoodVector(
param = mutableMapOf(
"pageNum" to "$pageNum",
"pageSize" to "$PAGE_SIZE",
"version" to GlobalData.foodModelVersion
)
) { items ->
if (items == null) {
getVectorErrorDialog()
return@getCollectedFoodVector
}
val list = items
if (pageNum == 1 && list.isEmpty()) {
block()
return@getCollectedFoodVector
}
if (list.size >= PAGE_SIZE) {
saveFoodVector(list)
pageNum++
getCollectedFoodVector(block)
return@getCollectedFoodVector
}
if (list.isNotEmpty()) {
saveFoodVector(list)
block()
}
}
}
// private val box by lazy { ObjectBox.boxStore.boxFor(Food::class) }
private fun saveFoodVector(list: List<FoodVector>) {
lifecycleScope.launch {
val vectorList = list.map { vt ->
val foodVector = vt.foodVector?.removeSurrounding("[", "]")?.split(",")
?.map { it.toFloatOrNull() ?: 0.0f }?.toFloatArray()
Food(
collectId = vt.id,
foodId = vt.foodId,
foodName = vt.foodName,
version = vt.version,
foodVector = foodVector
)
}
ObjectBox.putAll(vectorList)
}
}
override fun initialize() { override fun initialize() {
super.initialize() super.initialize()
val isSuccess = viewModel.checkEquipmentInfo() registerKeyEvent()
if (isSuccess) { initNetworkTimer()
goMainActivity() binding.okButton.clickWithDebounce(500) {
return checkNetworkTimer?.cancel()
} checkNetworkTimer?.start()
binding.imgQr.setImageBitmap(
QRCodeUtil.generateQRCode(
content = GlobalData.deviceId,
size = 200
)
)
binding.initButton.setOnClickListener {
viewModel.getDeviceToken()
} }
showWaitingDialog("网络连接中...")
checkNetworkTimer?.start()
// val isSuccess = viewModel.checkEquipmentInfo()
// if (isSuccess) {
// goMainActivity()
// return
// }
// binding.imgQr.setImageBitmap(
// QRCodeUtil.generateQRCode(
// content = GlobalData.deviceId,
// size = 200
// )
// )
// binding.initButton.setOnClickListener {
// viewModel.getDeviceToken()
// }
} }
override fun registerDataChange() { override fun registerDataChange() {
super.registerDataChange() super.registerDataChange()
// lifecycleScope.launch {
// viewModel.deviceInfoResult.drop(1).collect {
// if (it != true) return@collect
// goMainActivity()
// }
// }
}
private fun getCollectedFoodVector() {
showWaitingDialog2("加载中……")
lifecycleScope.launch { lifecycleScope.launch {
viewModel.deviceInfoResult.drop(1).collect { FoodModule.init(this@InitActivity) {
if (it != true) return@collect getCollectedFoodVector {
goMainActivity() runOnUiThread {
hideWaitingDialog()
binding.root.postDelayed({
checkCameraPermissionAndGo()
}, 1000)
}
}
} }
} }
} }
@@ -60,4 +166,95 @@ class InitActivity : BaseActivity<ActivityInitBinding>() {
startActivity(intent) startActivity(intent)
finish() finish()
} }
// 检查相机权限
private fun checkCameraPermissionAndGo() {
val hasCameraPermission = ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) == android.content.pm.PackageManager.PERMISSION_GRANTED
if (hasCameraPermission) {
// 有权限,直接打开 MainActivity
goMainActivity()
} else {
// 无权限,请求相机权限
requestCameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
// 从设置页面返回后检查权限
private fun checkCameraPermissionAfterSettings() {
val hasCameraPermission = ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) == android.content.pm.PackageManager.PERMISSION_GRANTED
if (hasCameraPermission) {
// 权限已授予,打开 MainActivity
goMainActivity()
} else {
// 权限仍未授予,再次显示弹窗
showPermissionDeniedDialog()
}
}
// 显示权限被拒绝的弹窗
private fun showPermissionDeniedDialog() {
RemindDialog(
context = context,
content = "暂无相机权限,请授权后重试",
confirmBlock = {
// 打开 App 设置页面
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = android.net.Uri.fromParts("package", packageName, null)
}
startSettingsLauncher.launch(intent)
}
).show()
}
private var checkNetworkTimer: CountDownTimer? = null
private fun initNetworkTimer() {
checkNetworkTimer = object : CountDownTimer(5 * 300, 300) {
override fun onTick(millisUntilFinished: Long) {
}
override fun onFinish() {
L.e("检测网络连接状态" + AppUtil.isNetworkConnected(this@InitActivity))
if (!AppUtil.isNetworkConnected(this@InitActivity)) {
hideWaitingDialog()
binding.okButton.visible()
loadNetworkErrorDialog()
return
}
getCollectedFoodVector()
}
}
}
private fun loadNetworkErrorDialog() {
RemindDialog(
context = context,
content = "网络连接异常,请检查WiFi连接状态后重试",
confirmBlock = {
startActivity(Intent("android.settings.WIFI_SETTINGS"))
}).show()
}
private fun getVectorErrorDialog() {
RemindDialog(
context = context,
content = "未查询到向量数据,请稍后重试?",
confirmBlock = {
getCollectedFoodVector()
}).show()
}
override fun onDestroy() {
checkNetworkTimer?.cancel()
super.onDestroy()
}
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,362 @@
package com.sw.dualscreen.activity
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import com.sw.dualscreen.GlobalKey
import com.sw.dualscreen.R
import com.sw.dualscreen.activity.fragment.pay.CashPayFragment
import com.sw.dualscreen.activity.fragment.pay.FacePayFragment
import com.sw.dualscreen.activity.fragment.pay.NumberPayFragment
import com.sw.dualscreen.activity.fragment.pay.PayResultFragment
import com.sw.dualscreen.activity.fragment.pay.ScanQrCodePayFragment
import com.sw.dualscreen.databinding.ActivityPayBinding
import com.sw.dualscreen.ext.gone
import com.sw.dualscreen.model.response.FoodInfo
import com.sw.dualscreen.model.response.MemberInfo
import com.sw.dualscreen.model.response.PaySuccessEvent
import com.sw.dualscreen.presentation.pay.PayPresentation
import com.sw.dualscreen.utils.Debouncer
import com.sw.dualscreen.utils.SPUtil
import com.sw.dualscreen.utils.SoundPoolUtil
import com.sw.dualscreen.viewmodel.BaseViewModel
import com.sw.dualscreen.viewmodel.UserViewModel
import com.sw.plate.utils.arcface.viewmodel.RecognizeViewModel
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
class PayActivity : BaseActivity<ActivityPayBinding>() {
companion object {
const val FOOD_INFO = "foodInfo"
const val TOTAL_AMOUNT = "totalAmount"
const val FOOD_ORDER_ID = "foodOrderId"
const val FOOD_EAT_NUM = "foodEatNum"
// const val MEMBER_INFO = "memberInfo"
const val TAG_PAY_QR_CODE = "tagPayQrCode"
const val TAG_PAY_CASH = "tagPayCash"
const val TAG_PAY_NUMBER = "tagPayNumber"
const val TAG_PAY_FACE = "tagPayFace"
const val TAG_PAY_RESULT = "tagPayResult"
const val PAY_SUCCESS = "pay_success"
}
val userViewModel by viewModels<UserViewModel>()
val recognizeViewModel by viewModels<RecognizeViewModel>()
override fun getViewModel(): BaseViewModel {
return userViewModel
}
override fun inflateViewBinding(): ActivityPayBinding {
return ActivityPayBinding.inflate(layoutInflater)
}
var foodInfo: FoodInfo? = null
// var totalAmount:Double = 0.0
private var qrCodePayFragment: ScanQrCodePayFragment? = null
private var cashPayFragment: CashPayFragment? = null
private var numberPayFragment: NumberPayFragment? = null
var facePayFragment: FacePayFragment? = null
private var payResultFragment: PayResultFragment? = null
var foodOrderId: String = ""
var eatNum: Int = 1
var isMember: Boolean = false
val presentation by lazy {
PayPresentation(
activity = this@PayActivity,
userViewModel = userViewModel,
recognizeViewModel = recognizeViewModel,
display = displays[1]
)
}
fun playSoundOnPaySuccess() {
SoundPoolUtil.getInstance().play(PAY_SUCCESS, 0)
}
@Suppress("DEPRECATION")
override fun initialize() {
super.initialize()
presentation.show()
registerKeyEvent()
addBackEventListener()
val soundMap = hashMapOf<String, Int>()
soundMap[PAY_SUCCESS] = R.raw.pay_success
SoundPoolUtil.getInstance().loadR(this, soundMap)
foodInfo = intent.getParcelableExtra(FOOD_INFO)
foodOrderId = intent.getStringExtra(FOOD_ORDER_ID) ?: ""
eatNum = intent.getIntExtra(FOOD_EAT_NUM, 1)
// totalAmount = intent.getDoubleExtra(TOTAL_AMOUNT,0.0)
// memberInfo = intent.getParcelableExtra(MEMBER_INFO)
binding.tvFoodName.text = foodInfo?.foodName
binding.include.ivPageBack.setOnClickListener { finish() }
binding.include.tvPageTitle.text = "下单结算"
binding.btnPayQrCode.setOnClickListener {
isMember = false
if (binding.btnPayQrCode.isChecked) {
return@setOnClickListener
}
showScanQrCodePay()
}
binding.btnPayCash.setOnClickListener {
isMember = false
if (binding.btnPayCash.isChecked) {
return@setOnClickListener
}
cashPayFragment = CashPayFragment()
showFragment(cashPayFragment!!, TAG_PAY_CASH)
switchButton(false, true, false, false)
}
binding.btnPayNumber.setOnClickListener {
if (binding.btnPayNumber.isChecked) {
return@setOnClickListener
}
numberPayFragment = NumberPayFragment()
showFragment(numberPayFragment!!, TAG_PAY_NUMBER)
switchButton(false, false, true, false)
}
binding.btnPayFace.setOnClickListener {
if (binding.btnPayFace.isChecked) {
return@setOnClickListener
}
showFacePay()
}
showScanQrCodePay()
}
private fun showScanQrCodePay() {
qrCodePayFragment = ScanQrCodePayFragment()
showFragment(qrCodePayFragment!!, TAG_PAY_QR_CODE)
switchButton(true, false, false, false)
}
private fun switchButton(vararg arr: Boolean) {
binding.btnPayQrCode.isChecked = arr[0]
binding.btnPayCash.isChecked = arr[1]
binding.btnPayNumber.isChecked = arr[2]
binding.btnPayFace.isChecked = arr[3]
}
fun showFacePay() {
facePayFragment = FacePayFragment()
showFragment(facePayFragment!!, TAG_PAY_FACE)
switchButton(false, false, false, true)
}
private fun showFragment(fragment: Fragment, tag: String) {
runCatching {
supportFragmentManager.beginTransaction().apply {
replace(R.id.fragmentContainerView, fragment)
commitNowAllowingStateLoss()
}
}.onFailure {
it.printStackTrace()
}
}
override fun onDestroy() {
presentation.dismiss()
super.onDestroy()
}
var memberInfo: MemberInfo? = null
fun showPayInfo(type: Int = 1, isVip: Boolean = false, memberInfo: MemberInfo? = null) {
this.memberInfo = memberInfo
payResultFragment = PayResultFragment.instance(type, memberInfo)
showFragment(payResultFragment!!, TAG_PAY_RESULT)
// if (displays.size > 1) {
// scanQrCodePayPresentation = ScanQrCodePayPresentation(
// activity = this,
// display = displays[1],
// type = type
// ) {
// scanQrCodePaypresentation.dismiss()
// }.also {
// it.foodName = foodInfo?.foodName
// //确认使用vipPrice 还是 specPrice
// val onePrice = if (isVip) foodInfo?.vipPrice else foodInfo?.specPrice
// it.totalPrice = (onePrice ?: 0.0) * eatNum
// }
// scanQrCodePaypresentation.show()
// }
presentation.let {
it.pageType = PayPresentation.QR_CODE_PAY
it.type = type
it.foodName = foodInfo?.foodName
//确认使用vipPrice 还是 specPrice
val onePrice = if (isVip) foodInfo?.vipPrice else foodInfo?.specPrice
it.totalPrice = (onePrice ?: 0.0) * eatNum
presentation.initView()
}
}
fun updateQrCodeImage(qrCodeUrl: String?) {
// scanQrCodePaypresentation.loadQrCodeImage(qrCodeUrl)
presentation.loadQrCodeImage(qrCodeUrl)
}
private var debouncer = Debouncer(5000)
fun showPaySuccess(isVip: Boolean) {
debouncer.debounce {
playSoundOnPaySuccess()
EventBus.getDefault().post(PaySuccessEvent())
showPayInfo(type = 2, isVip = isVip, memberInfo = memberInfo)
hidePayTab()
}
}
fun getQrCodeImg(
orderId: String,
userId: String? = null,
totalFee: String? = null,
block: (String?) -> Unit
) {
userViewModel.getQrCodeImg(
orderId = orderId,
userId = userId,
totalFee = totalFee
) { qrCodeImg ->
runOnUiThread {
if (qrCodeImg.isNullOrBlank()) {
//ToastUtils.showToast("获取二维码失败")
return@runOnUiThread
}
block(qrCodeImg)
}
}
}
fun cashPay(param: HashMap<String, String>, block: (Boolean) -> Unit) {
userViewModel.cashPay(param) {
runOnUiThread {
block(it)
}
}
}
fun memberPay(param: HashMap<String, String?>, block: () -> Unit) {
userViewModel.memberPay(param) {
runOnUiThread {
if (it.not()) {
//ToastUtils.showToast("支付失败,请稍后重试")
return@runOnUiThread
}
block()
}
}
}
suspend fun queryOrderState(block: (Boolean) -> Unit) {
userViewModel.queryOrderState(orderId = foodOrderId) { payResult ->
runOnUiThread {
if (payResult) {
block(true)
} else {
block(false)
}
}
}
}
fun hidePayTab() {
binding.llPayTab.gone()
}
fun getMemberInfoByPhone(phone: String, key: String, block: (MemberInfo?) -> Unit) {
userViewModel.getMemberInfoByPhone(phone, key) { memberInfo ->
runOnUiThread {
block(memberInfo)
}
}
}
fun getMemberInfoById(userId: String, block: (MemberInfo?) -> Unit) {
userViewModel.getMemberInfoById(memberId = userId) { memberInfo ->
runOnUiThread {
block(memberInfo)
}
}
}
fun bindOrder(userId: String, block: (Boolean) -> Unit) {
val pickupMode = SPUtil.getInstance().get(GlobalKey.KEY_PICKUP_MODE, 0)
val mode = if (pickupMode == 1) 1 else 2
userViewModel.bindOrder(userId, foodOrderId, mode = mode) { bindResult ->
runOnUiThread {
block(bindResult)
}
}
}
fun qrCodePay(scanInfo: String) {
showWaitingDialog("支付中……")
userViewModel.qrCodePay(scanInfo, foodOrderId, memberInfo?.id) { payState, backData ->
Timber.d("qrCodePay支付返回数据:state=$payState,backData=$backData")
hideWaitingDialog()
if (payState) {
showPaySuccess(isMember)
}
}
}
// fun bindOrder(userId: String, block: () -> Unit) {
// val pickupMode = SPUtil.getInstance().get(GlobalKey.KEY_PICKUP_MODE, 0)
// val mode = if (pickupMode == 1) 1 else 2
// userViewModel.bindOrder(userId, foodOrderId, mode = mode) { bindResult ->
// runOnUiThread {
// if (bindResult.not()) {
// hideWaitingDialog()
// //ToastUtils.showToast("订单绑定失败")
// return@runOnUiThread
// }
// binding.root.postDelayed({
// hideWaitingDialog()
// showPayInfo(type = 1, isVip = true, memberInfo = memberInfo)
// hidePayTab()
// block()
// }, 1000)
// }
// }
// }
// fun getMemberInfoByPhone(phone: String, key: String, block: (MemberInfo) -> Unit) {
// userViewModel.getMemberInfoByPhone(phone, key) { memberInfo ->
// runOnUiThread {
// if (memberInfo == null) {
// hideWaitingDialog()
// //ToastUtils.showToast("查询会员信息失败,请稍后重试")
// return@runOnUiThread
// }
// block(memberInfo)
// }
// }
// }
// fun getMemberInfo(userId: String, block: (MemberInfo) -> Unit) {
// userViewModel.getMemberInfoById(memberId = userId) { memberInfo ->
// runOnUiThread {
// if (memberInfo == null) {
// hideWaitingDialog()
// //ToastUtils.showToast("查询会员信息失败,请稍后重试")
// return@runOnUiThread
// }
// block(memberInfo)
// }
// }
// }
fun addBackEventListener() {
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
}
})
}
}
@@ -0,0 +1,88 @@
package com.sw.dualscreen.activity
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import com.sw.dualscreen.R
import com.sw.dualscreen.activity.fragment.BusinessFragment
import com.sw.dualscreen.activity.fragment.CollectFragment
import com.sw.dualscreen.databinding.ActivitySettingBinding
import com.sw.dualscreen.model.response.FoodInfo
import com.sw.dualscreen.model.response.ClickBackEvent
import com.sw.dualscreen.model.response.UpdateRefreshEvent
import com.sw.dualscreen.viewmodel.BaseViewModel
import com.sw.dualscreen.viewmodel.UserViewModel
import org.greenrobot.eventbus.EventBus
class SettingActivity : BaseActivity<ActivitySettingBinding>() {
val viewModel by viewModels<UserViewModel>()
override fun getViewModel(): BaseViewModel {
return viewModel
}
override fun inflateViewBinding(): ActivitySettingBinding {
return ActivitySettingBinding.inflate(layoutInflater)
}
private val fragmentList = mutableListOf<Fragment>().apply {
add(BusinessFragment())
add(CollectFragment())
}
override fun initialize() {
super.initialize()
registerKeyEvent()
initBackDispatcher()
binding.include.let {
it.ivPageBack.setOnClickListener {
//// val intent = Intent(this, MainActivity::class.java)
//// startActivity(intent)
// EventBus.getDefault().post(ClickBackEvent())
finish()
}
it.tvPageTitle.text = "设置"
}
binding.rgSetting.setOnCheckedChangeListener { group, checkedId ->
if (checkedId == R.id.rbBusiness) {
showFragment(fragmentList[0])
return@setOnCheckedChangeListener
}
if (checkedId == R.id.rbCollect) {
EventBus.getDefault().post(UpdateRefreshEvent())
showFragment(fragmentList[1])
return@setOnCheckedChangeListener
}
}
binding.rgSetting.check(R.id.rbBusiness)
}
private fun showFragment(fragment: Fragment) {
runCatching {
supportFragmentManager.beginTransaction().apply {
replace(R.id.fragmentContainerView, fragment)
commit()
}
}.onFailure {
it.printStackTrace()
}
}
fun searchByFoodName(foodName:String, action: (List<FoodInfo>) -> Unit) {
viewModel.searchByFoodName(foodName, action)
}
private lateinit var backPressedCallback: OnBackPressedCallback
private fun initBackDispatcher() {
// 创建回调,true表示初始启用状态
// backPressedCallback = object : OnBackPressedCallback(true) {
// override fun handleOnBackPressed() {
//// EventBus.getDefault().post(ClickBackEvent())
// }
// }
// // 注册回调,使用lifecycleOwner确保生命周期安全
// onBackPressedDispatcher.addCallback(this, backPressedCallback)
}
}
@@ -0,0 +1,60 @@
package com.sw.dualscreen.activity.fragment
import android.content.Context
import android.hardware.display.DisplayManager
import android.os.Bundle
import android.view.Display
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.sw.dualscreen.model.response.PostEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
abstract class BaseFragment<VB : ViewBinding>: Fragment() {
val displays: Array<Display> by lazy {
val displayManager = requireActivity().getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
displayManager.displays
}
protected lateinit var binding: VB
protected abstract fun inflateViewBinding(): VB
abstract fun initialize()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = inflateViewBinding()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initialize()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onPostEvent(event: PostEvent) {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
EventBus.getDefault().register(this)
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
}
@@ -0,0 +1,77 @@
package com.sw.dualscreen.activity.fragment
import android.view.LayoutInflater
import com.sw.dualscreen.GlobalKey
import com.sw.dualscreen.R
import com.sw.dualscreen.activity.SettingActivity
import com.sw.dualscreen.databinding.FragmentBusinessBinding
import com.sw.dualscreen.model.response.ChargeModeEvent
import com.sw.dualscreen.sdk.SensorScaleUtils
import com.sw.dualscreen.utils.SPUtil
import com.sw.plate.utils.ToastUtils
import org.greenrobot.eventbus.EventBus
import kotlin.math.roundToInt
class BusinessFragment: BaseFragment<FragmentBusinessBinding>() {
override fun inflateViewBinding(): FragmentBusinessBinding {
return FragmentBusinessBinding.inflate(LayoutInflater.from(context))
}
override fun initialize() {
binding.rgCharge.let {
// it.setOnCheckedChangeListener { group, checkedId ->
// val mode = if (checkedId == R.id.rbChargeYes) 0 else 1
// SPUtil.getInstance().put(GlobalKey.KEY_CHARGE_MODE, mode)
// }
val mode = SPUtil.getInstance().get(GlobalKey.KEY_CHARGE_MODE, 0)
it.check(if (mode == 0) R.id.rbChargeYes else R.id.rbChargeNot)
}
binding.rgTakeFood.let {
// it.setOnCheckedChangeListener { group, checkedId ->
// val mode = if (checkedId == R.id.rbPickAndPlace) 0 else 1
// SPUtil.getInstance().put(GlobalKey.KEY_PICKUP_MODE, mode)
// }
val mode = SPUtil.getInstance().get(GlobalKey.KEY_PICKUP_MODE, 0)
it.check(if (mode == 0) R.id.rbPickAndPlace else R.id.rbSurplusCalculate)
}
binding.btnClearZero.setOnClickListener {
SensorScaleUtils.tare()
}
binding.btnConfirm.setOnClickListener { v ->
if (binding.rgCharge.checkedRadioButtonId == -1) {
ToastUtils.showToast("请设置计费模式")
return@setOnClickListener
}
if (binding.rgTakeFood.checkedRadioButtonId == -1) {
ToastUtils.showToast("请设置取餐模式")
return@setOnClickListener
}
val chargeMode = if (binding.rgCharge.checkedRadioButtonId == R.id.rbChargeYes) 0 else 1
//原来的支付模式
val oldChargeMode = SPUtil.getInstance().get(GlobalKey.KEY_CHARGE_MODE, 0)
if (chargeMode != oldChargeMode) {
//支付模式有变化通知首页页面刷新
EventBus.getDefault().post(ChargeModeEvent(chargeMode))
}
SPUtil.getInstance().put(GlobalKey.KEY_CHARGE_MODE, chargeMode)
val pickupMode = if (binding.rgTakeFood.checkedRadioButtonId == R.id.rbPickAndPlace) 0 else 1
SPUtil.getInstance().put(GlobalKey.KEY_PICKUP_MODE, pickupMode)
//ToastUtils.showToast("设置已保存")
(activity as SettingActivity).let {
it.showWaitingDialog("设置保存中")
v.postDelayed({
it.hideWaitingDialog()
it.finish()
}, 1000)
}
}
SensorScaleUtils.addWeightListener { value ->
val realWeight = (value * 1000).roundToInt()
binding.tvFoodWeight.text = "$realWeight"
}
}
}
@@ -0,0 +1,441 @@
package com.sw.dualscreen.activity.fragment
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.camera.view.PreviewView
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.sw.dualscreen.GlobalData
import com.sw.dualscreen.R
import com.sw.dualscreen.activity.CollectedFoodActivity
import com.sw.dualscreen.activity.SettingActivity
import com.sw.dualscreen.adapter.CollectFoodListAdapter
import com.sw.dualscreen.adapter.FoodCollectionAdapter
import com.sw.dualscreen.databinding.FragmentCollectBinding
import com.sw.dualscreen.databinding.LayoutCameraPreviewBinding
import com.sw.dualscreen.ext.clickWithDebounce
import com.sw.dualscreen.ext.dp
import com.sw.dualscreen.model.response.FoodInfo
import com.sw.dualscreen.objbox.Food
import com.sw.dualscreen.objbox.FoodCollectionBean
import com.sw.dualscreen.objbox.FoodModule
import com.sw.dualscreen.objbox.ObjectBox
import com.sw.dualscreen.utils.BitmapSaver
import com.sw.dualscreen.utils.CameraUtils
import com.sw.dualscreen.utils.Debouncer
import com.sw.dualscreen.utils.ImageUploader
import com.sw.dualscreen.utils.ImageUtil
import com.sw.plate.utils.ToastUtils
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import timber.log.Timber
@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 previewView: PreviewView
private val cameraUtils: CameraUtils by lazy {
CameraUtils(requireActivity())
}
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 inflateViewBinding(): FragmentCollectBinding {
return FragmentCollectBinding.inflate(LayoutInflater.from(context))
}
private val cameraCallback: (Uri) -> Unit = { uri ->
try {
val index = foodCollectionList.indexOfFirst { it.imageFile == null }
if (index == -1) {
ToastUtils.showToast("每次只允许保存${MAX_COUNT}条数据")
settingActivity?.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)
}
// settingActivity?.hideWaitingDialog()
Thread {
ImageUtil.uriToBitmap(requireActivity(), uri)?.let { bitmap ->
getImageVector(index, bitmap)
}
}.start()
} catch (e: Exception) {
e.printStackTrace()
settingActivity?.hideWaitingDialog()
ToastUtils.showToast("程序异常${e.message}")
settingActivity?.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()
ToastUtils.showToast("操作失败")
settingActivity?.log("操作失败:${e.message}")
settingActivity?.hideWaitingDialog()
return
}
val file = BitmapSaver.saveToAppFilesDir(
bitmap, requireActivity(), "IMG_CROP_${System.currentTimeMillis()}.jpg"
)
settingActivity?.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()
}
settingActivity?.hideWaitingDialog()
}
@SuppressLint("NotifyDataSetChanged")
private fun takePhoto() {
val count = foodCollectionList.count { it.bitmap != null }
if (count >= MAX_COUNT) {
ToastUtils.showToast("每次只允许保存${MAX_COUNT}条数据")
return
}
settingActivity?.showWaitingDialog("采集中……")
cameraUtils.takePhoto(cameraCallback) { errMsg ->
settingActivity?.hideWaitingDialog()
// ToastUtils.showToast("拍照异常,请重新操作")
// if (cameraErrorCount >= 10) {
// ToastUtils.showToast("拍照异常,请重新操作")
// settingActivity?.log("拍照异常,请重新操作:$errMsg")
// cameraErrorCount = 0
// return@takePhoto
// }
// cameraErrorCount++
// takePhoto()
}
}
private var cameraErrorCount = 0
override fun initialize() {
settingActivity = activity as SettingActivity
cameraUtils.initCamera()
val previewBinding =
LayoutCameraPreviewBinding.inflate(layoutInflater, binding.flCameraPreview)
previewView = previewBinding.previewView.also {
it.updateLayoutParams {
width = 456.dp
height = 342.dp
}
}
cameraUtils.setPreviewController(previewView)
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()) {
ToastUtils.showToast("请选择菜品名称")
return@setOnClickListener
}
val count = foodCollectionList.count { it.imageFile != null }
if (count == 0) {
ToastUtils.showToast("请拍摄菜品照片")
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) {
ToastUtils.showToast("每次只允许保存${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 }
settingActivity?.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 = "]")
Timber.tag(TAG).d("json=$foodVectorJson")
params["foodVector"] = foodVectorJson.toRequestBody()
settingActivity?.viewModel?.uploadCollectFoodPics(files, params)
}, onProgress = { count, batch, idList ->
//batch.forEach {
// it.uploadSuccess = true
//}
runBlocking {
activity?.runOnUiThread {
settingActivity?.showWaitingDialog2("图片上传中$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({
settingActivity?.hideWaitingDialog()
ToastUtils.showToast("上传失败,请稍后重试")
}, 1000)
}
}, onComplete = {
//vectorThread()
binding.root.postDelayed({
settingActivity?.hideWaitingDialog()
ToastUtils.showToast("上传成功")
}, 1000)
}).processUploads()
}
// for (index in foodCollectionList.indices step 5) {
// val end = if(index + 5 < foodCollectionList.size - 1) index + 5 else foodCollectionList.size - 1
// val subList = foodCollectionList.subList(index, end)
// val subFiles = subList.map { it.imageFile }
// uploadCollectFoodPics(subFiles, params) { isSuccess->
// Timber.tag(TAG).d("uploadMultipleImages: ${isSuccess}")
// subList.filter { it.imageFile!=null }.forEach { it.uploadSuccess = isSuccess }
//
//// val count = collectList.count { it.imageFile!=null && it.uploadSuccess.not() }
//// runOnUiThread {
//// binding.btnUploadImage.text = "待上传图片${count}张"
//// if (count == 0) {
//// Loading.dismiss()
//// }
//// }
// }
// }
}
// private fun vectorThread() {
// settingActivity?.showWaitingDialog("加载中……")
// Thread {
// foodCollectionList
//// .filter { it.bitmap != null }
//// .filter { it.imageVector != null }
// .forEachIndexed { index, it ->
// if (it.imageVector == null) {
// return@forEachIndexed
// }
// image2VectorTask(imageVector = it.imageVector!!, index)
// }
// activity?.runOnUiThread {
// binding.root.postDelayed({
// settingActivity?.hideWaitingDialog()
// }, 1000)
// }
// }.start()
// }
// private fun image2VectorTask(imageVector: FloatArray?, position: Int) {
// if (imageVector == null) return
////// val imageVector = FoodModule.bitmap2FloatArray(item.bitmap!!)
//////
//////// val base64Str = FloatBase64Utils.floatArrayToBase64(imageVector)
//////// Timber.tag("mzf1").e(base64Str)
////////// viewModel.postImageData(
////////// context,
////////// foodId = selectedFoodId.toString(),
////////// foodName = selectedFoodName.toString(),
////////// foodVector = base64Str,
////////// uri = item.imageUri!!
////////// )
//// box.put(
//// Food(
//// collectId = null,
//// foodId = checkedItem!!.foodId,
//// foodName = checkedItem!!.foodName,
//// foodVector = imageVector,
//// version = "1.0.0"
//// )
//// )
//// if (position > -1) {
//// foodCollectionList[position].isFinish = true
//// activity?.runOnUiThread {
//// collectionAdapter.notifyItemChanged(position)
//// }
//// }
// }
@SuppressLint("NotifyDataSetChanged")
private fun searchFood() {
debouncer.debounce {
settingActivity?.searchByFoodName(binding.editFoodName.text.toString()) {
searchFoodList.clear()
searchFoodList.addAll(it)
searchFoodAdapter.notifyDataSetChanged()
}
}
}
private var clickIndex = -1
@SuppressLint("NotifyDataSetChanged")
private 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()
}
override fun onResume() {
super.onResume()
cameraUtils.bind()
binding.llCameraFlag.run {
visibility = View.VISIBLE
postDelayed({
visibility = View.GONE
}, 3000)
}
}
override fun onPause() {
super.onPause()
cameraUtils.unbind()
binding.llCameraFlag.visibility = View.VISIBLE
}
}
@@ -0,0 +1,104 @@
package com.sw.dualscreen.activity.fragment.pay
import android.text.Spanned
import android.text.SpannedString
import android.text.style.AbsoluteSizeSpan
import androidx.core.text.buildSpannedString
import com.sw.dualscreen.activity.PayActivity
import com.sw.dualscreen.activity.fragment.BaseFragment
import com.sw.dualscreen.databinding.FragmentCashPayBinding
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.presentation.pay.PayPresentation
import com.sw.plate.utils.ToastUtils
class CashPayFragment : BaseFragment<FragmentCashPayBinding>() {
private lateinit var payActivity: PayActivity
private var foodName: String? = null
private var payAmount: Double? = null
override fun inflateViewBinding(): FragmentCashPayBinding {
return FragmentCashPayBinding.inflate(layoutInflater)
}
override fun initialize() {
payActivity = requireActivity() as PayActivity
payActivity.foodInfo?.let {
foodName = it.foodName
payAmount = (it.specPrice ?: 0.0) * payActivity.eatNum
}
binding.tvRealAmount.text = getAmountText(payAmount.format2String(2))
binding.btnConfirmPayFinish.setOnClickListener {
payActivity.cashPay(
hashMapOf(
//标价金额(单位为元)
"totalFee" to payAmount.format2String(2),
//订单类型(0付款1会员充值)
"orderType" to "0",
//商户订单号
"orderNo" to payActivity.foodOrderId,
//支付来源:0线下收款 、3:线上纯会员支付 101:支付宝主动、102:支付宝被动、201:微信主动、202:微信被动
"paySource" to "0"
)
) { paySuccess ->
if (paySuccess.not()) {
ToastUtils.showToast("接口调用失败")
return@cashPay
}
payActivity.showPaySuccess(false)
}
}
showSubScreen()
}
// override fun onHiddenChanged(hidden: Boolean) {
// super.onHiddenChanged(hidden)
// if (hidden) {
// dismissSubScreen()
// return
// }
// //showSubScreen()
// }
//
// override fun onDestroy() {
// dismissSubScreen()
// super.onDestroy()
// }
//
// private fun dismissSubScreen() {
// }
private fun showSubScreen() {
// // 查找副屏(通常索引为1)
// if (displays.size > 1) {
// dismissSubScreen()
// presentation = PayPresentation(
// activity = payActivity,
// pageType = PayPresentation.CASH_PAY,
// userViewModel = payActivity.userViewModel,
// recognizeViewModel = payActivity.recognizeViewModel,
// display = displays[1]
// ) {
// presentation?.dismiss()
// }.also {
// it.foodName = foodName
// it.payAmount = payAmount.format2String(2)
// }
// presentation?.show()
// }
payActivity.presentation.let {
it.pageType = PayPresentation.CASH_PAY
it.foodName = foodName
it.payAmount = payAmount.format2String(2)
it.initView()
}
}
private fun getAmountText(amount: String): SpannedString {
return buildSpannedString {
append("¥", AbsoluteSizeSpan(36, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
append(amount, AbsoluteSizeSpan(60, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
@@ -0,0 +1,101 @@
package com.sw.dualscreen.activity.fragment.pay
import android.graphics.Bitmap
import com.sw.dualscreen.activity.PayActivity
import com.sw.dualscreen.activity.fragment.BaseFragment
import com.sw.dualscreen.databinding.FragmentFacePayBinding
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.presentation.pay.PayPresentation
class FacePayFragment : BaseFragment<FragmentFacePayBinding>() {
private lateinit var payActivity: PayActivity
private var foodName: String? = null
private var payAmount: Double? = null
override fun inflateViewBinding(): FragmentFacePayBinding {
return FragmentFacePayBinding.inflate(layoutInflater)
}
override fun initialize() {
payActivity = activity as PayActivity
// binding.tvFaceState.setOnClickListener {
// payActivity?.showPayResult()
// }
payActivity.foodInfo?.let {
foodName = it.foodName
payAmount = (it.vipPrice ?: 0.0) * payActivity.eatNum
}
showSubScreen()
}
//
// override fun onHiddenChanged(hidden: Boolean) {
// super.onHiddenChanged(hidden)
// if (hidden) {
//// dismissSubScreen()
// payActivity.presentation.pauseCamera()
// return
// }
// payActivity.presentation.resumeCamera()
// //showSubScreen()
// }
// override fun onDestroy() {
// dismissSubScreen()
// super.onDestroy()
// }
// private fun dismissSubScreen() {
// presentation?.let {
// if (it.isShowing) {
// it.dismiss()
// }
// }
// }
fun loadBitmap(frame: Bitmap) {
binding.ivFaceImage.setImageBitmap(frame)
}
private fun showSubScreen() {
// 查找副屏(通常索引为1
// if (displays.size > 1) {
// dismissSubScreen()
// presentation = PayPresentation(
// activity = payActivity,
// pageType = PayPresentation.FACE_PAY,
// userViewModel = payActivity.userViewModel,
// recognizeViewModel = payActivity.recognizeViewModel,
// display = displays[1]
// ) {
// presentation?.dismiss()
// }.also {
// it.foodName = foodName
// it.payAmount = payAmount.format2String(2)
// }
// presentation?.show()
// }
payActivity.presentation.let {
it.pageType = PayPresentation.FACE_PAY
it.foodName = foodName
it.payAmount = payAmount.format2String(2)
isResumeCamera = true
it.initView()
}
}
override fun onPause() {
super.onPause()
payActivity.presentation.pauseCamera()
}
private var isResumeCamera = false
override fun onResume() {
super.onResume()
if (isResumeCamera) {
payActivity.presentation.resumeCamera()
}
}
}
@@ -0,0 +1,185 @@
package com.sw.dualscreen.activity.fragment.pay
import android.text.InputType
import com.sw.dualscreen.R
import com.sw.dualscreen.activity.PayActivity
import com.sw.dualscreen.activity.fragment.BaseFragment
import com.sw.dualscreen.databinding.FragmentNumberPayBinding
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.ext.hideKeyboard
import com.sw.dualscreen.presentation.pay.PayPresentation
import com.sw.plate.utils.ToastUtils
class NumberPayFragment : BaseFragment<FragmentNumberPayBinding>() {
private lateinit var payActivity: PayActivity
private var foodName: String? = null
private var payAmount: Double? = null
// 密码是否显示的标志
private var isPasswordVisible = false
override fun inflateViewBinding(): FragmentNumberPayBinding {
return FragmentNumberPayBinding.inflate(layoutInflater)
}
override fun initialize() {
binding.root.setOnClickListener { v ->
v.hideKeyboard()
}
payActivity = requireActivity() as PayActivity
payActivity.foodInfo?.let {
foodName = it.foodName
payAmount = (it.specPrice ?: 0.0) * payActivity.eatNum
}
// 密码显示/隐藏切换
binding.ivTogglePassword.setOnClickListener {
togglePasswordVisibility()
}
binding.btnConfirm.setOnClickListener { v ->
val phone = binding.etInputPhone.text.toString().trim()
val key = binding.etInputNumber.text.toString().trim()
if (phone.isBlank() || key.isBlank()) {
ToastUtils.showToast("请输入会员验证信息")
return@setOnClickListener
}
payActivity.showWaitingDialog("加载中,请稍后……")
v.hideKeyboard()
// payActivity.getMemberInfoByPhone(phone, key) { memberInfo ->
// payActivity.bindOrder(memberInfo.id?:"") {
// ToastUtils.showToast("会员验证成功")
// }
// }
payActivity.isMember = false
payActivity.getMemberInfoByPhone(phone, key) { memberInfo ->
if (memberInfo == null) {
binding.root.postDelayed({
payActivity.hideWaitingDialog()
ToastUtils.showToast("未查询到会员信息,请稍后重试")
}, 1000)
return@getMemberInfoByPhone
}
//肯定是会员
memberInfo.member = true
payActivity.isMember = true
//绑定订单使用faceUserId
payActivity.bindOrder(memberInfo.faceUserId ?: "") { bindResult ->
if (bindResult.not()) {
payActivity.hideWaitingDialog()
//ToastUtils.showToast("订单绑定失败")
return@bindOrder
}
binding.root.postDelayed({
payActivity.hideWaitingDialog()
payActivity.showPayInfo(type = 1, isVip = memberInfo.member, memberInfo = memberInfo)
payActivity.hidePayTab()
}, 1000)
}
}
// getMemberInfo(phone, key) { memberInfo ->
// bindOrder(memberInfo.id ?: "") {
// binding.root.postDelayed({
// payActivity.hideWaitingDialog()
// payActivity.showPayInfo(type = 1, isVip = true, memberInfo = memberInfo)
// payActivity.hidePayTab()
// }, 1000)
// }
// }
}
showSubScreen()
}
// override fun onHiddenChanged(hidden: Boolean) {
// super.onHiddenChanged(hidden)
// if (hidden) {
// dismissSubScreen()
// return
// }
// //showSubScreen()
// }
//
// override fun onDestroy() {
// dismissSubScreen()
// super.onDestroy()
// }
// private fun dismissSubScreen() {
// presentation?.let {
// if (it.isShowing) {
// it.dismiss()
// }
// }
// }
private fun showSubScreen() {
// 查找副屏(通常索引为1
// if (displays.size > 1) {
// dismissSubScreen()
// presentation = PayPresentation(
// activity = payActivity,
// pageType = PayPresentation.CASH_PAY,
// userViewModel = payActivity.userViewModel,
// recognizeViewModel = payActivity.recognizeViewModel,
// display = displays[1]
// ).also {
// it.foodName = foodName
// it.payAmount = payAmount.format2String(2)
// }
// presentation?.show()
// }
payActivity.presentation.let {
it.pageType = PayPresentation.CASH_PAY
it.foodName = foodName
it.payAmount = payAmount.format2String(2)
it.initView()
}
}
// 切换密码显示/隐藏
private fun togglePasswordVisibility() {
val editText = binding.etInputNumber
val imageView = binding.ivTogglePassword
// 保存当前光标位置
val cursorPosition = editText.selectionStart
if (isPasswordVisible) {
// 当前显示,改为隐藏
editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
imageView.setImageResource(R.drawable.ic_eye_close)
isPasswordVisible = false
} else {
// 当前隐藏,改为显示
editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
imageView.setImageResource(R.drawable.ic_eye_open)
isPasswordVisible = true
}
// 恢复光标位置
editText.setSelection(cursorPosition)
}
// private fun bindOrder(userId: String, block: () -> Unit) {
// payActivity.bindOrder(userId) { bindResult ->
// if (bindResult.not()) {
// payActivity.hideWaitingDialog()
// //ToastUtils.showToast("订单绑定失败")
// return@bindOrder
// }
// block()
// }
// }
// private fun getMemberInfo(phone: String, key: String, block: (MemberInfo) -> Unit) {
// payActivity.getMemberInfoByPhone(phone, key) { memberInfo ->
// if (memberInfo == null) {
// payActivity.hideWaitingDialog()
// //ToastUtils.showToast("查询会员信息失败,请稍后重试")
// return@getMemberInfoByPhone
// }
// block(memberInfo)
// }
// }
}
@@ -0,0 +1,317 @@
package com.sw.dualscreen.activity.fragment.pay
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.sw.dualscreen.R
import com.sw.dualscreen.activity.PayActivity
import com.sw.dualscreen.activity.fragment.BaseFragment
import com.sw.dualscreen.databinding.FragmentPayResultBinding
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.ext.gone
import com.sw.dualscreen.ext.invisible
import com.sw.dualscreen.ext.load
import com.sw.dualscreen.ext.visible
import com.sw.dualscreen.model.response.MemberInfo
import com.sw.dualscreen.model.response.PaySuccessEvent
import com.sw.dualscreen.model.response.TextBean
import com.sw.dualscreen.utils.IntervalExecutor
import com.sw.dualscreen.utils.SpannedUtils
import com.sw.dualscreen.utils.countDownByFlow
import kotlinx.coroutines.Job
import org.greenrobot.eventbus.EventBus
class PayResultFragment : BaseFragment<FragmentPayResultBinding>() {
//type = 0,扫码支付默认显示二维码
//type = 1,会员结算显示二维码,是会员则显示名字、头像、手机号、可用余额
//type = 2,支付成功,是会员则显示名字、头像、手机号、可用余额
companion object {
const val PAGE_TYPE = "pageType"
const val MEMBER_INFO = "memberInfo"
fun instance(pageType: Int, memberInfo: MemberInfo?): PayResultFragment {
return PayResultFragment().apply {
arguments = Bundle().also {
it.putInt(PAGE_TYPE, pageType)
it.putParcelable(MEMBER_INFO, memberInfo)
}
}
}
}
private var pageType: Int = 1
private var memberInfo: MemberInfo? = null
override fun inflateViewBinding(): FragmentPayResultBinding {
return FragmentPayResultBinding.inflate(layoutInflater)
}
private var countDownJob: Job? = null
private fun closePageCountDown() {
countDownJob = countDownByFlow(
total = 3,
scope = lifecycleScope,
onStart = {
binding.btnBack.text = "返回(3s)..."
},
onTick = { seconds ->
binding.btnBack.text = "返回(${seconds}s)..."
},
onFinish = {
payActivity.finish()
}
)
}
private lateinit var payActivity: PayActivity
override fun initialize() {
payActivity = activity as PayActivity
binding.btnBack.setOnClickListener {
activity?.finish()
}
arguments?.let {
pageType = it.getInt(PAGE_TYPE, 0)
memberInfo = it.getParcelable(MEMBER_INFO)
}
if (memberInfo != null && memberInfo!!.member) {
totalPrice = (payActivity.foodInfo?.vipPrice ?: 0.0) * payActivity.eatNum
binding.layoutVip.visible()
balance = (memberInfo!!.topUpBalance ?: 0.0) + (memberInfo!!.rewardBalance ?: 0.0)
realPayPrice = if (balance >= totalPrice) 0.0 else totalPrice - balance
expensesBalance = if (balance >= totalPrice) totalPrice else balance
loadUserInfo(memberInfo!!)
} else {
binding.layoutVip.gone()
totalPrice = (payActivity.foodInfo?.specPrice ?: 0.0) * payActivity.eatNum
}
when (pageType) {
0 -> {
}
1 -> {
binding.layoutPayInfo.visible()
binding.layoutPaySuccess.gone()
binding.tvRealAmount.text = SpannedUtils.getAmountText(
listOf(
TextBean(text = "¥", textSize = 36),
TextBean(text = totalPrice.format2String(2), textSize = 60),
)
)
//余额扣除 -36.80 元,扣除后可用余额 10.00 元
//余额扣除 -16.80 元,还需支付 20.00 元
binding.tvUserBalance.text = SpannedUtils.getAmountText(
listOf(
TextBean(text = "¥", textSize = 24),
TextBean(text = balance.format2String(2), textSize = 36),
)
)
if (memberInfo != null && memberInfo!!.member) {
binding.tvAccountInfo.text = SpannedUtils.getAmountText(
getAmountList()
)
} else {
binding.tvAccountInfo.text = SpannedUtils.getAmountText(
getAmountListNotMember()
)
}
if (balance >= totalPrice) {
binding.ivPayQrCode.invisible()
binding.btnConfirmPay.run {
isEnabled = true
//点击支付,接口成功打开成功页面
setOnClickListener {
payActivity.showWaitingDialog("支付中,请稍后……")
memberPay(totalPrice.format2String(2)) {
binding.root.postDelayed({
payActivity.hideWaitingDialog()
payActivity.showPaySuccess(true)
}, 1000)
}
}
}
} else {
binding.ivPayQrCode.visible()
binding.btnConfirmPay.isEnabled = false
val payAmount = totalPrice - balance
payActivity.getQrCodeImg(
orderId = payActivity.foodOrderId,
userId = memberInfo!!.id,
//混合支付,实际支付金额
//totalFee = payAmount.format2String(2)
) { qrCodeImg ->
binding.ivPayQrCode.load(qrCodeImg)
//更新副屏二维码
payActivity.updateQrCodeImage(qrCodeImg)
}
paySuccessCallback {
//扫码成功回调打开成功页面,后端处理余额扣除
payActivity.showPaySuccess(true)
// if (balance > 0.0) {
// memberPay(balance.format2String(2)) {
// //扫码成功+会员支付完成后打开成功页面
// payActivity?.showPaySuccess(true)
// }
// } else {
// }
}
}
}
2 -> {
binding.layoutPayInfo.gone()
binding.layoutPaySuccess.visible()
if (memberInfo != null) {
val remainBalance = if (balance >= totalPrice) balance - totalPrice else 0.0
binding.tvUserBalance.text = SpannedUtils.getAmountText(
listOf(
TextBean(text = "¥", textSize = 24),
TextBean(text = remainBalance.format2String(2), textSize = 36),
)
)
val showTotalPrice = totalPrice.format2String(2)
binding.tvPayAmount.text = "收款金额 $showTotalPrice"
val showExpensesBalance = expensesBalance.format2String(2)
binding.tvPayInfo.text =
"应收 $showTotalPrice 元,余额扣除 $showExpensesBalance"
} else {
binding.tvPayAmount.text = "收款金额 ${totalPrice.format2String(2)}"
binding.tvPayInfo.text = "应收 ${totalPrice.format2String(2)}"
}
closePageCountDown()
}
else -> {}
}
}
//总价格
private var totalPrice = 0.0
//余额
private var balance = 0.0
//实际支付金额
private var realPayPrice = 0.0
//扣除余额
private var expensesBalance = 0.0
private fun getAmountListNotMember(): List<TextBean> {
val list: MutableList<TextBean> = mutableListOf()
list.add(TextBean(text = "应付金额 ", textSize = 30, textColor = "#FF889AC2"))
list.add(
TextBean(
text = "-${totalPrice.format2String(2)}",
textSize = 30,
textColor = "#FF0A1428",
isBold = true
)
)
list.add(TextBean(text = "", textSize = 30, textColor = "#FF889AC2"))
return list
}
private fun getAmountList(): List<TextBean> {
val list: MutableList<TextBean> = mutableListOf()
list.add(TextBean(text = "余额扣除 ", textSize = 30, textColor = "#FF889AC2"))
list.add(
TextBean(
text = "-${expensesBalance.format2String(2)}",
textSize = 30,
textColor = "#FF0A1428",
isBold = true
)
)
if (balance >= totalPrice) {
//余额大于等于总价格,使用余额支付
list.add(TextBean(text = " 元,扣除后可用余额 ", textSize = 30, textColor = "#FF889AC2"))
val remainingBalance = balance - totalPrice
list.add(
TextBean(
text = remainingBalance.format2String(2),
textSize = 30,
textColor = "#FF0A1428",
isBold = true
)
)
} else {
//余额小于总价格,使用余额+扫码支付
//实际支付金额
list.add(TextBean(text = " 元,还需支付 ", textSize = 30, textColor = "#FF889AC2"))
list.add(
TextBean(
text = realPayPrice.format2String(2),
textSize = 30,
textColor = "#FF0A1428",
isBold = true
)
)
}
list.add(TextBean(text = "", textSize = 30, textColor = "#FF889AC2"))
return list
}
private fun loadUserInfo(item: MemberInfo) {
binding.ivHeadPic.load(
if(item.faceUrl.isNullOrBlank()) R.drawable.ic_avatar_default
else item.faceUrl
)
binding.tvUserName.text = item.name
val phone = item.phone ?: ""
binding.tvUserPhone.text =
if (phone.length == 11)
phone.replace(phone.substring(3, 7), "****")
else
phone
}
private fun memberPay(total: String, callback: () -> Unit) {
payActivity.run {
memberPay(
param = hashMapOf(
//支付金额
"totalFee" to total,
//订单号
"orderNo" to payActivity.foodOrderId,
//用户id
"memberId" to memberInfo?.id
),
block = callback
)
}
}
override fun onDestroy() {
payTaskJob?.cancel()
super.onDestroy()
}
private val intervalExecutor by lazy { IntervalExecutor() }
private var payTaskJob: Job? = null
fun paySuccessCallback(callback: () -> Unit) {
payTaskJob = intervalExecutor.startIntervalTaskWithInitialDelay(200, 500) {
payActivity?.queryOrderState { paySuccess ->
if (paySuccess) {
callback()
payTaskJob?.cancel()
}
}
}
}
}
@@ -0,0 +1,143 @@
package com.sw.dualscreen.activity.fragment.pay
import android.text.Spanned
import android.text.SpannedString
import android.text.style.AbsoluteSizeSpan
import androidx.core.text.buildSpannedString
import androidx.lifecycle.lifecycleScope
import com.sw.dualscreen.activity.PayActivity
import com.sw.dualscreen.activity.fragment.BaseFragment
import com.sw.dualscreen.ext.load
import com.sw.dualscreen.utils.countDownByFlow
import kotlinx.coroutines.Job
import com.sw.dualscreen.databinding.FragmentScanQrcodePayBinding
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.presentation.pay.PayPresentation
import com.sw.dualscreen.utils.IntervalExecutor
class ScanQrCodePayFragment : BaseFragment<FragmentScanQrcodePayBinding>() {
companion object {
}
private lateinit var payActivity: PayActivity
private var foodName: String? = null
private var payAmount: Double? = null
private var payQrCodePic: String? = null
private var countDownJob: Job? = null
override fun inflateViewBinding(): FragmentScanQrcodePayBinding {
return FragmentScanQrcodePayBinding.inflate(layoutInflater)
}
override fun initialize() {
payActivity = requireActivity() as PayActivity
payActivity.foodInfo?.let {
foodName = it.foodName
payAmount = (it.specPrice ?: 0.0) * payActivity.eatNum
}
binding.tvRealAmount.text = getAmountText(payAmount.format2String(2))
//不需要绑定会员id
payActivity.getQrCodeImg(
orderId = payActivity.foodOrderId,
//非会员扫码支付,不用传金额,后端处理,混合支付要传
//totalFee = payAmount.format2String(2)
) {
payQrCodePic = it
binding.ivPayQrCode.load(payQrCodePic)
binding.tvPayResult.text = "待支付(60s)..."
paySuccessCallback(false)
showSubScreen()
startCountDown()
}
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
// if (hidden) {
//// dismissSubScreen()
// return
// }
//showSubScreen()
}
override fun onDestroy() {
// dismissSubScreen()
countDownJob?.cancel() // 自动取消订阅,防止内存泄漏
payTaskJob?.cancel()
super.onDestroy()
}
private fun dismissSubScreen() {
// presentation?.let {
// if (it.isShowing) {
// it.dismiss()
// }
// }
}
private fun showSubScreen() {
// // 查找副屏(通常索引为1)
// if (displays.size > 1) {
// dismissSubScreen()
// presentation =
// ScanQrCodePayPresentation(activity = payActivity, type = 0, display = displays[1]) {
// presentation?.dismiss()
// }.also {
// it.foodName = foodName
// it.totalPrice = payAmount ?: 0.0
// it.payQrCodePic = payQrCodePic
// }
// presentation?.show()
// }
payActivity.presentation.let {
it.pageType = PayPresentation.QR_CODE_PAY
it.foodName = foodName
it.totalPrice = payAmount ?: 0.0
it.payQrCodePic = payQrCodePic
it.initView()
}
}
private fun getAmountText(amount: String): SpannedString {
return buildSpannedString {
append("¥", AbsoluteSizeSpan(36, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
append(amount, AbsoluteSizeSpan(60, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
private fun startCountDown() {
countDownJob = countDownByFlow(
total = 60,
scope = lifecycleScope,
onStart = {
binding.tvPayResult.text = "待支付(60s)..."
},
onTick = { seconds ->
binding.tvPayResult.text = "待支付(${seconds}s)..."
},
onFinish = {
binding.tvPayResult.text = "待支付"
}
)
}
private val intervalExecutor by lazy { IntervalExecutor() }
private var payTaskJob: Job? = null
fun paySuccessCallback(isVip: Boolean) {
payTaskJob = intervalExecutor.startIntervalTaskWithInitialDelay(200, 500) {
payActivity.queryOrderState { paySuccess ->
if (paySuccess) {
payActivity.showPaySuccess(isVip)
payTaskJob?.cancel()
}
}
}
}
}
@@ -0,0 +1,41 @@
package com.sw.dualscreen.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.sw.dualscreen.R
import com.sw.dualscreen.databinding.ListItemSearchFoodBinding
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.model.response.FoodInfo
class CollectFoodListAdapter(var list: MutableList<FoodInfo>) :
BaseQuickAdapter<FoodInfo, CollectFoodListAdapter.VH>(list) {
inner class VH(var binding: ListItemSearchFoodBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemSearchFoodBinding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: FoodInfo?) {
holder.binding.root.setBackgroundResource(R.drawable.bg_text_collect)
holder.binding.tvFoodName.run {
if (item!!.score == 0) {
text = item.foodName
} else {
val score = (item.score / 100.0).format2String(2)
text = item.foodName + (if (item.score != 0) "-${score}%" else "")
}
isChecked = item.isChecked
setTextColor(
if (isChecked) "#FF3232".toColorInt()
else "#5E7585".toColorInt()
)
}
}
}
@@ -0,0 +1,32 @@
package com.sw.dualscreen.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.sw.dualscreen.databinding.ListItemCollectedFoodBinding
import com.sw.dualscreen.ext.gone
import com.sw.dualscreen.ext.visible
import com.sw.dualscreen.objbox.CollectedFoodInfo
class CollectedFoodNewAdapter(var list: MutableList<CollectedFoodInfo>) :
BaseQuickAdapter<CollectedFoodInfo, CollectedFoodNewAdapter.VH>(list) {
inner class VH(var binding: ListItemCollectedFoodBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemCollectedFoodBinding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: CollectedFoodInfo?) {
holder.binding.tvFoodName.text = item?.foodName
holder.binding.tvCollectedNum.text = "已采集${item?.foodCount}"
holder.binding.divider.run {
if (position == list.size-1) gone() else visible()
}
}
}
@@ -0,0 +1,38 @@
package com.sw.dualscreen.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.sw.dualscreen.R
import com.sw.dualscreen.databinding.ListItemSearchFood2Binding
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.model.response.FoodInfo
class DialogSearchFoodAdapter(var list: MutableList<FoodInfo>) :
BaseQuickAdapter<FoodInfo, DialogSearchFoodAdapter.VH>(list) {
inner class VH(var binding: ListItemSearchFood2Binding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemSearchFood2Binding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: FoodInfo?) {
holder.binding.tvFoodName.run {
if (item!!.score == 0) {
text = item.foodName
} else {
val score = (item.score / 100.0).format2String(2)
text = item.foodName + (if (item.score != 0) "-${score}%" else "")
}
isChecked = item.isChecked
}
}
}
@@ -0,0 +1,60 @@
package com.sw.dualscreen.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.sw.dualscreen.R
import com.sw.dualscreen.databinding.ListItemFoodCollectionBinding
import com.sw.dualscreen.ext.dp
import com.sw.dualscreen.ext.load
import com.sw.dualscreen.objbox.FoodCollectionBean
import com.sw.dualscreen.utils.GlideUtils
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
// )
// }
}
}
}
}
}
@@ -0,0 +1,44 @@
package com.sw.dualscreen.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.sw.dualscreen.R
import com.sw.dualscreen.databinding.ListItemSearchFoodBinding
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.model.response.FoodInfo
class MainFoodListAdapter(var list: MutableList<FoodInfo>) :
BaseQuickAdapter<FoodInfo, MainFoodListAdapter.VH>(list) {
inner class VH(var binding: ListItemSearchFoodBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemSearchFoodBinding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: FoodInfo?) {
holder.binding.root.setBackgroundResource(R.drawable.bg_text_main)
holder.binding.tvFoodName.run {
if (item!!.score == 0) {
text = item.foodName
} else {
val score = (item.score / 100.0).format2String(2)
text = item.foodName + (if (item.score != 0) "-${score}%" else "")
}
isChecked = item.isChecked
setTextColor(
if (isChecked) "#FF3232".toColorInt()
else "#0A1428".toColorInt()
)
}
}
}
@@ -0,0 +1,48 @@
package com.sw.dualscreen.dialog
import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.View
import com.sw.dualscreen.R
import com.sw.dualscreen.ext.dp
import com.sw.dualscreen.ext.hideKeyboard
abstract class BaseDialog(
context: Context,
var defWidth: Int = 400.dp,
var defHeight: Int = 260.dp
) : Dialog(context, R.style.DialogTheme) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val rootView = getRootView()
setContentView(rootView)
setCancelable(false)
setCanceledOnTouchOutside(false)
window?.apply {
setLayout(defWidth, defHeight)
setBackgroundDrawable(ColorDrawable())
setGravity(Gravity.CENTER)
}
rootView.setOnClickListener { it.hideKeyboard() }
initView()
}
abstract fun getRootView(): View
abstract fun initView()
// fun getReceiptActivity(): GoodsListActivity? {
// var ctx = context
// while (ctx is ContextWrapper) {
// ctx = ctx.baseContext
// if (ctx is GoodsListActivity) {
// return ctx
// }
// }
// return null
// }
}
@@ -0,0 +1,34 @@
package com.sw.dualscreen.dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import com.sw.dualscreen.databinding.DialogWarnBinding
class RemindDialog(
context: Context,
var content:String,
var cancelBlock: () -> Unit = {},
var confirmBlock: () -> Unit = {},
) : BaseDialog(context = context) {
private lateinit var binding: DialogWarnBinding
override fun getRootView(): View {
val inflater = LayoutInflater.from(context)
binding = DialogWarnBinding.inflate(inflater)
return binding.root
}
override fun initView() {
binding.tvWarnContent.text = content
binding.btnCancel.setOnClickListener {
cancelBlock()
dismiss()
}
binding.btnConfirm.setOnClickListener {
confirmBlock()
dismiss()
}
}
}
@@ -1,5 +1,6 @@
package com.sw.dualscreen.ext package com.sw.dualscreen.ext
import android.content.Context
import android.content.res.Resources import android.content.res.Resources
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
@@ -7,9 +8,20 @@ import android.graphics.ImageFormat
import android.graphics.Rect import android.graphics.Rect
import android.graphics.YuvImage import android.graphics.YuvImage
import android.util.TypedValue import android.util.TypedValue
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.Dimension import androidx.annotation.Dimension
import androidx.camera.core.ImageProxy import androidx.camera.core.ImageProxy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import java.math.BigDecimal
import java.math.RoundingMode
/** /**
* 将 Int 值转换为 dp 值 * 将 Int 值转换为 dp 值
@@ -55,7 +67,12 @@ val Float.sp: Float
Resources.getSystem().displayMetrics Resources.getSystem().displayMetrics
) )
fun Double.format2String(): String = "%.1f".format(this) fun Double.roundedDecimalPlace(num: Int = 2): Double {
return BigDecimal(this).setScale(num, RoundingMode.HALF_UP).toDouble()
}
fun Double?.format2String(): String = this.format2String(1)
fun Double?.format2String(num:Int): String = "%.${num}f".format(this?:0.0)
// 添加扩展函数 // 添加扩展函数
fun ImageProxy.toSafeBitmap(): Bitmap { fun ImageProxy.toSafeBitmap(): Bitmap {
@@ -81,4 +98,64 @@ fun ImageProxy.toSafeBitmap(): Bitmap {
yuvImage.compressToJpeg(Rect(0, 0, this.width, this.height), 100, out) yuvImage.compressToJpeg(Rect(0, 0, this.width, this.height), 100, out)
val imageBytes = out.toByteArray() val imageBytes = out.toByteArray()
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
} }
fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(this.windowToken, 0)
this.clearFocus() // 清除焦点避免键盘再次弹出
}
fun EditText.addOnActionSearchListener(searchCallback: () -> Unit) {
setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// 处理搜索逻辑
searchCallback()
return@setOnEditorActionListener true // 阻止事件继续传递
}
return@setOnEditorActionListener false
}
}
//fun View.clickWithDebounce(delay: Long = 500, action: () -> Unit) {
// var job: Job? = null
// setOnClickListener {
// job?.cancel()
// job = CoroutineScope(Dispatchers.Main).launch {
// delay(delay)
// action()
// }
// }
//}
/**
* 极简版防重复点击扩展函数
* @param delay 防抖时间(默认300ms
* @param action 点击执行逻辑
*/
fun View.clickWithDebounce(delay: Long = 300, action: () -> Unit) {
setOnClickListener {
// 用View的tag存储是否可点击的状态(默认可点击)
if (tag as? Boolean ?: true) {
tag = false // 标记为不可点击
action() // 立即执行点击逻辑
// 启动协程,延迟后恢复可点击状态
CoroutineScope(Dispatchers.Main).launch {
delay(delay)
tag = true // 恢复可点击
}
}
}
}
fun View.visible() {
visibility = View.VISIBLE
}
fun View.invisible() {
visibility = View.INVISIBLE
}
fun View.gone() {
visibility = View.GONE
}
@@ -2,8 +2,10 @@ package com.sw.dualscreen.ext
import android.graphics.drawable.GradientDrawable import android.graphics.drawable.GradientDrawable
import android.view.View import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorInt import androidx.annotation.ColorInt
import androidx.core.graphics.toColorInt import androidx.core.graphics.toColorInt
import com.sw.dualscreen.utils.GlideUtils
/** /**
* 设置圆角边框 * 设置圆角边框
@@ -27,4 +29,8 @@ fun View.setRoundedBorder(
private fun View.dpToPx(dp: Float): Float { private fun View.dpToPx(dp: Float): Float {
return dp * context.resources.displayMetrics.density return dp * context.resources.displayMetrics.density
}
fun ImageView.load(url: Any?) {
GlideUtils.loadImage(context, url, this)
} }
@@ -0,0 +1,24 @@
package com.sw.dualscreen.model;
import androidx.activity.result.ActivityResult;
import java.util.Map;
public interface IActivityResult {
interface LaunchActivityCallback {
void callback(ActivityResult result);
}
interface LaunchTackPictureCallback {
void callback(boolean result);
}
interface RequestPermissionCallback {
void callback(boolean result);
}
interface RequestMultiplePermissionsCallback {
void callback(Map<String,Boolean> result);
}
}
@@ -1,17 +1,10 @@
package com.sw.dualscreen.model.response package com.sw.dualscreen.model.response
data class ApiResponse<T>( data class ApiResponse<T>(
val code: Int? = 0, val code: String,
val message: String? = "", val msg: String? = "",
val data: T? = null,
val result: T? = null, val result: T? = null,
val success: Boolean? = false, )
val timestamp: Long? = 0
) {
fun isSuccess(): Boolean {
return success == true
}
}
@@ -0,0 +1,161 @@
package com.sw.dualscreen.model.response
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
data class FoodSearchReq(
var nameList: List<String>,
//"订单来源权举:1-营养秤,2-档口
var deviceType: Int = 2
)
data class FoodOrder(
//设备id
var deviceId: String,
//菜品id
var foodId: String,
//菜品名称
var foodName: String,
//菜品营养表id
var foodMaterialId: String,
//餐品规格ID
var specId: String,
//用户id(档口机,内部员工直接取餐:获取的用户ID/memberId
var userId: String? = null,
//食物重量
var foodWeight: Int,
//食用重量
var eatWeight: Int,
//份数
var eatNum: Int,
//是否需要付款
var notPay: Boolean,
//备注
var remark: String? = "",
//即放即取-1,称重-2
var mode: Int
)
@Parcelize
data class MemberInfo(
//会员id
val id: String?,
//刷脸识别用户ID
val faceUserId: String?,
//手机号
val phone: String?,
//姓名
val name: String?,
//头像
val faceUrl: String?,
//充值余额
val topUpBalance: Double?,
//赠送余额
val rewardBalance: Double?,
//积分余额
val integralBalance: Int?,
var member: Boolean = false
) : Parcelable
data class TextBean(
var text: String,
var textSize: Int = 0,
var textColor: String? = null,
var isBold: Boolean = false
)
data class UserNutrition(
//姓名
val name: String?,
//推荐能量
// val recommendEnergy: Double?,
//热量
val calorie: Double?,
//果蔬
val fruitsVegetables: Double?,
//肉蛋
val meatEggs: Double?,
//主食
val stapleFood: Double?,
//能量最大值
val maxCalorie: Double? = null,
//能量最小值
val minCalorie: Double? = null,
//推荐能量
val recommendCalorie: Double? = null,
//主食推荐值
val stapleFoodRecommend: String? = null,
//主食即将超量
val stapleFoodNearExcess: String? = null,
//主食超量
val stapleFoodExcess: String? = null,
//果蔬推荐值
val fruitsVegetablesRecommend: String? = null,
//果蔬即将超量
val fruitsVegetablesNearExcess: String? = null,
//果蔬超量
val fruitsVegetablesExcess: String? = null,
//肉蛋推荐值
val meatEggsRecommend: String? = null,
//肉蛋即将超量
val meatEggsNearExcess: String? = null,
//肉蛋超量
val meatEggsExcess: String? = null,
)
//{"code":"00000","data":"{\"orderType\":0,\"orderPayFrom\":2,\"payType\":\"1\",\"paySuc\":0,\"totalFee\":0.01,\"orderCode\":\"1998193614899372032\",\"message\":\"支付成功\",\"payCode\":\"1998193614899372032508227\"}","msg":"成功","total":0}
data class PayResult(
val paySuc: String? = null
)
data class UserEnergy(
var calorie: Double,
var grain: Double,
var fruitsVegetables: Double,
var meatEggs: Double,
)
data class RespCodeMsg(
val code: String?,
val msg: String?
)
data class PostEvent(var name: String = "")
data class UpdateRefreshEvent(var name:String = "")
data class PaySuccessEvent(
var name: String = ""
)
data class ChargeModeEvent(
var chargeMode: Int = 0
)
data class ClickBackEvent(
var name: String = ""
)
data class DeviceConfig(
var arcsoftAppId: String? = null,
var arcsoftSdkKey: String? = null,
var arcsoftActiveKey: String? = null
)
data class FoodVector(
val id: String? = null,
val foodId: String? = null,
val foodName: String? = null,
val foodVector: String? = null,
val version: String? = null
)
data class ResetBoxEvent(
var num: Int = 0
)
data class WeightRecord(
var foodInfo: FoodInfo? = null,
var lastWeight: Int = 0,
var currentWeight: Int = 0
)
@@ -1,42 +1,47 @@
package com.sw.dualscreen.model.response package com.sw.dualscreen.model.response
//{"id":"1992804086323437569","dinnerType":"晚餐","chargeType":1,"fixedAmount":3.0000}
import android.os.Parcelable data class DinnerType(
import com.google.gson.annotations.SerializedName val id: String? = "",
import kotlinx.parcelize.Parcelize //餐次
val dinnerType: String? = "",
@Parcelize //餐次收费模式(0称重,1固定,2不收费)
data class DinnerTypeInfo( val chargeType: Int = 0,
@SerializedName("dinnerType") //固定收费(元) 仅charge_type = 1 时
val dinnerType: DinnerType? = DinnerType() val fixedAmount: Double?=null
) : Parcelable { )
@Parcelize //@Parcelize
data class DinnerType( //data class DinnerTypeInfo(
@SerializedName("createBy") // @SerializedName("dinnerType")
val createBy: String? = "", // val dinnerType: DinnerType? = DinnerType()
@SerializedName("createTime") //) : Parcelable
val createTime: String? = "", //
@SerializedName("delFlag") //@Parcelize
val delFlag: Int? = 0, //data class DinnerType(
@SerializedName("dinnerType") // @SerializedName("createBy")
val dinnerType: String? = "", // val createBy: String? = "",
@SerializedName("endTime") // @SerializedName("createTime")
val endTime: String? = "", // val createTime: String? = "",
@SerializedName("id") // @SerializedName("delFlag")
val id: Int? = 0, // val delFlag: Int? = 0,
@SerializedName("isSync") // @SerializedName("dinnerType")
val isSync: Int? = 0, // val dinnerType: String? = "",
@SerializedName("isSyncCopy") // @SerializedName("endTime")
val isSyncCopy: Int? = 0, // val endTime: String? = "",
@SerializedName("restId") // @SerializedName("id")
val restId: String? = "", // val id: Int? = 0,
@SerializedName("startTime") // @SerializedName("isSync")
val startTime: String? = "", // val isSync: Int? = 0,
@SerializedName("sysOrgCode") // @SerializedName("isSyncCopy")
val sysOrgCode: String? = "", // val isSyncCopy: Int? = 0,
@SerializedName("updateBy") // @SerializedName("restId")
val updateBy: String? = "", // val restId: String? = "",
@SerializedName("updateTime") // @SerializedName("startTime")
val updateTime: String? = "" // val startTime: String? = "",
) : Parcelable // @SerializedName("sysOrgCode")
} // val sysOrgCode: String? = "",
// @SerializedName("updateBy")
// val updateBy: String? = "",
// @SerializedName("updateTime")
// val updateTime: String? = ""
//) : Parcelable
@@ -12,11 +12,11 @@ data class EquipmentInfo(
@SerializedName("appPackageUrl") @SerializedName("appPackageUrl")
val appPackageUrl: String? = "", val appPackageUrl: String? = "",
@SerializedName("arcsoftActiveKey") @SerializedName("arcsoftActiveKey")
val arcsoftActiveKey: String? = "", var arcsoftActiveKey: String? = "",
@SerializedName("arcsoftAppId") @SerializedName("arcsoftAppId")
val arcsoftAppId: String? = "", var arcsoftAppId: String? = "",
@SerializedName("arcsoftSdkKey") @SerializedName("arcsoftSdkKey")
val arcsoftSdkKey: String? = "", var arcsoftSdkKey: String? = "",
@SerializedName("arrayCross") @SerializedName("arrayCross")
val arrayCross: Int? = 0, val arrayCross: Int? = 0,
@SerializedName("arrayMode") @SerializedName("arrayMode")
@@ -24,9 +24,9 @@ data class EquipmentInfo(
@SerializedName("arrayVertical") @SerializedName("arrayVertical")
val arrayVertical: Int? = 0, val arrayVertical: Int? = 0,
@SerializedName("canteenId") @SerializedName("canteenId")
val canteenId: String? = "", var canteenId: String? = "",
@SerializedName("canteenName") @SerializedName("canteenName")
val canteenName: String? = "", var canteenName: String? = "",
@SerializedName("clientServerIp") @SerializedName("clientServerIp")
val clientServerIp: String? = "", val clientServerIp: String? = "",
@SerializedName("createBy") @SerializedName("createBy")
@@ -1,6 +1,6 @@
package com.sw.dualscreen.model.response package com.sw.dualscreen.model.response
import android.net.Uri
import android.os.Parcelable import android.os.Parcelable
import android.text.TextUtils import android.text.TextUtils
import com.google.gson.annotations.SerializedName import com.google.gson.annotations.SerializedName
@@ -11,286 +11,315 @@ import kotlinx.parcelize.Parcelize
*/ */
@Parcelize @Parcelize
data class FoodInfo( data class FoodInfo(
@SerializedName("foodLabel") //菜品id
val foodLabel: String? = "", val foodId: String,
@SerializedName("foodName") //菜品名称
val foodName: String? = "", val foodName: String? = null,
@SerializedName("foodTypeAndRealIntakeVoList") //能量
val foodTypeAndRealIntakeVoList: List<FoodTypeAndRealIntakeVo?>? = listOf(), val calorie: Double? = null,
/** //蛋白质
* 食物id val protein: Double? = null,
*/ //脂肪
val fat: Double? = null,
//碳水化合物
val carbohydrate: Double? = null,
//规格售卖价格(元)
val specPrice: Double? = null,
//VIP售卖价(元)
val vipPrice: Double? = null,
//餐品营养id
val foodMaterialId: String? = null,
//菜品规格id
val specId: String? = null,
//规格重量(g)
val specWeight: Double? = null,
//主食
val stapleFood: Double? = null,
//果蔬
val fruitsVegetables: Double? = null,
//肉蛋
val meatEggs: Double? = null,
//推荐能量
val recommendCalorie: Double? = null,
//图片
var foodImg: String? = "",
//-----------------------------------
var score: Int = 0,
var isChecked: Boolean = false,
var photoUri: Uri? = null,
//true-搜索结果数据,false-识别查询数据
var isFromSearch: Boolean? = null
// @SerializedName("foodTypeAndRealIntakeVoList")
// val foodTypeAndRealIntakeVoList: List<FoodTypeAndRealIntakeVo>? = listOf(),
// @SerializedName("stFoodInfoMaterial")
// val stFoodInfoMaterial: StFoodInfoMaterial? = StFoodInfoMaterial(),
// @SerializedName("stFoodInfoPagoda")
// val stFoodInfoPagoda: StFoodInfoPagoda? = StFoodInfoPagoda(),
// @SerializedName("stFoodInfoPagodaAPPVO")
// val stFoodInfoPagodaAPPVO: StFoodInfoPagodaAPPVO? = StFoodInfoPagodaAPPVO(),
// @SerializedName("stFoodInfoSetting")
// val stFoodInfoSetting: StFoodInfoSetting? = StFoodInfoSetting(),
// @SerializedName("stFoodInfoSpecificationList")
// val stFoodInfoSpecificationList: List<StFoodInfoSpecification>? = listOf(),
) : Parcelable
//@Parcelize
//data class FoodTypeAndRealIntakeVo(
// @SerializedName("childMaterClassName")
// val childMaterClassName: String? = "",
// @SerializedName("foodId")
// val foodId: String? = "",
// @SerializedName("goodsId")
// val goodsId: String? = "",
// @SerializedName("goodsName")
// val goodsName: String? = "",
// @SerializedName("materClassName")
// val materClassName: String? = "",
// @SerializedName("materId")
// val materId: String? = "",
// @SerializedName("materialType")
// val materialType: String? = "",
// @SerializedName("realityIntake")
// val realityIntake: String? = ""
//) : Parcelable
@Parcelize
data class StFoodInfoMaterial(
@SerializedName("ash")
val ash: Double? = 0.0,
@SerializedName("avitE")
val avitE: Double? = 0.0,
@SerializedName("ca")
val ca: Double? = 0.0,
@SerializedName("cho")
val cho: Double? = 0.0,
@SerializedName("cholesterol")
val cholesterol: Double? = 0.0,
@SerializedName("cu")
val cu: Double? = 0.0,
@SerializedName("delFlag")
val delFlag: String? = "",
@SerializedName("dietFiber")
val dietFiber: Double? = 0.0,
@SerializedName("elementI")
val elementI: Double? = 0.0,
@SerializedName("elementK")
val elementK: String? = "",
@SerializedName("elementP")
val elementP: String? = "",
@SerializedName("energyKcal")
val energyKcal: Double? = 0.0,
@SerializedName("energyKj")
val energyKj: Double? = 0.0,
@SerializedName("fat")
val fat: Double? = 0.0,
@SerializedName("fe")
val fe: Double? = 0.0,
@SerializedName("folate")
val folate: Double? = 0.0,
@SerializedName("foodId")
val foodId: String? = "",
@SerializedName("foodWeight")
val foodWeight: String? = "",
@SerializedName("historyStatus")
val historyStatus: String? = "",
@SerializedName("id") @SerializedName("id")
val id: String? = "", val id: String? = "",
@SerializedName("imgUrl") @SerializedName("isSync")
val imgUrl: String? = "", val isSync: String? = "",
@SerializedName("stFoodInfoMaterial") @SerializedName("isSyncCopy")
val stFoodInfoMaterial: StFoodInfoMaterial? = StFoodInfoMaterial(), val isSyncCopy: String? = "",
@SerializedName("stFoodInfoPagoda") @SerializedName("mg")
val stFoodInfoPagoda: StFoodInfoPagoda? = StFoodInfoPagoda(), val mg: Double? = 0.0,
@SerializedName("stFoodInfoPagodaAPPVO") @SerializedName("mn")
val stFoodInfoPagodaAPPVO: StFoodInfoPagodaAPPVO? = StFoodInfoPagodaAPPVO(), val mn: Double? = 0.0,
@SerializedName("stFoodInfoSetting") @SerializedName("na")
val stFoodInfoSetting: StFoodInfoSetting? = StFoodInfoSetting(), val na: Double? = 0.0,
@SerializedName("stFoodInfoSpecificationList") @SerializedName("naicin")
val stFoodInfoSpecificationList: List<StFoodInfoSpecification?>? = listOf() val naicin: Double? = 0.0,
@SerializedName("protein")
val protein: Double? = 0.0,
@SerializedName("retionl")
val retionl: Double? = 0.0,
@SerializedName("riboflavin")
val riboflavin: Double? = 0.0,
@SerializedName("se")
val se: Double? = 0.0,
@SerializedName("thiamin")
val thiamin: Double? = 0.0,
@SerializedName("totCarotene")
val totCarotene: Double? = 0.0,
@SerializedName("vitA")
val vitA: Double? = 0.0,
@SerializedName("vitB12")
val vitB12: Double? = 0.0,
@SerializedName("vitB6")
val vitB6: Double? = 0.0,
@SerializedName("vitC")
val vitC: Double? = 0.0,
@SerializedName("vitE")
val vitE: Double? = 0.0,
@SerializedName("water")
val water: Double? = 0.0,
@SerializedName("zn")
val zn: Double? = 0.0
) : Parcelable
//@Parcelize
//data class StFoodInfoPagoda(
// @SerializedName("aquatic")
// val aquatic: String? = "",
// @SerializedName("birds")
// val birds: String? = "",
// @SerializedName("delFlag")
// val delFlag: String? = "",
// @SerializedName("egg")
// val egg: String? = "",
// @SerializedName("foodId")
// val foodId: String? = "",
// @SerializedName("fruits")
// val fruits: String? = "",
// @SerializedName("grain")
// val grain: String? = "",
// @SerializedName("id")
// val id: String? = "",
// @SerializedName("isSync")
// val isSync: String? = "",
// @SerializedName("isSyncCopy")
// val isSyncCopy: String? = "",
// @SerializedName("livestock")
// val livestock: String? = "",
// @SerializedName("milk")
// val milk: String? = "",
// @SerializedName("nuts")
// val nuts: String? = "",
// @SerializedName("oil")
// val oil: String? = "",
// @SerializedName("potato")
// val potato: String? = "",
// @SerializedName("salt")
// val salt: String? = "",
// @SerializedName("soya")
// val soya: String? = "",
// @SerializedName("sugar")
// val sugar: String? = "",
// @SerializedName("vegetable")
// val vegetable: String? = ""
//) : Parcelable
@Parcelize
data class StFoodInfoPagodaAPPVO(
@SerializedName("fruits")
val fruits: String? = "",
@SerializedName("fruitsRecommend")
val fruitsRecommend: String? = "",
@SerializedName("grain")
val grain: String? = "",
@SerializedName("grainRecommend")
val grainRecommend: String? = "",
@SerializedName("meat")
val meat: String? = "",
@SerializedName("meatRecommend")
val meatRecommend: String? = "",
@SerializedName("oil")
val oil: String? = "",
@SerializedName("salt")
val salt: String? = "",
@SerializedName("soya")
val soya: String? = "",
@SerializedName("soyaRecommend")
val soyaRecommend: String? = "",
@SerializedName("sugar")
val sugar: String? = "",
@SerializedName("vegetable")
val vegetable: String? = "",
@SerializedName("vegetableRecommend")
val vegetableRecommend: String? = ""
) : Parcelable { ) : Parcelable {
@Parcelize
data class FoodTypeAndRealIntakeVo(
@SerializedName("childMaterClassName")
val childMaterClassName: String? = "",
@SerializedName("foodId")
val foodId: String? = "",
@SerializedName("goodsId")
val goodsId: String? = "",
@SerializedName("goodsName")
val goodsName: String? = "",
@SerializedName("materClassName")
val materClassName: String? = "",
@SerializedName("materId")
val materId: String? = "",
@SerializedName("materialType")
val materialType: String? = "",
@SerializedName("realityIntake")
val realityIntake: String? = ""
) : Parcelable
@Parcelize fun fruitsValue(): Double =
data class StFoodInfoMaterial( if (TextUtils.isEmpty(fruits))
@SerializedName("ash") 0.0
val ash: Double? = 0.0, else fruits!!.toDouble()
@SerializedName("avitE")
val avitE: Double? = 0.0,
@SerializedName("ca")
val ca: Double? = 0.0,
@SerializedName("cho")
val cho: Double? = 0.0,
@SerializedName("cholesterol")
val cholesterol: Double? = 0.0,
@SerializedName("cu")
val cu: Double? = 0.0,
@SerializedName("delFlag")
val delFlag: String? = "",
@SerializedName("dietFiber")
val dietFiber: Double? = 0.0,
@SerializedName("elementI")
val elementI: Double? = 0.0,
@SerializedName("elementK")
val elementK: String? = "",
@SerializedName("elementP")
val elementP: String? = "",
@SerializedName("energyKcal")
val energyKcal: Double? = 0.0,
@SerializedName("energyKj")
val energyKj: Double? = 0.0,
@SerializedName("fat")
val fat: Double? = 0.0,
@SerializedName("fe")
val fe: Double? = 0.0,
@SerializedName("folate")
val folate: Double? = 0.0,
@SerializedName("foodId")
val foodId: String? = "",
@SerializedName("foodWeight")
val foodWeight: String? = "",
@SerializedName("historyStatus")
val historyStatus: String? = "",
@SerializedName("id")
val id: String? = "",
@SerializedName("isSync")
val isSync: String? = "",
@SerializedName("isSyncCopy")
val isSyncCopy: String? = "",
@SerializedName("mg")
val mg: Double? = 0.0,
@SerializedName("mn")
val mn: Double? = 0.0,
@SerializedName("na")
val na: Double? = 0.0,
@SerializedName("naicin")
val naicin: Double? = 0.0,
@SerializedName("protein")
val protein: Double? = 0.0,
@SerializedName("retionl")
val retionl: Double? = 0.0,
@SerializedName("riboflavin")
val riboflavin: Double? = 0.0,
@SerializedName("se")
val se: Double? = 0.0,
@SerializedName("thiamin")
val thiamin: Double? = 0.0,
@SerializedName("totCarotene")
val totCarotene: Double? = 0.0,
@SerializedName("vitA")
val vitA: Double? = 0.0,
@SerializedName("vitB12")
val vitB12: Double? = 0.0,
@SerializedName("vitB6")
val vitB6: Double? = 0.0,
@SerializedName("vitC")
val vitC: Double? = 0.0,
@SerializedName("vitE")
val vitE: Double? = 0.0,
@SerializedName("water")
val water: Double? = 0.0,
@SerializedName("zn")
val zn: Double? = 0.0
) : Parcelable
@Parcelize fun grainValue(): Double =
data class StFoodInfoPagoda( if (TextUtils.isEmpty(grain))
@SerializedName("aquatic") 0.0
val aquatic: String? = "", else grain!!.toDouble()
@SerializedName("birds")
val birds: String? = "",
@SerializedName("delFlag")
val delFlag: String? = "",
@SerializedName("egg")
val egg: String? = "",
@SerializedName("foodId")
val foodId: String? = "",
@SerializedName("fruits")
val fruits: String? = "",
@SerializedName("grain")
val grain: String? = "",
@SerializedName("id")
val id: String? = "",
@SerializedName("isSync")
val isSync: String? = "",
@SerializedName("isSyncCopy")
val isSyncCopy: String? = "",
@SerializedName("livestock")
val livestock: String? = "",
@SerializedName("milk")
val milk: String? = "",
@SerializedName("nuts")
val nuts: String? = "",
@SerializedName("oil")
val oil: String? = "",
@SerializedName("potato")
val potato: String? = "",
@SerializedName("salt")
val salt: String? = "",
@SerializedName("soya")
val soya: String? = "",
@SerializedName("sugar")
val sugar: String? = "",
@SerializedName("vegetable")
val vegetable: String? = ""
) : Parcelable
@Parcelize fun vegetableValue(): Double =
data class StFoodInfoPagodaAPPVO( if (TextUtils.isEmpty(vegetable))
@SerializedName("fruits") 0.0
val fruits: String? = "", else vegetable!!.toDouble()
@SerializedName("fruitsRecommend")
val fruitsRecommend: String? = "",
@SerializedName("grain")
val grain: String? = "",
@SerializedName("grainRecommend")
val grainRecommend: String? = "",
@SerializedName("meat")
val meat: String? = "",
@SerializedName("meatRecommend")
val meatRecommend: String? = "",
@SerializedName("oil")
val oil: String? = "",
@SerializedName("salt")
val salt: String? = "",
@SerializedName("soya")
val soya: String? = "",
@SerializedName("soyaRecommend")
val soyaRecommend: String? = "",
@SerializedName("sugar")
val sugar: String? = "",
@SerializedName("vegetable")
val vegetable: String? = "",
@SerializedName("vegetableRecommend")
val vegetableRecommend: String? = ""
) : Parcelable {
fun fruitsValue(): Double = fun meatValue(): Double =
if (TextUtils.isEmpty(fruits)) if (TextUtils.isEmpty(meat))
0.0 0.0
else fruits!!.toDouble() else meat!!.toDouble()
}
fun grainValue(): Double = //@Parcelize
if (TextUtils.isEmpty(grain)) //data class StFoodInfoSetting(
0.0 // @SerializedName("addFoodWeight")
else grain!!.toDouble() // val addFoodWeight: String? = "",
// @SerializedName("bowlPlateWeight")
// val bowlPlateWeight: String? = "",
// @SerializedName("delFlag")
// val delFlag: String? = "",
// @SerializedName("foodId")
// val foodId: String? = "",
// @SerializedName("foodStatus")
// val foodStatus: String? = "",
// @SerializedName("id")
// val id: String? = "",
// @SerializedName("inventoryStatus")
// val inventoryStatus: Boolean? = false,
// @SerializedName("isSync")
// val isSync: String? = "",
// @SerializedName("isSyncCopy")
// val isSyncCopy: String? = "",
// @SerializedName("replenishWeight")
// val replenishWeight: String? = "",
// @SerializedName("residueType")
// val residueType: String? = "",
// @SerializedName("tablewareStatus")
// val tablewareStatus: Boolean? = false,
// @SerializedName("tablewareWeight")
// val tablewareWeight: String? = "",
// @SerializedName("warningStatus")
// val warningStatus: String? = "",
// @SerializedName("weighStatus")
// val weighStatus: String? = "",
// @SerializedName("weighUnitId")
// val weighUnitId: String? = "",
// @SerializedName("weighUnitName")
// val weighUnitName: String? = ""
//) : Parcelable
fun vegetableValue(): Double = //@Parcelize
if (TextUtils.isEmpty(vegetable)) //data class StFoodInfoSpecification(
0.0 // @SerializedName("bowlPlateWeight")
else vegetable!!.toDouble() // val bowlPlateWeight: Double? = 0.0,
// @SerializedName("defaultStatus")
fun meatValue(): Double = // val defaultStatus: String? = "",
if (TextUtils.isEmpty(meat)) // @SerializedName("delFlag")
0.0 // val delFlag: String? = "",
else meat!!.toDouble() // @SerializedName("foodId")
} // val foodId: String? = "",
// @SerializedName("id")
@Parcelize // val id: String? = "",
data class StFoodInfoSetting( // @SerializedName("isSync")
@SerializedName("addFoodWeight") // val isSync: String? = "",
val addFoodWeight: String? = "", // @SerializedName("isSyncCopy")
@SerializedName("bowlPlateWeight") // val isSyncCopy: String? = "",
val bowlPlateWeight: String? = "", // @SerializedName("specId")
@SerializedName("delFlag") // val specId: String? = "",
val delFlag: String? = "", // @SerializedName("specName")
@SerializedName("foodId") // val specName: String? = "",
val foodId: String? = "", // @SerializedName("specPrice")
@SerializedName("foodStatus") // val specPrice: String? = "",
val foodStatus: String? = "", // @SerializedName("specWeight")
@SerializedName("id") // val specWeight: Double? = 0.0
val id: String? = "", //) : Parcelable
@SerializedName("inventoryStatus")
val inventoryStatus: Boolean? = false,
@SerializedName("isSync")
val isSync: String? = "",
@SerializedName("isSyncCopy")
val isSyncCopy: String? = "",
@SerializedName("replenishWeight")
val replenishWeight: String? = "",
@SerializedName("residueType")
val residueType: String? = "",
@SerializedName("tablewareStatus")
val tablewareStatus: Boolean? = false,
@SerializedName("tablewareWeight")
val tablewareWeight: String? = "",
@SerializedName("warningStatus")
val warningStatus: String? = "",
@SerializedName("weighStatus")
val weighStatus: String? = "",
@SerializedName("weighUnitId")
val weighUnitId: String? = "",
@SerializedName("weighUnitName")
val weighUnitName: String? = ""
) : Parcelable
@Parcelize
data class StFoodInfoSpecification(
@SerializedName("bowlPlateWeight")
val bowlPlateWeight: Double? = 0.0,
@SerializedName("defaultStatus")
val defaultStatus: String? = "",
@SerializedName("delFlag")
val delFlag: String? = "",
@SerializedName("foodId")
val foodId: String? = "",
@SerializedName("id")
val id: String? = "",
@SerializedName("isSync")
val isSync: String? = "",
@SerializedName("isSyncCopy")
val isSyncCopy: String? = "",
@SerializedName("specId")
val specId: String? = "",
@SerializedName("specName")
val specName: String? = "",
@SerializedName("specPrice")
val specPrice: String? = "",
@SerializedName("specWeight")
val specWeight: Double? = 0.0
) : Parcelable
}
@@ -10,14 +10,43 @@ import kotlinx.parcelize.Parcelize
*/ */
@Parcelize @Parcelize
data class UserFaceModel( data class UserFaceModel(
@SerializedName("faceFeature") // @SerializedName("faceFeature")
val faceFeature: String? = "", // val faceFeature: String? = "",
@SerializedName("faceFeatureString") // @SerializedName("faceFeatureString")
// val faceFeatureString: String? = "",
// @SerializedName("faceType")
// val faceType: String? = "",
// @SerializedName("userFaceId")
// val userFaceId: String? = "",
// @SerializedName("userId")
val userId: String? = "",
val faceFeatureStr: String? = "",
val faceUpdateTimestamp:Long?=null,
val faceDeleted: Boolean? = false,
/**
* 会员编号
*/
val cardNo: String,
/**
* 是否会员
*/
val member: Boolean
) : Parcelable
@Parcelize
data class UserFaceModel2(
val userId: String? = "",
val faceFeatureString: String? = "", val faceFeatureString: String? = "",
@SerializedName("faceType") val face: String? = ""
val faceType: String? = "", ) : Parcelable
@SerializedName("userFaceId")
val userFaceId: String? = "", data class FaceData(
@SerializedName("userId") val nextPageIndex:Int,
val userId: String? = "" val total:Int,
) : Parcelable val size:Int,
val current:Int,
val pages:Int,
val records: List<UserFaceModel2>?=null
)
@@ -1,253 +1,253 @@
package com.sw.dualscreen.model.response //package com.sw.dualscreen.model.response
//
//
import android.os.Parcelable //import android.os.Parcelable
import android.text.TextUtils //import android.text.TextUtils
import com.google.gson.annotations.SerializedName //import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize //import kotlinx.parcelize.Parcelize
//
/** ///**
* 就餐数据 // * 就餐数据
*/ // */
@Parcelize //@Parcelize
data class UserNutritionData( //data class UserNutritionData(
/** // /**
* 总胆固醇 // * 总胆固醇
*/ // */
@SerializedName("cho") // @SerializedName("cho")
val cho: String? = "", // val cho: String? = "",
/** // /**
* 饮食纤维 // * 饮食纤维
*/ // */
@SerializedName("dietFiber") // @SerializedName("dietFiber")
val dietFiber: String? = "", // val dietFiber: String? = "",
/** // /**
* 能量 // * 能量
*/ // */
@SerializedName("energy") // @SerializedName("energy")
val energy: String? = "", // val energy: String? = "",
/** // /**
* 脂肪 // * 脂肪
*/ // */
@SerializedName("fat") // @SerializedName("fat")
val fat: String? = "", // val fat: String? = "",
/** // /**
* 食物类型和实际摄入量清单 // * 食物类型和实际摄入量清单
*/ // */
@SerializedName("foodTypeAndRealIntakeVoList") // @SerializedName("foodTypeAndRealIntakeVoList")
val foodTypeAndRealIntakeVoList: List<FoodTypeAndRealIntakeVo?>? = listOf(), // val foodTypeAndRealIntakeVoList: List<FoodTypeAndRealIntakeVo?>? = listOf(),
@SerializedName("foodWeight") // @SerializedName("foodWeight")
val foodWeight: String? = "", // val foodWeight: String? = "",
@SerializedName("message") // @SerializedName("message")
val message: String? = "", // val message: String? = "",
/** // /**
* 钠 // * 钠
*/ // */
@SerializedName("na") // @SerializedName("na")
val na: String? = "", // val na: String? = "",
/** // /**
* 蛋白质 // * 蛋白质
*/ // */
@SerializedName("protein") // @SerializedName("protein")
val protein: String? = "", // val protein: String? = "",
/** // /**
* 最大推荐热量 // * 最大推荐热量
*/ // */
@SerializedName("recommendMax") // @SerializedName("recommendMax")
val recommendMax: String? = "", // val recommendMax: String? = "",
/** // /**
* 最小推荐热量 // * 最小推荐热量
*/ // */
@SerializedName("recommendMin") // @SerializedName("recommendMin")
val recommendMin: String? = "", // val recommendMin: String? = "",
/** // /**
* 热量详情 // * 热量详情
*/ // */
@SerializedName("stFoodInfoPagoda") // @SerializedName("stFoodInfoPagoda")
val stFoodInfoPagoda: StFoodInfoPagoda? = StFoodInfoPagoda(), // val stFoodInfoPagoda: StFoodInfoPagoda? = StFoodInfoPagoda(),
@SerializedName("stUserFoodInfoList") // @SerializedName("stUserFoodInfoList")
val stUserFoodInfoList: List<StUserFoodInfo?>? = listOf(), // val stUserFoodInfoList: List<StUserFoodInfo?>? = listOf(),
/** // /**
* 每日总热量 // * 每日总热量
*/ // */
@SerializedName("totalEnergyCalculateScore") // @SerializedName("totalEnergyCalculateScore")
val totalEnergyCalculateScore: String? = "", // val totalEnergyCalculateScore: String? = "",
/** // /**
* 用户所在部门 // * 用户所在部门
*/ // */
@SerializedName("userDept") // @SerializedName("userDept")
val userDept: String? = "", // val userDept: String? = "",
/** // /**
* 用户id // * 用户id
*/ // */
@SerializedName("userId") // @SerializedName("userId")
val userId: String? = "", // val userId: String? = "",
/** // /**
* 姓名 // * 姓名
*/ // */
@SerializedName("userName") // @SerializedName("userName")
val userName: String? = "" // val userName: String? = ""
) : Parcelable { //) : Parcelable {
fun recommendMaxValue(): Double = // fun recommendMaxValue(): Double =
if (TextUtils.isEmpty(recommendMax)) 0.0 // if (TextUtils.isEmpty(recommendMax)) 0.0
else recommendMax!!.toDouble() // else recommendMax!!.toDouble()
//
fun recommendMinValue(): Double = // fun recommendMinValue(): Double =
if (TextUtils.isEmpty(recommendMin)) 0.0 // if (TextUtils.isEmpty(recommendMin)) 0.0
else recommendMin!!.toDouble() // else recommendMin!!.toDouble()
//
fun energyValue(): Double = // fun energyValue(): Double =
if (TextUtils.isEmpty(energy)) 0.0 // if (TextUtils.isEmpty(energy)) 0.0
else energy!!.toDouble() // else energy!!.toDouble()
//
fun totalEnergyCalculateScoreValue(): Double = // fun totalEnergyCalculateScoreValue(): Double =
if (TextUtils.isEmpty(totalEnergyCalculateScore)) 0.0 // if (TextUtils.isEmpty(totalEnergyCalculateScore)) 0.0
else totalEnergyCalculateScore!!.toDouble() // else totalEnergyCalculateScore!!.toDouble()
//
@Parcelize // @Parcelize
data class FoodTypeAndRealIntakeVo( // data class FoodTypeAndRealIntakeVo(
@SerializedName("childMaterClassName") // @SerializedName("childMaterClassName")
val childMaterClassName: String? = "", // val childMaterClassName: String? = "",
@SerializedName("foodId") // @SerializedName("foodId")
val foodId: String? = "", // val foodId: String? = "",
@SerializedName("goodsId") // @SerializedName("goodsId")
val goodsId: String? = "", // val goodsId: String? = "",
@SerializedName("goodsName") // @SerializedName("goodsName")
val goodsName: String? = "", // val goodsName: String? = "",
@SerializedName("materClassName") // @SerializedName("materClassName")
val materClassName: String? = "", // val materClassName: String? = "",
@SerializedName("materId") // @SerializedName("materId")
val materId: String? = "", // val materId: String? = "",
@SerializedName("materialType") // @SerializedName("materialType")
val materialType: String? = "", // val materialType: String? = "",
@SerializedName("realityIntake") // @SerializedName("realityIntake")
val realityIntake: String? = "" // val realityIntake: String? = ""
) : Parcelable // ) : Parcelable
//
@Parcelize // @Parcelize
data class StFoodInfoPagoda( // data class StFoodInfoPagoda(
/** // /**
* 水果 // * 水果
*/ // */
@SerializedName("fruits") // @SerializedName("fruits")
val fruits: String? = "", // val fruits: String? = "",
@SerializedName("fruitsRecommend") // @SerializedName("fruitsRecommend")
val fruitsRecommend: String? = "", // val fruitsRecommend: String? = "",
/** // /**
* 粮食 // * 粮食
*/ // */
@SerializedName("grain") // @SerializedName("grain")
val grain: String? = "", // val grain: String? = "",
@SerializedName("grainRecommend") // @SerializedName("grainRecommend")
val grainRecommend: String? = "", // val grainRecommend: String? = "",
/** // /**
* 肉 // * 肉
*/ // */
@SerializedName("meat") // @SerializedName("meat")
val meat: String? = "", // val meat: String? = "",
@SerializedName("meatRecommend") // @SerializedName("meatRecommend")
val meatRecommend: String? = "", // val meatRecommend: String? = "",
/** // /**
* 油 // * 油
*/ // */
@SerializedName("oil") // @SerializedName("oil")
val oil: String? = "", // val oil: String? = "",
/** // /**
* 盐 // * 盐
*/ // */
@SerializedName("salt") // @SerializedName("salt")
val salt: String? = "", // val salt: String? = "",
/** // /**
* 大豆 // * 大豆
*/ // */
@SerializedName("soya") // @SerializedName("soya")
val soya: String? = "", // val soya: String? = "",
@SerializedName("soyaRecommend") // @SerializedName("soyaRecommend")
val soyaRecommend: String? = "", // val soyaRecommend: String? = "",
/** // /**
* 糖 // * 糖
*/ // */
@SerializedName("sugar") // @SerializedName("sugar")
val sugar: String? = "", // val sugar: String? = "",
/** // /**
* 蔬菜 // * 蔬菜
*/ // */
@SerializedName("vegetable") // @SerializedName("vegetable")
val vegetable: String? = "", // val vegetable: String? = "",
@SerializedName("vegetableRecommend") // @SerializedName("vegetableRecommend")
val vegetableRecommend: String? = "" // val vegetableRecommend: String? = ""
) : Parcelable { // ) : Parcelable {
fun fruitsValue(): Double = // fun fruitsValue(): Double =
if (TextUtils.isEmpty(fruits)) // if (TextUtils.isEmpty(fruits))
0.0 // 0.0
else fruits!!.toDouble() // else fruits!!.toDouble()
//
fun grainValue(): Double = // fun grainValue(): Double =
if (TextUtils.isEmpty(grain)) // if (TextUtils.isEmpty(grain))
0.0 // 0.0
else grain!!.toDouble() // else grain!!.toDouble()
//
fun vegetableValue(): Double = // fun vegetableValue(): Double =
if (TextUtils.isEmpty(vegetable)) // if (TextUtils.isEmpty(vegetable))
0.0 // 0.0
else vegetable!!.toDouble() // else vegetable!!.toDouble()
//
fun meatValue(): Double = // fun meatValue(): Double =
if (TextUtils.isEmpty(meat)) // if (TextUtils.isEmpty(meat))
0.0 // 0.0
else meat!!.toDouble() // else meat!!.toDouble()
//
} // }
//
@Parcelize // @Parcelize
data class StUserFoodInfo( // data class StUserFoodInfo(
@SerializedName("canteenId") // @SerializedName("canteenId")
val canteenId: String? = "", // val canteenId: String? = "",
@SerializedName("createBy") // @SerializedName("createBy")
val createBy: String? = "", // val createBy: String? = "",
@SerializedName("createTime") // @SerializedName("createTime")
val createTime: String? = "", // val createTime: String? = "",
@SerializedName("dataSource") // @SerializedName("dataSource")
val dataSource: String? = "", // val dataSource: String? = "",
@SerializedName("dataType") // @SerializedName("dataType")
val dataType: String? = "", // val dataType: String? = "",
@SerializedName("delFlag") // @SerializedName("delFlag")
val delFlag: String? = "", // val delFlag: String? = "",
@SerializedName("deviceId") // @SerializedName("deviceId")
val deviceId: String? = "", // val deviceId: String? = "",
@SerializedName("dinnerType") // @SerializedName("dinnerType")
val dinnerType: String? = "", // val dinnerType: String? = "",
@SerializedName("eatDay") // @SerializedName("eatDay")
val eatDay: String? = "", // val eatDay: String? = "",
@SerializedName("eatNum") // @SerializedName("eatNum")
val eatNum: String? = "", // val eatNum: String? = "",
@SerializedName("eatWeight") // @SerializedName("eatWeight")
val eatWeight: Double? = 0.0, // val eatWeight: Double? = 0.0,
@SerializedName("foodId") // @SerializedName("foodId")
val foodId: String? = "", // val foodId: String? = "",
@SerializedName("foodImg") // @SerializedName("foodImg")
val foodImg: String? = "", // val foodImg: String? = "",
@SerializedName("foodMaterialId") // @SerializedName("foodMaterialId")
val foodMaterialId: String? = "", // val foodMaterialId: String? = "",
@SerializedName("foodName") // @SerializedName("foodName")
val foodName: String? = "", // val foodName: String? = "",
@SerializedName("foodWeight") // @SerializedName("foodWeight")
val foodWeight: String? = "", // val foodWeight: String? = "",
@SerializedName("id") // @SerializedName("id")
val id: String? = "", // val id: String? = "",
@SerializedName("isSync") // @SerializedName("isSync")
val isSync: String? = "", // val isSync: String? = "",
@SerializedName("isSyncCopy") // @SerializedName("isSyncCopy")
val isSyncCopy: String? = "", // val isSyncCopy: String? = "",
@SerializedName("specId") // @SerializedName("specId")
val specId: String? = "", // val specId: String? = "",
@SerializedName("stBasicDiningInformationUserESVo") // @SerializedName("stBasicDiningInformationUserESVo")
val stBasicDiningInformationUserESVo: String? = "", // val stBasicDiningInformationUserESVo: String? = "",
@SerializedName("stallType") // @SerializedName("stallType")
val stallType: String? = "", // val stallType: String? = "",
@SerializedName("type") // @SerializedName("type")
val type: String? = "", // val type: String? = "",
@SerializedName("userId") // @SerializedName("userId")
val userId: String? = "" // val userId: String? = ""
) : Parcelable // ) : Parcelable
} //}
@@ -3,16 +3,30 @@ package com.sw.dualscreen.network.api
import com.sw.dualscreen.GlobalData import com.sw.dualscreen.GlobalData
import com.sw.dualscreen.model.request.UserNutritionParam import com.sw.dualscreen.model.request.UserNutritionParam
import com.sw.dualscreen.model.response.ApiResponse import com.sw.dualscreen.model.response.ApiResponse
import com.sw.dualscreen.model.response.DinnerTypeInfo import com.sw.dualscreen.model.response.DeviceConfig
import com.sw.dualscreen.model.response.EquipmentInfo import com.sw.dualscreen.model.response.DinnerType
import com.sw.dualscreen.model.response.FaceData
import com.sw.dualscreen.model.response.FoodInfo import com.sw.dualscreen.model.response.FoodInfo
import com.sw.dualscreen.model.response.UserFaceInfo import com.sw.dualscreen.model.response.FoodOrder
import com.sw.dualscreen.model.response.UserNutritionData import com.sw.dualscreen.model.response.FoodSearchReq
import com.sw.dualscreen.model.response.FoodVector
import com.sw.dualscreen.model.response.MemberInfo
import com.sw.dualscreen.model.response.UserFaceModel
import com.sw.dualscreen.model.response.UserNutrition
import com.sw.dualscreen.objbox.CollectedFoodInfo
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.http.Body import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.FieldMap
import retrofit2.http.FormUrlEncoded
import retrofit2.http.GET import retrofit2.http.GET
import retrofit2.http.Header import retrofit2.http.Multipart
import retrofit2.http.POST import retrofit2.http.POST
import retrofit2.http.Part
import retrofit2.http.PartMap
import retrofit2.http.Query import retrofit2.http.Query
import retrofit2.http.QueryMap
import retrofit2.http.Url import retrofit2.http.Url
interface ApiService { interface ApiService {
@@ -20,76 +34,119 @@ interface ApiService {
/** /**
* device获取token * device获取token
*/ */
@GET("sys/getEquipmentToken") // @GET("sys/getEquipmentToken")
suspend fun getDeviceToken( // suspend fun getDeviceToken(
@Query("qrcodeId") qrcodeId: String, // @Query("qrcodeId") qrcodeId: String,
@Query("appVersion") appVersion: String = GlobalData.appVersion // @Query("appVersion") appVersion: String = GlobalData.appVersion
): ApiResponse<String> // ): ApiResponse<String>
/** /**
*获取配置信息 *获取配置信息
*/ */
@GET("equipment/stEquipment/queryByEquipmentCode") // @GET("equipment/stEquipment/queryByEquipmentCode")
suspend fun getDeviceInfo( // suspend fun getDeviceInfo(
@Query("equipmentCode") equipmentCode: String, // @Query("equipmentCode") equipmentCode: String,
@Query("appVersion") appVersion: String = GlobalData.appVersion, // @Query("appVersion") appVersion: String = GlobalData.appVersion,
@Header("X-Access-Token") token: String // @Header("X-Access-Token") token: String
): ApiResponse<EquipmentInfo> // ): ApiResponse<EquipmentInfo>
/** /**
* 获取业务服务器token * 获取业务服务器token
*/ */
@GET // @GET
suspend fun getEquipmentToken( // suspend fun getEquipmentToken(
@Url url: String = "${GlobalData.appBaseUrl}/sys/getEquipmentToken", // @Url url: String = "${GlobalData.appBaseUrl}/sys/getEquipmentToken",
@Query("appVersion") appVersion: String = GlobalData.appVersion, // @Query("appVersion") appVersion: String = GlobalData.appVersion,
@Query("qrcodeId") qrcodeId: String // @Query("qrcodeId") qrcodeId: String
): ApiResponse<String> // ): ApiResponse<String>
/** /**
* 获取人脸数据 * 获取人脸数据
*/ */
@GET @POST
suspend fun getUserFaceCache( suspend fun getUserFaceCache(
@Url url: String = "${GlobalData.appBaseUrl}/stapi/cquser/getUserFaceCache/v2", // @Url url: String = "${GlobalData.appBaseUrl}/stapi/cquser/getUserFaceCache/v2",
@Query("appVersion") appVersion: String = GlobalData.appVersion, @Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/common/app/faceFeature/list",
@Query("pageIndex") pageIndex: Int // @Query("appVersion") appVersion: String = GlobalData.appVersion,
): ApiResponse<UserFaceInfo> // @Query("pageIndex") pageIndex: Int
@Body param: Map<String, Int>
// @Query("pageNum") pageNum: Int,
// @Query("pageSize") pageSize: Int
): ApiResponse<List<UserFaceModel>?>
@GET
suspend fun getUserFaceCache2(
@Url url: String = "http://192.168.1.230:2223/userface/swUserFaceimgSub/list",
@Query("pageNum") pageNum: Int,
@Query("pageSize") pageSize: Int
): ApiResponse<FaceData>
/**
* 获取已采集数据列表
*/
@POST
suspend fun getCollectedFoodList(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/dishPage",
@Body param: Map<String, String>
): ApiResponse<List<CollectedFoodInfo>>
// /**
// * 获取档口菜品信息
// */
// @GET
// suspend fun getRestInfoFoodsByType(
//// @Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/getRestInfoFoodsByType/stall",
//// @Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/getFoodsByFoodNamePage",
// @Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/getFoodsByFoodNameList",
// @Query("name") foodName: String,
//// @Query("appVersion") appVersion: String = GlobalData.appVersion,
//// @Query("restId") restId: String,
//// @Query("type") type: Int,
//// @Query("foodName") foodName: String,
// ): ApiResponse<List<FoodInfo>>
/** /**
* 获取档口菜品信息 * 获取档口菜品信息
*/ */
@GET @POST
suspend fun getRestInfoFoodsByType( suspend fun getRestInfoFoodsByType(
@Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/getRestInfoFoodsByType/stall", @Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/getFoodsByFoodNameList",
@Query("appVersion") appVersion: String = GlobalData.appVersion, @Body param: HashMap<String, String>
@Query("restId") restId: String,
@Query("type") type: Int,
@Query("foodName") foodName: String,
): ApiResponse<List<FoodInfo>> ): ApiResponse<List<FoodInfo>>
// /**
// * 通过用户信息获取就餐数据
// */
// @GET
// suspend fun getUserNutritionData(
// @Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/getUserNutritionData/face",
// @Query("appVersion") appVersion: String = GlobalData.appVersion,
// @Query("restId") restId: String,
// @Query("userId") userId: String,
// @Query("foodId") foodId: String,
// ): ApiResponse<UserNutritionData>
/** /**
* 通过用户信息获取就餐数据 * 通过用户信息获取就餐数据
*/ */
@GET @GET
suspend fun getUserNutritionData( suspend fun getUserNutritionData(
@Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/getUserNutritionData/face", @Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/getUserCurrentFoodDetails",
@Query("appVersion") appVersion: String = GlobalData.appVersion, @Query("id") userId: String
@Query("restId") restId: String, ): ApiResponse<UserNutrition>
@Query("userId") userId: String,
@Query("foodId") foodId: String,
): ApiResponse<UserNutritionData>
/** /**
* 获取当前餐点类型 * 获取当前餐点类型
*/ */
@GET @GET
suspend fun getDinnerType( suspend fun getDinnerType(
@Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/getCanteenDinnerType", // @Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/getCanteenDinnerType",
@Query("appVersion") appVersion: String = GlobalData.appVersion, @Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/common/app/getRegionRule",
@Query("canteenId") restId: String, // @Query("appVersion") appVersion: String = GlobalData.appVersion,
): ApiResponse<DinnerTypeInfo> // @Query("canteenId") restId: String,
): ApiResponse<DinnerType>
/** /**
* 提交就餐数据 * 提交就餐数据
@@ -99,4 +156,159 @@ interface ApiService {
@Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/userEatFood/doubleBalance/face/stall", @Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/userEatFood/doubleBalance/face/stall",
@Body param: List<UserNutritionParam> @Body param: List<UserNutritionParam>
): ApiResponse<String> ): ApiResponse<String>
/**
* 获取菜品信息
*/
@POST
suspend fun getFoodInfo(
// @Url url: String = "${GlobalData.appBaseUrl}/zhstapi/zhst/getRestInfoFoodsByType/stall/v2",
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/goodsList",
// @Query("restId") restId: String,
// @Query("foodNames") foodName: String
@Body req: FoodSearchReq
): ApiResponse<List<FoodInfo>>
// /**
// * 查询支付结果
// */
// @POST
// suspend fun queryOrderState(
// @Url url: String = "${GlobalData.appBaseUrl}/pay/yx-check-out-pay/turnOrderInfo",
// @Body param: HashMap<String, String>
// ): ApiResponse<PayResult?>
/**
* 查询支付结果
*/
@GET
suspend fun queryOrderState(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/pay/app/turnOrderInfo",
@Query("orderNo") orderNo: String
// @Body param: HashMap<String, String>
): ApiResponse<Any?>
/**
* 现金支付
*/
@POST
suspend fun cashPay(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/pay/app/cashPayment",
@Body param: HashMap<String, String>
): ApiResponse<Boolean?>
/**
* 会员支付
*/
@POST
suspend fun memberPay(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/pay/app/memberPay",
@Body param: HashMap<String, String?>
): ApiResponse<Any?>
/**
* 获取支付二维码
*/
@GET
suspend fun getQrCodeImg(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/pay/app/getQrCodeImg",
@Query("orderNo") orderNo: String,
@Query("memberId") memberId: String?,
@Query("totalFee") totalFee: String? = null
): ApiResponse<String?>
/**
* 二维码支付
* @param orderType 0付款 1会员充值
*/
@POST
suspend fun qrCodePay(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/pay/app/qrCodePay",
@Body param: HashMap<String, String?>
): ApiResponse<String?>
/**
* 开餐-生成订单
*/
@POST
suspend fun createOrder(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/userEatFood/doubleScale",
@Body order: FoodOrder
): ApiResponse<Any?>
/**
* APP根据id获取会员或员工信息及余额
*/
@GET
suspend fun getMemberInfoById(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/common/app/getUserInfoBalanceById",
@Query("id") memberId: String,
): ApiResponse<MemberInfo?>
/**
* 根据手机尾号和密钥查询员工信息及余额
*/
@POST
suspend fun getMemberInfoByPhone(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/common/app/queryUserInfoBalanceByPhone",
@Body param: HashMap<String, String>
): ApiResponse<MemberInfo?>
/**
* 绑定用户与订单号
*/
@GET
suspend fun bindOrder(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/bingOrder",
@Query("userId") userId: String,
@Query("orderNo") orderId: String,
@Query("mode") mode: Int
): ApiResponse<Any?>
/**
* 提交采集图片数据
*/
@Multipart
@POST
suspend fun uploadCollectFoodPics(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/dishCollectionVectorData/add",
@PartMap params: HashMap<String, RequestBody>,
@Part foodPics: List<MultipartBody.Part>
): ApiResponse<List<String>?>
/**
* 获取设备配置数据
*/
@GET
suspend fun getDeviceConfig(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/common/app/getYxEquipmentByEquipmentCode"
): ApiResponse<DeviceConfig?>
/**
* 获取人脸增量数据
*/
@POST
suspend fun getFaceIncrementList(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/common/app/faceFeature/increment/list",
@Body param: Map<String, Long>
): ApiResponse<List<UserFaceModel>?>
/**
* 档口机向量数据分页查询
*/
@POST
suspend fun getCollectedFoodVector(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/collectionVectorPage",
@Body param: MutableMap<String, String>
): ApiResponse<List<FoodVector>?>
/**
* 档口机向量数据分页查询
*/
@DELETE
suspend fun deleteCollectFood(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/boothMachine/app/deleteBoothMachineCollection",
@QueryMap param: MutableMap<String, String?>
): ApiResponse<Any?>
} }
@@ -1,8 +1,9 @@
package com.sw.dualscreen.network.interceptor package com.sw.dualscreen.network.interceptor
import android.text.TextUtils import android.text.TextUtils
import com.sw.dualscreen.GlobalData
import com.sw.dualscreen.GlobalKey import com.sw.dualscreen.GlobalKey
import com.sw.inbound.utils.SPUtil import com.sw.dualscreen.utils.SPUtil
import com.sw.plate.App import com.sw.plate.App
import okhttp3.Interceptor import okhttp3.Interceptor
import okhttp3.Request import okhttp3.Request
@@ -18,7 +19,11 @@ class RequestInterceptor : Interceptor {
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.header("Accept", "application/json") .header("Accept", "application/json")
// .header("Authorization", "Bearer ${getToken()}") // .header("Authorization", "Bearer ${getToken()}")
.header("X-Access-Token", getToken(originalRequest)) // .header("X-Access-Token", getToken(originalRequest))
.header("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjYW50ZWVuSWQiOiJiZTE1NDgzMS0zNDY2LTNiYTItYTJlYS01NzY1MmM5MTlmZWQiLCJ0eXBlIjoiNCIsInVzZXJJZCI6IjAwMDAwMDAwMDAwMDAwMDAwMDEifQ.sN40cOC-O5WQFrF4IDUs8fFlkNdUKLbJt_rHyTsgYYM")
// .header("X-DEVICE-CODE", "bcf396ed-78f6-3864-9837-7c37c5b2ec41")
.header("X-DEVICE-CODE", GlobalData.deviceId)
.header("authorization", "57ee87183f2a4fa59683ec9ef41c8f5d")
val newRequest = requestBuilder.build() val newRequest = requestBuilder.build()
@@ -0,0 +1,66 @@
package com.sw.dualscreen.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 FoodQueryResult(
// var id: Long,
// var name: String?,
// var foodIdx: Int,
// var score: Double
//)
data class FoodCollectionBean(
var imageFile: File? = null,
var imageUri: Uri? = null,
var bitmap: Bitmap? = null,
var imageVector: FloatArray? = null,
var isShowCamera: Boolean = false,
var isFinish:Boolean = false,
var uploadSuccess:Boolean = false
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FoodCollectionBean
if (isShowCamera != other.isShowCamera) return false
if (isFinish != other.isFinish) return false
if (uploadSuccess != other.uploadSuccess) return false
if (imageFile != other.imageFile) return false
if (imageUri != other.imageUri) return false
if (bitmap != other.bitmap) return false
if (!imageVector.contentEquals(other.imageVector)) return false
return true
}
override fun hashCode(): Int {
var result = isShowCamera.hashCode()
result = 31 * result + isFinish.hashCode()
result = 31 * result + uploadSuccess.hashCode()
result = 31 * result + (imageFile?.hashCode() ?: 0)
result = 31 * result + (imageUri?.hashCode() ?: 0)
result = 31 * result + (bitmap?.hashCode() ?: 0)
result = 31 * result + (imageVector?.contentHashCode() ?: 0)
return result
}
}
data class CollectedFoodInfo(
// var id: String? = null,
// var placeId: String? = null,
var foodId: String? = null,
var foodName: String? = null,
// var foodPic: Any? = null,
// var foodVector: Any? = null,
var foodCount: Int = 0
)
@@ -0,0 +1,55 @@
package com.sw.dualscreen.objbox
import com.sw.dualscreen.utils.DateTimeUtil
import io.objectbox.annotation.Entity
import io.objectbox.annotation.HnswIndex
import io.objectbox.annotation.Id
import io.objectbox.annotation.VectorDistanceType
import java.time.LocalDateTime
@Entity
data class Food(
@Id var id: Long = 0,
var collectId: String? = null,
var foodId: String? = null,
var foodName: String? = null,
var version: String? = null,
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now()),
var isDel: Boolean = false,
var otherField: String? = null,
@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 (isDel != other.isDel) return false
if (collectId != other.collectId) return false
if (foodId != other.foodId) return false
if (foodName != other.foodName) return false
if (version != other.version) return false
if (createTime != other.createTime) return false
if (otherField != other.otherField) return false
if (!foodVector.contentEquals(other.foodVector)) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + isDel.hashCode()
result = 31 * result + (collectId?.hashCode() ?: 0)
result = 31 * result + (foodId?.hashCode() ?: 0)
result = 31 * result + (foodName?.hashCode() ?: 0)
result = 31 * result + (version?.hashCode() ?: 0)
result = 31 * result + createTime.hashCode()
result = 31 * result + (otherField?.hashCode() ?: 0)
result = 31 * result + (foodVector?.contentHashCode() ?: 0)
return result
}
}
@@ -0,0 +1,341 @@
package com.sw.dualscreen.objbox
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import androidx.core.graphics.scale
import com.sw.dualscreen.MyApp
import com.sw.dualscreen.utils.GsonUtils
import com.sw.dualscreen.utils.ImageUtil
import com.sw.plate.utils.ToastUtils
import io.objectbox.Box
import io.objectbox.kotlin.boxFor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.pytorch.IValue
import org.pytorch.Module
import org.pytorch.torchvision.TensorImageUtils
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
object FoodModule {
private const val TAG = "FoodModule"
private const val THRESHOLD = 0.8
// private const val THRESHOLD = 0.0
private var module: Module? = null
// private lateinit var embeddingsList: List<List<Float>>
// private lateinit var labelsList: IntArray
// private lateinit var classInfo: FoodClassInfo
val NO_MEAN_RGB = floatArrayOf(0.0f, 0.0f, 0.0f)
val NO_STD_RGB = floatArrayOf(1.0f, 1.0f, 1.0f)
// val DEFAULT_FOOD_INDEX = -1
// 1. 定义你的模型固定输入尺寸 (根据你的tflite模型修改,比如224x224)
private const val MODEL_INPUT_WIDTH = 224
private const val MODEL_INPUT_HEIGHT = 224
@SuppressLint("SuspiciousIndentation")
suspend fun init(context: Context, block: () -> Unit = {}) {
// Thread {}.start()
withContext(Dispatchers.IO) {
val modelPath = copyAssetToCache(context, "best_embedding_model_mobile.pt")
module = Module.load(modelPath)
//初始化默认重新拉取数据,先清空本地数据
val list = ObjectBox.getAll()
if (list.isNotEmpty()) {
ObjectBox.removeAll()
}
//if (box.all.isEmpty()) {
// initDefFoodData(context)
//}
block()
}
}
// 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
)
if (module == null) {
return null
}
val outputTensor = module?.forward(IValue.from(inputTensor))?.toTensor()
return outputTensor?.dataAsFloatArray
} catch (e: OutOfMemoryError) {
e.printStackTrace()
} finally {
if (rgb565Bitmap != null && rgb565Bitmap.isRecycled.not()) {
rgb565Bitmap.recycle()
}
//System.gc()
//System.runFinalization()
}
return null
}
// fun queryFood(uri: Uri, queryCount: Int = 15): List<String>? {
// return uri2FloatArray(uri)?.let {
// queryFood(it, queryCount)
// }
// }
/**
* 返回识别物品名称列表
*/
// fun queryFood(bitmap: Bitmap, queryCount: Int = 15): List<String> {
// val floatArray = bitmap2FloatArray(bitmap)
// return queryFood(floatArray, queryCount)
// }
/**
* 返回识别物品IdNameScore对象列表
*/
// fun queryFoodNameScore(bitmap: Bitmap, queryCount: Int = 15): List<IdNameScore> {
// val floatArray = bitmap2FloatArray(bitmap)
// return queryFoodNameScore(floatArray, queryCount)
// }
suspend fun queryFoodNameScore(
floatArray: FloatArray?,
queryCount: Int = 15
): List<IdNameScore> {
if (floatArray == null) return emptyList()
val startTime = System.currentTimeMillis()
val size = ObjectBox.getAll().filter { it.isDel.not() }.size
Timber.tag(TAG).d("queryFoodNameScore-已采集向量总数:${size}")
//查询比较分数
// val tempList = query.findWithScores().sortedBy { it.score }.map { "${it.get().name}|${it.get().foodIdx}|${it.score}" }
// val idScoreList = query.findIdsWithScores()
val objScoreList = ObjectBox.query(floatArray, queryCount)
Timber.tag(TAG).d("idScoreList:${GsonUtils.toJson(objScoreList)}")
val nameScoreList = mutableListOf<IdNameScore>()
objScoreList.forEach {
val food = it.get()
nameScoreList.add(
IdNameScore(
id = food.id,
name = food.foodName ?: "",
score = it.score
)
)
}
val nameScoreData = GsonUtils.toJson(nameScoreList)
Timber.tag(TAG).d("queryFood,耗时:${System.currentTimeMillis() - startTime},数据:$nameScoreData")
return nameScoreList
}
suspend fun getFoodScoreList(bitmap: Bitmap, queryCount: Int = 15): List<IdNameScore> {
val startTime = System.currentTimeMillis()
val floatArray = bitmap2FloatArray(bitmap, false)
Timber.tag(TAG).d("bitmap2FloatArray,耗时:${System.currentTimeMillis() - startTime}")
val nameScoreList = queryFoodNameScore(floatArray, queryCount)
if (nameScoreList.isEmpty()) {
return emptyList()
}
val maxScoreList = nameScoreList
.filter { it.score < 1 - THRESHOLD }
.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)
})
if (bitmap.isRecycled.not()) {
bitmap.recycle()
}
//Timber.tag("FoodModule").d("getFoodScoreList数据:${sortedScoreList.toJsonString()}")
return sortedScoreList
}
// fun queryFood(floatArray: FloatArray, queryCount: Int = 15): List<String> {
// val query = box.query()
// .equal(Food_.isDel, false)
// .and()
// .nearestNeighbors(Food_.foodVector, floatArray, queryCount)
// .build()
//// 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}" }
// val map = mutableMapOf<String, Int>()
// query.findIdsWithScores().forEach {
// val food = box.get(it.id)
// Timber.d("${food.foodName}|${food.foodId}|${food.collectId}|${food.version}|${food.otherField}|${it.score}")
// if (1 - it.score >= THRESHOLD) {
// //FoodQueryResult(id = it.id, name = food.name, foodIdx = food.foodIdx, score = it.score)
// food.foodName?.let { key ->
// val count = map[key] ?: 0
// map.put(key, count + 1)
// }
// }
// }
// val list = map.entries.sortedByDescending { it.value }.map { it.key }
// return list
//
//// 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
)
// fun initDefFoodData(context: Context, action: () -> Unit = {}) {
// //val count = box.all.count { it.foodIdx == 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")
//
// embeddingsList =
// Gson().fromJson(embeddingsJson, object : TypeToken<List<List<Float>>>() {}.type)
// labelsList = Gson().fromJson(labelsJson, IntArray::class.java)
// classInfo =
// Gson().fromJson(classInfoJson, FoodClassInfo::class.java)
//
// val foodMap = classInfo.idx_to_class
// embeddingsList.forEachIndexed { index, floatList ->
// val classIdx = labelsList[index]
// val foodName = foodMap["$classIdx"]
// val array = floatList.toFloatArray()
// box.put(
// Food(
// foodName = foodName,
// foodVector = array,
// //foodIdx = DEFAULT_FOOD_INDEX
// )
// )
// }
// action()
// }
/**
* ,此方法的主要目的是:从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.cacheDir
// 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.assets.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.absolutePath
// }
// } 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()
Timber.tag("FoodModule").d("文件拷贝失败 fileName=$fileName, error=${e.message}")
// 拷贝失败时删除残缺文件,避免下次读取到损坏文件
if (cacheFile.exists()) {
cacheFile.delete()
}
} finally {
outputStream?.close()
inputStream?.close()
}
return null
}
}
@@ -0,0 +1,285 @@
/*
* 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.sw.dualscreen.objbox
import android.content.Context
import android.os.Environment
import android.util.Log
import com.sw.plate.App
import io.objectbox.Box
import io.objectbox.BoxStore
import io.objectbox.BoxStoreBuilder
import io.objectbox.android.Admin
import io.objectbox.android.ObjectBoxLiveData
import io.objectbox.config.DebugFlags
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 timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.util.Date
import java.util.zip.GZIPOutputStream
import kotlin.also
import kotlin.and
import kotlin.io.copyTo
import kotlin.io.inputStream
import kotlin.io.outputStream
import kotlin.io.use
import kotlin.jvm.java
import kotlin.jvm.javaClass
/**
* 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"
var boxStore: BoxStore? = null
/**
* If building the [boxStore] failed, contains the thrown error message.
*/
var dbExceptionMessage: String? = null
private set
fun init(context: Context) {
// On Android make sure to pass a Context when building the Store.
boxStore = try {
MyObjectBox.builder()
.androidContext(context.applicationContext)
.debugFlags(DebugFlags.LOG_QUERY_PARAMETERS)
.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()
return
} else {
// Failed to build BoxStore due to developer error.
throw e
}
}
// if (BuildConfig.DEBUG) {
val syncAvailable = if (Sync.isAvailable()) "available" else "unavailable"
Timber.tag(TAG)
.d("Using ObjectBox ${BoxStore.getVersion()} (${BoxStore.getVersionNative()}, sync $syncAvailable)")
// Enable ObjectBox Admin on debug builds.
// https://docs.objectbox.io/data-browser
Admin(boxStore).start(context.applicationContext)
// }
}
/**
* If the database file is not in use, compresses (GZIP) and copies it to the given [target].
*/
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.
Timber.tag(TAG).e("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
File(context.filesDir, "objectbox/$dbName/data.mdb").inputStream().use { input ->
target.parentFile?.mkdirs()
GZIPOutputStream(target.outputStream()).use { output ->
input.copyTo(output, DEFAULT_BUFFER_SIZE)
}
}
return true
}
// 获取指定实体的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) {
// 操作中触发损坏,尝试重建数据库
//val context = boxStore.context
//deleteDbFiles(context)
init(App.getContext()!!)
null
} catch (e: Exception) {
e.printStackTrace()
null
} finally {
// 线程资源清理
boxStore?.closeThreadResources()
}
}
}
suspend fun query(floatArray: FloatArray, queryCount: Int) = safeDbOp {
val query: Query<Food>? = getBox<Food>()?.query()
?.equal(Food_.isDel, false)
?.and()
?.nearestNeighbors(Food_.foodVector, floatArray, queryCount)
?.build()
try {
query?.findWithScores()
} finally {
// 先关闭Query,释放Cursor
query?.close()
}
} ?: emptyList()
suspend fun get(id: Long) = safeDbOp {
getBox<Food>()?.get(id)
}
suspend fun put(entity: Food) = safeDbOp {
getBox<Food>()?.put(entity)
}
suspend fun putAll(entities: List<Food>) = safeDbOp {
getBox<Food>()?.put(entities)
}
suspend fun getAll() = safeDbOp {
getBox<Food>()?.all
} ?: emptyList()
suspend fun filter(name: String?) = safeDbOp {
if (!name.isNullOrBlank()) {
getBox<Food>()?.query(Food_.foodName.contains(name))?.build()?.find()
?.distinctBy { it.foodName }
} else {
getBox<Food>()?.all?.distinctBy { it.foodName }
} ?: emptyList()
} ?: emptyList()
suspend fun removeAll() = safeDbOp {
getBox<Food>()?.removeAll()
}
suspend fun remove(name: String) = safeDbOp {
getBox<Food>()?.query(Food_.foodName.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
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -4,74 +4,125 @@ package com.sw.dualscreen.presentation
import android.text.TextUtils import android.text.TextUtils
import com.sw.dualscreen.ext.toSafeDouble import com.sw.dualscreen.ext.toSafeDouble
import com.sw.dualscreen.model.response.FoodInfo import com.sw.dualscreen.model.response.FoodInfo
import com.sw.dualscreen.model.response.UserNutritionData import com.sw.dualscreen.model.response.UserEnergy
import com.sw.dualscreen.model.response.UserNutrition
import timber.log.Timber import timber.log.Timber
import kotlin.math.max import kotlin.math.max
import kotlin.math.min
/**
* 用户营养信息计算工具
*/
object UserNutritionUtils { object UserNutritionUtils {
/** /**
* 计算热量信息 * 计算热量信息
*/ */
fun calculateNutrition( fun calculateNutrition2(
foodInfo: FoodInfo, foodInfo: FoodInfo,
userModel: UserNutritionData, nutrition: UserNutrition,
weight: Double, weight: Double,
dinnerType: String dinnerType: String
): CalcResultInfo { ): UserEnergy {
// 初始化变量 // 初始化变量
var foodKcal = 0.0 //var totalKcal = 0.0
var totalKcal = 0.0 var (calorie, grain, fruitsVegetables, meatEggs) = List(4) { 0.0 }
var (vegetable, meat, fruits, grain) = List(4) { 0.0 }
// 处理食物信息 // 处理食物信息
foodKcal = calculateValue(foodInfo.stFoodInfoMaterial?.energyKcal, weight) if (weight > 0.0) {
Timber.d("calculateNutrition foodKcal = ${foodKcal}, energyKcal = ${foodInfo.stFoodInfoMaterial?.energyKcal}, weight = $weight") calorie = calculateValue2(foodInfo.calorie,weight)
grain = calculateValue(foodInfo.stFoodInfoPagodaAPPVO?.grainValue(), weight) grain = calculateValue2(foodInfo.stapleFood, weight)
fruits = calculateValue(foodInfo.stFoodInfoPagodaAPPVO?.fruitsValue(), weight) fruitsVegetables = calculateValue2(foodInfo.fruitsVegetables, weight)
vegetable = calculateValue(foodInfo.stFoodInfoPagodaAPPVO?.vegetableValue(), weight) meatEggs = calculateValue2(foodInfo.meatEggs, weight)
meat = calculateValue(foodInfo.stFoodInfoPagodaAPPVO?.meatValue(), weight) }
// 合并用户数据 // 合并用户数据
grain += userModel.stFoodInfoPagoda?.grainValue() ?: 0.0 //val maxKcal = (nutrition.calorie?:0.0) * calculateDinnerTypeRatio(dinnerType) / 10.0
calorie += nutrition.calorie ?: 0.0
grain += nutrition.stapleFood ?: 0.0
fruitsVegetables += nutrition.fruitsVegetables ?: 0.0
meatEggs += nutrition.meatEggs ?: 0.0
fruits += userModel.stFoodInfoPagoda?.fruitsValue() ?: 0.0 //totalKcal = max(calorie, 0.0)
vegetable = vegetable.plus(userModel.stFoodInfoPagoda?.vegetableValue() ?: 0.0)
meat += userModel.stFoodInfoPagoda?.meatValue() ?: 0.0
totalKcal = foodKcal + userModel.energyValue()
Timber.d("calculateNutrition totalKcal = ${totalKcal}, energyValue = ${userModel.energyValue()}")
if (totalKcal < 0){
totalKcal = 0.0
}
// 判断当餐最大热量 // 判断当餐最大热量
val maxKcal = //val maxKcal = userModel.totalEnergyCalculateScoreValue() * calculateDinnerTypeRatio(dinnerType) / 10
userModel.totalEnergyCalculateScoreValue() * calculateDinnerTypeRatio(dinnerType) / 10 //Timber.d("calculateNutrition maxKcal = ${maxKcal}, CalculateScoreValue = ${userModel.totalEnergyCalculateScoreValue()}")
Timber.d("calculateNutrition maxKcal = ${maxKcal}, CalculateScoreValue = ${userModel.totalEnergyCalculateScoreValue()}") // val calcResult = CalcResultInfo(
val pagoda = userModel.stFoodInfoPagoda // totalKcal = CalcInfo(
val fruitsInfo = parseRecommend(pagoda?.fruitsRecommend, fruits) // max = maxKcal,
val vegetableInfo = parseRecommend(pagoda?.vegetableRecommend, vegetable) // min = 0.0,
val calcResult = CalcResultInfo( // current = totalKcal
totalKcal = CalcInfo( // ),
max = maxKcal, // grain = parseRecommend(foodInfo.stapleFoodRecommend, grain),
min = 0.0, // fruits = parseRecommend(foodInfo.fruitsVegetablesRecommend, fruitsVegetables),
current = totalKcal // meat = parseRecommend(foodInfo.meatEggsRecommend, meatEggs)
), // )
grain = parseRecommend(pagoda?.grainRecommend, grain), return UserEnergy(
fruits = CalcInfo( // 果蔬 = 水果+蔬菜 calorie = calorie,
max = fruitsInfo.max + vegetableInfo.max, grain = grain,
min = fruitsInfo.min + vegetableInfo.min, fruitsVegetables = fruitsVegetables,
current = fruitsInfo.current + vegetableInfo.current meatEggs = meatEggs
),
meat = parseRecommend(pagoda?.meatRecommend, meat)
) )
return calcResult
} }
// fun calculateNutrition(
// foodInfo: FoodInfo,
// userModel: UserNutritionData,
//// userModel: UserNutrition,
// weight: Double,
// dinnerType: String
// ): CalcResultInfo {
//
// // 初始化变量
// var foodKcal = 0.0
// var totalKcal = 0.0
// var (vegetable, meat, fruits, grain) = List(4) { 0.0 }
//
// // 处理食物信息
// foodKcal = calculateValue(foodInfo.stFoodInfoMaterial?.energyKcal, weight)
// Timber.d("calculateNutrition foodKcal = ${foodKcal}, energyKcal = ${foodInfo.stFoodInfoMaterial?.energyKcal}, weight = $weight")
// grain = calculateValue(foodInfo.stFoodInfoPagodaAPPVO?.grainValue(), weight)
// fruits = calculateValue(foodInfo.stFoodInfoPagodaAPPVO?.fruitsValue(), weight)
// vegetable = calculateValue(foodInfo.stFoodInfoPagodaAPPVO?.vegetableValue(), weight)
// meat = calculateValue(foodInfo.stFoodInfoPagodaAPPVO?.meatValue(), weight)
//
// // 合并用户数据
// grain += userModel.stFoodInfoPagoda?.grainValue() ?: 0.0
//
// fruits += userModel.stFoodInfoPagoda?.fruitsValue() ?: 0.0
// vegetable = vegetable.plus(userModel.stFoodInfoPagoda?.vegetableValue() ?: 0.0)
// meat += userModel.stFoodInfoPagoda?.meatValue() ?: 0.0
//
// totalKcal = foodKcal + userModel.energyValue()
// Timber.d("calculateNutrition totalKcal = ${totalKcal}, energyValue = ${userModel.energyValue()}")
// if (totalKcal < 0) {
// totalKcal = 0.0
// }
// // 判断当餐最大热量
// val maxKcal =
// userModel.totalEnergyCalculateScoreValue() * calculateDinnerTypeRatio(dinnerType) / 10
// Timber.d("calculateNutrition maxKcal = ${maxKcal}, CalculateScoreValue = ${userModel.totalEnergyCalculateScoreValue()}")
// val pagoda = userModel.stFoodInfoPagoda
// val fruitsInfo = parseRecommend(pagoda?.fruitsRecommend, fruits)
// val vegetableInfo = parseRecommend(pagoda?.vegetableRecommend, vegetable)
// val calcResult = CalcResultInfo(
// totalKcal = CalcInfo(
// max = maxKcal,
// min = 0.0,
// current = totalKcal
// ),
// grain = parseRecommend(pagoda?.grainRecommend, grain),
// fruits = CalcInfo( // 果蔬 = 水果+蔬菜
// max = fruitsInfo.max + vegetableInfo.max,
// min = fruitsInfo.min + vegetableInfo.min,
// current = fruitsInfo.current + vegetableInfo.current
// ),
// meat = parseRecommend(pagoda?.meatRecommend, meat)
// )
// return calcResult
// }
fun parseRecommend(recommend: String?, current: Double): CalcInfo { fun parseRecommend(recommend: String?, current: Double): CalcInfo {
var newCurrent = if (current < 0) 0.0 else current val newCurrent = if (current < 0) 0.0 else current
if (TextUtils.isEmpty(recommend) || !recommend!!.contains("-")) { if (TextUtils.isEmpty(recommend) || !recommend!!.contains("-")) {
Timber.e("parseRecommend recommend 格式错误") Timber.e("parseRecommend recommend 格式错误")
return CalcInfo( return CalcInfo(
@@ -91,7 +142,10 @@ object UserNutritionUtils {
else -> 0 else -> 0
} }
} }
private fun calculateValue2(nutrient: Double?, weight: Double): Double {
if ((nutrient?:0.0) == 0.0) return 0.0
return nutrient!! * weight / 100.0
}
/** /**
* 计算每百克含量 * 计算每百克含量
*/ */
@@ -104,6 +158,36 @@ object UserNutritionUtils {
return max(max1, calcResultInfo.meat.max).toInt() return max(max1, calcResultInfo.meat.max).toInt()
} }
fun getCalorieArray(left:String?, mid:String?, right: String?):DoubleArray {
val leftArray = (left?.ifBlank { "0-0" } ?: "0-0").split("-").map { it.toSafeDouble() }
val midArray = (mid?.ifBlank { "0-0" } ?: "0-0").split("-").map { it.toSafeDouble() }
val rightArray = (right?.ifBlank { "0-0" } ?: "0-0").split("-").map { it.toSafeDouble() }
return doubleArrayOf(
0.0, leftArray[0], midArray[0], rightArray[0], rightArray[1]
)
}
fun findCalorieIndex(num: Double, array: DoubleArray): Int {
if (array.isEmpty()) return 0
if (num < array[0]) return 0
if (num >= array[array.lastIndex]) return array.lastIndex
var left = 0
var right = array.lastIndex
while (left < right) {
val mid = left + (right - left) / 2
if (array[mid] <= num && num < array[mid + 1]) {
return mid
} else if (num < array[mid]) {
right = mid
} else {
left = mid + 1
}
}
return 0
}
data class CalcInfo( data class CalcInfo(
var max: Double, var max: Double,
var min: Double, var min: Double,
@@ -0,0 +1,49 @@
//package com.sw.dualscreen.presentation.pay
//
//import android.R
//import android.app.Presentation
//import android.os.Bundle
//import android.text.Spanned
//import android.text.SpannedString
//import android.text.style.AbsoluteSizeSpan
//import android.view.Display
//import androidx.core.text.buildSpannedString
//import com.sw.dualscreen.activity.PayActivity
//import com.sw.dualscreen.databinding.PresentationCashPayBinding
//import com.sw.dualscreen.ext.load
//
//class CashPayPresentation(
// val activity: PayActivity,
// display: Display,
// private val onDismissListener: () -> Unit = {}
//) : Presentation(activity, display) {
//
// private lateinit var binding: PresentationCashPayBinding
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// binding = PresentationCashPayBinding.inflate(layoutInflater)
// setContentView(binding.root)
// window?.setBackgroundDrawableResource(R.color.transparent)
// initView()
// }
//
// var foodName: String? = null
// var payAmount: String? = null
// private fun initView() {
// binding.tvFoodName.text = foodName
// binding.tvRealAmount.text = getAmountText(payAmount ?: "")
// }
//
// private fun getAmountText(amount: String): SpannedString {
// return buildSpannedString {
// append("¥", AbsoluteSizeSpan(32, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
// append(amount, AbsoluteSizeSpan(48, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
// }
// }
//
// override fun onDisplayRemoved() {
// super.onDisplayRemoved()
// onDismissListener()
// }
//}
@@ -0,0 +1,585 @@
//package com.sw.dualscreen.presentation.pay
//
//import android.Manifest
//import android.app.Dialog
//import android.app.Presentation
//import android.content.pm.PackageManager
//import android.graphics.Point
//import android.hardware.Camera
//import android.os.Build
//import android.os.Bundle
//import android.text.TextUtils
//import android.view.Display
//import android.view.View
//import android.view.ViewGroup
//import android.view.ViewTreeObserver
//import android.widget.FrameLayout
//import android.widget.TextView
//import androidx.annotation.RequiresApi
//import androidx.core.content.ContextCompat
//import androidx.lifecycle.Observer
//import androidx.lifecycle.lifecycleScope
//import com.arcsoft.face.ErrorInfo
//import com.sw.dualscreen.GlobalKey
//import com.sw.dualscreen.R
//import com.sw.dualscreen.activity.PayActivity
//import com.sw.dualscreen.databinding.PresentationFacePayBinding
//import com.sw.dualscreen.ext.dp
//import com.sw.dualscreen.model.response.MemberInfo
//import com.sw.dualscreen.model.response.TextBean
//import com.sw.dualscreen.utils.SPUtil
//import com.sw.dualscreen.utils.SpannedUtils
//import com.sw.dualscreen.view.CustomDialog
//import com.sw.dualscreen.viewmodel.UserViewModel
//import com.sw.plate.utils.ToastUtils
//import com.sw.plate.utils.arcface.ConfigUtil
//import com.sw.plate.utils.arcface.ErrorCodeUtil
//import com.sw.plate.utils.arcface.FaceRectTransformer
//import com.sw.plate.utils.arcface.FaceRectView
//import com.sw.plate.utils.arcface.FaceRectView.DrawInfo
//import com.sw.plate.utils.arcface.PreviewConfig
//import com.sw.plate.utils.arcface.camera.CameraListener
//import com.sw.plate.utils.arcface.camera.DualCameraHelper
//import com.sw.plate.utils.arcface.face.constants.LivenessType
//import com.sw.plate.utils.arcface.face.model.CompareResult
//import com.sw.plate.utils.arcface.face.model.FacePreviewInfo
//import com.sw.plate.utils.arcface.face.model.RecognizeConfiguration
//import com.sw.plate.utils.arcface.viewmodel.RecognizeViewModel
//import kotlinx.coroutines.launch
//import timber.log.Timber
//
//class FacePayPresentation(
// val activity: PayActivity,
// display: Display,
// val userViewModel: UserViewModel,
// val recognizeViewModel: RecognizeViewModel,
//// val //parentTextureView: TextureView,
// private val onDismissListener: () -> Unit = {}
//) : Presentation(activity, display), ViewTreeObserver.OnGlobalLayoutListener {
//
// companion object {
// private const val TAG = "FacePayPresentation"
// }
//
// private lateinit var binding: PresentationFacePayBinding
//
// // 虹软人脸配置 ⬇
// private var isRecognition = false
// private var rgbCameraHelper: DualCameraHelper? = null
// private var rgbFaceRectTransformer: FaceRectTransformer? = null
// private val livenessType = LivenessType.IR
// private var openRectInfoDraw = false
//
// private var irCameraHelper: DualCameraHelper? = null
// private var irFaceRectTransformer: FaceRectTransformer? = null
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// binding = PresentationFacePayBinding.inflate(layoutInflater)
// setContentView(binding.root)
// window?.setBackgroundDrawableResource(android.R.color.white)
// initView()
// setupArcCamera()
// registerDataChange()
//
// pauseCamera()
// }
//
// override fun show() {
// super.show()
//
// binding.root.postDelayed({
// resumeCamera()
// }, 1500)
// }
//
// var foodName: String? = null
// var payAmount: String? = null
// private fun initView() {
// binding.tvFoodName.text = foodName
// binding.tvRealAmount.text = SpannedUtils.getAmountText(
// listOf(
// TextBean(text = "¥", textSize = 32),
// TextBean(text = payAmount ?: "", textSize = 48),
// )
// )
//// binding.ivPreviewImage.let {
//// it.outlineProvider = object : ViewOutlineProvider() {
//// override fun getOutline(view: View, outline: Outline) {
//// outline.setRoundRect(0, 0, view.width, view.height, 12f.dp)
//// }
//// }
//// it.clipToOutline = true
//// }
// }
//
// override fun onGlobalLayout() {
// Timber.tag(TAG).d("onGlobalLayout")
// binding.dualCameraTexturePreviewRgb.getViewTreeObserver().removeOnGlobalLayoutListener(this)
// //parentTextureView.getViewTreeObserver().removeOnGlobalLayoutListener(this)
// openCamera()
// }
//
// private fun openCamera() {
// Timber.tag(TAG).d("openCamera")
// if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) !=
// PackageManager.PERMISSION_GRANTED
// ) {
// ToastUtils.showToast("无摄像头权限")
// return
// }
// try {
// val cameraCount = Camera.getNumberOfCameras()
// if (cameraCount < 3) {
// ToastUtils.showToast("摄像头数量异常")
// return
// }
// recognizeViewModel.init(
// PreviewConfig(
// 2, 1, 90, 90
// )
// )
// initRgbCamera()
// if (DualCameraHelper.hasDualCamera() && livenessType === LivenessType.IR) {
// initIrCamera()
// }
// } catch (e: Exception) {
// Timber.tag(TAG).e(e, "打开摄像头失败")
// }
// }
//
// /**
// * 启用虹软人脸失败
// */
// private fun setupArcCamera() {
// initArcViewModel()
// initArcView()
// openRectInfoDraw = true
// }
//
// private fun registerDataChange() {
// activity.lifecycleScope.launch {
// userViewModel.loadFaceResult.collect { needUpdate ->
// if (needUpdate) {
// recognizeViewModel.refreshFaceList()
// }
// }
// }
// }
//
// override fun onStop() {
// rgbCameraHelper?.release()
// rgbCameraHelper = null
// irCameraHelper?.release()
// irCameraHelper = null
// recognizeViewModel.destroy()
// super.onStop()
// }
//
// fun resumeCamera() {
// Timber.tag(TAG).d("resumeCamera isRecognition = $isRecognition")
// isRecognition = true
// if (rgbCameraHelper?.isStopped == true) {
// rgbCameraHelper?.start()
// }
// }
//
// fun pauseCamera() {
// Timber.tag(TAG).d("pauseCamera isRecognition = $isRecognition")
// isRecognition = false
//
// recognizeViewModel.onPreviewFrame(ByteArray(1382400), true)
// }
//
// private fun initArcViewModel() {
// recognizeViewModel.setLiveType(livenessType)
// recognizeViewModel.ftInitCode.observe(activity, Observer { ftInitCode: Int? ->
// if (ftInitCode != ErrorInfo.MOK) {
// val error: String? = context.getString(
// R.string.specific_engine_init_failed, "ftEngine",
// ftInitCode, ErrorCodeUtil.arcFaceErrorCodeToFieldName(ftInitCode!!)
// )
// Timber.tag(TAG).e("ftInitCode observe = $error")
// ToastUtils.showToast(error)
// }
// })
// recognizeViewModel.frInitCode.observe(activity, Observer { frInitCode: Int? ->
// if (frInitCode != ErrorInfo.MOK) {
// val error: String? = context.getString(
// R.string.specific_engine_init_failed, "frEngine",
// frInitCode, ErrorCodeUtil.arcFaceErrorCodeToFieldName(frInitCode!!)
// )
// Timber.tag(TAG).e("frInitCode observe = $error")
// ToastUtils.showToast(error)
// }
// })
// recognizeViewModel.flInitCode.observe(activity, Observer { flInitCode: Int? ->
// if (flInitCode != ErrorInfo.MOK) {
// val error: String? = context.getString(
// R.string.specific_engine_init_failed, "flEngine",
// flInitCode, ErrorCodeUtil.arcFaceErrorCodeToFieldName(flInitCode!!)
// )
// Timber.tag(TAG).e("flInitCode observe = $error")
// ToastUtils.showToast(error)
// }
// })
//
// recognizeViewModel.recognizeConfiguration
// .observe(activity, Observer { recognizeConfiguration: RecognizeConfiguration? ->
// Timber.tag(TAG)
// .i("recognizeConfiguration: observe = ${recognizeConfiguration.toString()}")
// })
// recognizeViewModel.recognizeNotice.observe(activity, Observer { notice: String? ->
// Timber.tag(TAG).i("recognizeNotice observe notice = $notice")
// })
//
// recognizeViewModel.recognizeUserId.observe(
// activity,
// Observer { compareResult: CompareResult ->
// Timber.tag(TAG)
// .i("recognizeUserId observe compareResult = ${compareResult.trackId}, userId = ${compareResult.faceEntity.userName}")
//// recognitionTime = System.currentTimeMillis()
//// recognitionWeight = lastWeight
// lastFaceTrackId = compareResult.trackId
// val faceEntity = compareResult.faceEntity
// val userId = faceEntity.userName
// if (userId == null) return@Observer
// // TODO: 测试支付用户id
//// userId = "1987710988425662466"
// faceRecSuccess(userId)
// })
//
// recognizeViewModel.drawRectInfoText.observe(activity, Observer { info ->
// Timber.tag(TAG).i("drawRectInfoText observe info = $info")
// })
// }
//
// private fun initArcView() {
// //在布局结束后才做初始化操作
// binding.dualCameraTexturePreviewRgb.getViewTreeObserver().addOnGlobalLayoutListener(this)
// //parentTextureView.getViewTreeObserver().addOnGlobalLayoutListener(this)
// recognizeViewModel.getCompareResultList().getValue()
// }
//
// /**
// * 调整View的宽高,使预览显示正常且采集框固定为
// *
// * @param rgbPreview RGB预览View
// * @param previewView 显示预览数据的view
// * @param faceRectView 画框的view
// * @param previewSize 预览大小
// * @param displayOrientation 相机旋转角度
// * @param scale 缩放比例
// * @return 调整后的LayoutParams
// */
// private fun adjustPreviewViewSize(
// rgbPreview: View,
// previewView: View,
// faceRectView: FaceRectView,
// previewSize: Camera.Size,
// displayOrientation: Int,
// scale: Float
// ): ViewGroup.LayoutParams {
// val w = (600.dp * 1.5).toInt()
// val h = 1068.dp
// val layoutParams = FrameLayout.LayoutParams(w, h)
//
// previewView.setLayoutParams(layoutParams)
// faceRectView.setLayoutParams(layoutParams)
// return layoutParams
// }
//
// private fun initRgbCamera() {
// val cameraListener: CameraListener = object : CameraListener {
// override fun onCameraOpened(
// camera: Camera,
// cameraId: Int,
// displayOrientation: Int,
// isMirror: Boolean
// ) {
// Timber.tag(TAG)
// .d("initRgbCamera Rgb onCameraOpened: cameraId = $cameraId, displayOrientation = $displayOrientation")
// activity.runOnUiThread({
// val previewSizeRgb = camera.getParameters().getPreviewSize()
// val layoutParams = adjustPreviewViewSize(
// binding.dualCameraTexturePreviewRgb,
// binding.dualCameraTexturePreviewRgb, binding.dualCameraFaceRectView,
// previewSizeRgb, displayOrientation, 0.6F
// )
//
// Timber.tag(TAG)
// .d("initRgbCamera previewSizeRgb = ${previewSizeRgb.width}-${previewSizeRgb.height}")
// Timber.tag(TAG)
// .d("initRgbCamera layoutParams = ${layoutParams.width}-${layoutParams.height}")
// Timber.tag(TAG).d(
// "initRgbCamera isMirror = ${isMirror}, isDrawRgbRectHorizontalMirror = ${
// ConfigUtil.isDrawRgbRectHorizontalMirror(
// context
// )
// }, isDrawRgbRectVerticalMirror = ${
// ConfigUtil.isDrawRgbRectVerticalMirror(
// context
// )
// }"
// )
// // 调整识别窗口位置
// rgbFaceRectTransformer = FaceRectTransformer(
// previewSizeRgb.width,
// previewSizeRgb.height,
//// layoutParams.width,
//// layoutParams.height,
// layoutParams.width,
// layoutParams.height,
// 90,
// cameraId,
// isMirror,
// true,
// true
// )
//
// recognizeViewModel.onRgbCameraOpened(camera)
// recognizeViewModel.setRgbFaceRectTransformer(rgbFaceRectTransformer)
// })
// }
//
// @RequiresApi(api = Build.VERSION_CODES.Q)
// override fun onPreview(nv21: ByteArray?, camera: Camera?) {
// if (!isRecognition) {
// return
// }
// binding.dualCameraFaceRectView.clearFaceInfo()
// val facePreviewInfoList: MutableList<FacePreviewInfo?>? =
// recognizeViewModel.onPreviewFrame(nv21, true)
// if (facePreviewInfoList != null && rgbFaceRectTransformer != null) {
// drawPreviewInfo(facePreviewInfoList)
// }
// recognizeViewModel.clearLeftFace(facePreviewInfoList)
// }
//
// override fun onCameraClosed() {
// Timber.tag(TAG).i("initRgbCamera onCameraClosed: ")
// }
//
// override fun onCameraError(e: java.lang.Exception) {
// Timber.tag(TAG).i("initRgbCamera onCameraError: %s", e.message)
// e.printStackTrace()
// }
//
// override fun onCameraConfigurationChanged(cameraID: Int, displayOrientation: Int) {
// Timber.tag(TAG)
// .i("initRgbCamera onCameraConfigurationChanged: threadName = ${Thread.currentThread().name}")
// if (rgbFaceRectTransformer != null) {
// rgbFaceRectTransformer!!.cameraDisplayOrientation = displayOrientation
// }
// Timber.tag(TAG)
// .i("initRgbCamera onCameraConfigurationChanged: $cameraID $displayOrientation")
// }
// }
// val measuredWidth = binding.dualCameraTexturePreviewRgb.measuredWidth
// val measuredHeight = binding.dualCameraTexturePreviewRgb.measuredHeight
// Timber.tag(TAG)
// .i("initRgbCamera measuredWidth=$measuredWidthmeasuredHeight=$measuredHeight")
//
// val previewConfig: PreviewConfig = recognizeViewModel.previewConfig
// rgbCameraHelper = DualCameraHelper.Builder()
// .previewViewSize(Point(measuredWidth, measuredHeight))
// .rotation(activity.windowManager.defaultDisplay.rotation)
// .additionalRotation(previewConfig.rgbAdditionalDisplayOrientation) // 角度
// .previewSize(recognizeViewModel.loadPreviewSize())
// .specificCameraId(previewConfig.rgbCameraId)
// .isMirror(true)
// .previewOn(binding.dualCameraTexturePreviewRgb)
// .cameraListener(cameraListener)
// .build()
// rgbCameraHelper!!.setSurfaceFrameCallback { frame ->
// activity.facePayFragment?.loadBitmap(frame)
// }
// rgbCameraHelper!!.init()
//// rgbCameraHelper!!.start()
// }
//
// /**
// * 初始化红外相机,若活体检测类型是可见光活体检测或不启用活体,则不需要启用
// */
// private fun initIrCamera() {
// Timber.tag(TAG).d("initIrCamera: livenessType = $livenessType")
// if (livenessType === LivenessType.RGB) {
// return
// }
// val irCameraListener: CameraListener = object : CameraListener {
// override fun onCameraOpened(
// camera: Camera,
// cameraId: Int,
// displayOrientation: Int,
// isMirror: Boolean
// ) {
// Timber.tag(TAG)
// .d("initIrCamera IR onCameraOpened: cameraId = $cameraId, displayOrientation = $displayOrientation")
// val previewSizeIr = camera.getParameters().getPreviewSize()
// val layoutParams = adjustPreviewViewSize(
// binding.dualCameraTexturePreviewRgb,
// binding.dualCameraTexturePreviewIr, binding.dualCameraFaceRectViewIr,
// previewSizeIr, displayOrientation, 0.25f
// )
//
// irFaceRectTransformer = FaceRectTransformer(
// previewSizeIr.width, previewSizeIr.height,
//// layoutParams.width, layoutParams.height,
// layoutParams.width, layoutParams.height,
// displayOrientation, cameraId, isMirror,
// ConfigUtil.isDrawIrRectHorizontalMirror(context),
// ConfigUtil.isDrawIrRectVerticalMirror(context)
// )
//
// recognizeViewModel.onIrCameraOpened(camera)
// recognizeViewModel.setIrFaceRectTransformer(irFaceRectTransformer)
// }
//
//
// override fun onPreview(nv21: ByteArray?, camera: Camera?) {
// recognizeViewModel.refreshIrPreviewData(nv21)
// }
//
// override fun onCameraClosed() {
// Timber.tag(TAG).i("initIrCamera onCameraClosed: ")
// }
//
// override fun onCameraError(e: java.lang.Exception) {
// Timber.tag(TAG).i("initIrCamera onCameraError: ${e.message}")
// e.printStackTrace()
// }
//
// override fun onCameraConfigurationChanged(
// cameraID: Int,
// displayOrientation: Int
// ) {
// if (irFaceRectTransformer != null) {
// irFaceRectTransformer!!.cameraDisplayOrientation = displayOrientation
// }
// Timber.tag(TAG)
// .i("initIrCamera onCameraConfigurationChanged: cameraID = $cameraID, displayOrientation = $displayOrientation")
// }
// }
//
// val previewConfig = recognizeViewModel.previewConfig
// irCameraHelper = DualCameraHelper.Builder()
// .previewViewSize(
// Point(
// binding.dualCameraTexturePreviewIr.measuredWidth,
// binding.dualCameraTexturePreviewIr.measuredHeight
// )
// )
// .rotation(activity.windowManager.defaultDisplay.rotation)
// .specificCameraId(previewConfig.irCameraId)
// .previewOn(binding.dualCameraTexturePreviewIr)
// .cameraListener(irCameraListener)
// .isMirror(true)
// .previewSize(recognizeViewModel.loadPreviewSize()) //相机预览大小设置,RGB与IR需使用相同大小
// .additionalRotation(previewConfig.irAdditionalDisplayOrientation) //额外旋转角度
// .build()
// irCameraHelper!!.init()
// try {
// irCameraHelper!!.start()
// } catch (e: RuntimeException) {
// ToastUtils.showToast(e.message + context.getString(R.string.camera_error_notice))
// }
// }
//
// /**
// * 绘制RGB、IR画面的实时人脸信息
// *
// * @param facePreviewInfoList RGB画面的实时人脸信息
// */
// private fun drawPreviewInfo(facePreviewInfoList: MutableList<FacePreviewInfo?>) {
//// Timber.tag(TAG).d("drawPreviewInfo facePreviewInfoList = ${facePreviewInfoList.size}, rgbFaceRectTransformer = ${rgbFaceRectTransformer != null}")
// if (rgbFaceRectTransformer != null) {
// val rgbDrawInfoList: MutableList<DrawInfo?>? = recognizeViewModel.getDrawInfo(
// facePreviewInfoList,
// LivenessType.RGB,
// openRectInfoDraw
// )
// // 识别成功
// binding.dualCameraFaceRectView.drawRealtimeFaceInfo(rgbDrawInfoList)
// }
//
// if (facePreviewInfoList.isEmpty() || (lastFaceTrackId != facePreviewInfoList[0]!!.trackId)) {
// if (lastFaceTrackId != -1) {
// // mealPickupMode = SPUtil.getInstance().get(GlobalKey.KEY_PICKUP_MODE, 0) ?: 0
// // Timber.tag(TAG).i("$lastFaceTrackId 用户离开")
// // lastFaceTrackId = -1
// // postUserData()
// // if (mealPickupMode == 0) {
// // step1FoodRecognizing()
// // } else {
// // step2FaceRecognizing(currentFood!!)
// // }
//
// resumeCamera()
// }
// }
// }
//
// private var lastFaceTrackId: Int = -1 // 上一次的人脸信息
//
// override fun onDisplayRemoved() {
// super.onDisplayRemoved()
// onDismissListener()
// }
//
//
// private fun faceRecSuccess(userId: String) {
// activity.runOnUiThread {
// activity.showWaitingDialog("加载中,请稍后……")
// }
// activity.getMemberInfoById(userId) { memberInfo ->
// if (memberInfo == null) {
// activity.hideWaitingDialog()
// //ToastUtils.showToast("查询会员信息失败,请稍后重试")
// return@getMemberInfoById
// }
// activity.bindOrder(memberInfo.faceUserId?:"") { bindResult ->
// if (bindResult.not()) {
// activity.hideWaitingDialog()
// //ToastUtils.showToast("订单绑定失败")
// return@bindOrder
// }
// binding.root.postDelayed({
// activity.hideWaitingDialog()
// activity.showPayInfo(type = 1, isVip = true, memberInfo = memberInfo)
// activity.hidePayTab()
// binding.root.postDelayed({
// dismiss()
// }, 500)
// }, 1000)
// }
// }
// }
//
//// private fun bindOrder(userId: String, block: () -> Unit) {
//// val pickupMode = SPUtil.getInstance().get(GlobalKey.KEY_PICKUP_MODE, 0)
//// val mode = if (pickupMode == 1) 1 else 2
//// userViewModel.bindOrder(userId, activity.foodOrderId, mode = mode) { bindResult ->
//// activity.runOnUiThread {
//// if (bindResult.not()) {
//// activity.hideWaitingDialog()
//// //ToastUtils.showToast("订单绑定失败")
//// return@runOnUiThread
//// }
//// block()
//// }
//// }
//// }
//// private fun getMemberInfo(userId: String, block:(MemberInfo)-> Unit) {
//// userViewModel.getMemberInfoById(memberId = userId) { memberInfo ->
//// activity.runOnUiThread {
//// if (memberInfo == null) {
//// activity.hideWaitingDialog()
//// //ToastUtils.showToast("查询会员信息失败,请稍后重试")
//// return@runOnUiThread
//// }
//// block(memberInfo)
//// }
//// }
//// }
//
//}
@@ -0,0 +1,826 @@
package com.sw.dualscreen.presentation.pay
import android.Manifest
import android.annotation.SuppressLint
import android.app.Presentation
import android.content.pm.PackageManager
import android.graphics.Point
import android.hardware.Camera
import android.os.Build
import android.os.Bundle
import android.text.Spanned
import android.text.SpannedString
import android.text.style.AbsoluteSizeSpan
import android.view.Display
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.FrameLayout
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.text.buildSpannedString
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.arcsoft.face.ErrorInfo
import com.sw.dualscreen.R
import com.sw.dualscreen.activity.PayActivity
import com.sw.dualscreen.databinding.PresentationPayBinding
import com.sw.dualscreen.ext.dp
import com.sw.dualscreen.ext.format2String
import com.sw.dualscreen.ext.gone
import com.sw.dualscreen.ext.invisible
import com.sw.dualscreen.ext.load
import com.sw.dualscreen.ext.visible
import com.sw.dualscreen.model.response.MemberInfo
import com.sw.dualscreen.model.response.TextBean
import com.sw.dualscreen.utils.SpannedUtils
import com.sw.dualscreen.viewmodel.UserViewModel
import com.sw.plate.utils.ToastUtils
import com.sw.plate.utils.arcface.ConfigUtil
import com.sw.plate.utils.arcface.ErrorCodeUtil
import com.sw.plate.utils.arcface.FaceRectTransformer
import com.sw.plate.utils.arcface.FaceRectView
import com.sw.plate.utils.arcface.FaceRectView.DrawInfo
import com.sw.plate.utils.arcface.PreviewConfig
import com.sw.plate.utils.arcface.camera.CameraListener
import com.sw.plate.utils.arcface.camera.DualCameraHelper
import com.sw.plate.utils.arcface.face.constants.LivenessType
import com.sw.plate.utils.arcface.face.model.CompareResult
import com.sw.plate.utils.arcface.face.model.FacePreviewInfo
import com.sw.plate.utils.arcface.face.model.RecognizeConfiguration
import com.sw.plate.utils.arcface.viewmodel.RecognizeViewModel
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.concurrent.atomic.AtomicBoolean
class PayPresentation(
val activity: PayActivity,
display: Display,
val userViewModel: UserViewModel,
val recognizeViewModel: RecognizeViewModel,
private val onDismissListener: () -> Unit = {}
) : Presentation(activity, display), ViewTreeObserver.OnGlobalLayoutListener {
companion object {
private const val TAG = "PayPresentation"
const val CASH_PAY = 100
const val FACE_PAY = 200
const val QR_CODE_PAY = 300
}
private lateinit var binding: PresentationPayBinding
// 虹软人脸配置 ⬇
private var isRecognition = false
private var rgbCameraHelper: DualCameraHelper? = null
private var rgbFaceRectTransformer: FaceRectTransformer? = null
private val livenessType = LivenessType.IR
private var openRectInfoDraw = false
private var irCameraHelper: DualCameraHelper? = null
private var irFaceRectTransformer: FaceRectTransformer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = PresentationPayBinding.inflate(layoutInflater)
setContentView(binding.root)
window?.setBackgroundDrawableResource(android.R.color.white)
setupArcCamera()
registerDataChange()
initView()
}
override fun show() {
super.show()
pauseCamera()
}
var pageType: Int = 0
var type: Int = 0
// fun updatePage(pageType:Int, type:Int = -1) {
// this.pageType == pageType
// this.type = type
// if (pageType == PayPresentation.CASH_PAY) {
//
// return
// }
// if (pageType == PayPresentation.FACE_PAY) {
//
// return
// }
// if (pageType == PayPresentation.QR_CODE_PAY) {
//
// return
// }
// }
var foodName: String? = null
var payAmount: String? = null
fun initView() {
when (pageType) {
FACE_PAY -> {
//人脸识别
binding.flCashPay.gone()
binding.flQrCodePay.gone()
binding.flFacePay.visible()
binding.tvFoodName.text = foodName
binding.tvRealAmount.text = SpannedUtils.getAmountText(
listOf(
TextBean(text = "¥", textSize = 32),
TextBean(text = payAmount ?: "", textSize = 48),
)
)
//pauseCamera()
resumeCamera()
// binding.root.postDelayed({
// resumeCamera()
// }, 1000)
}
QR_CODE_PAY -> {
//二维码
binding.flCashPay.gone()
binding.flQrCodePay.visible()
binding.flFacePay.gone()
initQrCodeView()
}
CASH_PAY -> {
binding.flCashPay.visible()
binding.flQrCodePay.gone()
binding.flFacePay.gone()
binding.tvFoodName2.text = foodName
binding.tvRealAmount2.text = getAmountText(payAmount ?: "")
}
}
}
private fun getAmountText(amount: String): SpannedString {
return buildSpannedString {
append("¥", AbsoluteSizeSpan(32, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
append(amount, AbsoluteSizeSpan(48, true), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
override fun onGlobalLayout() {
Timber.tag(TAG).d("onGlobalLayout")
binding.dualCameraTexturePreviewRgb.getViewTreeObserver().removeOnGlobalLayoutListener(this)
//parentTextureView.getViewTreeObserver().removeOnGlobalLayoutListener(this)
openCamera()
}
private fun openCamera() {
Timber.tag(TAG).d("openCamera")
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED
) {
ToastUtils.showToast("无摄像头权限")
return
}
try {
val cameraCount = Camera.getNumberOfCameras()
if (cameraCount < 3) {
ToastUtils.showToast("摄像头数量异常")
return
}
recognizeViewModel.init(
PreviewConfig(
2, 1, 90, 90
)
)
initRgbCamera()
if (DualCameraHelper.hasDualCamera() && livenessType === LivenessType.IR) {
initIrCamera()
}
} catch (e: Exception) {
Timber.tag(TAG).e(e, "打开摄像头失败")
}
}
/**
* 启用虹软人脸失败
*/
private fun setupArcCamera() {
initArcViewModel()
initArcView()
openRectInfoDraw = true
}
private fun registerDataChange() {
activity.lifecycleScope.launch {
userViewModel.loadFaceResult.collect { needUpdate ->
if (needUpdate) {
recognizeViewModel.refreshFaceList()
}
}
}
}
override fun onStop() {
rgbCameraHelper?.release()
rgbCameraHelper = null
irCameraHelper?.release()
irCameraHelper = null
recognizeViewModel.destroy()
super.onStop()
}
fun resumeCamera() {
Timber.tag(TAG).d("resumeCamera isRecognition = $isRecognition")
isRecognition = true
if (rgbCameraHelper?.isStopped == true) {
rgbCameraHelper?.start()
}
}
fun pauseCamera() {
Timber.tag(TAG).d("pauseCamera isRecognition = $isRecognition")
isRecognition = false
recognizeViewModel.onPreviewFrame(ByteArray(1382400), true)
}
private fun initArcViewModel() {
recognizeViewModel.setLiveType(livenessType)
recognizeViewModel.ftInitCode.observe(activity, Observer { ftInitCode: Int? ->
if (ftInitCode != ErrorInfo.MOK) {
val error: String? = context.getString(
R.string.specific_engine_init_failed, "ftEngine",
ftInitCode, ErrorCodeUtil.arcFaceErrorCodeToFieldName(ftInitCode!!)
)
Timber.tag(TAG).e("ftInitCode observe = $error")
ToastUtils.showToast(error)
}
})
recognizeViewModel.frInitCode.observe(activity, Observer { frInitCode: Int? ->
if (frInitCode != ErrorInfo.MOK) {
val error: String? = context.getString(
R.string.specific_engine_init_failed, "frEngine",
frInitCode, ErrorCodeUtil.arcFaceErrorCodeToFieldName(frInitCode!!)
)
Timber.tag(TAG).e("frInitCode observe = $error")
ToastUtils.showToast(error)
}
})
recognizeViewModel.flInitCode.observe(activity, Observer { flInitCode: Int? ->
if (flInitCode != ErrorInfo.MOK) {
val error: String? = context.getString(
R.string.specific_engine_init_failed, "flEngine",
flInitCode, ErrorCodeUtil.arcFaceErrorCodeToFieldName(flInitCode!!)
)
Timber.tag(TAG).e("flInitCode observe = $error")
ToastUtils.showToast(error)
}
})
recognizeViewModel.recognizeConfiguration
.observe(activity, Observer { recognizeConfiguration: RecognizeConfiguration? ->
Timber.tag(TAG)
.i("recognizeConfiguration: observe = ${recognizeConfiguration.toString()}")
})
recognizeViewModel.recognizeNotice.observe(activity, Observer { notice: String? ->
Timber.tag(TAG).i("recognizeNotice observe notice = $notice")
})
recognizeViewModel.recognizeUserId.observe(
activity,
Observer { compareResult: CompareResult ->
Timber.tag(TAG)
.i("recognizeUserId observe compareResult = ${compareResult.trackId}, userId = ${compareResult.faceEntity.userName}")
// recognitionTime = System.currentTimeMillis()
// recognitionWeight = lastWeight
if (isExistNotPayOrder.get()) return@Observer
lastFaceTrackId = compareResult.trackId
val faceEntity = compareResult.faceEntity
val userId = faceEntity.userName
val isMember = faceEntity.userType == "1"
activity.isMember = isMember
if (userId.isNullOrBlank()) return@Observer
// TODO: 测试支付用户id
// userId = "1987710988425662466"
isExistNotPayOrder.set(true)
faceRecSuccess(userId, isMember)
})
recognizeViewModel.drawRectInfoText.observe(activity, Observer { info ->
Timber.tag(TAG).i("drawRectInfoText observe info = $info")
})
}
private var isExistNotPayOrder = AtomicBoolean(false)
private fun initArcView() {
//在布局结束后才做初始化操作
binding.dualCameraTexturePreviewRgb.getViewTreeObserver().addOnGlobalLayoutListener(this)
//parentTextureView.getViewTreeObserver().addOnGlobalLayoutListener(this)
recognizeViewModel.getCompareResultList().getValue()
}
/**
* 调整View的宽高,使预览显示正常且采集框固定为
*
* @param rgbPreview RGB预览View
* @param previewView 显示预览数据的view
* @param faceRectView 画框的view
* @param previewSize 预览大小
* @param displayOrientation 相机旋转角度
* @param scale 缩放比例
* @return 调整后的LayoutParams
*/
private fun adjustPreviewViewSize(
rgbPreview: View,
previewView: View,
faceRectView: FaceRectView,
previewSize: Camera.Size,
displayOrientation: Int,
scale: Float
): ViewGroup.LayoutParams {
val w = (600.dp * 1.5).toInt()
val h = 1068.dp
val layoutParams = FrameLayout.LayoutParams(w, h)
previewView.setLayoutParams(layoutParams)
faceRectView.setLayoutParams(layoutParams)
return layoutParams
}
private fun initRgbCamera() {
val cameraListener: CameraListener = object : CameraListener {
override fun onCameraOpened(
camera: Camera,
cameraId: Int,
displayOrientation: Int,
isMirror: Boolean
) {
Timber.tag(TAG)
.d("initRgbCamera Rgb onCameraOpened: cameraId = $cameraId, displayOrientation = $displayOrientation")
activity.runOnUiThread({
val previewSizeRgb = camera.getParameters().getPreviewSize()
val layoutParams = adjustPreviewViewSize(
binding.dualCameraTexturePreviewRgb,
binding.dualCameraTexturePreviewRgb, binding.dualCameraFaceRectView,
previewSizeRgb, displayOrientation, 0.6F
)
Timber.tag(TAG)
.d("initRgbCamera previewSizeRgb = ${previewSizeRgb.width}-${previewSizeRgb.height}")
Timber.tag(TAG)
.d("initRgbCamera layoutParams = ${layoutParams.width}-${layoutParams.height}")
Timber.tag(TAG).d(
"initRgbCamera isMirror = ${isMirror}, isDrawRgbRectHorizontalMirror = ${
ConfigUtil.isDrawRgbRectHorizontalMirror(
context
)
}, isDrawRgbRectVerticalMirror = ${
ConfigUtil.isDrawRgbRectVerticalMirror(
context
)
}"
)
// 调整识别窗口位置
rgbFaceRectTransformer = FaceRectTransformer(
previewSizeRgb.width,
previewSizeRgb.height,
// layoutParams.width,
// layoutParams.height,
layoutParams.width,
layoutParams.height,
90,
cameraId,
isMirror,
true,
true
)
recognizeViewModel.onRgbCameraOpened(camera)
recognizeViewModel.setRgbFaceRectTransformer(rgbFaceRectTransformer)
})
}
@RequiresApi(api = Build.VERSION_CODES.Q)
override fun onPreview(nv21: ByteArray?, camera: Camera?) {
if (!isRecognition) {
return
}
binding.dualCameraFaceRectView.clearFaceInfo()
val facePreviewInfoList: MutableList<FacePreviewInfo?>? =
recognizeViewModel.onPreviewFrame(nv21, true)
if (facePreviewInfoList != null && rgbFaceRectTransformer != null) {
drawPreviewInfo(facePreviewInfoList)
}
recognizeViewModel.clearLeftFace(facePreviewInfoList)
}
override fun onCameraClosed() {
Timber.tag(TAG).i("initRgbCamera onCameraClosed: ")
}
override fun onCameraError(e: java.lang.Exception) {
Timber.tag(TAG).i("initRgbCamera onCameraError: %s", e.message)
e.printStackTrace()
}
override fun onCameraConfigurationChanged(cameraID: Int, displayOrientation: Int) {
Timber.tag(TAG)
.i("initRgbCamera onCameraConfigurationChanged: threadName = ${Thread.currentThread().name}")
if (rgbFaceRectTransformer != null) {
rgbFaceRectTransformer!!.cameraDisplayOrientation = displayOrientation
}
Timber.tag(TAG)
.i("initRgbCamera onCameraConfigurationChanged: $cameraID $displayOrientation")
}
}
val measuredWidth = binding.dualCameraTexturePreviewRgb.measuredWidth
val measuredHeight = binding.dualCameraTexturePreviewRgb.measuredHeight
Timber.tag(TAG)
.i("initRgbCamera measuredWidth=$measuredWidthmeasuredHeight=$measuredHeight")
val previewConfig: PreviewConfig = recognizeViewModel.previewConfig
rgbCameraHelper = DualCameraHelper.Builder()
.previewViewSize(Point(measuredWidth, measuredHeight))
.rotation(activity.windowManager.defaultDisplay.rotation)
.additionalRotation(previewConfig.rgbAdditionalDisplayOrientation) // 角度
.previewSize(recognizeViewModel.loadPreviewSize())
.specificCameraId(previewConfig.rgbCameraId)
.isMirror(true)
.previewOn(binding.dualCameraTexturePreviewRgb)
.cameraListener(cameraListener)
.build()
rgbCameraHelper!!.setSurfaceFrameCallback { frame ->
activity.facePayFragment?.loadBitmap(frame)
}
rgbCameraHelper!!.init()
// rgbCameraHelper!!.start()
}
/**
* 初始化红外相机,若活体检测类型是可见光活体检测或不启用活体,则不需要启用
*/
private fun initIrCamera() {
Timber.tag(TAG).d("initIrCamera: livenessType = $livenessType")
if (livenessType === LivenessType.RGB) {
return
}
val irCameraListener: CameraListener = object : CameraListener {
override fun onCameraOpened(
camera: Camera,
cameraId: Int,
displayOrientation: Int,
isMirror: Boolean
) {
Timber.tag(TAG)
.d("initIrCamera IR onCameraOpened: cameraId = $cameraId, displayOrientation = $displayOrientation")
val previewSizeIr = camera.getParameters().getPreviewSize()
val layoutParams = adjustPreviewViewSize(
binding.dualCameraTexturePreviewRgb,
binding.dualCameraTexturePreviewIr, binding.dualCameraFaceRectViewIr,
previewSizeIr, displayOrientation, 0.25f
)
irFaceRectTransformer = FaceRectTransformer(
previewSizeIr.width, previewSizeIr.height,
// layoutParams.width, layoutParams.height,
layoutParams.width, layoutParams.height,
displayOrientation, cameraId, isMirror,
ConfigUtil.isDrawIrRectHorizontalMirror(context),
ConfigUtil.isDrawIrRectVerticalMirror(context)
)
recognizeViewModel.onIrCameraOpened(camera)
recognizeViewModel.setIrFaceRectTransformer(irFaceRectTransformer)
}
override fun onPreview(nv21: ByteArray?, camera: Camera?) {
recognizeViewModel.refreshIrPreviewData(nv21)
}
override fun onCameraClosed() {
Timber.tag(TAG).i("initIrCamera onCameraClosed: ")
}
override fun onCameraError(e: java.lang.Exception) {
Timber.tag(TAG).i("initIrCamera onCameraError: ${e.message}")
e.printStackTrace()
}
override fun onCameraConfigurationChanged(
cameraID: Int,
displayOrientation: Int
) {
if (irFaceRectTransformer != null) {
irFaceRectTransformer!!.cameraDisplayOrientation = displayOrientation
}
Timber.tag(TAG)
.i("initIrCamera onCameraConfigurationChanged: cameraID = $cameraID, displayOrientation = $displayOrientation")
}
}
val previewConfig = recognizeViewModel.previewConfig
irCameraHelper = DualCameraHelper.Builder()
.previewViewSize(
Point(
binding.dualCameraTexturePreviewIr.measuredWidth,
binding.dualCameraTexturePreviewIr.measuredHeight
)
)
.rotation(activity.windowManager.defaultDisplay.rotation)
.specificCameraId(previewConfig.irCameraId)
.previewOn(binding.dualCameraTexturePreviewIr)
.cameraListener(irCameraListener)
.isMirror(true)
.previewSize(recognizeViewModel.loadPreviewSize()) //相机预览大小设置,RGB与IR需使用相同大小
.additionalRotation(previewConfig.irAdditionalDisplayOrientation) //额外旋转角度
.build()
irCameraHelper!!.init()
try {
irCameraHelper!!.start()
} catch (e: RuntimeException) {
ToastUtils.showToast(e.message + context.getString(R.string.camera_error_notice))
}
}
/**
* 绘制RGB、IR画面的实时人脸信息
*
* @param facePreviewInfoList RGB画面的实时人脸信息
*/
private fun drawPreviewInfo(facePreviewInfoList: MutableList<FacePreviewInfo?>) {
// Timber.tag(TAG).d("drawPreviewInfo facePreviewInfoList = ${facePreviewInfoList.size}, rgbFaceRectTransformer = ${rgbFaceRectTransformer != null}")
if (rgbFaceRectTransformer != null) {
val rgbDrawInfoList: MutableList<DrawInfo?>? = recognizeViewModel.getDrawInfo(
facePreviewInfoList,
LivenessType.RGB,
openRectInfoDraw
)
// 识别成功
binding.dualCameraFaceRectView.drawRealtimeFaceInfo(rgbDrawInfoList)
}
if (facePreviewInfoList.isEmpty() || (lastFaceTrackId != facePreviewInfoList[0]!!.trackId)) {
if (lastFaceTrackId != -1) {
// mealPickupMode = SPUtil.getInstance().get(GlobalKey.KEY_PICKUP_MODE, 0) ?: 0
// Timber.tag(TAG).i("$lastFaceTrackId 用户离开")
// lastFaceTrackId = -1
// postUserData()
// if (mealPickupMode == 0) {
// step1FoodRecognizing()
// } else {
// step2FaceRecognizing(currentFood!!)
// }
resumeCamera()
}
}
}
private var lastFaceTrackId: Int = -1 // 上一次的人脸信息
override fun onDisplayRemoved() {
super.onDisplayRemoved()
onDismissListener()
}
private fun faceRecSuccess(userId: String, isMember: Boolean) {
activity.runOnUiThread {
activity.showWaitingDialog("加载中,请稍后……")
}
activity.getMemberInfoById(userId) { memberInfo ->
if (memberInfo == null) {
activity.hideWaitingDialog()
//ToastUtils.showToast("查询会员信息失败,请稍后重试")
return@getMemberInfoById
}
memberInfo.member = isMember
activity.bindOrder(memberInfo.faceUserId ?: "") { bindResult ->
if (bindResult.not()) {
activity.hideWaitingDialog()
//ToastUtils.showToast("订单绑定失败")
return@bindOrder
}
binding.root.postDelayed({
activity.hideWaitingDialog()
// TODO: 测试 memberInfo.member是否返回正常数据---------------
activity.showPayInfo(type = 1, isVip = memberInfo.member, memberInfo = memberInfo)
activity.hidePayTab()
// binding.root.postDelayed({
// dismiss()
// }, 500)
}, 1000)
}
}
}
// private fun bindOrder(userId: String, block: () -> Unit) {
// val pickupMode = SPUtil.getInstance().get(GlobalKey.KEY_PICKUP_MODE, 0)
// val mode = if (pickupMode == 1) 1 else 2
// userViewModel.bindOrder(userId, activity.foodOrderId, mode = mode) { bindResult ->
// activity.runOnUiThread {
// if (bindResult.not()) {
// activity.hideWaitingDialog()
// //ToastUtils.showToast("订单绑定失败")
// return@runOnUiThread
// }
// block()
// }
// }
// }
// private fun getMemberInfo(userId: String, block:(MemberInfo)-> Unit) {
// userViewModel.getMemberInfoById(memberId = userId) { memberInfo ->
// activity.runOnUiThread {
// if (memberInfo == null) {
// activity.hideWaitingDialog()
// //ToastUtils.showToast("查询会员信息失败,请稍后重试")
// return@runOnUiThread
// }
// block(memberInfo)
// }
// }
// }
var payQrCodePic: Any? = null
//总价格
var totalPrice = 0.0
//余额
private var balance = 0.0
//实际支付金额
private var realPayPrice = 0.0
//扣除余额
private var expensesBalance = 0.0
@SuppressLint("SetTextI18n")
private fun initQrCodeView() {
when (type) {
0 -> {
binding.layoutVip.gone()
binding.layoutPaySuccess.gone()
binding.layoutScanQrCode.visible()
binding.tvPayTip.text = "请扫码支付或出示付款码"
binding.tvFoodName3.text = foodName
binding.tvRealAmount3.text = SpannedUtils.getAmountText(
listOf(
TextBean(text = "¥", textSize = 32),
TextBean(text = totalPrice.format2String(2), textSize = 48),
)
)
binding.ivPayQrCode.load(payQrCodePic)
}
1 -> {
val memberInfo = activity.memberInfo
binding.layoutVip.run {
if (memberInfo != null && memberInfo.member) visible() else gone()
}
binding.layoutPaySuccess.gone()
binding.layoutScanQrCode.visible()
balance = (memberInfo?.topUpBalance ?: 0.0) + (memberInfo?.rewardBalance ?: 0.0)
realPayPrice = if (balance >= totalPrice) 0.0 else totalPrice - balance
expensesBalance = if (balance >= totalPrice) totalPrice else balance
memberInfo?.let { loadUserInfo(it) }
binding.tvUserBalance.text = SpannedUtils.getAmountText(
listOf(
TextBean(text = "¥", textSize = 20),
TextBean(text = balance.format2String(2), textSize = 32),
)
)
binding.tvFoodName3.text = foodName
binding.tvRealAmount3.text = SpannedUtils.getAmountText(
listOf(
TextBean(text = "¥", textSize = 32),
TextBean(text = totalPrice.format2String(2), textSize = 48),
)
)
binding.ivPayQrCode.run {
// load(payQrCodePic)
if (balance >= totalPrice) invisible() else visible()
}
if (memberInfo !=null && memberInfo!!.member) {
binding.tvPayTip.text = SpannedUtils.getAmountText(getAmountList())
} else {
binding.tvPayTip.text = SpannedUtils.getAmountText(getAmountListNotMember())
}
}
2 -> {
val memberInfo = activity.memberInfo
binding.layoutVip.run {
if (memberInfo != null && memberInfo.member) visible() else gone()
}
binding.layoutPaySuccess.visible()
binding.layoutScanQrCode.gone()
balance = if (memberInfo != null && memberInfo.member) (memberInfo.topUpBalance
?: 0.0) + (memberInfo.rewardBalance ?: 0.0) else 0.0
realPayPrice = if (balance >= totalPrice) 0.0 else totalPrice - balance
expensesBalance = if (balance >= totalPrice) totalPrice else balance
memberInfo?.let { loadUserInfo(it) }
val remainBalance = if (balance >= totalPrice) balance - totalPrice else 0.0
binding.tvUserBalance.text = SpannedUtils.getAmountText(
listOf(
TextBean(text = "¥", textSize = 24),
TextBean(text = remainBalance.format2String(2), textSize = 36),
)
)
val showBalance = expensesBalance.format2String(2)
val showTotal = totalPrice.format2String(2)
binding.tvPayInfo.text = "余额扣除 $showBalance 元,在线支付 $showTotal"
}
}
}
fun loadQrCodeImage(qrCodeUrl: String?) {
binding.ivPayQrCode.load(qrCodeUrl)
}
private fun loadUserInfo(item: MemberInfo) {
binding.ivHeadPic.load(
if (item.faceUrl.isNullOrBlank()) R.drawable.ic_avatar_default
else item.faceUrl
)
binding.tvUserName.text = item.name
val phone = item.phone ?: ""
binding.tvUserPhone.text =
if (phone.length == 11) phone.replace(phone.substring(3, 7), "****")
else phone
}
private fun getAmountListNotMember(): List<TextBean> {
val list: MutableList<TextBean> = mutableListOf()
list.add(TextBean(text = "应付金额 ", textSize = 30, textColor = "#FF889AC2"))
list.add(
TextBean(
text = "-${totalPrice.format2String(2)}",
textSize = 30,
textColor = "#FF0A1428",
isBold = true
)
)
list.add(TextBean(text = "", textSize = 30, textColor = "#FF889AC2"))
return list
}
private fun getAmountList(): List<TextBean> {
val list: MutableList<TextBean> = mutableListOf()
list.add(TextBean(text = "余额扣除 ", textSize = 30, textColor = "#FF5E7585"))
list.add(
TextBean(
text = "-${expensesBalance.format2String(2)}",
textSize = 30,
textColor = "#FF0A1428",
isBold = true
)
)
if (balance >= totalPrice) {
//余额大于等于总价格,使用余额支付
list.add(TextBean(text = " 元,扣除后可用余额 ", textSize = 30, textColor = "#FF5E7585"))
val remainingBalance = balance - totalPrice
list.add(
TextBean(
text = remainingBalance.format2String(2),
textSize = 30,
textColor = "#FF0A1428",
isBold = true
)
)
} else {
//余额小于总价格,使用余额+扫码支付
//实际支付金额
list.add(TextBean(text = " 元,还需支付 ", textSize = 30, textColor = "#FF5E7585"))
list.add(
TextBean(
text = realPayPrice.format2String(2),
textSize = 30,
textColor = "#FF0A1428",
isBold = true
)
)
}
list.add(TextBean(text = "", textSize = 30, textColor = "#FF5E7585"))
return list
}
}
@@ -0,0 +1,202 @@
//package com.sw.dualscreen.presentation.pay
//
//import android.annotation.SuppressLint
//import android.app.Presentation
//import android.os.Bundle
//import android.view.Display
//import com.sw.dualscreen.R
//import com.sw.dualscreen.activity.PayActivity
//import com.sw.dualscreen.databinding.PresentationScanQrcodePayBinding
//import com.sw.dualscreen.ext.format2String
//import com.sw.dualscreen.ext.gone
//import com.sw.dualscreen.ext.invisible
//import com.sw.dualscreen.ext.load
//import com.sw.dualscreen.ext.visible
//import com.sw.dualscreen.model.response.MemberInfo
//import com.sw.dualscreen.model.response.TextBean
//import com.sw.dualscreen.utils.SpannedUtils
//
//class ScanQrCodePayPresentation(
// val activity: PayActivity,
// display: Display,
// val type: Int,
// private val onDismissListener: () -> Unit = {}
//) : Presentation(activity, display) {
//
// //type = 0,扫码支付默认显示二维码
// //type = 1,会员结算显示二维码,是会员则显示名字、头像、手机号、可用余额
// //type = 2,支付成功,是会员则显示名字、头像、手机号、可用余额
//
// private lateinit var binding: PresentationScanQrcodePayBinding
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// binding = PresentationScanQrcodePayBinding.inflate(layoutInflater)
// setContentView(binding.root)
// window?.setBackgroundDrawableResource(android.R.color.transparent)
// initView()
// }
//
// var foodName: String? = null
// var payQrCodePic: Any? = null
//
// //总价格
// var totalPrice = 0.0
//
// //余额
// private var balance = 0.0
//
// //实际支付金额
// private var realPayPrice = 0.0
//
// //扣除余额
// private var expensesBalance = 0.0
//
// @SuppressLint("SetTextI18n")
// private fun initView() {
// when (type) {
// 0 -> {
// binding.layoutVip.gone()
// binding.layoutPaySuccess.gone()
// binding.layoutScanQrCode.visible()
//
// binding.tvPayTip.text = "请扫码支付或出示付款码"
// binding.tvFoodName.text = foodName
// binding.tvRealAmount.text = SpannedUtils.getAmountText(
// listOf(
// TextBean(text = "¥", textSize = 32),
// TextBean(text = totalPrice.format2String(2), textSize = 48),
// )
// )
// binding.ivPayQrCode.load(payQrCodePic)
// }
//
// 1 -> {
// val memberInfo = activity.memberInfo
// binding.layoutVip.run {
// if (memberInfo != null) visible() else gone()
// }
// binding.layoutPaySuccess.gone()
// binding.layoutScanQrCode.visible()
//
// balance = (memberInfo?.topUpBalance ?: 0.0) + (memberInfo?.rewardBalance ?: 0.0)
// realPayPrice = if (balance >= totalPrice) 0.0 else totalPrice - balance
// expensesBalance = if (balance >= totalPrice) totalPrice else balance
//
// memberInfo?.let { loadUserInfo(it) }
// binding.tvUserBalance.text = SpannedUtils.getAmountText(
// listOf(
// TextBean(text = "¥", textSize = 20),
// TextBean(text = balance.format2String(2), textSize = 32),
// )
// )
//
// binding.tvFoodName.text = foodName
// binding.tvRealAmount.text = SpannedUtils.getAmountText(
// listOf(
// TextBean(text = "¥", textSize = 32),
// TextBean(text = totalPrice.format2String(2), textSize = 48),
// )
// )
// binding.ivPayQrCode.run {
//// load(payQrCodePic)
// if (balance >= totalPrice) invisible() else visible()
// }
//
// binding.tvPayTip.text = SpannedUtils.getAmountText(getAmountList())
// }
//
// 2 -> {
// val memberInfo = activity.memberInfo
// binding.layoutVip.run {
// if (memberInfo != null) visible() else gone()
// }
// binding.layoutPaySuccess.visible()
// binding.layoutScanQrCode.gone()
//
// balance = if (memberInfo != null) (memberInfo.topUpBalance
// ?: 0.0) + (memberInfo.rewardBalance ?: 0.0) else 0.0
// realPayPrice = if (balance >= totalPrice) 0.0 else totalPrice - balance
// expensesBalance = if (balance >= totalPrice) totalPrice else balance
//
// memberInfo?.let { loadUserInfo(it) }
// val remainBalance = if (balance >= totalPrice) balance - totalPrice else 0.0
// binding.tvUserBalance.text = SpannedUtils.getAmountText(
// listOf(
// TextBean(text = "¥", textSize = 24),
// TextBean(text = remainBalance.format2String(2), textSize = 36),
// )
// )
//
// val showBalance = expensesBalance.format2String(2)
// val showTotal = totalPrice.format2String(2)
// binding.tvPayInfo.text = "余额扣除 $showBalance 元,在线支付 $showTotal 元"
// }
// }
// }
//
// fun loadQrCodeImage(qrCodeUrl: String?) {
// binding.ivPayQrCode.load(qrCodeUrl)
// }
//
// private fun loadUserInfo(item: MemberInfo) {
// binding.ivHeadPic.load(
// if(item.faceUrl.isNullOrBlank()) R.drawable.ic_avatar_default
// else item.faceUrl
// )
// binding.tvUserName.text = item.name
//
// val phone = item.phone ?: ""
// binding.tvUserPhone.text =
// if (phone.length == 11) phone.replace(phone.substring(3, 7), "****")
// else phone
// }
//
// private fun getAmountList(): List<TextBean> {
// val list: MutableList<TextBean> = mutableListOf()
//
// list.add(TextBean(text = "余额扣除 ", textSize = 30, textColor = "#FF5E7585"))
// list.add(
// TextBean(
// text = "-${expensesBalance.format2String(2)}",
// textSize = 30,
// textColor = "#FF0A1428",
// isBold = true
// )
// )
//
// if (balance >= totalPrice) {
// //余额大于等于总价格,使用余额支付
// list.add(TextBean(text = " 元,扣除后可用余额 ", textSize = 30, textColor = "#FF5E7585"))
// val remainingBalance = balance - totalPrice
// list.add(
// TextBean(
// text = remainingBalance.format2String(2),
// textSize = 30,
// textColor = "#FF0A1428",
// isBold = true
// )
// )
// } else {
// //余额小于总价格,使用余额+扫码支付
// //实际支付金额
// list.add(TextBean(text = " 元,还需支付 ", textSize = 30, textColor = "#FF5E7585"))
// list.add(
// TextBean(
// text = realPayPrice.format2String(2),
// textSize = 30,
// textColor = "#FF0A1428",
// isBold = true
// )
// )
// }
// list.add(TextBean(text = " 元", textSize = 30, textColor = "#FF5E7585"))
//
// return list
// }
//
// override fun onDisplayRemoved() {
// super.onDisplayRemoved()
// onDismissListener()
// }
//}
@@ -0,0 +1,12 @@
package com.sw.dualscreen.presentation.pay
import android.view.TextureView
import androidx.camera.lifecycle.ProcessCameraProvider
import java.util.concurrent.ExecutorService
class TransmitScreen {
}
@@ -0,0 +1,19 @@
package com.sw.dualscreen.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.sw.dualscreen.activity.InitActivity
import timber.log.Timber
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
Timber.d("设备启动完成,开始执行自启动逻辑")
val intent = Intent(context, InitActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
}
}
@@ -2,6 +2,8 @@ package com.sw.dualscreen.repository
import com.google.gson.JsonParseException import com.google.gson.JsonParseException
import com.sw.dualscreen.model.response.ApiResponse import com.sw.dualscreen.model.response.ApiResponse
import com.sw.dualscreen.model.response.RespCodeMsg
import com.sw.dualscreen.utils.GsonUtils
import retrofit2.HttpException import retrofit2.HttpException
import timber.log.Timber import timber.log.Timber
import java.io.IOException import java.io.IOException
@@ -18,31 +20,37 @@ abstract class BaseRepository {
when (e) { when (e) {
is HttpException -> { is HttpException -> {
ApiResponse(code = e.code(), message = e.message()) val respData = e.response()?.errorBody()?.string()
val respCodeMsg = GsonUtils.fromJson(respData, RespCodeMsg::class.java)
if (respCodeMsg?.msg.isNullOrBlank()) {
ApiResponse(code = "${e.code()}", msg = e.message())
} else {
ApiResponse(code = respCodeMsg.code ?:"-10", msg = respCodeMsg.msg)
}
} }
is SocketTimeoutException -> { is SocketTimeoutException -> {
ApiResponse(code = -2, message = "请求超时: ${e.message}") ApiResponse(code = "-2", msg = "请求超时: ${e.message}")
} }
is ConnectException -> { is ConnectException -> {
ApiResponse(code = -3, message = "连接失败: ${e.message}") ApiResponse(code = "-3", msg = "连接失败: ${e.message}")
} }
is SSLHandshakeException -> { is SSLHandshakeException -> {
ApiResponse(code = -4, message = "SSL握手失败: ${e.message}") ApiResponse(code = "-4", msg = "SSL握手失败: ${e.message}")
} }
is JsonParseException -> { is JsonParseException -> {
ApiResponse(code = -5, message = "JSON解析错误: ${e.message}") ApiResponse(code = "-5", msg = "JSON解析错误: ${e.message}")
} }
is IOException -> { is IOException -> {
ApiResponse(code = -6, message = "网络IO错误: ${e.message}") ApiResponse(code = "-6", msg = "网络IO错误: ${e.message}")
} }
else -> { else -> {
ApiResponse(code = -1, message = "未知错误: ${e.message ?: "无错误信息"}") ApiResponse(code = "-1", msg = "未知错误: ${e.message ?: "无错误信息"}")
} }
} }
} }
@@ -3,12 +3,24 @@ package com.sw.dualscreen.repository
import com.sw.dualscreen.GlobalData import com.sw.dualscreen.GlobalData
import com.sw.dualscreen.model.request.UserNutritionParam import com.sw.dualscreen.model.request.UserNutritionParam
import com.sw.dualscreen.model.response.ApiResponse import com.sw.dualscreen.model.response.ApiResponse
import com.sw.dualscreen.model.response.DinnerTypeInfo import com.sw.dualscreen.model.response.DeviceConfig
import com.sw.dualscreen.model.response.EquipmentInfo import com.sw.dualscreen.model.response.DinnerType
import com.sw.dualscreen.model.response.FaceData
import com.sw.dualscreen.model.response.FoodInfo import com.sw.dualscreen.model.response.FoodInfo
import com.sw.dualscreen.model.response.UserFaceInfo import com.sw.dualscreen.model.response.FoodSearchReq
import com.sw.dualscreen.model.response.UserNutritionData import com.sw.dualscreen.model.response.FoodOrder
import com.sw.dualscreen.model.response.FoodVector
import com.sw.dualscreen.model.response.MemberInfo
import com.sw.dualscreen.model.response.UserFaceModel
import com.sw.dualscreen.model.response.UserNutrition
import com.sw.dualscreen.network.api.ApiService import com.sw.dualscreen.network.api.ApiService
import com.sw.dualscreen.objbox.CollectedFoodInfo
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import kotlin.Int
/** /**
* 远程数据处理 * 远程数据处理
@@ -19,43 +31,99 @@ class RemoteRepository constructor(
/** /**
* 生成token * 生成token
*/ */
suspend fun getDeviceToken(qrcodeId: String): ApiResponse<String> { // suspend fun getDeviceToken(qrcodeId: String): ApiResponse<String> {
return safeApiCall { // return safeApiCall {
apiService.getDeviceToken( // apiService.getDeviceToken(
qrcodeId // qrcodeId
) // )
} // }
} // }
/** /**
* 获取设备信息 * 获取设备信息
*/ */
suspend fun getDeviceInfo(equipmentCode: String, token: String): ApiResponse<EquipmentInfo> { // suspend fun getDeviceInfo(equipmentCode: String, token: String): ApiResponse<EquipmentInfo> {
return safeApiCall { // return safeApiCall {
apiService.getDeviceInfo( // apiService.getDeviceInfo(
equipmentCode, // equipmentCode,
token = token // token = token
) // )
} // }
} // }
/** /**
* 获取业务服务器token * 获取业务服务器token
*/ */
suspend fun getEquipmentToken(qrcodeId: String): ApiResponse<String> { // suspend fun getEquipmentToken(qrcodeId: String): ApiResponse<String> {
// return safeApiCall {
// apiService.getEquipmentToken(qrcodeId = qrcodeId)
// }
// }
/**
* 获取人脸数据
*/
suspend fun getUserFaceCache(
pageNum: Int,
pageSize: Int = 100,
): ApiResponse<List<UserFaceModel>?> {
return safeApiCall { return safeApiCall {
apiService.getEquipmentToken(qrcodeId = qrcodeId) apiService.getUserFaceCache(
param = mapOf(
"pageNum" to pageNum,
"pageSize" to pageSize
)
)
} }
} }
/** /**
* 获取人脸数据 * 获取人脸数据
*/ */
suspend fun getUserFaceCache( suspend fun getFaceIncrementList(
pageIndex: Int pageNum: Long,
): ApiResponse<UserFaceInfo> { pageSize: Long = 100L,
timestamp: Long
): ApiResponse<List<UserFaceModel>?> {
return safeApiCall { return safeApiCall {
apiService.getUserFaceCache(pageIndex = pageIndex) apiService.getFaceIncrementList(
param = mapOf(
"pageNum" to pageNum,
"pageSize" to pageSize,
"timestamp" to timestamp
)
)
}
}
suspend fun getUserFaceCache2(
pageNum: Int,
pageSize: Int = 160,
): ApiResponse<FaceData> {
return safeApiCall {
apiService.getUserFaceCache2(
pageNum = pageNum,
pageSize = pageSize
)
}
}
/**
* 获取人脸数据
*/
suspend fun getCollectedFoodList(
pageNum: Int,
pageSize: Int = 100,
foodName: String,
): ApiResponse<List<CollectedFoodInfo>> {
return safeApiCall {
apiService.getCollectedFoodList(
param = mapOf(
"pageNum" to "$pageNum",
"pageSize" to "$pageSize",
"foodName" to foodName,
)
)
} }
} }
@@ -65,33 +133,87 @@ class RemoteRepository constructor(
* @param type 0全部 1餐次 * @param type 0全部 1餐次
*/ */
suspend fun getRestInfoFoodsByType( suspend fun getRestInfoFoodsByType(
restId: String = GlobalData.restId,
type: Int = 0,
foodName: String, foodName: String,
pageNum: Int = 1,
pageSize: Int = 50
): ApiResponse<List<FoodInfo>> { ): ApiResponse<List<FoodInfo>> {
return safeApiCall { return safeApiCall {
apiService.getRestInfoFoodsByType(restId = restId, type = type, foodName = foodName) apiService.getRestInfoFoodsByType(
param = hashMapOf(
"name" to foodName,
"pageNum" to "$pageNum",
"pageSize" to "$pageSize",
//"订单来源权举:1-营养秤,2-档口
"deviceType" to "2"
)
)
} }
} }
// /**
// * 通过用户信息获取就餐数据
// */
// suspend fun getUserNutritionData(
// restId: String = GlobalData.restId,
// userId: String,
// foodId: String,
// ): ApiResponse<UserNutritionData> {
// return safeApiCall {
// apiService.getUserNutritionData(restId = restId, userId = userId, foodId = foodId)
// }
// }
/** /**
* 通过用户信息获取就餐数据 * 通过用户信息获取就餐数据
*/ */
suspend fun getUserNutritionData( suspend fun getUserNutritionData(userId: String): ApiResponse<UserNutrition> {
restId: String = GlobalData.restId,
userId: String,
foodId: String,
): ApiResponse<UserNutritionData> {
return safeApiCall { return safeApiCall {
apiService.getUserNutritionData(restId = restId, userId = userId, foodId = foodId) apiService.getUserNutritionData(userId = userId)
}
}
/**
* 获取支付二维码
*/
suspend fun getQrCodeImg(
orderNo: String,
memberId: String? = null,
totalFee: String? = null
): ApiResponse<String?> {
return safeApiCall {
apiService.getQrCodeImg(
orderNo = orderNo,
memberId = memberId,
totalFee = totalFee
)
}
}
/**
* 二维码支付
*/
suspend fun qrCodePay(
authCode: String,
orderNo: String,
memberId: String?
): ApiResponse<String?> {
return safeApiCall {
apiService.qrCodePay(
param = hashMapOf(
"authCode" to authCode,
"outTradeNo" to orderNo,
"memberId" to memberId,
"orderType" to "0"
)
)
} }
} }
suspend fun getDinnerType( suspend fun getDinnerType(
restId: String = GlobalData.restId, // restId: String = GlobalData.restId,
): ApiResponse<DinnerTypeInfo> { ): ApiResponse<DinnerType> {
return safeApiCall { return safeApiCall {
apiService.getDinnerType(restId = restId) apiService.getDinnerType()
} }
} }
@@ -103,4 +225,131 @@ class RemoteRepository constructor(
): ApiResponse<String> { ): ApiResponse<String> {
return safeApiCall { apiService.postUserNutritionData(param = param) } return safeApiCall { apiService.postUserNutritionData(param = param) }
} }
/**
* 获取菜品信息
* @param restId 从device服务获取的canteenId字段
* @param foodName 菜品名称,多个使用逗号拼接
*/
suspend fun getFoodInfo(foodName: String): ApiResponse<List<FoodInfo>> {
return safeApiCall {
// val map = mutableMapOf<String, List<String>>()
// map["nameList"] = foodName.split(",")
apiService.getFoodInfo(req = FoodSearchReq(nameList = foodName.split(",")))
}
}
/**
* 创建订单
*/
suspend fun createOrder(order: FoodOrder): ApiResponse<Any?> {
return safeApiCall {
apiService.createOrder(order = order)
}
}
/**
* 现金支付
*/
suspend fun cashPay(param: HashMap<String, String>): ApiResponse<Boolean?> {
return safeApiCall {
apiService.cashPay(param = param)
}
}
/**
* 查询订单状态
* @param orderNo 订单号
*/
suspend fun queryOrderState(orderNo: String): ApiResponse<Any?> {
return safeApiCall {
apiService.queryOrderState(orderNo = orderNo)
}
}
/**
* 会员支付
*/
suspend fun memberPay(param: HashMap<String, String?>): ApiResponse<Any?> {
return safeApiCall {
apiService.memberPay(param = param)
}
}
/**
* 绑定订单
*/
suspend fun bindOrder(userId: String, orderId: String, mode: Int): ApiResponse<Any?> {
return safeApiCall {
apiService.bindOrder(userId = userId, orderId = orderId, mode = mode)
}
}
/**
* 根据id查询会员信息
*/
suspend fun getMemberInfoById(memberId: String): ApiResponse<MemberInfo?> {
return safeApiCall {
apiService.getMemberInfoById(memberId = memberId)
}
}
/**
* 根据id查询会员信息
*/
suspend fun getMemberInfoByPhone(phone: String, key: String): ApiResponse<MemberInfo?> {
return safeApiCall {
apiService.getMemberInfoByPhone(
param = hashMapOf(
"phone" to phone,
"password" to key
)
)
}
}
/**
* 上传采集菜品信息
*/
suspend fun uploadCollectFoodPics(
fileList: List<File>,
params: HashMap<String, RequestBody>
): ApiResponse<List<String>?> {
// 准备文件参数
val fileParts = mutableListOf<MultipartBody.Part>()
fileList.forEachIndexed { index, file ->
val requestFile = file
.asRequestBody("multipart/form-data".toMediaTypeOrNull())
val filePart = MultipartBody.Part.createFormData(
"foodPics",
file.name,
requestFile
)
fileParts.add(filePart)
}
return safeApiCall {
apiService.uploadCollectFoodPics(params = params, foodPics = fileParts)
}
}
suspend fun getDeviceConfig(): ApiResponse<DeviceConfig?> {
return safeApiCall { apiService.getDeviceConfig() }
}
suspend fun getCollectedFoodVector(param: MutableMap<String, String>): ApiResponse<List<FoodVector>?> {
return safeApiCall {
apiService.getCollectedFoodVector(param = param)
}
}
suspend fun deleteCollectFood(foodId: String?, version: String?): ApiResponse<Any?> {
return safeApiCall {
apiService.deleteCollectFood(
param = mutableMapOf(
"foodId" to foodId,
"version" to version
)
)
}
}
} }
@@ -4,8 +4,10 @@ import com.sw.plate.utils.ToastUtils
import com.wabon.wbintelligenthardwaresdk.api.SensorScale import com.wabon.wbintelligenthardwaresdk.api.SensorScale
import com.wabon.wbintelligenthardwaresdk.api.SensorScale.OnScaleResult import com.wabon.wbintelligenthardwaresdk.api.SensorScale.OnScaleResult
import timber.log.Timber import timber.log.Timber
import kotlin.math.roundToInt
typealias Callback = (Double) -> Unit typealias Callback = (Double) -> Unit
typealias WeightCallback = (Double) -> Unit
private const val TAG = "SensorScaleUtils" private const val TAG = "SensorScaleUtils"
@@ -19,7 +21,7 @@ object SensorScaleUtils {
private var mSensorScale: SensorScale? = null private var mSensorScale: SensorScale? = null
private var isOpened: Boolean = false private var isOpened: Boolean = false
private var isRead: Boolean = false private var isRead: Boolean = false
private var isZero = false var isZero = false
private var callback: Callback? = {} private var callback: Callback? = {}
private var lastWeight: Double? = null private var lastWeight: Double? = null
@@ -41,6 +43,10 @@ object SensorScaleUtils {
lastWeight = value lastWeight = value
callback?.invoke(value) callback?.invoke(value)
} }
weightCallbackList.forEach {
it.invoke(value)
}
} }
/** /**
@@ -60,7 +66,7 @@ object SensorScaleUtils {
* 开启称重 * 开启称重
* @param autoScale 是否开启自动读取 * @param autoScale 是否开启自动读取
*/ */
fun startScale(autoScale: Boolean = true, callback: Callback?) { fun startScale(autoScale: Boolean = true, callback: Callback? = null) {
Timber.d("startScale isOpened = $isOpened") Timber.d("startScale isOpened = $isOpened")
if (isOpened) { if (isOpened) {
startContinuousRead(callback = callback) startContinuousRead(callback = callback)
@@ -74,12 +80,16 @@ object SensorScaleUtils {
if (open) { if (open) {
// zero() // zero()
if (autoScale) { if (autoScale) {
Thread({ Thread {
Thread.sleep(1000) Thread.sleep(1000)
// 打开后需要等待后才能调用,否则会 1001 SDK未初始化 // 打开后需要等待后才能调用,否则会 1001 SDK未初始化
mSensorScale?.startContinuousRead() mSensorScale?.startContinuousRead()
// Thread.sleep(1000)
}).start() // TODO: 暂时不标定---------
//zero()
}.start()
} }
} }
} }
@@ -110,15 +120,22 @@ object SensorScaleUtils {
mSensorScale?.readWeight() mSensorScale?.readWeight()
} }
private var weightCallbackList: MutableList<WeightCallback> = mutableListOf()
fun addWeightListener(weightCallback: WeightCallback) {
if (weightCallbackList.contains(weightCallback).not()) {
weightCallbackList.add(weightCallback)
}
}
/** /**
* 零位标定 * 零位标定
*/ */
fun zero() { fun zero() {
Timber.d("zero isOpened = $isOpened") Timber.d("zero isOpened = $isOpened, mSensorScale = $mSensorScale")
if (!isOpened) return if (!isOpened) return
// isZero = true
mSensorScale?.zero { mSensorScale?.zero {
Timber.d("零位标定操作成功") isZero = true
Timber.d("zero 零位标定操作成功")
ToastUtils.showToast("零位标定操作成功") ToastUtils.showToast("零位标定操作成功")
} }
} }
@@ -0,0 +1,300 @@
package com.sw.dualscreen.socket;
import android.annotation.SuppressLint;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 局域网多客户端通信管理器:支持并发、心跳、认证、广播、点对点发送
* 可用于 Android 和 JVM 程序。
*/
public class LanCommunicationManager {
// ============ 监听配置 ============
private final int port;
private final long HEARTBEAT_TIMEOUT_MS;
private final int MAX_CLIENT_THREADS;
// ============ 状态 ============
private volatile boolean running = false;
private ServerSocket serverSocket;
// ============ 线程池 ============
private final ExecutorService acceptExecutor = Executors.newSingleThreadExecutor();
private final ExecutorService clientExecutor;
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
// ============ 客户端会话 ============
private final ConcurrentHashMap<String, ClientSession> clients = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Socket, ClientSession> unAuthSessions = new ConcurrentHashMap<>();
// ============ 回调接口 ============
public interface Listener {
// 新客户端完成 AUTH / 认证
void onClientConnected(String clientId);
// 客户端断开
void onClientDisconnected(String clientId);
// 收到业务消息(type != heartbeat/auth)
void onMessageReceived(String clientId, JSONObject message);
}
private Listener listener;
// ============ 构造 ============
public LanCommunicationManager(int port, int maxClientThreads, long heartbeatTimeoutMs) {
this.port = port;
this.MAX_CLIENT_THREADS = maxClientThreads;
this.HEARTBEAT_TIMEOUT_MS = heartbeatTimeoutMs;
this.clientExecutor = Executors.newFixedThreadPool(Math.max(2, maxClientThreads));
}
public void setListener(Listener listener) {
this.listener = listener;
}
// ============ 启动服务端 ============
@SuppressLint("DiscouragedApi")
public void start() throws IOException {
if (running) return;
running = true;
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(2000);
acceptExecutor.execute(this::acceptLoop);
scheduler.scheduleAtFixedRate(this::heartbeatCheck,
HEARTBEAT_TIMEOUT_MS,
HEARTBEAT_TIMEOUT_MS,
TimeUnit.MILLISECONDS);
System.out.println("LanCommunicationManager started on port " + port);
}
private void acceptLoop() {
while (running) {
try {
Socket socket = serverSocket.accept();
socket.setSoTimeout((int) HEARTBEAT_TIMEOUT_MS * 2);
ClientSession session = new ClientSession(socket);
unAuthSessions.put(socket, session);
clientExecutor.execute(() -> clientReadLoop(session));
} catch (SocketTimeoutException ignore) {
} catch (Exception e) {
if (running) e.printStackTrace();
}
}
}
// ============ 处理客户端数据读取 ============
private void clientReadLoop(ClientSession session) {
Socket socket = session.socket;
try (DataInputStream in = new DataInputStream(socket.getInputStream())) {
while (running && !socket.isClosed()) {
int len;
try {
len = in.readInt();
} catch (SocketTimeoutException ste) {
continue;
}
if (len <= 0 || len > 10 * 1024 * 1024) break;
byte[] buf = new byte[len];
in.readFully(buf);
session.updateLastSeen();
JSONObject msg = new JSONObject(new String(buf));
handleMessage(session, msg);
}
} catch (Exception ignored) {
} finally {
closeSession(session);
}
}
private void handleMessage(ClientSession session, JSONObject msg) {
String type = msg.optString("type", "");
switch (type) {
case "auth":
handleAuth(session, msg);
break;
case "heartbeat":
session.updateLastSeen();
break;
default:
if (listener != null && session.clientId != null) {
listener.onMessageReceived(session.clientId, msg);
}
break;
}
}
private void handleAuth(ClientSession session, JSONObject msg) {
String clientId = msg.optString("clientId", null);
if (clientId == null) return;
session.clientId = clientId;
// 移动到已认证 map
unAuthSessions.remove(session.socket);
clients.put(clientId, session);
if (listener != null) listener.onClientConnected(clientId);
sendToSession(session, ack("auth_ok"));
}
// ============ 心跳超时 ============
private void heartbeatCheck() {
long now = System.currentTimeMillis();
for (Map.Entry<String, ClientSession> e : clients.entrySet()) {
ClientSession s = e.getValue();
if (now - s.lastSeen > HEARTBEAT_TIMEOUT_MS) {
closeSession(s);
}
}
for (ClientSession s : unAuthSessions.values()) {
if (now - s.lastSeen > HEARTBEAT_TIMEOUT_MS * 2) {
closeSession(s);
}
}
}
// ============ 发送 ============
public boolean sendToClient(String clientId, JSONObject json) {
ClientSession s = clients.get(clientId);
return s != null && sendToSession(s, json);
}
public void broadcast(JSONObject json) {
for (ClientSession s : clients.values()) {
sendToSession(s, json);
}
}
private boolean sendToSession(ClientSession s, JSONObject json) {
try {
DataOutputStream out = s.out;
synchronized (out) {
byte[] data = json.toString().getBytes();
out.writeInt(data.length);
out.write(data);
out.flush();
}
return true;
} catch (Exception e) {
closeSession(s);
return false;
}
}
// ============ ACK ============
private JSONObject ack(String type) {
JSONObject j = new JSONObject();
try {
j.put("type", "ack");
j.put("ack", type);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return j;
}
// ============ 停止 ============
public void stop() {
running = false;
try {
serverSocket.close();
} catch (Exception ignored) {
}
for (ClientSession s : clients.values()) closeSession(s);
for (ClientSession s : unAuthSessions.values()) closeSession(s);
acceptExecutor.shutdownNow();
clientExecutor.shutdownNow();
scheduler.shutdownNow();
System.out.println("LanCommunicationManager stopped");
}
// ============ 会话类 ============
public static class ClientSession {
public final Socket socket;
public final DataOutputStream out;
public volatile long lastSeen = System.currentTimeMillis();
public volatile String clientId;
public ClientSession(Socket socket) throws IOException {
this.socket = socket;
this.out = new DataOutputStream(socket.getOutputStream());
}
public void updateLastSeen() {
lastSeen = System.currentTimeMillis();
}
}
public void closeSession(ClientSession session) {
if (session == null) return;
try {
Socket socket = session.socket;
// 1. 从已认证表移除
if (session.clientId != null) {
ClientSession removed = clients.remove(session.clientId);
if (removed != null && listener != null) {
listener.onClientDisconnected(session.clientId);
}
}
// 2. 从未认证表移除
unAuthSessions.remove(socket);
// 3. 关闭输出流
try {
session.out.close();
} catch (Exception ignored) {
}
// 4. 关闭 socket
try {
if (!socket.isClosed()) socket.close();
} catch (Exception ignored) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,21 @@
package com.sw.dualscreen.socket;
public class LanServer {
private static volatile LanCommunicationManager instance;
public static LanCommunicationManager getInstance() {
if (instance == null) {
synchronized (LanServer.class) {
if (instance == null) {
instance = new LanCommunicationManager(
5000, // 监听端口
20, // 最大客户端数
10_000 // 心跳超时时间 10 秒
);
}
}
}
return instance;
}
}
@@ -0,0 +1,21 @@
package com.sw.dualscreen.socket
import android.util.Log
import org.json.JSONObject
open class LanServerListenerImpl: LanCommunicationManager.Listener {
companion object {
private const val TAG = "LanServerListenerImpl"
}
override fun onClientConnected(clientId: String?) {
Log.d(TAG, "addSocketListener,onClientConnected: clientId = $clientId")
}
override fun onClientDisconnected(clientId: String?) {
Log.d(TAG, "addSocketListener,onClientDisconnected: clientId = $clientId")
}
override fun onMessageReceived(clientId: String?, message: JSONObject?) {
Log.d(TAG, "addSocketListener,onMessageReceived: clientId = $clientIdmessage = $message")
}
}
@@ -0,0 +1,330 @@
package com.sw.dualscreen.socket;
import android.util.Log;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* TcpClient - Android ready
* <p>
* Features:
* - length-prefix protocol (int length + bytes)
* - separate read thread and write queue & writer thread
* - auto-reconnect with exponential backoff
* - heartbeat scheduler
* - send queue with optional callback for send result
* - auto send "auth" JSON after connection
*/
public class TcpClient {
private static final String TAG = "TcpClient";
// configuration
private final String serverIp;
private final int serverPort;
private final String clientId; // will be sent in auth message
private final int connectTimeoutMs;
private final long heartbeatIntervalMs;
private final long heartbeatTimeoutMs;
// socket + streams
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
// threads & executors
private final ExecutorService writerExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, "TcpClient-Writer"));
private final ExecutorService readerExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, "TcpClient-Reader"));
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "TcpClient-Scheduler"));
private final ExecutorService connectExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, "TcpClient-Connect"));
// send queue
private final BlockingQueue<JSONObject> sendQueue = new LinkedBlockingQueue<>();
// state
private final AtomicBoolean running = new AtomicBoolean(false);
private final AtomicBoolean connected = new AtomicBoolean(false);
private final AtomicBoolean authSent = new AtomicBoolean(false);
// reconnection/backoff
private final long baseReconnectDelayMs = 1000; // 1s
private final long maxReconnectDelayMs = 30_000; // 30s
private final AtomicInteger reconnectAttempt = new AtomicInteger(0);
// heartbeat task future
private ScheduledFuture<?> heartbeatFuture;
// listener
public interface Listener {
void onConnected();
void onDisconnected(Exception e);
void onMessage(JSONObject json);
void onSendSuccess(JSONObject json);
void onSendFailed(JSONObject json, Exception e);
}
private Listener listener;
public void setListener(Listener l) {
this.listener = l;
}
// ctor
public TcpClient(String serverIp, int serverPort, String clientId,
int connectTimeoutMs, long heartbeatIntervalMs, long heartbeatTimeoutMs) {
this.serverIp = serverIp;
this.serverPort = serverPort;
this.clientId = clientId;
this.connectTimeoutMs = connectTimeoutMs;
this.heartbeatIntervalMs = heartbeatIntervalMs;
this.heartbeatTimeoutMs = heartbeatTimeoutMs;
}
// start client (will attempt connect)
public void start() {
if (running.getAndSet(true)) return;
scheduleConnect(0);
// writer thread drains sendQueue
writerExecutor.execute(this::writerLoop);
}
// stop client and cleanup
public void stop() {
running.set(false);
cancelHeartbeat();
closeSocketQuiet();
writerExecutor.shutdownNow();
readerExecutor.shutdownNow();
scheduler.shutdownNow();
connectExecutor.shutdownNow();
sendQueue.clear();
}
// send JSON (queued). Non-blocking.
public void send(JSONObject json) {
if (!running.get()) return;
sendQueue.offer(json);
}
// AUTH shortcut (immediately send auth JSON)
private void sendAuth() {
try {
JSONObject auth = new JSONObject();
auth.put("type", "auth");
auth.put("clientId", clientId);
sendQueue.offer(auth);
authSent.set(true);
} catch (Exception ignored) {
}
}
// writer thread loop (serializes sends)
private void writerLoop() {
while (running.get()) {
try {
JSONObject json = sendQueue.take(); // blocks
if (connected.get() && out != null) {
try {
byte[] data = json.toString().getBytes();
synchronized (out) {
out.writeInt(data.length);
out.write(data);
out.flush();
}
if (listener != null) listener.onSendSuccess(json);
} catch (Exception e) {
if (listener != null) listener.onSendFailed(json, e);
// on write failure, attempt reconnect
safeCloseAndScheduleReconnect(e);
}
} else {
// not connected: requeue it and wait for connection
sendQueue.offer(json);
Thread.sleep(500); // avoid busy loop
}
} catch (InterruptedException ignored) {
break;
}
}
}
// reader loop (runs in readerExecutor)
private void startReaderLoop() {
readerExecutor.execute(() -> {
try {
while (running.get() && connected.get() && in != null) {
int length;
try {
length = in.readInt(); // will throw SocketTimeoutException if set
} catch (SocketTimeoutException ste) {
// used to detect socket liveness; continue loop
continue;
}
if (length <= 0 || length > 10 * 1024 * 1024) {
// invalid length, break
throw new RuntimeException("Invalid message length: " + length);
}
byte[] buf = new byte[length];
in.readFully(buf);
String s = new String(buf);
try {
JSONObject json = new JSONObject(s);
// update last seen time via heartbeat ack if needed
if ("heartbeat".equals(json.optString("type"))) {
// optionally respond or update time
} else if ("auth_ok".equals(json.optString("type")) || "ack".equals(json.optString("type"))) {
// ignore or process ack
} else {
if (listener != null) listener.onMessage(json);
}
} catch (Exception je) {
Log.w(TAG, "Invalid JSON from server: " + s, je);
}
}
} catch (Exception e) {
if (running.get()) {
safeCloseAndScheduleReconnect(e);
}
}
});
}
// schedule connect attempt with delay (ms)
private void scheduleConnect(long delayMs) {
connectExecutor.execute(() -> {
try {
if (delayMs > 0) Thread.sleep(delayMs);
} catch (InterruptedException ignored) {
}
if (!running.get()) return;
tryConnect();
});
}
// connect logic
private void tryConnect() {
if (!running.get()) return;
closeSocketQuiet(); // ensure closed
try {
Socket s = new Socket();
s.connect(new InetSocketAddress(serverIp, serverPort), connectTimeoutMs);
s.setSoTimeout((int) Math.max(heartbeatTimeoutMs, 5_000));
socket = s;
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
connected.set(true);
reconnectAttempt.set(0);
authSent.set(false);
// start reader
startReaderLoop();
// send auth immediately
sendAuth();
// start heartbeat
startHeartbeat();
if (listener != null) listener.onConnected();
Log.i(TAG, "Connected to " + serverIp + ":" + serverPort);
} catch (Exception e) {
Log.w(TAG, "Connect failed: " + e.getMessage());
scheduleReconnectWithBackoff();
}
}
// start heartbeat scheduler
private void startHeartbeat() {
cancelHeartbeat();
heartbeatFuture = scheduler.scheduleAtFixedRate(() -> {
if (!running.get() || !connected.get()) return;
try {
JSONObject hb = new JSONObject();
hb.put("type", "heartbeat");
hb.put("time", System.currentTimeMillis());
sendQueue.offer(hb);
} catch (Exception ignored) {
}
}, 0, heartbeatIntervalMs, TimeUnit.MILLISECONDS);
}
private void cancelHeartbeat() {
if (heartbeatFuture != null && !heartbeatFuture.isCancelled()) {
heartbeatFuture.cancel(true);
heartbeatFuture = null;
}
}
// close socket quietly and notify listener
private void safeCloseAndScheduleReconnect(Exception cause) {
closeSocketQuiet();
if (listener != null) listener.onDisconnected(cause);
scheduleReconnectWithBackoff();
}
private void scheduleReconnectWithBackoff() {
int attempt = reconnectAttempt.incrementAndGet();
long delay = Math.min(maxReconnectDelayMsFromAttempt(attempt), maxReconnectDelayMs);
Log.i(TAG, "Scheduling reconnect attempt " + attempt + " after " + delay + "ms");
scheduleConnect(delay);
}
// compute exponential backoff
private long maxReconnectDelayMsFromAttempt(int attempt) {
long d = baseReconnectDelayMs * (1L << Math.min(attempt, 30));
if (d < 0) d = maxReconnectDelayMs;
return Math.min(d, maxReconnectDelayMs);
}
// close socket and streams
private void closeSocketQuiet() {
connected.set(false);
cancelHeartbeat();
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {
}
try {
if (in != null) {
in.close();
}
} catch (Exception ignored) {
}
try {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (Exception ignored) {
}
out = null;
in = null;
socket = null;
}
// helper: when manually call reconnect (immediately)
public void reconnectNow() {
scheduleConnect(0);
}
// helper to set immediate send of a JSON and wait (blocking) until it is queued (not until delivered)
public boolean sendBlocking(JSONObject json, long timeoutMs) throws InterruptedException {
return sendQueue.offer(json, timeoutMs, TimeUnit.MILLISECONDS);
}
}
@@ -0,0 +1,32 @@
package com.sw.dualscreen.socket
import android.util.Log
import org.json.JSONObject
import java.lang.Exception
open class TcpClientListenerImpl : TcpClient.Listener {
companion object {
private const val TAG = "TcpClientListenerImpl"
}
override fun onConnected() {
Log.d(TAG, "addSocketListener,onConnected: ")
}
override fun onDisconnected(e: Exception?) {
Log.d(TAG, "addSocketListener,onDisconnected: ${e?.toString()}")
}
override fun onMessage(json: JSONObject?) {
Log.d(TAG, "addSocketListener,onMessage: $json")
}
override fun onSendSuccess(json: JSONObject?) {
Log.d(TAG, "addSocketListener,onSendSuccess: $json")
}
override fun onSendFailed(json: JSONObject?, e: Exception?) {
Log.d(TAG, "addSocketListener,onSendFailed: $json,e:${e?.toString()}")
}
}
@@ -0,0 +1,47 @@
package com.sw.dualscreen.socket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* Simple UDP discovery client:
* Sends "DISCOVER_SERVER" broadcast and waits for first reply "SERVER_FOUND:serverName:ip"
*/
public class UdpDiscoveryClient {
public interface Listener {
void onFound(String ip, String serverName);
void onError(Exception e);
}
public void discover(int discoveryPort, int timeoutMs, Listener listener) {
new Thread(() -> {
try (DatagramSocket socket = new DatagramSocket()) {
socket.setBroadcast(true);
byte[] data = "DISCOVER_SERVER".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("255.255.255.255"), discoveryPort);
socket.send(packet);
socket.setSoTimeout(timeoutMs);
byte[] buf = new byte[512];
DatagramPacket resp = new DatagramPacket(buf, buf.length);
socket.receive(resp);
String msg = new String(resp.getData(), 0, resp.getLength());
if (msg.startsWith("SERVER_FOUND")) {
// format: SERVER_FOUND:serverName:ip
String[] parts = msg.split(":", 3);
if (parts.length >= 3) {
listener.onFound(parts[2], parts[1]);
return;
}
}
listener.onError(new Exception("Invalid response"));
} catch (Exception e) {
listener.onError(e);
}
}).start();
}
}
@@ -0,0 +1,113 @@
package com.sw.dualscreen.socket;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class test {
LanCommunicationManager manager = new LanCommunicationManager(
9999, // 端口
20, // 最大客户端线程
30_000 // 心跳超时 30 秒
);
public void test() {
manager.setListener(new LanCommunicationManager.Listener() {
@Override
public void onClientConnected(String clientId) {
System.out.println("新的客户端上线:" + clientId);
}
@Override
public void onClientDisconnected(String clientId) {
System.out.println("客户端离线:" + clientId);
}
@Override
public void onMessageReceived(String clientId, JSONObject msg) {
System.out.println("收到 " + clientId + " 的消息:" + msg);
}
});
// 启动
try {
manager.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
// 给某个客户端发送
JSONObject j = new JSONObject();
try {
j.put("type", "cmd");
j.put("content", "hello");
} catch (JSONException e) {
throw new RuntimeException(e);
}
manager.sendToClient("device123", j);
// 广播
manager.broadcast(j);
}
public void clientTets() {
// 1) discover server (optional)
UdpDiscoveryClient disc = new UdpDiscoveryClient();
disc.discover(9876, 3000, new UdpDiscoveryClient.Listener() {
@Override
public void onFound(String ip, String serverName) {
startClient(ip);
}
@Override
public void onError(Exception e) { /* fallback to manual IP */ }
});
}
// 2) start client
private TcpClient client;
private void startClient(String serverIp) {
client = new TcpClient(
serverIp,
9999,
"device123", // clientId
5000, // connectTimeoutMs
10_000, // heartbeatIntervalMs
30_000 // heartbeatTimeoutMs
);
client.setListener(new TcpClient.Listener() {
@Override
public void onConnected() {
Log.i("APP", "connected");
}
@Override
public void onDisconnected(Exception e) {
Log.i("APP", "disconnected", e);
}
@Override
public void onMessage(JSONObject json) {
Log.i("APP", "msg:" + json);
}
@Override
public void onSendSuccess(JSONObject json) {
}
@Override
public void onSendFailed(JSONObject json, Exception e) {
}
});
client.start();
}
}
@@ -0,0 +1,57 @@
package com.sw.dualscreen.utils
import android.app.Activity
import android.os.Process
import java.util.Stack
object ActivityManager {
private val activityStack = Stack<Activity>()
// 添加Activity到栈
fun addActivity(activity: Activity) {
activityStack.add(activity)
}
// 移除指定Activity
fun removeActivity(activity: Activity) {
activityStack.remove(activity)
}
// 获取当前Activity
fun currentActivity(): Activity? {
return if (activityStack.isEmpty()) null else activityStack.lastElement()
}
// 结束指定Activity
fun finishActivity(activity: Activity) {
if (!activity.isFinishing) {
activity.finish()
}
}
// 结束所有Activity
fun finishAllActivity() {
activityStack.forEach {
if (!it.isFinishing) {
it.finish()
}
}
activityStack.clear()
}
// 退出应用程序
fun exitApp() {
finishAllActivity()
Process.killProcess(Process.myPid())
}
fun getActivityStack(): Stack<Activity>{
return activityStack
}
fun isEmpty() : Boolean {
return activityStack.isEmpty()
}
}
@@ -0,0 +1,76 @@
package com.sw.dualscreen.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,42 @@
package com.sw.dualscreen.utils
import android.graphics.Bitmap
object BitmapCropper {
/**
* 裁剪Bitmap中心区域为指定尺寸
* @param original 原始Bitmap
* @param targetWidth 目标宽度
* @param targetHeight 目标高度
* @return 裁剪后的Bitmap
*/
fun cropCenter(original: Bitmap, targetWidth: Int, targetHeight: Int, offsetX:Int = 0, offsetY:Int = 0): Bitmap {
val originalWidth = original.width
val originalHeight = original.height
// 计算中心点坐标
var startX = (originalWidth - targetWidth) / 2 + offsetX
var startY = (originalHeight - targetHeight) / 2 + offsetY
// 边界检查
startX = startX.coerceAtLeast(0)
startY = startY.coerceAtLeast(0)
val actualWidth = minOf(targetWidth, originalWidth - startX)
val actualHeight = minOf(targetHeight, originalHeight - startY)
return Bitmap.createBitmap(original, startX, startY, actualWidth, actualHeight).also {
// it.setConfig(Bitmap.Config.RGB_565)
// it.density = DisplayMetrics.DENSITY_LOW
}
}
}
// 使用示例
//fun main() {
// // 假设这是从资源加载的Bitmap
// val originalBitmap = Bitmap.createBitmap(1000, 1000, Bitmap.Config.ARGB_8888)
// // 裁剪中心500x500区域
// val croppedBitmap = BitmapCropper.cropCenter(originalBitmap, 500, 500)
// println("裁剪后尺寸:${croppedBitmap.width}x${croppedBitmap.height}")
//}
@@ -0,0 +1,57 @@
package com.sw.dualscreen.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,68 @@
package com.sw.dualscreen.utils
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import android.widget.Toast
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import java.io.File
import java.io.FileOutputStream
/**
* 简洁相机工具类
* 调用系统相机拍照并返回照片路径
*/
class CameraHelper(
private val context: Context,
caller: ActivityResultCaller,
private val authority: String,
private val onResult: (uri: Uri, filePath: String?) -> Unit
) {
private lateinit var imageUri: Uri
private val takePictureLauncher: ActivityResultLauncher<Uri>
init {
takePictureLauncher =
caller.registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
if (success) {
val path = getRealPathFromUri(context, imageUri)
onResult(imageUri, path)
} else {
Toast.makeText(context, "拍照取消", Toast.LENGTH_SHORT).show()
}
}
}
/** 打开系统相机 */
fun openCamera() {
// 1. 创建存储图片的文件
val photoFile = File(context.externalCacheDir, "IMG_${System.currentTimeMillis()}.jpg")
photoFile.parentFile?.mkdirs() // 确保目录存在
// 2. 生成 content:// Uri
imageUri = FileProvider.getUriForFile(context, authority, photoFile)
// 3. 启动相机
takePictureLauncher.launch(imageUri)
}
/** 可选:将 content:// 转为实际路径 */
private fun getRealPathFromUri(context: Context, uri: Uri): String? {
var filePath: String? = null
context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
cursor.moveToFirst()
val fileName = cursor.getString(nameIndex)
val file = File(context.cacheDir, fileName)
context.contentResolver.openInputStream(uri)?.use { input ->
FileOutputStream(file).use { output -> input.copyTo(output) }
}
filePath = file.absolutePath
}
return filePath
}
}
@@ -0,0 +1,84 @@
package com.sw.dualscreen.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,32 @@
package com.sw.dualscreen.utils
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Date
object DateTimeUtil {
const val YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"
fun formatDateTime(dateTime: LocalDateTime, pattern: String = YYYY_MM_DD_HH_MM_SS): String {
val formatter = DateTimeFormatter.ofPattern(pattern)
return dateTime.format(formatter)
}
fun convert(dateStr: String, pattern: String = YYYY_MM_DD_HH_MM_SS): Date {
val formatter = DateTimeFormatter.ofPattern(pattern)
val ldt = LocalDateTime.parse(dateStr, formatter)
val zdt = ldt.atZone(ZoneId.systemDefault())
return Date.from(zdt.toInstant())
}
fun main() {
val now = LocalDateTime.now()
println("默认格式: ${formatDateTime(now)}")
println("自定义格式: ${formatDateTime(now, "yyyy年MM月dd日 HH时mm分ss秒")}")
}
}
@@ -1,6 +1,9 @@
package com.sw.dualscreen.utils package com.sw.dualscreen.utils
class Debouncer(private val delayMillis: Long) { /**
* 防抖工具
*/
class Debouncer(private val delayMillis: Long = 2000) {
private var lastActionTime = 0L private var lastActionTime = 0L
/** /**
@@ -0,0 +1,697 @@
package com.sw.dualscreen.utils;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.sw.plate.App;
import com.sw.plate.utils.AppUtil;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class FileUtil {
private static boolean isSaveLog = true;
public static final String FILE_STR_PATH = App.getContext().getExternalCacheDir().getAbsolutePath();
public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值
private static String urlNull = "原文件路径不存在";
private static String isFile = "原文件不是文件";
private static String canRead = "原文件不能读";
private static String copyFalse = "备份失败!";
private static String cFromFile = "创建原文件出错:";
private static String ctoFile = "创建备份文件出错:";
/**
* 写入文件
* FileUtil.byteWriteFile(getExternalFilesDir("123"),"test.jpg",nv21);
*
* @param filePath
* @param fileName
* @param bytes
*/
public static void byteWriteFile(File filePath, String fileName, byte[] bytes) {
BufferedOutputStream bout = null;
try {
File file = new File(filePath, fileName);
if (file.exists() == false) {
if (file.getParentFile().exists() == false) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
bout = new BufferedOutputStream(new FileOutputStream(file, false));
bout.write(bytes);
bout.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bout != null) {
try {
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取文件名
*
* @param path 路径
* @return 文件名
*/
public static String getFileName(String path) {
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
/**
* 根据文件路径获取文件
*
* @param path 路径
* @return
*/
public static File getFileByPath(String path) {
File file = new File(path);
if (file.exists()) {
return new File(path);
} else {
return null;
}
}
/**
* 重命名文件
*
* @param filePath 文件路径
* @param newName 新名称
* @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
*/
public static boolean rename(String filePath, String newName) {
return rename(getFileByPath(filePath), newName);
}
/**
* 重命名文件
*
* @param file 文件
* @param newName 新名称
* @return {@code true}: 重命名成功<br>{@code false}: 重命名失败
*/
public static boolean rename(File file, String newName) {
// 文件为空返回false
if (file == null) return false;
// 文件不存在返回false
if (!file.exists()) return false;
// 新的文件名为空返回false
if (AppUtil.isEmpty(newName)) return false;
// 如果文件名没有改变返回true
if (newName.equals(file.getName())) return true;
File newFile = new File(file.getParent() + File.separator + newName);
// 如果重命名的文件已存在返回false
return !newFile.exists()
&& file.renameTo(newFile);
}
/**
* 判断文件是否存在
*
* @param path 文件的路径,含文件后缀和文件名
* @return 是否存在
*/
public static boolean isFileExists(String path) {
File file = new File(path);
if (file.exists()) {
return true;
} else {
return false;
}
}
/**
* 判断文件是否存在
*
* @return 是否存在
*/
public static boolean isFileExists(File file) {
if (file.exists()) {
return true;
} else {
return false;
}
}
/**
* 删除文件夹及文件夹下所有内容
*
* @param path 文件夹路径
* @return 返回是否删除成功
*/
public static boolean deleteFiles(String path) {
if (getFileByPath(path) != null) {
return deleteFiles(getFileByPath(path));
} else {
return false;
}
}
/**
* 删除文件夹及文件夹下所有内容
*
* @param file 文件
* @return 返回是否删除成功
*/
public static boolean deleteFiles(File file) {
try {
if (file.exists()) { // 判断文件是否存在
if (file.isFile()) { // 判断是否是文件
file.delete(); // delete()方法
} else if (file.isDirectory()) { // 否则如果它是一个目录
File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
deleteFiles(files[i].getPath()); // 把每个文件 用这个方法进行迭代
}
file.delete();//删除目录
}
//file.delete();
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 获取文件的Uri
*
* @param path 文件的路径
* @return 文件的Uri
*/
public static Uri getUriFromFile(String path) {
File file = new File(path);
return Uri.fromFile(file);
}
/**
* 获取文件指定文件的指定单位的大小
*
* @param filePath 文件路径
* @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
* @return double值的大小
*/
public static double getFileOrFilesSize(String filePath, int sizeType) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
} else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
L.i("获取文件大小", "获取失败!");
}
return FormetFileSize(blockSize, sizeType);
}
/**
* 调用此方法自动计算指定文件或指定文件夹的大小
*
* @param filePath 文件路径
* @return 计算好的带B、KB、MB、GB的字符串
*/
public static String getAutoFileOrFilesSize(String filePath) {
File file = new File(filePath);
long blockSize = 0;
try {
if (file.isDirectory()) {
blockSize = getFileSizes(file);
} else {
blockSize = getFileSize(file);
}
} catch (Exception e) {
e.printStackTrace();
L.i("获取文件大小", "获取失败!");
}
return FormetFileSize(blockSize);
}
/**
* 获取指定文件大小
*
* @param file
* @return
* @throws Exception
*/
private static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
// file.createNewFile();
L.i("获取文件大小", "文件不存在!");
}
return size;
}
/**
* 获取目录下指定文件名的文件包括子目录
* <p>大小写忽略</p>
*
* @param dirPath 目录路径
* @param fileName 文件名
* @return 文件链表
*/
public static List<File> searchFileInDir(String dirPath, String fileName) {
return searchFileInDir(getFileByPath(dirPath), fileName);
}
/**
* 获取目录下指定文件名的文件包括子目录
* <p>大小写忽略</p>
*
* @param dir 目录
* @param fileName 文件名
* @return 文件链表
*/
public static List<File> searchFileInDir(File dir, String fileName) {
if (dir == null || !dir.isDirectory()) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.getName().toUpperCase().equals(fileName.toUpperCase())) {
list.add(file);
}
if (file.isDirectory()) {
list.addAll(searchFileInDir(file, fileName));
}
}
}
return list;
}
/**
* 获取指定文件夹
*
* @param f
* @return
* @throws Exception
*/
private static long getFileSizes(File f) throws Exception {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSizes(flist[i]);
} else {
size = size + getFileSize(flist[i]);
}
}
return size;
}
/**
* 转换文件大小
*
* @param fileS
* @return
*/
private static String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
}
return fileSizeString;
}
/**
* 转换文件大小,指定转换的类型
*
* @param fileS
* @param sizeType
* @return
*/
private static double FormetFileSize(long fileS, int sizeType) {
DecimalFormat df = new DecimalFormat("#.00");
double fileSizeLong = 0;
switch (sizeType) {
case SIZETYPE_B:
fileSizeLong = Double.valueOf(df.format((double) fileS));
break;
case SIZETYPE_KB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
break;
case SIZETYPE_MB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
break;
case SIZETYPE_GB:
fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
break;
default:
break;
}
return fileSizeLong;
}
/**
* 复制文件
*
* @param fromFilePath 旧文件地址和名称
* @param toFilePath 新文件地址和名称
* @return 返回备份文件的信息,ok是成功,其它就是错误
*/
public static File copyFile(String fromFilePath, String toFilePath) {
File fromFile = null;
File toFile = null;
try {
fromFile = new File(fromFilePath);
} catch (Exception e) {
L.i(cFromFile + e.getMessage());
return null;
}
try {
toFile = new File(toFilePath);
if (toFile.isDirectory()) {
toFile = new File(toFilePath.endsWith("/") ? toFilePath + fromFile.getName() : toFilePath + "/" + fromFile.getName());
}
} catch (Exception e) {
L.i(ctoFile + e.getMessage());
return null;
}
if (!fromFile.exists()) {
L.i(urlNull);
return null;
}
if (!fromFile.isFile()) {
L.i(isFile);
return null;
}
if (!fromFile.canRead()) {
L.i(canRead);
return null;
}
// 复制到的路径如果不存在就创建
if (!toFile.getParentFile().exists()) {
toFile.getParentFile().mkdirs();
}
if (toFile.exists()) {
toFile.delete();
}
if (!toFile.canWrite()) {
//return notWrite;
}
try {
FileInputStream fosfrom = new FileInputStream(
fromFile);
FileOutputStream fosto = new FileOutputStream(toFile);
byte bt[] = new byte[1024];
int c;
while ((c = fosfrom.read(bt)) > 0) {
fosto.write(bt, 0, c); // 将内容写到新文件当中
}
//关闭数据流
fosfrom.close();
fosto.close();
} catch (Exception e) {
e.printStackTrace();
L.i(copyFalse + e.getMessage());
return null;
}
return toFile;
}
/**
* 创建文件
*
* @param path 文件路径
* @return 创建的文件
*/
public static synchronized File createNewFile(String path) {
File file = new File(path);
String parentPath = path.substring(0, path.lastIndexOf("/") + 1);
File parentFile = new File(parentPath);
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return file;
}
/***
* 根据文件后缀回去MIME类型
****/
private static String getMIMEType(File file) {
String type = "*/*";
String fName = file.getName();
//获取后缀名前的分隔符"."在fName中的位置。
int dotIndex = fName.lastIndexOf(".");
if (dotIndex < 0) {
return type;
}
/* 获取文件的后缀名*/
String end = fName.substring(dotIndex, fName.length()).toLowerCase();
if (end == "") return type;
//在MIME和文件类型的匹配表中找到对应的MIME类型。
for (int i = 0; i < MIME_MapTable.length; i++) { //MIME_MapTable??在这里你一定有疑问,这个MIME_MapTable是什么?
if (end.equals(MIME_MapTable[i][0]))
type = MIME_MapTable[i][1];
}
return type;
}
/**
* 获取全路径中的文件拓展名
*
* @param file 文件
* @return 文件拓展名
*/
public static String getFileExtension(File file) {
if (file == null) return null;
return getFileExtension(file.getPath());
}
/**
* 获取全路径中的文件拓展名
*
* @param filePath 文件路径
* @return 文件拓展名
*/
public static String getFileExtension(String filePath) {
if (AppUtil.isEmpty(filePath)) return filePath;
int lastPoi = filePath.lastIndexOf('.');
int lastSep = filePath.lastIndexOf(File.separator);
if (lastPoi == -1 || lastSep >= lastPoi) return "";
return filePath.substring(lastPoi + 1);
}
/**
* 调用系统应用打开文件
*
* @param context 上下文
* @param file 文件
*/
public static void openFile(Context context, File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//设置intent的Action属性
intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型
String type = getMIMEType(file);
//设置intent的data和Type属性。
intent.setDataAndType(Uri.fromFile(file), type);
//跳转
try {
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
L.i("找不到打开此文件的应用!");
}
}
/**
* 保存文本文件
* FileUtil.saveStrFile("测试", "log.txt", FILE_STR_PATH, true);
*
* @param res 写入内容
* @param fileName 文件名
* @param filePath 路径
* @param append true新增 false替换
* @return
*/
public static boolean saveStrFile(String res, String fileName, String filePath, boolean append) {
boolean flag = true;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
File file = new File(filePath, fileName);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
bufferedReader = new BufferedReader(new StringReader(res));
bufferedWriter = new BufferedWriter(new FileWriter(file, append));
char buf[] = new char[1024]; //字符缓冲区
int len;
while ((len = bufferedReader.read(buf)) != -1) {
bufferedWriter.write(buf, 0, len);
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
flag = false;
return flag;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
public static void saveLog(String... logs) {
if (!isSaveLog) {
return;
}
new Thread() {
@Override
public void run() {
super.run();
StringBuilder sb = new StringBuilder();
for (String log : logs) {
sb.append("===")
.append((AppUtil.formatDateGetCurrentTime()))
.append("===")
.append("\n")
.append(log)
.append("\n");
}
String fileName = "log" + AppUtil.formatDateGetDay(System.currentTimeMillis()) + ".txt";
FileUtil.saveStrFile(sb.toString(), fileName, FILE_STR_PATH, true);
}
}.start();
}
private static final String[][] MIME_MapTable = {
// {后缀名,MIME类型}
{".3gp", "video/3gpp"},
{".apk", "application/vnd.android.package-archive"},
{".asf", "video/x-ms-asf"},
{".avi", "video/x-msvideo"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".class", "application/octet-stream"},
{".conf", "text/plain"},
{".cpp", "text/plain"},
{".doc", "application/msword"},
{".docx",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".xls", "application/vnd.ms-excel"},
{".xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".exe", "application/octet-stream"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".htm", "text/html"},
{".html", "text/html"},
{".jar", "application/java-archive"},
{".java", "text/plain"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/x-javascript"},
{".log", "text/plain"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4a-latm"},
{".m4b", "audio/mp4a-latm"},
{".m4p", "audio/mp4a-latm"},
{".m4u", "video/vnd.mpegurl"},
{".m4v", "video/x-m4v"},
{".mov", "video/quicktime"},
{".mp2", "audio/x-mpeg"},
{".mp3", "audio/x-mpeg"},
{".mp4", "video/mp4"},
{".mpc", "application/vnd.mpohun.certificate"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpg4", "video/mp4"},
{".mpga", "audio/mpeg"},
{".msg", "application/vnd.ms-outlook"},
{".ogg", "audio/ogg"},
{".pdf", "application/pdf"},
{".png", "image/png"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptx",
"application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prop", "text/plain"}, {".rc", "text/plain"},
{".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"},
{".sh", "text/plain"}, {".tar", "application/x-tar"},
{".tgz", "application/x-compressed"}, {".txt", "text/plain"},
{".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"},
{".wmv", "audio/x-ms-wmv"},
{".wps", "application/vnd.ms-works"}, {".xml", "text/plain"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"}, {"", "*/*"}};
}
@@ -1,156 +0,0 @@
package com.sw.dualscreen.utils
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import timber.log.Timber
import java.io.File
object FileUtils {
/**
* 从Uri获取File
* example: file:///data/user/0/com.sw.inbound/cache/IMG_17515262353556856678814444882273.jpg
*/
private fun getFileFromUri(context: Context, uri: Uri): File? {
Timber.d("getFileFromUri uri = ${uri.scheme}")
return when (uri.scheme) {
"file" -> File(uri.path ?: return null)
"content" -> {
try {
val inputStream = context.contentResolver.openInputStream(uri) ?: return null
val cacheDir = context.cacheDir
val file = File.createTempFile(
"upload_${System.currentTimeMillis()}",
".jpg",
cacheDir
)
file.outputStream().use { output ->
inputStream.copyTo(output)
}
file
} catch (e: Exception) {
Timber.e(e)
null
}
}
else -> null
}
}
/**
* 通过uri生成http请求体
*/
fun genRequestPart(context: Context, imageUri: Uri): MultipartBody.Part? {
Timber.d("genRequestPart imageUri = $imageUri")
// 1. 从Uri获取文件
val file = getFileFromUri(context, imageUri)
if (file == null) {
Timber.e("getFileFromUri file is null")
return null
}
// 2. 创建请求体
val requestFile = file
.asRequestBody("application/octet-stream".toMediaTypeOrNull())
val imagePart = MultipartBody.Part.createFormData(
"file",
file.name,
requestFile
)
return imagePart
}
/**
* 通过Uri删除文件
* @param context 上下文
* @param uri 文件Uri
* @return Boolean 是否删除成功
*/
fun deleteFileWithUri(context: Context, uri: Uri): Boolean {
Timber.d("deleteFileWithUri uri = ${uri.scheme}")
return when {
// 1. 处理 content:// 类型的Uri (MediaStore)
uri.scheme.equals("content", ignoreCase = true) -> {
deleteContentUriFile(context, uri)
}
// 2. 处理 file:// 类型的Uri
uri.scheme.equals("file", ignoreCase = true) -> {
deleteFileUriFile(uri)
}
// 3. 其他情况尝试直接解析路径
else -> {
deleteFileFromPath(uri.path ?: return false)
}
}
}
// 删除Content Uri文件
private fun deleteContentUriFile(context: Context, uri: Uri): Boolean {
Timber.d("deleteContentUriFile uri = ${uri.scheme}")
return try {
context.contentResolver.delete(uri, null, null) > 0
} catch (e: SecurityException) {
// Android 10+需要特殊处理
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
deleteMediaStoreFile(context, uri)
} else {
false
}
} catch (e: Exception) {
Timber.e(e)
false
}
}
// Android 10+删除MediaStore文件
@RequiresApi(Build.VERSION_CODES.Q)
private fun deleteMediaStoreFile(context: Context, uri: Uri): Boolean {
Timber.d("deleteMediaStoreFile uri = ${uri.scheme}")
val contentResolver = context.contentResolver
val projection = arrayOf(MediaStore.MediaColumns._ID)
return try {
contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) {
val id =
cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID))
val contentUri = ContentUris.withAppendedId(uri, id)
contentResolver.delete(contentUri, null, null) > 0
} else {
false
}
} ?: false
} catch (e: Exception) {
Timber.e(e)
false
}
}
// 删除File Uri文件
private fun deleteFileUriFile(uri: Uri): Boolean {
Timber.d("deleteFileUriFile uri = $uri")
return try {
File(uri.path ?: return false).delete()
} catch (e: Exception) {
Timber.e(e)
false
}
}
// 直接通过路径删除文件
private fun deleteFileFromPath(path: String): Boolean {
Timber.d("deleteFileFromPath path = $path")
return try {
File(path).delete()
} catch (e: Exception) {
Timber.e(e)
false
}
}
}
@@ -0,0 +1,47 @@
package com.example.utils
import android.util.Base64
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* 工具类:float[] 与 Base64 字符串互转
* 无需外部依赖,适用于 Android 原生项目。
*/
object FloatBase64Utils {
/**
* float数组 → Base64字符串
* @param values FloatArray
* @return Base64字符串(无换行)
*/
fun floatArrayToBase64(values: FloatArray): String {
if (values.isEmpty()) return ""
val buffer = ByteBuffer.allocate(values.size * 4)
buffer.order(ByteOrder.BIG_ENDIAN) // 默认大端序,可改 LITTLE_ENDIAN
values.forEach { buffer.putFloat(it) }
val bytes = buffer.array()
return Base64.encodeToString(bytes, Base64.NO_WRAP)
}
/**
* Base64字符串 → float数组
* @param base64 Base64字符串
* @return FloatArray
*/
fun base64ToFloatArray(base64: String?): FloatArray {
if (base64.isNullOrEmpty()) return FloatArray(0)
val bytes = Base64.decode(base64, Base64.NO_WRAP)
val buffer = ByteBuffer.wrap(bytes)
buffer.order(ByteOrder.BIG_ENDIAN)
val result = FloatArray(bytes.size / 4)
for (i in result.indices) {
result[i] = buffer.getFloat()
}
return result
}
}
@@ -0,0 +1,32 @@
package com.sw.dualscreen.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
// 倒计时Flow扩展函数
fun countDownByFlow(
total: Int,
scope: CoroutineScope,
onTick: (Int) -> Unit,
onStart: (() -> Unit)? = null,
onFinish: (() -> Unit)? = null
): Job {
return flow {
for (i in total downTo 0) {
emit(i)
if (i != 0) delay(1000)
}
}.flowOn(Dispatchers.Main)
.onStart { onStart?.invoke() }
.onCompletion { onFinish?.invoke() }
.onEach { onTick.invoke(it) }
.launchIn(scope)
}
@@ -104,6 +104,21 @@ object GlideUtils {
.into(imageView) .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 * 加载图片并获取Bitmap
* @param context 上下文 * @param context 上下文
@@ -0,0 +1,38 @@
package com.sw.dualscreen.utils
import com.sw.dualscreen.objbox.FoodCollectionBean
import java.util.concurrent.atomic.AtomicInteger
class ImageUploader(
private val totalList: List<FoodCollectionBean>,
private val uploadImage: suspend (List<FoodCollectionBean>)-> List<String>?,
private val onProgress: (Int, List<FoodCollectionBean>, List<String>) -> Unit,
private val onError:(List<FoodCollectionBean>) -> Unit,
private val onComplete:() -> Unit
) {
companion object {
private const val BATCH_SIZE = 3
}
private val uploadedCount = AtomicInteger(0)
suspend fun processUploads() {
val batches = totalList.filter { it.imageVector!=null }.chunked(BATCH_SIZE)
for (batch in batches) {
val idList = uploadImage(batch)
if (idList.isNullOrEmpty()) {
//println("上传失败,终止流程")
onError(batch)
return
}
val fileCount = batch.count { it.imageFile!=null }
uploadedCount.addAndGet(fileCount)
onProgress(uploadedCount.get(), batch, idList)
//println("已上传 ${uploadedCount.get()}/$totalImages")
}
onComplete()
//println("流程完成,总计上传 ${uploadedCount.get()} 张图片")
}
}
@@ -0,0 +1,56 @@
package com.sw.dualscreen.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,64 @@
package com.sw.dualscreen.utils
import kotlinx.coroutines.*
class IntervalExecutor {
/**
* 启动定时任务
* @param delayMillis 延迟时间(毫秒)
* @param action 要执行的方法
* @return Job 可用于取消任务
*/
fun startIntervalTask(delayMillis: Long, action: suspend () -> Unit): Job {
return CoroutineScope(Dispatchers.Default).launch {
while (isActive) {
action()
delay(delayMillis)
}
}
}
/**
* 启动定时任务(带初始延迟)
* @param initialDelay 初始延迟时间(毫秒)
* @param delayMillis 后续执行间隔(毫秒)
* @param action 要执行的方法
* @return Job 可用于取消任务
*/
fun startIntervalTaskWithInitialDelay(
initialDelay: Long,
delayMillis: Long,
action: suspend () -> Unit
): Job {
return CoroutineScope(Dispatchers.Default).launch {
delay(initialDelay)
while (isActive) {
action()
delay(delayMillis)
}
}
}
}
// 使用示例
fun main() = runBlocking {
val executor = IntervalExecutor()
// 示例1:每隔10秒执行一次
val job1 = executor.startIntervalTask(10000) {
println("定时任务执行: ${System.currentTimeMillis()}")
// 这里可以执行你的业务逻辑
}
// 示例2:先延迟5秒,然后每隔3秒执行一次
val job2 = executor.startIntervalTaskWithInitialDelay(5000, 3000) {
println("带初始延迟的定时任务: ${System.currentTimeMillis()}")
}
// 运行30秒后取消任务
delay(30000)
job1.cancel()
job2.cancel()
println("所有定时任务已取消")
}

Some files were not shown because too many files have changed in this diff Show More