Author SHA1 Message Date
mazengfei b4720b103a feat(shelf): 支持格口列表下拉刷新和搜索食材验收状态显示
- 在格口列表布局中集成 SmartRefreshLayout,实现下拉刷新功能
- 新增 accepted_green 颜色资源用于验收状态标识
- FoodItem 数据类新增 materCode 和 todayAccepted 字段,支持显示食材编码及验收状态
- HomeV3Activity 中添加 refreshLayout 初始化和刷新逻辑,支持下拉刷新时不弹 Loading,失败时仅提示
- 空视图点击重试由重新拉取改为调用刷新接口 refreshSlots
- 搜索食材列表项布局改为 MaterialCardView,增加显示食材编码副行和右上角验收绿色圆点
- PendingInboundAdapter 根据选中状态调整名称和编码文字颜色及边框颜色
- 根据今日是否已验收决定是否显示食材右上角绿色圆点
2026-09-17 15:13:07 +08:00
mazengfei 9db8996d44 chore(app): 添加日志定期清理机制,优化日志文件管理
- 应用启动时立即清理过期日志文件和崩溃日志
- 新增每日24小时定时任务,持续清理过期日志
- 在 CrashHandler 初始化时清理旧的崩溃日志,默认保留7天
- FileLogger新增日志文件大小限制,防止异常刷屏占满存储
- 新增 FileLogger 清理过期日志的方法,按文件修改时间删除过旧日志
- 修改全局API地址为UAT环境域名,更新PROD_BASE_URL常量
2026-08-31 15:09:16 +08:00
mazengfeiandClaude Fable 5 5ffdb3ea64 feat(log): 增加日志定期清理机制,防止长期运行日志无限累加
- FileLogger 新增过期清理(保留7天)及单文件100MB写入上限(适配异步写入版)
- CrashHandler 激活崩溃日志清理并补充异常保护
- App 启动清理 + 运行中每24小时定时清理,覆盖设备长期不断电场景

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 15:08:22 +08:00
mazengfei 8e8ab6936c fix(net): 优化 HttpException 错误消息解析逻辑
- 添加从 HttpException 错误响应体解析后台业务 msg 的扩展方法
- 优先使用后台返回的业务 msg,失败时回退到 HTTP 状态短语
- 处理解析过程中可能出现的异常,确保安全降级
- 添加相关注释说明业务错误消息提取的设计意图
2026-07-28 19:45:00 +08:00
mazengfei 23d211bfdb fix(shelf): 实现负漂移抑制以提高重量显示准确性
- 在ShelfV3Activity中针对-5克以内的负读数做归零处理,避免误导显示
- 修改获取重量逻辑,保证显示重量与真实重量区分
- 在ShelfV3Adapter中对空秤零点附近的小负重量做归零处理
- 优化重量单位显示逻辑,根据负漂移抑制后的值显示克或千克
- 更新local.properties中SDK路径配置
2026-07-13 18:26:16 +08:00
mazengfei 7ab8e09a46 refactor(scale): 优化串口数据处理逻辑和自动应答机制
- 在串口数据读取中增加帧拼装与解析,统一自动应答发送
- 实现心跳日志降频,减少重复日志,避免主线程无效计算
- 将数据回调分派至主线程,确保线程安全
- 缓存时间格式化器,避免重复创建对象
- 增加秤重数据变更判断,避免无变化时刷新UI和日志
- 异步优化文件日志写入,使用协程通道和单线程写入,避免多线程SimpleDateFormat竞争
- 修复文件路径和上下文使用,防止Activity内存泄漏
- 精简部分注释和代码未使用段落,提高代码清晰度
2026-07-03 14:57:25 +08:00
mazengfei 1e44cd2765 fix(scale): 优化秤数据同步及格口显示顺序
- 增加秤号到列表索引的映射,提升心跳回调数据定位效率
- 调整重量数据处理逻辑,减少索引查找开销
- 按设备物理布局重排格口列表,解决多列设备显示错乱问题
- 定义同步间隔和首次同步延迟常量,统一定时任务配置
- 调整重量上报心跳间隔为1秒,提升秤数据实时性
- 清空列表时同步清理秤号映射,防止脏数据影响展示
- 优化空格口清理逻辑,改用映射位置快速更新对应项
2026-07-02 17:58:46 +08:00
lvmeng 3757b851be refactor(home): 移除旧版首页和货架相关界面及代码
- 删除 activity_home.xml 布局文件
- 删除 activity_shelf.xml 布局文件
- 删除 activity_shelf_v2.xml 布局文件
- 从 AndroidManifest.xml 中移除 HomeActivity 和 ShelfActivity 等旧页面声明
- 删除 ApiService.kt 网络接口文件
- 删除 ApiServiceV2.kt 网络接口文件
- 删除 CabinetInitResult.kt 数据模型文件
- 删除 CleanPackageAdapter.kt 适配器文件
- 删除 CleanPackageOption.kt 数据模型文件
- 删除 Constant.kt 常量定义文件
- 删除 DeviceConfigInfo.kt 数据模型文件
- 删除 DrawableExt.kt 扩展工具文件
- 删除 F2C.kt 温度转换工具文件
- 删除 GoodsModel.kt 数据模型文件
- 删除 GoodsRecord.kt 数据模型文件
- 删除 GridLayoutTool.kt 布局工具文件
- 删除 HexUtils.java 十六进制工具类
2026-06-30 11:27:29 +08:00
lvmeng 947afd06e8 fix(dialog): 修复Chip选择对话框的标题显示和布局问题
- 修改对话框确认按钮提示文本,使用动态标题变量替代固定文本
- 移除手动设置Chip的LayoutParams,改为直接使用addView方法
- 设置ChipGroup为多行显示以支持更多选项
- 调整布局文件中ChipGroup的宽度为wrap_content并居中对齐
- 添加水平和垂直间距属性以改善Chip排列效果
- 修正ShelfV3Activity中传递给对话框的标题文本格式
2026-06-26 16:43:45 +08:00
lvmeng 5412f0b6b9 feat(shelf): 更新货架界面和菜品分类功能
- 重命名tvFoodType为tvVegTypeName以统一命名规范
- 新增bg_pressed.xml选择器用于按钮按下效果
- 在ChipSelectDialog中添加必选验证和改进布局参数
- 扩展HomeV3Activity传递菜品名称和蔬菜类型信息
- 调整list_item_shelf_v3.xml布局尺寸和权重配置
- 新增tvFoodType显示菜品分类并调整字体间距
- 更新ShelfV3Activity处理菜品分类数据传递和显示
- 修改SlotModel数据结构支持蔬菜类型ID和名称字段
- 优化适配器中菜品分类文本显示逻辑和颜色设置
2026-06-26 16:24:53 +08:00
lvmeng 0e0c2fe47b feat(shelf): 添加净菜毛菜搜索和分类选择功能
- 新增 tvFoodType TextView 显示食品分类
- 将搜索框可见性从 gone 改为 visible
- 添加 FoodItem 和 FoodType 数据模型
- 添加 SearchFoodRequest 请求模型
- 在 ApiServiceV3 中新增 searchFood 接口
- 在 NetViewModelV3 中新增 searchFood 方法
- 修改 PutSlotRequest 模型字段为可空类型并添加 vegTypeId
- 更新 HomeV3Activity 中行列计算逻辑
- 缩短商品数据同步间隔时间
- 修改 InitActivity 中的基础URL配置
- 将 PendingInboundAdapter 适配器改为使用 FoodItem 类型
- 在 ShelfV3Activity 中实现净菜分类选择对话框功能
- 添加 ChipSelectDialog 自定义对话框组件
- 添加 chip 相关的颜色资源文件
- 实现搜索功能替换原有的待入库查询逻辑
2026-06-26 14:57:07 +08:00
lvmengandClaude Opus 4.7 84634f843d refactor(home): 用FlexboxLayoutManager替换GridLayoutManager,支持动态行列布局
FlexboxLayoutManager(COLUMN+WRAP)天然列优先排列,数据无需重排。
item宽高在拿到接口行列数后直接计算,适配任意rows×cols配置。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-26 09:17:06 +08:00
lvmeng 419e08c0e0 fix(shelf): 解决货架模型重量数据同步问题
- 在HomeV3Activity中添加重量值赋值逻辑确保模型数据完整
- 临时注释PendingInboundItem中的重量赋值避免数据冲突
- 修复货架适配器数据更新时重量信息丢失的问题
2026-06-25 14:48:04 +08:00
lvmeng 70f4146509 fix(init): 移除测试设备号硬编码
- 注释掉测试用的固定设备号赋值代码
- 确保使用实际的设备唯一标识符获取逻辑
- 保留设备号获取的日志记录功能
2026-06-25 14:10:58 +08:00
lvmeng 45bd586e7a refactor(model): 更新PendingInboundItem数据模型字段类型
- 将vegTypeId从Int类型改为Long?可空类型,默认值为null
- 将vegTypeName从String类型改为String?可空类型,默认值为null
- 将spec从String类型改为String?可空类型,默认值为null
- 所有修改的字段都设置了默认值以保持向后兼容性
2026-06-25 11:31:14 +08:00
lvmeng a78eaf7233 feat(app): 集成V3货柜管理功能
- 将应用包名从com.shuwei.intelligent.shelves迁移至com.sw.scalefusion.shelf
- 更新AndroidManifest.xml中的Activity声明路径以匹配新包名
- 在InitActivity中同步更新包名引用及依赖导入
- 修改GridLayoutTool工具类适配V3货柜布局排序逻辑
- 新增ApiResponse和BaseRepository统一网络响应处理
- 添加V3 API服务定义支持毛菜柜/净菜柜功能
- 新增HomeV3Activity和ShelfV3Activity实现新版货柜界面
- 集成API文档定义的货柜初始化、入柜、同步重量等核心功能
- 添加SlotModel等数据模型支持V3货柜操作
- 更新ProtocolConstants增加设备类型映射配置
- 重构网络管理层实现V2/V3接口实例分离管理
2026-06-24 17:39:44 +08:00
mazengfei 8aaba07cb6 perf(home): 调整货架商品同步到服务器的时间间隔
- 将定时任务的执行间隔从5秒调整为2分钟
- 保持初始延迟时间不变(10秒)
- 优化服务器同步频率以减少资源消耗
2026-06-04 18:10:17 +08:00
mazengfei 4f1a9dd0a1 refactor(home): 重构货架重量数据模型和显示逻辑
- 将实际重量计算统一到weight字段,移除actualQty和totalWeightG字段
- 修改HomeV2Activity中的重量数据处理逻辑,统一转换为千克单位
- 更新ShelfV2Activity中重量显示格式,优化单位转换逻辑
- 调整ShelfV2Adapter中重量显示逻辑,统一使用weight字段进行展示
- 在日志记录中增加温度信息输出
- 移除废弃的条件判断逻辑,简化代码结构
2026-06-04 17:28:23 +08:00
lvmeng 694e20023a refactor(layout): 优化网格布局工具和货架界面排序逻辑
- 新增 getLayoutManagerV2 方法用于创建垂直方向的网格布局管理器
- 修改 initListSortV2 方法支持动态行列参数控制排序逻辑
- 添加 submitListSortV2 方法用于提交时按槽位号排序
- 重构 HomeV2Activity 中的 UI 更新逻辑,支持动态行列配置
- 修复 RecyclerView 初始化时机问题,避免重复设置适配器
- 优化 ShelfV2Activity 中的清空操作,添加加载提示和自动关闭功能
- 完善槽位状态管理,支持空置和存放中状态标识
2026-06-04 14:32:08 +08:00
mazengfei ac17fca325 fix(home): 解决格口数据更新和权重计算问题
- 将超时时间从5分钟调整为1分钟
- 优化格口数据匹配逻辑,提高查找效率
- 根据物品类型分别处理重量数据存储
- 添加JSON序列化支持用于调试日志
- 修复itemType字段类型不一致问题
- 优化重量显示计算逻辑并简化条件判断
- 修复代码格式化问题
2026-06-04 11:19:25 +08:00
lvmeng 4b8e5f84e6 refactor(net): 重构网络请求配置以支持动态域名切换
- 在 ApiServiceV2 中使用 @Url 注解实现动态 URL 配置
- 添加 DynamicBaseUrlInterceptor 拦截器用于实时替换基础 URL
- 更新环境切换对话框中的环境名称和对应的 URL 映射关系
- 修改 UrlConfig 中的常量为变量并包含完整的基础 URL 路径
- 在 HttpManager 中为两个 API 服务实例都添加动态域名拦截器
- 调整环境配置常量定义顺序以匹配新的环境切换逻辑
2026-06-03 16:30:05 +08:00
lvmeng d6ba6cf527 feat(model): 更新货柜初始化结果和净菜包选项数据结构
- 在 CabinetInitResult 中添加 horizontalRows 和 verticalCount 字段
- 为 CleanPackageOption 和 MealPackageOption 添加 orderNo、foodId、needCount、needQtyKg 等字段
- 修改 CleanPackageOption 的 itemType 为 1,MealPackageOption 的 itemType 为 2
- 在 ShelfModelV2 中添加 cleanOrderNo 字段用于关联净菜订单号
- 更新 SyncItem 数据结构,添加 cleanOrderNo 字段
- 移除 HomeV2Activity 中的测试代码和硬编码逻辑
- 修改格口编号显示格式,补零显示两位数
- 调整定时任务执行频率,缩短同步间隔时间
2026-05-28 17:39:04 +08:00
lvmeng 4408acfca4 refactor(net): 注释掉设备令牌和配置相关功能
- 注释掉 getDeviceToken 方法及其相关逻辑
- 注释掉 getDeviceConfig 方法及其相关逻辑
- 注释掉 getAccessToken 方法及其相关逻辑
- 保留了 UiState 相关的状态流定义
- 维持了其他网络请求方法的正常功能
2026-05-27 19:55:02 +08:00
lvmengandClaude Sonnet 4.6 b0739605b9 feat(v2): 新增 V2 货柜接口层、页面及数据同步功能
- 新增 ApiServiceV2 / NetViewModelV2 承载 v1.1 接口(初始化、净菜包/餐品净菜包选项、数据同步)
- 新增 CabinetRequestInterceptor 独立 Retrofit 实例
- 新增 HomeV2Activity + ShelfV2Activity 及对应布局
- 新增 ShelfV2Adapter / CleanPackageAdapter / MealPackageAdapter
- 新增 ShelfModelV2 / CabinetInitResult / SyncBody / SyncItem / CleanPackageOption / MealPackageOption 数据模型
- HomeV2Activity 实现 syncShelfGoodsToServer 定时同步逻辑
- GridLayoutTool 新增 initListSortV2 支持 ShelfModelV2 排序

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 19:54:06 +08:00
lvmeng d524da1af3 refactor(net): 注释掉设备token和配置信息相关API接口
- 将getDeviceToken接口注释掉
- 将getDeviceInfo接口注释掉
- 将getAccessToken接口注释掉
- 保留了原有的文档注释
- 维持了文件结构完整性
2026-05-27 13:51:23 +08:00
lvmengandClaude Sonnet 4.6 967d06ce1e docs(serial): 更新 ScaleManager 类注释
- 同步典型用法为当前链式 start() 写法
- 职责说明补充 Channel 发送队列描述
- release() 说明补充"清空队列"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 15:47:56 +08:00
lvmengandClaude Sonnet 4.6 d5c6ec92d4 refactor(serial): sendCmd 改用 Channel 保证串口写入顺序
- 新增 sendChannel(无界 Channel)作为发送队列
- openPort() 启动单一消费者协程顺序消费队列,避免并发写串口
- sendCmd() 改为 trySend() 入队,不再每次创建新协程
- release() 关闭 Channel,确保消费者协程正常退出

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 15:02:15 +08:00
lvmengandClaude Sonnet 4.6 7b28eb03d6 refactor(serial): 清理废弃类并复用现有工具函数
- 删除 SerialProtocolHandler(旧版协议解析器,已无任何引用)
- 删除 SerialFrameParser(仅被 SerialProtocolHandler 使用,随其废弃)
- ScaleFrameParser.parseFrame 改用项目已有的 String.hexToBytes(),移除重复的私有 hexToByteArray()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 15:00:08 +08:00
lvmengandClaude Sonnet 4.6 4d545ceb46 refactor(serial): 将 SerialPortManager 合并到 ScaleManager
- 删除 SerialPortManager,串口生命周期(open/startReceive/release)内嵌到 ScaleManager
- ScaleManager 改为 object 单例,去除 .instance 调用
- init() 简化为只接收 activateCode,去除 deviceId + activateMap 查表逻辑
- 新增 start(preHook) 方法合并 open + startReceive,支持链式调用到末尾
- BaseActivity.sendCmd 改为直接调用 ScaleManager.sendCmd

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 14:59:19 +08:00
mazengfeiandClaude Sonnet 4.6 0eede1059c feat(serial): 封装 ScaleManager 替换现有秤功能逻辑
新增 SDK 核心类:
- ScaleProtocolConstants:协议常量(命令字节、帧偏移)
- ScaleFrameParser:分片拼装、帧解析、BCD重量解析(修复旧代码 hex 误用问题)
- ScaleFrame / ScaleWeight / HeartbeatData / StatusData:数据模型
- ScaleManager:单例入口,支持链式回调注册、自动应答、指令构建
- ScaleFrameParserTest:基于实际抓包数据的单元测试

业务层替换:
- HomeActivity:移除 SerialProtocolHandler/SerialFrameParser,改用 ScaleManager 回调
- BaseActivity:sendCmd() 保持调用 SerialPortManager,与 ScaleManager.sendAction 独立
- ShelfActivity:秤置零、获取状态指令改用 ScaleManager 构建方法

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
2026-05-21 13:54:02 +08:00
lvmeng 8145eb588b refactor(serial): 将串口配置常量重命名为大写格式
- 将 portName 常量重命名为 PORT_NAME
- 将 baudRate 常量重命名为 BAUD_RATE
- 更新代码中对这些常量的引用以使用新的命名约定
- 保持串口通信功能完全不变
2026-05-21 09:01:27 +08:00
mazengfei c91d5656aa 修改旧版设备秤数量导致数据显示不准的问题 2026-05-20 16:50:53 +08:00
mazengfei 532b22a5c6 设备支持3列显示,统一处理显示和提交数据顺序 2026-05-20 15:36:28 +08:00
mazengfei e9d04bfb70 优化启动页面样式 2026-04-28 16:52:54 +08:00
mazengfei afba5220b3 首页设置禁止返回按钮 2026-04-28 16:41:21 +08:00
lvmeng 4ace12c6c7 style(ui): 调整加载动画尺寸并替换为矢量资源
- 将加载动画ImageView尺寸从160dp调整为120dp
- 替换loading_spinner为新的loading矢量资源
- 添加loading.xml矢量动画资源文件
- 注释掉HomeActivity中的临时报告对话框逻辑
- 简化HomeActivity中的RespData类型转换代码
2026-04-28 15:37:47 +08:00
mazengfei ee36869003 优化 2026-04-07 17:19:12 +08:00
lvmengandClaude Sonnet 4.6 c23c215941 fix: 修复 noDataWatchdogTask 潜在的内存泄漏问题
在 Runnable 中添加生命周期检查,防止 Activity 销毁后任务继续执行。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 17:58:22 +08:00
lvmengandClaude Sonnet 4.6 3d67dd2c2d refactor: 优化货架列表转换逻辑并支持奇数长度处理
- 移除 subList 创建,直接通过索引访问元素
- 修复奇数长度列表的处理逻辑
- 保持单次循环,提升性能

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 17:53:00 +08:00
mazengfeiandClaude Sonnet 4.6 133f309d4b refactor: 统一时钟管理并优化状态栏显示逻辑
- 在 BaseActivity 中实现统一的时钟管理机制,避免各子类重复实现
- LogActivity 和 ShelfActivity 覆写 onClockTick() 自定义状态栏显示
- HomeActivity 移除重复的时间更新逻辑,启用右侧状态栏菜单
- 提取协议常量到 ProtocolConstants,提高代码可维护性
- 优化开锁逻辑判断,改为基于 deviceId 的动态判断
- 新增右侧状态栏弹出菜单布局文件

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 17:07:41 +08:00
mazengfeiandClaude Sonnet 4.6 3e5c7c6caa refactor(HomeActivity): 修复内存泄漏并优化错误处理
1. 修复内存泄漏问题
   - 在 onDestroy 中清理所有 Handler 回调
   - 在 onDestroy 中释放 Dialog 引用

2. 增强类型安全
   - updateUI 中增加类型检查和日志
   - updateOverdueState 中增加完整的类型检查

3. 优化串口异常处理
   - 串口数据处理异常时向用户提示

4. 消除代码重复
   - 删除冗余的 saveShelfGoodsList 方法
   - 定时任务直接调用 syncShelfGoodsToServer

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 14:19:45 +08:00
mazengfeiandClaude Sonnet 4.6 04fe3ec2c1 refactor: 全面重构 HomeActivity 架构并修复多项 Bug
- 新增 SerialProtocolHandler 类,将串口协议解析逻辑从 HomeActivity 剥离
- ProtocolConstants 补充命令码常量(CMD_*)及帧解析偏移常量
- 修复 NetViewModel.getDeviceConfig 更新错误 StateFlow 的 Bug
- 修复 getWeightInfo 中 toInt() 整数溢出崩溃风险,改用 toLongOrNull(16)
- 升级废弃的 getSerializableExtra,使用 Build.VERSION.SDK_INT 版本分支
- BaseActivity 提取 onUserInactive() 虚方法,消除对子类 HomeActivity 的直接引用
- 修复 BaseActivity 中错误的 LIGHT_OPEN/CLOSE 导入(改从 ProtocolConstants 导入)
- repeatOnLifecycle 由 CREATED 改为 STARTED,避免 UI 不可见时无效更新
- updateOverdueState 从回调风格改为 StateFlow,与项目其他接口保持一致
- 提取 syncShelfGoodsToServer() 消除重复的 ShelfBody 构建逻辑
- 清理 NetViewModel 和 BaseActivity 中大段注释死代码

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 11:26:05 +08:00
lvmengandClaude Sonnet 4.6 9a795b9710 feat(HomeActivity): 新增串口无数据超时提示弹窗
超过5分钟未收到串口数据时,自动弹窗提示用户考虑断电重启设备;
收到新数据后自动关闭弹窗并重置计时。
同步提交串口协议常量(ProtocolConstants)与帧解析器(SerialFrameParser)重构代码。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 10:18:00 +08:00
mazengfei fff6a2a3b3 配置生产域名 2026-03-31 19:16:56 +08:00
lvmeng 3b79f6d6aa feat(config): 实现应用基础URL配置管理与环境切换功能
- 引入GlobalData对象统一管理应用基础URL配置
- 添加TEST/UAT/PROD三套环境切换弹窗功能
- 在BaseActivity中集成双击右上角状态栏显示环境切换对话框
- 将网络请求配置从App.configUrl迁移至GlobalData.appBaseUrl
- 扩展SpTool工具类支持baseUrl本地存储
- 增加HTTP连接和写入超时时间至30秒
- 更新构建配置启用BuildConfig支持
- 添加环境切换相关UI资源文件和样式定义
2026-03-31 14:06:04 +08:00
lvmeng 76b67b545d Merge remote-tracking branch 'origin/dev_优化_基于分支代码备份' 2026-03-31 10:58:32 +08:00
lvmeng 3bd60990b9 Revert "重构 HomeActivity:修复多项稳定性与架构问题"
This reverts commit 85903eb646.
2026-03-31 10:57:46 +08:00
lvmeng a116c4fc6c Revert "重构:拆分 HomeActivity 职责,分层解耦串口与业务逻辑"
This reverts commit e6cfc4dff2.
2026-03-31 10:57:40 +08:00
lvmengandClaude Sonnet 4.6 e6cfc4dff2 重构:拆分 HomeActivity 职责,分层解耦串口与业务逻辑
- 新建 SerialEventListener:定义串口协议解析回调接口契约
- 新建 SerialProtocolParser:迁移全部协议解析逻辑(拼包、12种命令分发、重量解析),无 Android 依赖,可单元测试
- 新建 SerialViewModel:管理串口生命周期(open/close)、Channel 数据传递,暴露 weightFlow / tempCtrlEventFlow / deviceStatusRefreshFlow
- 扩展 HomeViewModel:迁入定时任务(保存货架数据、刷新过期状态),改用 viewModelScope 管理,新增 deviceName 属性与 overdueUpdateFlow
- 精简 HomeActivity:从 835 行削减至 255 行,仅保留 UI 协调职责,所有串口与业务逻辑由 ViewModel 层处理

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 13:41:01 +08:00
lvmengandClaude Sonnet 4.6 85903eb646 重构 HomeActivity:修复多项稳定性与架构问题
架构优化:
- 新增 HomeViewModel,将 companion object 中的共享状态(shelfItems、
  weightMap、selectedShelfIndex、temperatureC、humidity)迁移至 ViewModel,
  消除 Activity 重建时的状态残留与全局状态污染问题

协程修复:
- repeatOnLifecycle(CREATED) 改为 STARTED,确保 Flow 收集与 UI 可见性
  生命周期对齐,进入后台时自动停止订阅
- 串口数据接收改用 Channel<String> + 单一消费协程,替代多 launch 并发模式,
  彻底消除 StringBuilder(serialReader)的并发竞争问题

稳定性修复:
- 修复 tipDialog 从未赋值导致 Dialog 功能失效及 onDestroy 窗口泄漏问题
- 修复 weightHex.toInt() 十进制解析错误,改为 toIntOrNull(16) 并添加兜底
- 修复 updateOverdueState 按索引访问接口数据导致的越界风险,
  改为按 deviceNo 精确匹配,同时修正交叉排列导致的状态串位问题
- 废弃 API getSerializableExtra 替换为版本分支兼容写法(minSdk 25+)

依赖升级:
- androidx.core-ktx 1.10.1 → 1.12.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-11 11:45:44 +08:00
96 changed files with 4867 additions and 3289 deletions
+4 -1
View File
@@ -16,7 +16,7 @@ android {
compileSdk = 34
defaultConfig {
applicationId = "com.shuwei.intelligent.shelves"
applicationId = "com.sw.scalefusion.shelf"
minSdk = 25
//noinspection EditedTargetSdkVersion,ExpiredTargetSdkVersion
targetSdk = 30
@@ -44,6 +44,7 @@ android {
}
buildFeatures {
viewBinding = true
buildConfig = true
}
ndkVersion = "29.0.13846066"
@@ -86,6 +87,8 @@ dependencies {
implementation("org.greenrobot:eventbus:3.3.1")
implementation("com.google.android.flexbox:flexbox:3.0.0")
// implementation("io.github.jeremyliao:live-event-bus-x:1.8.0")
// implementation("com.hoho:android-usb-serial:1.3.0")
// implementation("io.github.jeadyx:jserialport:1.5")
+4 -8
View File
@@ -26,7 +26,7 @@
android:theme="@style/Theme.IntelligentShelves"
android:usesCleartextTraffic="true">
<activity
android:name=".activity.InitActivity"
android:name="com.sw.scalefusion.shelf.InitActivity"
android:exported="true"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity">
@@ -36,15 +36,11 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activity.HomeActivity"
android:screenOrientation="portrait"/>
<activity
android:name=".activity.ShelfActivity"
<activity android:name="com.shuwei.intelligent.shelves.activity.LogActivity" />
<activity android:name="com.sw.scalefusion.shelf.HomeV3Activity" />
<activity android:name="com.sw.scalefusion.shelf.ShelfV3Activity"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name="com.shuwei.intelligent.shelves.activity.SettingActivity" />
<activity android:name="com.shuwei.intelligent.shelves.activity.LogActivity" />
<receiver
android:name=".utils.BootReceiver"
@@ -5,8 +5,11 @@ import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import com.shuwei.intelligent.shelves.utils.BootReceiver
import com.shuwei.intelligent.shelves.utils.CrashHandler
import com.shuwei.intelligent.shelves.utils.FileLogger
/**
* @author: star
@@ -19,10 +22,22 @@ class App : Application() {
super.onCreate()
app = this
CrashHandler.init(this)
// 启动时立即清理一次过期日志
cleanupLogs()
// 设备长期不断电、进程不会重新启动,运行中每24小时定期清理一次
logCleanupHandler.postDelayed(logCleanupRunnable, LOG_CLEANUP_INTERVAL)
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
registerReceiver(BootReceiver(), filter)
}
/**
* 清理过期的日志文件:文件日志与崩溃日志均保留最近7天
*/
private fun cleanupLogs() {
FileLogger.cleanupExpiredLogs(this)
CrashHandler.getInstance()?.cleanupOldCrashReports()
}
companion object {
private lateinit var app: App
var canteenId = "0"
@@ -36,6 +51,19 @@ class App : Application() {
@Volatile
private var sharedPref: SharedPreferences? = null
/** 日志定期清理间隔:24小时,与日志文件按天滚动对齐 */
private const val LOG_CLEANUP_INTERVAL = 24L * 60 * 60 * 1000
private val logCleanupHandler = Handler(Looper.getMainLooper())
/** 日志定期清理任务:执行后重新调度自身,形成循环 */
private val logCleanupRunnable = object : Runnable {
override fun run() {
getInstance().cleanupLogs()
logCleanupHandler.postDelayed(this, LOG_CLEANUP_INTERVAL)
}
}
fun getInstance(): App {
return app
}
@@ -0,0 +1,39 @@
package com.shuwei.intelligent.shelves
object GlobalData {
// /**
// * 设备id
// */
// var deviceId: String = ""
// /**
// * app版本号
// */
// var appVersion: String = "1"
var appBaseUrl: String = ""
/**
* 具体业务 BaseUrl
*/
// const val LOCAL_BASE_URL = "http://192.168.1.201:14801"
const val LOCAL_BASE_URL = "http://192.168.10.101:24801"
const val TEST_BASE_URL = "https://dev.yixiong-tech.com:8081"
const val PROD_BASE_URL = "https://platform-api.uat.shuziweidao.com"
}
/**
* 全局常量
*/
object Constants {
}
/**
* key
*/
object GlobalKey {
const val KEY_BASE_URL = "baseUrlKey"
}
@@ -1,811 +0,0 @@
package com.shuwei.intelligent.shelves.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.util.SparseIntArray
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.adapter.ShelfAdapter
import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityHomeBinding
import com.shuwei.intelligent.shelves.dialog.CommonDialog
import com.shuwei.intelligent.shelves.model.ClearShelfEvent
import com.shuwei.intelligent.shelves.model.SendWeightEvent
import com.shuwei.intelligent.shelves.model.ShelfBody
import com.shuwei.intelligent.shelves.model.ShelfModel
import com.shuwei.intelligent.shelves.model.ShelfResult
import com.shuwei.intelligent.shelves.model.WeightEvent
import com.shuwei.intelligent.shelves.net.Loading
import com.shuwei.intelligent.shelves.net.NetViewModel
import com.shuwei.intelligent.shelves.net.RespData
import com.shuwei.intelligent.shelves.net.UiState
import com.shuwei.intelligent.shelves.net.apiService
import com.shuwei.intelligent.shelves.serial.SerialPortManager
import com.shuwei.intelligent.shelves.utils.HexUtils
import com.shuwei.intelligent.shelves.utils.IntervalExecutor
import com.shuwei.intelligent.shelves.utils.binaryToHex
import com.shuwei.intelligent.shelves.utils.ext.copyTextToClipboard
import com.shuwei.intelligent.shelves.utils.ext.gone
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
import com.shuwei.intelligent.shelves.utils.ext.toast
import com.shuwei.intelligent.shelves.utils.ext.visible
import com.shuwei.intelligent.shelves.utils.hexToBinary
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class HomeActivity : BaseActivity() {
companion object {
private const val TAG = "HomeActivity"
private const val LOG_PREFIX = "receiveSerialPortData:收到"
private const val MM_DD_EEEE__HH_MM_SS = "MM月dd日 EEEE HH:mm:ss"
//协议头
const val HEADER = "D6DADEDB"
//协议尾
const val FOOTER = "FFFF"
// const val ACTIVE_CMD =
// "${HEADER}000281C5D70A7D428A4FA67B50F7DACA241938938B4B9CBD73673E9C8E7F2E15062D${FOOTER}"
const val LEFT_SHELF_OPEN_CMD =
"${HEADER}020101000000000000000000000000000000000000${FOOTER}"
const val RIGHT_SHELF_OPEN_CMD =
"${HEADER}020100010000000000000000000000000000000000${FOOTER}"
//const val TEMPERATURE_CMD = "${HEADER}1001${FOOTER}"
const val DEVICE_INFO_CMD = "${HEADER}0301000000000000000000000000${FOOTER}"
const val START_TEMP_CTRL_CMD = "${HEADER}0F01360000${FOOTER}"
//const val START_CMD= "${HEADER}0F01050020${FOOTER}"
// const val ACTIVE_CMD = "${HEADER}000281C5D70A7D428948AD7254FADBB1516738938B4B9CBD73673E9D8E7F2E15062D$FOOTER"
// 410激活码
// const val ACTIVE_CMD = "${HEADER}000281C5D70A7D42894EA17650F5D0BB516838E7863C9ABD766C38958AFF0F3C062D${FOOTER}"
//1楼餐厅激活码
const val ACTIVE_CMD =
"${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}"
//华氏温度单位
const val F_TEMP_CMD = "${HEADER}0F01390000${FOOTER}"
//摄氏温度单位
const val C_TEMP_CMD = "${HEADER}0F01390001${FOOTER}"
//开灯(开 继电器1
const val LIGHT_CLOSE = "${HEADER}020102020102020000000000000000000000000000${FOOTER}"
const val LIGHT_OPEN = "${HEADER}020102020002020000000000000000000000000000${FOOTER}"
const val TEMPERATURE_CTRL = "${HEADER}0F01040000${FOOTER}"
val list: MutableList<ShelfModel> = mutableListOf()
val weightArray = SparseIntArray()
var shelfIndex = 0
// public fun getRealWeight():Double = weightArray[shelfIndex]?:0.0
// 温度
var showTemperatureC = "0"
// 湿度
var showHumidity = "0"
}
//401-false1楼餐厅-true
private var isNeedOpenLock = true
private lateinit var binding: ActivityHomeBinding
private val viewModel: NetViewModel by viewModels()
@SuppressLint("NotifyDataSetChanged", "HardwareIds")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHomeBinding.inflate(layoutInflater)
EventBus.getDefault().register(this)
setBackground()
setContentView(binding.root)
// updateLeftStatus("-°C / -%")
updateLeftStatus("")
initRecyclerView()
lifecycleScope.launch {
val openState = SerialPortManager.open()
log("onCreate: openState=$openState")
if (openState) {
SerialPortManager.startReceive { data ->
// 更新UI显示接收数据
lifecycleScope.launch {
try {
receiveSerialPortData(data)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
//SerialPortManager.send(DEVICE_INFO_CMD)
}
repeatOnLifecycle(Lifecycle.State.CREATED) {
launch {
viewModel.getAccessTokenUiState.collect { state ->
when (state) {
is UiState.Loading -> {}
is UiState.Success<*> -> getTokenSuccess(state.data)
is UiState.Error -> toast(state.msg)
else -> {}
}
}
}
launch {
viewModel.getShelfListUiState.collect { state ->
when (state) {
is UiState.Loading -> showProgress()
is UiState.Success<*> -> updateUI(state.data)
is UiState.Error -> showError(state.msg)
else -> {}
}
}
}
}
}
//sendCmd(ACTIVE_CMD)
binding.root.postDelayed({
sendCmd(START_TEMP_CTRL_CMD)
sendCmd(C_TEMP_CMD)
}, 5000)
// TaskManager.startTask()
saveGoodsTask()
overdueTask()
// var androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
//// androidId = "d0e7a2d5f25c775c"
// log("onCreate: androidId=${androidId}")
// if (androidId == "65e1012638f78260" || androidId == "40f89e91ee40611d") {
// androidId = "d0e7a2d5f25c775c"
// }
// App.deviceId = androidId
// //"53babf69-0d2f-3875-a649-f2e12f80ad4c1"
//
// val swDpValue = resources?.configuration?.smallestScreenWidthDp
// log("onCreate: swDpValue=$swDpValue")
// viewModel.getAccessToken(App.deviceId)
viewModel.getShelfList(deviceId = App.deviceId)
// binding.root.postDelayed({
// loadTestData()
// }, 30*1000)
}
private fun loadTestData() {
list.add(ShelfModel(deviceNo = 1, goodsName = "鸡蛋", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 6, goodsName = "", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 2, goodsName = "", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 7, goodsName = "生姜", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 3, goodsName = "黄瓜", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 8, goodsName = "", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 4, goodsName = "", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 9, goodsName = "", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 5, goodsName = "", deviceId = App.deviceId))
list.add(ShelfModel(deviceNo = 10, goodsName = "", deviceId = App.deviceId))
shelfAdapter.notifyDataSetChanged()
}
private fun getTokenSuccess(data: RespData<*>) {
log("getTokenSuccess: $data")
data.data?.let {
App.accessToken = it.toString()
//UIUtils.toast(it.toString())
viewModel.getShelfList(deviceId = App.deviceId)
}
}
private fun showProgress() {
Loading.show(this)
}
@SuppressLint("NotifyDataSetChanged")
private fun updateUI(data: RespData<*>) {
binding.include?.root?.gone()
window?.decorView?.postDelayed({ Loading.dismiss() }, 500)
if (data.data !is ShelfResult) {
loadEmptyView()
return
}
deviceName = data.data.deviceName
// updateLeftStatus("$deviceName -°C / -%")
updateLeftStatus("$deviceName")
App.canteenId = data.data.placeId
val tempList = data.data.containerGoodsList
if (tempList.isNullOrEmpty()) {
loadEmptyView()
return
}
// if (tempList.size < 10) {
// toast("数据错误")
// return
// }
list.clear()
val subList01 = tempList.subList(0, tempList.size / 2)
val subList02 = tempList.subList(tempList.size / 2, tempList.size)
repeat(tempList.size / 2) { index ->
list.add(subList01[index].also { it.deviceId = App.deviceId })
list.add(subList02[index].also { it.deviceId = App.deviceId })
}
shelfAdapter.notifyDataSetChanged()
}
private fun showError(message: String) {
Loading.dismiss()
toast(message)
loadEmptyView()
}
/**
* 终端id
*/
private var terminalId: String = ""
/**
* 固件版本
*/
private var terminalVersion: String = ""
private val serialReader by lazy { StringBuilder() }
private fun receiveSerialPortData(srcData: String) {
log("receiveSerialPortData: $srcData")
var data = ""
if (srcData.contains(HEADER) && srcData.contains(FOOTER)) {
serialReader.clear()
val startIndex = srcData.lastIndexOf(HEADER)
var endIndex = srcData.indexOf(FOOTER) + FOOTER.length
if (endIndex < startIndex) {
//类似这种:31314FFFFFD6DADEDB01010CFOOTER在HEADER前
data = srcData.substring(startIndex)
if (data.contains(FOOTER)) {
endIndex = srcData.indexOf(FOOTER) + FOOTER.length
data = data.substring(0, endIndex)
handleReceivedData(data)
serialReader.clear()
return
}
serialReader.clear()
serialReader.append(data).append(",")
return
}
serialReader.append(srcData.substring(startIndex, endIndex))
data = serialReader.toString()
handleReceivedData(data)
serialReader.clear()
return
}
if (srcData.contains(HEADER) && srcData.contains(FOOTER).not()) {
serialReader.clear()
val startIndex = srcData.lastIndexOf(HEADER)
serialReader.append(srcData.substring(startIndex)).append(",")
return
}
if (srcData.contains(HEADER).not() && srcData.contains(FOOTER).not()) {
serialReader.append(srcData).append(",")
return
}
//if (srcData.contains(HEADER).not() && srcData.contains(FOOTER))
val endIndex = srcData.indexOf(FOOTER) + FOOTER.length
serialReader.append(srcData.substring(0, endIndex))
log("receiveSerialPortData:serialReader: $serialReader")
data = serialReader.toString().replace(",", "")
handleReceivedData(data)
}
private fun handleReceivedData(data: String) {
if (data.isEmpty()) {
return
}
val cmd = data.substring(HEADER.length, HEADER.length + 4)
val cmdFlag = cmd.substring(0, 2)
when (cmd) {
"0001" -> {
//终端发起激活指令,拿到固定数据体(终端ID-15字节、固件版本-5字节、命令次数-1字节)
val reqBody =
data.substring(HEADER.length + cmd.length, data.length - FOOTER.length)
if (reqBody.length == 44) {
terminalId = reqBody.substring(2, 32)
terminalVersion = reqBody.substring(32, 42)
log("${LOG_PREFIX}[激活]${cmdFlag}指令:${data},终端id:${terminalId},固件版本:${terminalVersion},发送激活命令:$ACTIVE_CMD")
sendCmd(ACTIVE_CMD)
}
}
"0101", "8101" -> {
//心跳0102${p1}${p2}${version}
//心跳81(终端发起,当终端发送此命令时需要服务端存储串口屏显示信息)
val respCmd = "${HEADER}01020506${terminalVersion}$FOOTER"
log("${LOG_PREFIX}[心跳]${cmdFlag}指令:${data},发送应答指令:${respCmd}")
sendCmd(respCmd)
heartBeat(data)
}
"0202" -> {
//开关锁反馈020200${deviceId}${version}
val respCmd = "${HEADER}020200${terminalId}${terminalVersion}$FOOTER"
log("${LOG_PREFIX}[开锁]${cmdFlag}指令:${data},发送应答指令:${respCmd}")
sendCmd(respCmd)
//lockFeedback(data)
}
"0302" -> {
//获取设备状态
log("${LOG_PREFIX}[获取设备状态]${cmdFlag}指令:${data}")
getDeviceInfo(data)
}
"0501" -> {
//卡号上发
val respCmd = "${HEADER}050203$FOOTER"
log("${LOG_PREFIX}[卡号上发]${cmdFlag}指令:${data},发送应答指令:${respCmd}")
sendCmd(respCmd)
}
"0B01" -> {
//操作记录上传
val respCmd = "${HEADER}0B0203$FOOTER"
log("${LOG_PREFIX}[操作记录上传]${cmdFlag}指令:${data},发送应答指令:${respCmd}")
sendCmd(respCmd)
}
"0C01" -> {
//对时
val timeLong = System.currentTimeMillis() / 1000 + (8 * 3600)
val timeStr = "0000000" + String.format("%X", timeLong)
val time =
timeStr.substring(timeStr.length - 8).chunked(2).reversed().joinToString("")
val respCmd = "${HEADER}0B02${time}$FOOTER"
log("${LOG_PREFIX}[对时]${cmdFlag}指令:${data},发送应答指令:${respCmd}")
sendCmd(respCmd)
}
"0E01" -> {
//终端位置上报
val respCmd = "${HEADER}0E0200$FOOTER"
log("${LOG_PREFIX}[终端位置上报]${cmdFlag}指令:${data},发送应答指令:${respCmd}")
sendCmd(respCmd)
}
"1001" -> {
//温控信息上报
val respCmd = "${HEADER}100200$FOOTER"
val logMsg =
"${LOG_PREFIX}[温控信息上报]${cmdFlag}指令:${data},发送应答指令:${respCmd}"
log(logMsg)
sendCmd(respCmd)
//val tempC = HexUtils.signedHexToDec(data.take(4)) * 0.1
// updateLeftStatus("$deviceName ${"%.1f".format(tempC)}°C / -%")
// updateLeftStatus("$deviceName -°C / -%")
updateLeftStatus("$deviceName")
//D6DADEDB1001015D020000000027001E00020000001E001C00B40000000000010000000100040000001900440003000F00000000000FFFE6000200010002FFD80044000300010005001E0001FFD80056001400280000000000000000008300090000003C00D2000000000000007F003700000000A100000031323136334238423134303233303456322E313100FFFF
runOnUiThread {
if (tipDialog == null) {
CommonDialog(this).apply {
dialogTitle = "温馨提示"
// dialogContent = logMsg
confirmBlock = {
logMsg?.copyTextToClipboard(this@HomeActivity)
}
}
}
if (tipDialog?.isShowing == false) {
tipDialog?.dialogContent = logMsg
tipDialog?.show()
}
}
}
"1002" -> {
log("${LOG_PREFIX}[温控信息应答]1002数据:${data}")
}
"0F02" -> {
log("${LOG_PREFIX}[温控信息应答]0F02数据:${data}")
//D6DADEDB0F020331323136334238423134303233303456322E31313EFFFF00000055010000000000002707000001000000220100000000000091040000120100000100000095140080611400800000000000000000000000000000000000000000010100005031323136334238423134303233303456322E31313EFFFF
runOnUiThread { }
}
else -> {}
}
}
private var tipDialog: CommonDialog? = null
private var fixedDataBody = ""
// private fun lockFeedback(data: String) {
// runCatching {
// val fixedDataBodyEndIndex = data.length - FOOTER.length
// val fixedDataBodyStartIndex = HEADER.length + "0202".length + 42
// fixedDataBody = data.substring(fixedDataBodyStartIndex, fixedDataBodyEndIndex)
//
// val lockNo = if (list[shelfIndex].deviceNo in 1..5) "01" else "02"
// val lockOneState = data.substring(HEADER.length + 4, HEADER.length + 6)
// if (lockOneState == "00") {
// //锁1关
// SerialPortManager.send("${HEADER}0202${lockNo}${FOOTER}")
// }
// val lockTwoState = data.substring(HEADER.length + 6, HEADER.length + 8)
// if (lockTwoState == "00") {
// //锁2关
// SerialPortManager.send("${HEADER}0202${lockNo}${FOOTER}")
// }
// }.onFailure {
// it.printStackTrace()
// }
// }
private fun heartBeat(data: String) {
runCatching {
if (data.length < 200) {
return
}
val weightStartIndex = 14
val weightEndIndex = weightStartIndex + 12 * 8
getWeightInfo(
start = weightStartIndex,
end = weightEndIndex,
data = data
)
val temperatureStartIndex = 158
val temperatureEndIndex = temperatureStartIndex + 2
// val temperatureHex = data.substring(temperatureStartIndex, temperatureEndIndex)
// val temperature = hexToDec(temperatureHex)
// val tempC = f2C(temperature.toDouble())
// showTemperatureC = "%.1f".format(tempC)
//val percent = 10 * list.count { it.goodsName.isNullOrBlank().not() }
// updateLeftStatus("${deviceName} [$temperatureHex] ${showTemperatureC}°C / -%")
getFixDataBody(data, temperatureEndIndex)
}.onFailure {
it.printStackTrace()
}
}
private var deviceName = ""
private fun getWeightInfo(start: Int, end: Int, data: String) {
var index = 1
var count = start
while (count < end) {
val weightInfo = data.substring(count, count + 8)
var weightHex = ""
weightInfo.run {
weightHex =
substring(6, 8) + substring(4, 6) + substring(2, 4) + substring(0, 2)
}
var realWeight = 0
var firstByteBinary = hexToBinary(weightHex.substring(0, 2))
if (firstByteBinary.startsWith("0")) {
//正数
realWeight = weightHex.toInt()
} else {
//负数
firstByteBinary = "0${firstByteBinary.substring(1)}"
val firstByteHex = binaryToHex(firstByteBinary)
weightHex = firstByteHex + weightHex.substring(2)
realWeight = -1 * weightHex.toInt()
}
weightArray.put(index, realWeight)
if (index in 1..10 && list.size == 10) {
list.firstOrNull { it.deviceNo == index }?.let {
it.weight = realWeight.toDouble()
val pos = list.indexOf(it)
shelfAdapter.notifyItemChanged(pos)
log("getWeightInfo: deviceNo=${it.deviceNo},realWeight=${realWeight}")
EventBus.getDefault().post(SendWeightEvent(it.deviceNo, realWeight))
}
// val pos = index - 1
// val item = list[pos]
// item.weight = realWeight.toDouble()
// shelfAdapter.notifyItemChanged(pos)
// log("getWeightInfo: deviceNo=${item.deviceNo},realWeight=${realWeight}")
// EventBus.getDefault().post(SendWeightEvent(item.deviceNo, realWeight))
}
count += 8
index++
}
// ShelfActivity.updateWeight(getRealWeight())
// if (list.isNotEmpty()) {
// val intent = Intent(ShelfActivity.RECEIVER_DEVICE_INFO + list[shelfIndex].deviceNo)
// intent.putExtra(ShelfActivity.SHELF_WEIGHT, weightArray[shelfIndex])
// LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
// }
}
private fun getDeviceInfo(data: String) {
log("getDeviceInfo: data=$data")
val weightStartIndex = HEADER.length + 14
val temperatureStartIndex = weightStartIndex + 12 * 8
val temperatureEndIndex = temperatureStartIndex + 2
val temperatureHex = try {
data.substring(temperatureStartIndex, temperatureEndIndex)
} catch (e: Exception) {
e.printStackTrace()
return
}
// val temperature = hexToDec(temperatureHex)
// val tempC = f2C(temperature.toDouble())
// showTemperatureC = "%.1f".format(tempC)
//val percent = 10 * list.count { it.goodsName.isNullOrBlank().not() }
// updateLeftStatus("${deviceName} ${showTemperatureC}°C / -%")
// val tempC = HexUtils.signedHexToDec(temperatureHex) * 0.1
// updateLeftStatus("$deviceName -°C / -%")
updateLeftStatus("$deviceName")
getWeightInfo(
start = weightStartIndex,
end = temperatureStartIndex,
data = data
)
getFixDataBody(data, temperatureEndIndex)
}
fun getFixDataBody(data: String, temperatureEndIndex: Int) {
try {
if (terminalId.isNotBlank() && terminalVersion.isNotBlank()) {
return
}
val fixDataBodyStartIndex = temperatureEndIndex + 1
val fixDataBody = data.substring(fixDataBodyStartIndex, data.length - FOOTER.length)
if (fixDataBody.length == 42) {
terminalId = fixDataBody.substring(0, 30)
terminalVersion = fixDataBody.substring(30, 40)
log("receiveSerialPortData:从设备状态获取数据,终端id:${terminalId},固件版本:${terminalVersion}")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onDestroy() {
lifecycleScope.launch {
SerialPortManager.close()
}
// TaskManager.cancelTask()
saveTaskJob?.cancel()
overdueTaskJob?.cancel()
EventBus.getDefault().unregister(this)
super.onDestroy()
}
@Suppress("DEPRECATION")
private val shelfAdapter by lazy {
ShelfAdapter(list).apply {
setOnItemClickListener { _, _, position ->
shelfIndex = position
lifecycleScope.launch {
if (isNeedOpenLock) {
val openCmd = if (list[position].deviceNo in 1..5)
LEFT_SHELF_OPEN_CMD
else
RIGHT_SHELF_OPEN_CMD
val openState = SerialPortManager.send(openCmd)
}
// if (openState.not()) {
// toast("${list[position].goodsName}柜门开启失败")
// return@launch
// }
//SerialPortManager.send(START_CMD)
launch(Intent(this@HomeActivity, ShelfActivity::class.java).also {
it.putExtra(ShelfActivity.SHELF_MODEL, list[position])
}) {
it?.run {
val model =
getSerializableExtra(ShelfActivity.SHELF_MODEL) as ShelfModel
list[position].apply {
goodsId = model.goodsId
goodsName = model.goodsName
weight = model.weight
if (model.putCabinetDay.isNullOrBlank().not()) {
putCabinetDay = model.putCabinetDay
}
}
notifyItemChanged(position)
try {
val submitList = list.sortedBy { item -> item.deviceNo }
val body = ShelfBody().also { body ->
body.deviceId = App.deviceId ?: ""
body.canteenId = App.canteenId
body.temperature = showTemperatureC
body.humidity = showHumidity
body.goodsList = submitList
}
Log.d("mzf", "performSync: body:${body.toJsonString()}")
lifecycleScope.launch {
val resp = apiService.saveShelfGoodsList(body = body)
Log.d("mzf", "performSync: resp:${resp.toJsonString()}")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
}
}
}
private fun initRecyclerView() {
binding.rvShelf.run {
layoutManager =
GridLayoutManager(this@HomeActivity, 2, GridLayoutManager.VERTICAL, false)
adapter = shelfAdapter
itemAnimator.let {
if (it is DefaultItemAnimator) {
it.supportsChangeAnimations = false
}
}
}
}
private fun updateDateTime() {
val sdf = SimpleDateFormat(MM_DD_EEEE__HH_MM_SS, Locale.CHINA)
val dateTime = sdf.format(Date())
updateRightStatus(dateTime)
}
private val handler = Handler(Looper.getMainLooper())
private val updateTask = object : Runnable {
override fun run() {
updateDateTime()
handler.postDelayed(this, 1000)
}
}
override fun onResume() {
super.onResume()
hideStatusBar()
handler.post(updateTask)
// D6DADEDB00010031323136334238423134303233303456322E313100FFFF
// sendCmd("${HEADER}00010031323136334238423134303233303456322E313152${FOOTER}")
}
override fun onPause() {
super.onPause()
handler.removeCallbacks(updateTask)
}
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
list.clear()
shelfAdapter.notifyDataSetChanged()
binding.include?.let {
it.root.visible()
it.root.setOnClickListener {
//viewModel.getAccessToken(App.deviceId)
viewModel.getShelfList(deviceId = App.deviceId)
}
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_white)
it.tvEmptyContent.setTextColor(Color.WHITE)
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public fun weightEvent(event: WeightEvent) {
}
@Subscribe(threadMode = ThreadMode.MAIN)
public fun clearEmptyShelf(event: ClearShelfEvent) {
val item = list.firstOrNull { it.deviceNo == event.shelfNo }
item?.apply {
goodsId = ""
goodsName = null
weight = 0.0
weightBak = if (event.weight <= 0.0) 0.0 else -1 * event.weight.toDouble()
createTime = null
overdueDay = null
}
shelfAdapter.notifyItemChanged(list.indexOf(item))
}
private val taskExecutor by lazy { IntervalExecutor() }
private var saveTaskJob: Job?=null
/**
* 保存定时任务
*/
private fun saveGoodsTask() {
saveTaskJob = taskExecutor.startIntervalTaskWithInitialDelay(1 * 60 * 1000L, 5 * 60 * 1000L) {
saveShelfGoodsList()
}
}
private var overdueTaskJob: Job?=null
/**
* 过期时间定时任务
*/
private fun overdueTask() {
overdueTaskJob = taskExecutor.startIntervalTaskWithInitialDelay(5 * 1000L, 5 * 60* 1000L) {
updateOverdueState()
}
}
private fun updateOverdueState() {
viewModel.updateOverdueState { state, items ->
if (items.isNullOrEmpty()) return@updateOverdueState
list.forEachIndexed { index, model ->
//接口过期状态变化后更新状态
if (items[index].overdue != model.overdue) {
model.overdue = items[index].overdue
shelfAdapter.notifyItemChanged(index)
log("更新编号为${model.deviceNo}物品:${model.goodsName}的过期状态:${model.overdue}")
}
}
}
}
private fun saveShelfGoodsList() {
log("performSync: list:${list.toJsonString()}")
val submitList = list.sortedBy { it.deviceNo }
submitList.forEach {
if (it.goodsId.isNullOrBlank()) {
it.weight = it.weightBak
}
}
// submitList.forEach {
// it.temperature = HomeActivity.showTemperatureC
// it.humidity = HomeActivity.showHumidity
// }
val body = ShelfBody().also {
it.deviceId = App.deviceId
it.canteenId = App.canteenId
it.temperature = showTemperatureC
it.humidity = showHumidity
it.goodsList = submitList
}
log("performSync: body:${body.toJsonString()}")
viewModel.saveShelfGoodsList(body)
}
}
@@ -1,315 +0,0 @@
package com.shuwei.intelligent.shelves.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.KeyEvent
import android.view.animation.RotateAnimation
import androidx.activity.viewModels
import androidx.core.graphics.toColorInt
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityInitBinding
import com.shuwei.intelligent.shelves.model.DeviceConfigInfo
import com.shuwei.intelligent.shelves.net.NetViewModel
import com.shuwei.intelligent.shelves.net.UiState
import com.shuwei.intelligent.shelves.net.UrlConfig
import com.shuwei.intelligent.shelves.utils.AppUtil
import com.shuwei.intelligent.shelves.utils.NetworkUtils
import com.shuwei.intelligent.shelves.utils.QRCodeUtil
import com.shuwei.intelligent.shelves.utils.SpTool
import com.shuwei.intelligent.shelves.utils.ext.dp
import com.shuwei.intelligent.shelves.utils.ext.invisible
import com.shuwei.intelligent.shelves.utils.ext.startActivity
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
import com.shuwei.intelligent.shelves.utils.ext.toObject
import com.shuwei.intelligent.shelves.utils.ext.toast
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlin.collections.forEach
import kotlin.getValue
import kotlin.ranges.downTo
import kotlin.text.isBlank
class InitActivity : BaseActivity() {
companion object {
const val TAG = "InitActivity"
}
private lateinit var binding: ActivityInitBinding
private val viewModel: NetViewModel by viewModels()
private val handler = Handler(Looper.getMainLooper())
private var startTime = 0L // 倒计时开始时间
private var lastNetworkCheckTime = 0L // 上次检测网络的时间
@SuppressLint("HardwareIds")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityInitBinding.inflate(layoutInflater)
setContentView(binding.root)
App.deviceId = AppUtil.getUDID( this)
// App.deviceId = "4787e213-90ab-3e32-88e0-ac271a937751"
Log.d(TAG, "onCreate: deviceId = ${App.deviceId}")
SpTool.put(SpTool.DEVICE_ID, App.deviceId)
App.configUrl = UrlConfig.BASE_URL
App.canteenId = "0"
// var deviceId = AppUtil.getUDID(this)
// Log.d(TAG, "onCreate: deviceId=$deviceId")
//// deviceId = "39a7abdd06b3c7ab"
//// deviceId = "3ea47dc0-3cf0-3c2f-909c-265a9a65572e"
// App.deviceId = deviceId
//
// SpTool.put(SpTool.DEVICE_ID, deviceId)
// val deviceConfigCache = SpTool.getString(SpTool.DEVICE_CONFIG_CACHE)
// val checkResult = checkConfigData(deviceConfigCache)
// if (checkResult.not()) {
// binding.ivQrCode.visible()
// binding.btnInit.visible()
// //进行初始化操作
// initConfig()
// return
// }
binding.ivQrCode.invisible()
binding.btnInit.invisible()
// countDown()
initViews()
}
private fun countDown() {
lifecycleScope.launch {
flow {
(2 downTo 1).forEach {
delay(1000)
emit(it)
}
}.collect {
// 倒计时结束执行跳转
if (it == 1) {
startActivity<HomeActivity>()
finish()
}
}
}
}
private fun initConfig() {
binding.ivQrCode.setImageBitmap(
QRCodeUtil.generateQRCode(
content = App.deviceId,
size = 200.dp
)
)
binding.btnInit.setOnClickListener {
viewModel.getDeviceToken(App.deviceId)
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
launch {
viewModel.getDeviceTokenUiState.collect { state ->
when (state) {
is UiState.Loading -> {}
is UiState.Success<*> -> {
state.data.data?.let { deviceToken ->
Log.d(TAG, "initConfig: $deviceToken")
viewModel.getDeviceConfig(
deviceId = App.deviceId,
deviceToken = deviceToken.toString()
)
}
}
is UiState.Error -> toast(state.msg)
else -> {}
}
}
}
launch {
viewModel.getDeviceConfigUiState.collect { state ->
when (state) {
is UiState.Loading -> {}
is UiState.Success<*> -> {
state.data.data?.let {
if (it is DeviceConfigInfo) {
SpTool.put(SpTool.DEVICE_CONFIG_CACHE, it.toJsonString())
App.configUrl = it.appPackageUrl?:""
App.canteenId = it.canteenId?:""
startActivity<HomeActivity>()
finish()
}
}
}
is UiState.Error -> toast(message = state.msg)
else -> {}
}
}
}
}
}
}
private fun checkConfigData(data: String): Boolean {
if (data.isBlank()) {
return false
}
val config = data.toObject<DeviceConfigInfo?>()
if (config == null) {
return false
}
App.configUrl = config.appPackageUrl?:""
App.canteenId = config.canteenId?:""
return true
}
/**
* 初始化控件事件
*/
private fun initViews() {
// 连接网络按钮点击事件
binding.btnConnectNetwork.setOnClickListener {
openNetworkSettings()
}
// 启动加载动画 - 持续旋转
startLoadingAnimation()
}
/**
* 启动加载动画 - ImageView 持续旋转
*/
private fun startLoadingAnimation() {
val rotateAnimation = RotateAnimation(
0f, 360f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f
).apply {
duration = 1200 // 旋转周期 1.2 秒
repeatCount = RotateAnimation.INFINITE // 无限循环
repeatMode = RotateAnimation.RESTART
}
binding.ivLoading.startAnimation(rotateAnimation)
}
override fun onResume() {
super.onResume()
if (NetworkUtils.isNetworkConnected(this)) {
navigateToHome()
return
}
startCountdown()
}
override fun onPause() {
super.onPause()
// 页面不可见时停止倒计时
handler.removeCallbacksAndMessages(null)
}
/**
* 启动 60 秒倒计时
*/
private fun startCountdown() {
startTime = SystemClock.elapsedRealtime()
lastNetworkCheckTime = 0
binding.llNetwork.setBackgroundColor(Color.TRANSPARENT)
binding.llLoading.visibility = android.view.View.VISIBLE
binding.llNetworkButton.visibility = android.view.View.GONE
binding.tvCountdown.text = "60秒"
scheduleCountdown()
}
/**
* 定时更新倒计时
* 使用 SystemClock.elapsedRealtime() 确保精确计时
*/
private fun scheduleCountdown() {
handler.postDelayed({
val elapsedTime = SystemClock.elapsedRealtime() - startTime
val remainingTime = 60 - (elapsedTime / 1000).toInt()
val currentNetworkCheckTime = (elapsedTime / 1000).toInt()
// 每 10 秒检测一次网络
if (currentNetworkCheckTime > 0 && currentNetworkCheckTime % 10 == 0 && currentNetworkCheckTime != lastNetworkCheckTime.toInt()) {
lastNetworkCheckTime = currentNetworkCheckTime.toLong()
checkNetworkConnection()
}
// 倒计时未结束,继续更新 UI
if (remainingTime > 0) {
binding.tvCountdown.text = "${remainingTime}"
scheduleCountdown()
} else {
// 倒计时结束,最后检测一次网络
if (NetworkUtils.isNetworkConnected(this)) {
navigateToHome()
} else {
// 网络未连接,显示"连接网络"按钮
showNetworkButton()
}
}
}, 100) // 每 100ms 检查一次,确保精确性
}
/**
* 检测网络连接
*/
private fun checkNetworkConnection() {
if (NetworkUtils.isNetworkConnected(this)) {
// 网络连接成功,停止倒计时并跳转到 HomeActivity
handler.removeCallbacksAndMessages(null)
navigateToHome()
}
}
/**
* 跳转到 HomeActivity
*/
private fun navigateToHome() {
startActivity<HomeActivity>()
finish()
}
/**
* 显示"连接网络"按钮
*/
private fun showNetworkButton() {
binding.llNetwork.setBackgroundColor("#5C77F7".toColorInt())
binding.llLoading.visibility = android.view.View.GONE
binding.llNetworkButton.visibility = android.view.View.VISIBLE
}
/**
* 打开系统网络设置页面
*/
private fun openNetworkSettings() {
val intent = Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)
startActivity(intent)
}
/**
* 禁用返回键
*/
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
return if (keyCode == KeyEvent.KEYCODE_BACK) {
// 禁用返回键,不执行任何操作
true
} else {
super.onKeyDown(keyCode, event)
}
}
}
@@ -1,28 +1,53 @@
package com.shuwei.intelligent.shelves.activity
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import com.shuwei.intelligent.shelves.adapter.LogAdapter
import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityLogListBinding
import com.shuwei.intelligent.shelves.dialog.CommonDialog
import com.shuwei.intelligent.shelves.utils.ext.copyTextToClipboard
import com.shuwei.intelligent.shelves.utils.ext.dp
import com.shuwei.intelligent.shelves.utils.ext.gone
import com.shuwei.intelligent.shelves.utils.ext.startActivity
import com.shuwei.intelligent.shelves.utils.ext.toast
import com.shuwei.intelligent.shelves.serial.ProtocolConstants
import com.shuwei.intelligent.shelves.utils.ext.visible
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class LogActivity : BaseActivity() {
companion object {
const val IS_LOG_DIR = "isLogDir"
const val LOG_DATE = "logDate"
const val YYYY_MM_DD__EEEE_HH_MM_SS = "yyyy年MM月dd日 EEEE***HH:mm:ss"
}
/**
* 覆写时钟回调:左侧状态栏显示年月日星期,右侧状态栏显示时分秒
*/
override fun onClockTick() {
val sdf = SimpleDateFormat(YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
val arr = sdf.format(Date()).split("***")
updateLeftStatus(arr[0])
updateRightStatus(arr[1])
}
private lateinit var binding:ActivityLogListBinding
private var isLogDir = false
private var logDate = ""
private val logList = mutableListOf<String>()
private val originalLogList = mutableListOf<String>() // 原始日志备份
private val logAdapter by lazy {
LogAdapter(logList).apply {
setOnItemClickListener { _, _, position ->
@@ -62,24 +87,20 @@ class LogActivity : BaseActivity() {
logAdapter.notifyDataSetChanged()
}
if (isLogDir) {
logList.addAll(fileLogger.getLogFiles())
} else {
logList.addAll(fileLogger.readLogsByName(logDate))
}
binding.rvLogList.let {
it.layoutManager = LinearLayoutManager(this)
it.adapter = logAdapter
}
setupSearch()
setupJumpButton()
binding.btnFind.run {
if (isLogDir) gone() else visible()
}
binding.btnFind.setOnClickListener {
if (isLogDir) {
return@setOnClickListener
}
val list = logList.filter { it.contains("${HomeActivity.HEADER}1001") }
if (isLogDir) return@setOnClickListener
val list = logList.filter { it.contains("${ProtocolConstants.HEADER}${ProtocolConstants.CMD_TEMP_REPORT}") }
if (list.isEmpty()) {
toast("未找到到1001指令")
return@setOnClickListener
@@ -88,6 +109,95 @@ class LogActivity : BaseActivity() {
logList.addAll(list)
logAdapter.notifyDataSetChanged()
}
// 后台加载日志数据
lifecycleScope.launch {
binding.progressBar.visible()
val data = withContext(Dispatchers.IO) {
if (isLogDir) fileLogger.getLogFiles()
else fileLogger.readLogsByName(logDate)
}
logList.addAll(data)
originalLogList.addAll(data)
logAdapter.notifyDataSetChanged()
binding.progressBar.gone()
setupTimeNavigation()
}
}
// 搜索功能
private fun setupSearch() {
binding.etSearch.addTextChangedListener(afterTextChanged = { s ->
val keyword = s?.toString() ?: ""
logList.clear()
logList.addAll(if (keyword.isEmpty()) originalLogList else originalLogList.filter { it.contains(keyword, ignoreCase = true) })
logAdapter.notifyDataSetChanged()
})
}
// 快速跳转功能
private fun setupJumpButton() {
var isAtTop = true
binding.fabJump.setOnClickListener {
if (isAtTop) {
binding.rvLogList.scrollToPosition(logList.size - 1)
} else {
binding.rvLogList.scrollToPosition(0)
}
isAtTop = !isAtTop
}
}
// 时间导航功能
private fun setupTimeNavigation() {
if (isLogDir) {
binding.hsvTimeNav.gone()
return
}
val timeMap = mutableMapOf<String, Int>()
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
originalLogList.forEachIndexed { index, log ->
val timeStr = log.substringAfter("[").substringBefore("]")
try {
val date = dateFormat.parse(timeStr)
date?.let {
val hourKey = SimpleDateFormat("HH:00", Locale.getDefault()).format(it)
if (!timeMap.containsKey(hourKey)) {
timeMap[hourKey] = index
}
}
} catch (e: Exception) {
// 忽略解析失败的日志
}
}
if (timeMap.isEmpty()) {
binding.hsvTimeNav.gone()
return
}
timeMap.toSortedMap().forEach { (hour, position) ->
val btn = TextView(this).apply {
text = hour
textSize = 14f
setTextColor(Color.BLACK)
setPadding(12.dp, 8.dp, 12.dp, 8.dp)
gravity = Gravity.CENTER
setBackgroundColor(Color.parseColor("#E0E0E0"))
setOnClickListener {
binding.rvLogList.scrollToPosition(position)
}
}
val params = android.widget.LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
android.widget.LinearLayout.LayoutParams.MATCH_PARENT
).apply {
marginEnd = 8.dp
}
binding.llTimeNav.addView(btn, params)
}
}
}
@@ -1,66 +0,0 @@
//package com.shuwei.intelligent.shelves.activity
//
//import android.os.Bundle
//import android.os.Handler
//import android.os.Looper
//import com.shuwei.intelligent.shelves.base.BaseActivity
//import com.shuwei.intelligent.shelves.databinding.ActivitySettingBinding
//import com.shuwei.intelligent.shelves.utils.KeyboardUtil
//import java.text.SimpleDateFormat
//import java.util.Date
//import java.util.Locale
//
//class SettingActivity: BaseActivity() {
//
// private lateinit var binding: ActivitySettingBinding
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// binding = ActivitySettingBinding.inflate(layoutInflater)
// setBackground()
// setContentView(binding.root)
// binding.btnSendCmd.setOnClickListener{
// val cmd = binding.etInputCmd.text.toString().trim()
// if (cmd.isBlank()) {
// return@setOnClickListener
// }
// var record = binding.tvCmdRecord.text.toString().trim()
// record = cmd+"\n"+record
// binding.tvCmdRecord.text = record
// val realCmd = "${HomeActivity.HEADER}0F01${cmd}${HomeActivity.FOOTER}"
// sendCmd(realCmd)
// }
// binding.ivBack.setOnClickListener { finish() }
// binding.root.setOnClickListener { v ->
// KeyboardUtil.hideKeyboard(v)
// }
// }
//
//
// private fun updateDateTime() {
// val sdf = SimpleDateFormat(ShelfActivity.YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
// val dateTime = sdf.format(Date())
// val arr = dateTime.split("***")
// updateLeftStatus(arr[0])
// updateRightStatus(arr[1])
// }
//
// private val handler = Handler(Looper.getMainLooper())
// private val updateTask = object : Runnable {
// override fun run() {
// updateDateTime()
// handler.postDelayed(this, 1000)
// }
// }
//
// override fun onResume() {
// super.onResume()
// hideStatusBar()
// handler.post(updateTask)
// }
//
// override fun onPause() {
// super.onPause()
// handler.removeCallbacks(updateTask)
// }
//
//}
@@ -1,392 +0,0 @@
package com.shuwei.intelligent.shelves.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.core.view.updateLayoutParams
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter4.util.setOnDebouncedItemClick
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.activity.HomeActivity.Companion.DEVICE_INFO_CMD
import com.shuwei.intelligent.shelves.adapter.SearchAdapter
import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityShelfBinding
import com.shuwei.intelligent.shelves.model.ClearShelfEvent
import com.shuwei.intelligent.shelves.model.GoodsModel
import com.shuwei.intelligent.shelves.model.SendWeightEvent
import com.shuwei.intelligent.shelves.model.ShelfModel
import com.shuwei.intelligent.shelves.net.Loading
import com.shuwei.intelligent.shelves.net.NetViewModel
import com.shuwei.intelligent.shelves.net.RespData
import com.shuwei.intelligent.shelves.net.UiState
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
import com.shuwei.intelligent.shelves.utils.KeyboardUtil
import com.shuwei.intelligent.shelves.utils.ext.addOnActionSearchListener
import com.shuwei.intelligent.shelves.utils.ext.clickWithDebounce
import com.shuwei.intelligent.shelves.utils.ext.dp
import com.shuwei.intelligent.shelves.utils.ext.gone
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
import com.shuwei.intelligent.shelves.utils.ext.toast
import com.shuwei.intelligent.shelves.utils.ext.visible
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@SuppressLint("NotifyDataSetChanged")
class ShelfActivity : BaseActivity() {
companion object {
private const val TAG = "ShelfActivity"
const val YYYY_MM_DD__EEEE_HH_MM_SS = "yyyy年MM月dd日 EEEE***HH:mm:ss"
const val SHELF_MODEL = "shelfModel"
const val RECEIVER_DEVICE_INFO = "receiverDeviceInfo"
const val SHELF_WEIGHT = "shelfWeight"
const val SHELF_INDEX = "shelfIndex"
const val PAGE_SIZE = 100
}
private lateinit var binding: ActivityShelfBinding
private var shelfModel: ShelfModel? = null
private var clickIndex: Int = -1
private var realWeight: Int = 0
private var pageNo: Int = 1
private val viewModel: NetViewModel by viewModels()
@SuppressLint("UnspecifiedRegisterReceiverFlag")
@Suppress("DEPRECATION")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityShelfBinding.inflate(layoutInflater)
setBackground()
setContentView(binding.root)
EventBus.getDefault().register(this)
// tvFoodWeight =binding.tvFoodWeight
shelfModel = intent.getSerializableExtra(SHELF_MODEL) as ShelfModel?
shelfModel?.let {
binding.tvShelfName.text = it.shelfName
binding.tvFoodName.text = if (it.goodsName.isNullOrBlank()) "-" else it.goodsName
realWeight = it.weight?.toInt()?:0
binding.tvFoodWeight.text = if(realWeight < 1000) "${realWeight}" else "%.3f千克".format(realWeight/1000.0)
startTime = System.currentTimeMillis()
}
initRecyclerView()
binding.etInputFood.run {
addOnActionSearchListener {
if (text.isNullOrBlank()) {
toast(hint.toString())
return@addOnActionSearchListener
}
pageNo = 1
getGoodsList()
KeyboardUtil.hideKeyboard(context, this)
}
addTextChangedListener(afterTextChanged = { editable ->
if (editable.isNullOrBlank()) {
pageNo = 1
getGoodsList()
}
})
}
binding.btnConfirm.clickWithDebounce {
if (clickIndex < 0) {
toast("请选择食材")
return@clickWithDebounce
}
val currentGoodsId = list[clickIndex].goodsId ?: ""
val data = ShelfModel(
shelfName = shelfModel?.shelfName,
goodsId = currentGoodsId,
goodsName = list[clickIndex].goodsName,
weight = realWeight.toDouble(),
overdueDay = list[clickIndex].overdueDay,
// createTime = if (shelfModel?.goodsId == currentGoodsId) null else DateTimeUtil.formatDateTime(dateTime = Date())
putCabinetDay = DateTimeUtil.formatDateTime(dateTime = Date())
)
val intent = Intent().apply {
putExtra(SHELF_MODEL, data)
}
setResult(RESULT_OK, intent)
finish()
}
binding.root.setOnClickListener { v ->
KeyboardUtil.hideKeyboard(v)
}
binding.btnClearZero.setOnClickListener {
clearZero()
}
binding.btnClearEmpty.setOnClickListener {
val tempWeight = shelfModel?.weight?.toInt()?:0
clearZero()
binding.tvFoodName.text = "-"
//binding.tvFoodWeight.text = "0克"
EventBus.getDefault().post(ClearShelfEvent(shelfModel!!.deviceNo, tempWeight))
}
sendCmd(DEVICE_INFO_CMD)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.getGoodsListUiState.collect { state ->
when (state) {
is UiState.Loading -> showProgress()
is UiState.Success<*> -> updateUI(state.data)
is UiState.Error -> showError(state.msg)
else -> {}
}
}
}
}
// registerReceiver(receiver, IntentFilter(RECEIVER_DEVICE_INFO + shelfModel?.deviceNo))
binding.ivBack?.setOnClickListener { finish() }
binding.refreshLayout.let {
it.setEnableRefresh(true)
it.setEnableLoadMore(false)
it.setOnRefreshListener {
pageNo = 1
getGoodsList()
}
it.setOnLoadMoreListener { getGoodsList() }
}
getGoodsList()
// TaskManager.startDeviceTask()
}
private fun finishRefresh() {
binding.refreshLayout.let {
if (it.state == RefreshState.Refreshing) {
it.finishRefresh(500)
} else if (binding.refreshLayout.state == RefreshState.Loading) {
it.finishLoadMore(500)
} else {
}
}
}
private fun getGoodsList() {
viewModel.getGoodsList(
canteenId = App.canteenId,
goodsName = binding.etInputFood.text.trim().toString(),
pageNo = pageNo,
pageSize = PAGE_SIZE
)
}
private fun showProgress() {
Loading.show(this)
}
@SuppressLint("NotifyDataSetChanged")
private fun updateUI(data: RespData<*>) {
binding.include?.root?.gone()
finishRefresh()
binding.root.postDelayed({ Loading.dismiss() }, 200)
Log.d(TAG, "updateUI: ${data.toJsonString()}")
val goodsList = data.data as MutableList<GoodsModel>
if (data.data.isNullOrEmpty()) {
if (pageNo == 1) {
loadEmptyView()
}
return
}
if(pageNo == 1){
list.clear()
}
// var firstOne:GoodsModel?=null
// if (pageNo == 1) {
// if (shelfModel?.goodsId.isNullOrBlank().not()) {
// firstOne = list.firstOrNull { it.goodsId == shelfModel?.goodsId }
// if (firstOne == null) {
// firstOne = GoodsModel(
// goodsId = shelfModel?.goodsId,
// goodsName = shelfModel?.goodsName,
// isClicked = true
// )
// }
// }
// list.clear()
// }
// val records = data.data.records
// if (pageNo == 1) {
// firstOne?.let { one ->
// val filterResult = records.firstOrNull{one.goodsId == it.goodsId }
// if (filterResult != null) {
// records.remove(filterResult)
// }
// clickIndex = 0
// list.add(one)
// }
// }
list.addAll(goodsList)
val enableLoadMore = goodsList.size >= PAGE_SIZE
binding.refreshLayout.setEnableLoadMore(enableLoadMore)
if (enableLoadMore) {
pageNo++
}
searchAdapter.notifyDataSetChanged()
}
private fun showError(message: String) {
finishRefresh()
Loading.dismiss()
toast(message)
if (pageNo == 1) {
loadEmptyView()
}
}
// private val receiver = object : BroadcastReceiver() {
// override fun onReceive(context: Context?, intent: Intent?) {
// intent?.let {
// if (it.action == RECEIVER_DEVICE_INFO + shelfModel?.deviceNo) {
// val weight = it.getDoubleExtra(SHELF_WEIGHT, 0.0)
// Log.d(TAG, "getDeviceInfo:onReceive: weight=$weight")
// realWeight = (weight * 1000).toInt()
// binding.tvFoodWeight.text = "${realWeight}克"
// }
// }
// }
// }
override fun onDestroy() {
// unregisterReceiver(receiver)
EventBus.getDefault().unregister(this)
// TaskManager.cancelDeviceTask()
super.onDestroy()
}
private val list: MutableList<GoodsModel> = mutableListOf()
private val searchAdapter by lazy {
SearchAdapter(list).apply {
setOnDebouncedItemClick { adapter, v, position ->
this@ShelfActivity.clickIndex = position
list.forEach { it.isClicked = false }
list[position].isClicked = true
notifyDataSetChanged()
binding.tvFoodName.text = list[position].goodsName
KeyboardUtil.hideKeyboard(v.context, v)
}
}
}
private fun initRecyclerView() {
binding.rvSearch.run {
layoutManager = GridLayoutManager(this@ShelfActivity, 2)
adapter = searchAdapter
}
}
private fun updateDateTime() {
val sdf = SimpleDateFormat(YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
val dateTime = sdf.format(Date())
val arr = dateTime.split("***")
updateLeftStatus(arr[0])
updateRightStatus(arr[1])
}
private val handler = Handler(Looper.getMainLooper())
private val updateTask = object : Runnable {
override fun run() {
updateDateTime()
handler.postDelayed(this, 1000)
}
}
override fun onResume() {
super.onResume()
hideStatusBar()
handler.post(updateTask)
}
override fun onPause() {
super.onPause()
handler.removeCallbacks(updateTask)
}
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
list.clear()
searchAdapter.notifyDataSetChanged()
binding.include?.let {
it.root.visible()
it.root.setOnClickListener {
pageNo = 1
getGoodsList()
}
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_gray)
it.ivEmptyIcon.updateLayoutParams<LinearLayout.LayoutParams> {
val swDpValue = resources?.configuration?.smallestScreenWidthDp ?: 0
width = if (swDpValue > 600) 200.dp else 120.dp
}
}
binding.refreshLayout.run {
setEnableRefresh(false)
setEnableLoadMore(false)
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public fun receiveWeightEvent(event: SendWeightEvent) {
if (event.shelfNo == (shelfModel?.deviceNo ?: 0)) {
val intervalTime = System.currentTimeMillis() - startTime
val weight = event.weight
log("编号${event.shelfNo}货架获取重量成功:${weight}克,数据获取间隔时间为:${intervalTime}")
binding.tvFoodWeight.text = if(weight < 1000) "${weight}" else "%.3f千克".format(weight/1000.0)
startTime = System.currentTimeMillis()
window.decorView.postDelayed({ Loading.dismiss() }, 1000)
}
}
private fun clearZero() {
lifecycleScope.launch {
val shelfNo = shelfModel?.deviceNo ?: 0
val hex = shelfNo.toString(16).padStart(2, '0').uppercase()
Log.d(TAG, "onCreate: hex=$hex")
val zeroClearingCmd = "${HomeActivity.HEADER}0401${hex}${HomeActivity.FOOTER}"
log("编号${shelfNo}货架执行清零指令:${zeroClearingCmd}")
sendCmd(zeroClearingCmd)
sendCmd(
if (shelfNo in 1..5) HomeActivity.LEFT_SHELF_OPEN_CMD else HomeActivity.RIGHT_SHELF_OPEN_CMD
)
//清零
realWeight = 0
// binding.tvFoodWeight.text = "${realWeight}克"
sendCmd(DEVICE_INFO_CMD)
startTime = System.currentTimeMillis()
Loading.show(this@ShelfActivity)
// window.decorView.postDelayed({ Loading.dismiss() }, 5000)
}
KeyboardUtil.hideKeyboard(window.decorView)
}
private var startTime = 0L
}
@@ -1,50 +0,0 @@
package com.shuwei.intelligent.shelves.adapter
import android.content.Context
import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.databinding.ListItemSearchBinding
import com.shuwei.intelligent.shelves.model.GoodsModel
class SearchAdapter(list: MutableList<GoodsModel>) :
BaseQuickAdapter<GoodsModel, SearchAdapter.VH>(list) {
inner class VH(var binding: ListItemSearchBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemSearchBinding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: GoodsModel?) {
val binding = holder.binding
binding.btnFoodName.run {
text = " ${item!!.goodsName}"
setTextColor(
getColor(if (item.isClicked) R.color.shelf_name_blue else R.color.black999)
)
val btnStrokeColor = if (item.isClicked) "#4969F5" else "#E6E6E6"
strokeColor = ColorStateList.valueOf(btnStrokeColor.toColorInt())
}
// val bgDrawable = createCustomDrawable(
// solidColor = "#FFFFFF",
// strokeWidth = 2.dp,
// strokeColor = if (item!!.isClicked) "#4969F5" else "#E6E6E6",
// radius = 12.dp
// )
// binding.root.background = bgDrawable
}
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
}
@@ -1,117 +0,0 @@
package com.shuwei.intelligent.shelves.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.databinding.ListItemShelfBinding
import com.shuwei.intelligent.shelves.model.ShelfModel
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
import com.shuwei.intelligent.shelves.utils.ext.gone
import com.shuwei.intelligent.shelves.utils.ext.visible
import java.util.Date
import kotlin.math.abs
class ShelfAdapter(list: MutableList<ShelfModel>) :
BaseQuickAdapter<ShelfModel, ShelfAdapter.VH>(list) {
inner class VH(var binding: ListItemShelfBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemShelfBinding.inflate(inflater, parent, false)
return VH(binding)
}
private fun stringToDate(createTime: String?): Date? {
if (createTime.isNullOrBlank()) {
return null
}
return DateTimeUtil.stringToDate(createTime)
}
override fun onBindViewHolder(holder: VH, position: Int, item: ShelfModel?) {
val shelfNo = item!!.deviceNo
//货架-
item.shelfName = "${if (shelfNo < 10) "0${shelfNo}" else "$shelfNo"}"
val weight = item.weight ?: 0.0
val binding = holder.binding
if (item.overdueDay.isNullOrBlank()) {
binding.ivStaleFood.gone()
} else {
runCatching {
// val shelfDate = stringToDate(item.putCabinetDay)
binding.ivStaleFood.run {
if (item.overdue == true) visible() else gone()
}
// if (shelfDate == null) {
// binding.ivStaleFood.gone()
// } else {
// val days = item.overdueDay!!.toInt()
// val resultDate = DateTimeUtil.addDays(shelfDate, days)
// if (resultDate.before(Date())) {
// binding.ivStaleFood.visible()
// } else {
// binding.ivStaleFood.gone()
// }
// }
}.onFailure {
binding.ivStaleFood.gone()
}
}
//?.setImageResource()
binding.tvFoodWeight.run {
setTextColor(getColor(R.color.food_weight_orange))
//val showWeight = if (weight == 0.toDouble()) "0克" else "%.3f千克".format(weight)
text = if(abs(weight) < 1000) "${weight.toInt()}" else "%.3f千克".format(weight/1000.0)
//"${(weight*1000).roundToInt()}克"
}
//val isBlankShelf = weight <= 0
val isBlankShelf = item.goodsName.isNullOrBlank()
if (isBlankShelf) {
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_blue))
binding.tvShelfName.run {
setTextColor(getColor(R.color.shelf_name_white))
text = item.shelfName
}
binding.tvFoodName.run {
setTextColor(getColor(R.color.white))
text = ""
}
// binding.tvFoodWeight.run {
// setTextColor(getColor(R.color.food_weight_blue))
// text = "0千克"
// }
binding.tvStoreDate.run {
setTextColor(getColor(R.color.food_weight_blue))
text = "-"
}
return
}
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_white))
binding.tvShelfName.run {
setTextColor(getColor(R.color.shelf_name_blue))
text = item.shelfName
}
binding.tvFoodName.run {
setTextColor(getColor(R.color.food_name_black))
text = item.goodsName
}
// binding.tvFoodWeight.run {
// setTextColor(getColor(R.color.food_weight_orange))
//// text = "${weight/1000F}千克"
// text = "${weight}克"
// }
binding.tvStoreDate.run {
setTextColor(getColor(R.color.black999))
text = item.putCabinetDay
}
}
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
}
@@ -5,26 +5,33 @@ import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.PopupWindow
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.shuwei.intelligent.shelves.activity.HomeActivity
import com.shuwei.intelligent.shelves.activity.HomeActivity.Companion.LIGHT_CLOSE
import com.shuwei.intelligent.shelves.activity.HomeActivity.Companion.LIGHT_OPEN
import com.shuwei.intelligent.shelves.activity.LogActivity
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.databinding.ActivityBaseBinding
import com.shuwei.intelligent.shelves.serial.SerialPortManager
import com.shuwei.intelligent.shelves.databinding.PopupRightStatusMenuBinding
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.LIGHT_CLOSE
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.LIGHT_OPEN
import com.shuwei.intelligent.shelves.serial.ScaleManager
import com.shuwei.intelligent.shelves.utils.FileLogger
import com.shuwei.intelligent.shelves.utils.ext.clickWithDebounce
import com.shuwei.intelligent.shelves.utils.ext.dp
import com.shuwei.intelligent.shelves.utils.ext.startActivity
import kotlinx.coroutines.launch
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.shuwei.intelligent.shelves.utils.ext.setOnDoubleClickListener
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@Suppress("DEPRECATION")
open class BaseActivity : AppCompatActivity() {
@@ -57,35 +64,28 @@ open class BaseActivity : AppCompatActivity() {
}
}
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// window.setDecorFitsSystemWindows(false)
// window.insetsController?.apply {
// hide(WindowInsets.Type.statusBars()) // 隐藏状态栏
// systemBarsBehavior =
// WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE // 滑动时临时显示
// }
// }
lightSwitchClick()
binding.tvLeftStatus.setOnDoubleClickListener {
finish()
//finish()
val intent = Intent(Intent.ACTION_MAIN).apply {
addCategory(Intent.CATEGORY_HOME)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
startActivity(intent)
}
binding.tvRightStatus.setOnDoubleClickListener {
if (enableRightStatusMenu) showRightStatusPopup(binding.tvRightStatus)
}
}
fun hideStatusBar() {
//// enableEdgeToEdge()
//// val uiOptions = (View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
//// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) // 隐藏导航栏(可选)
//// window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
//
// ImmersionBar.with(this)
// .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
// .init()
}
/** 是否允许右侧状态栏双击弹出菜单,默认关闭,仅 HomeActivity 开启 */
protected open val enableRightStatusMenu: Boolean = false
fun hideStatusBar() {}
fun statusBarDarkFont() {
//window.decorView.systemUiVisibility = if (enable) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
val color = ContextCompat.getColor(this, R.color.white)
binding.tvLeftStatus.setTextColor(color)
binding.tvRightStatus.setTextColor(color)
@@ -104,7 +104,7 @@ open class BaseActivity : AppCompatActivity() {
}
fun updateLeftStatus(data: String) {
binding.tvLeftStatus.text = data
binding.tvLeftStatus.text = data.ifBlank { " " }
}
fun updateRightStatus(data: String) {
@@ -112,14 +112,38 @@ open class BaseActivity : AppCompatActivity() {
}
// 5分钟
private val TIME_OUT: Long = (5 * 60 * 1000).toLong()
private val TIME_OUT: Long = (1 * 60 * 1000).toLong()
private val mHandler by lazy { Handler(Looper.getMainLooper()) }
private val mTimeoutRunnable = Runnable {
if (this is HomeActivity) {
this.switchLight(false)
// 用户长时间无操作时回调,子类可覆写实现具体逻辑(如关灯)
onUserInactive()
}
// ---- 右侧状态栏时钟 ----
// 默认时间格式:月日星期 时:分:秒
private val CLOCK_FORMAT = "MM月dd日 EEEE HH:mm:ss"
private val clockFormatter by lazy { SimpleDateFormat(CLOCK_FORMAT, Locale.CHINA) }
/**
* 每秒时钟回调,默认将当前时间显示在右侧状态栏。
* 子类可覆写以自定义格式或同时更新左侧状态栏。
*/
open fun onClockTick() {
updateRightStatus(clockFormatter.format(Date()))
}
private val clockTask = object : Runnable {
override fun run() {
onClockTick()
mHandler.postDelayed(this, 1000)
}
}
/**
* 用户超时无操作时回调,默认空实现,子类按需覆写
*/
open fun onUserInactive() {}
override fun onUserInteraction() {
super.onUserInteraction()
//开灯
@@ -136,14 +160,18 @@ open class BaseActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
// 启动定时器
// 启动超时定时器
mHandler.postDelayed(mTimeoutRunnable, TIME_OUT)
// 启动右侧状态栏时钟
mHandler.post(clockTask)
}
override fun onPause() {
super.onPause()
// 取消定时器
// 取消超时定时器
mHandler.removeCallbacks(mTimeoutRunnable)
// 停止右侧状态栏时钟
mHandler.removeCallbacks(clockTask)
}
fun switchLight(isOpen: Boolean) {
@@ -161,23 +189,33 @@ open class BaseActivity : AppCompatActivity() {
val tag = binding.tvLeftStatus.tag?.toString()?.toBoolean() ?: true
switchLight(tag.not())
}
binding.tvRightStatus.clickWithDebounce {
// if (this is HomeActivity) {
// startActivity<LogActivity> {
// putExtra(LogActivity.IS_LOG_DIR, true)
// }
// return@clickWithDebounce
// }
// startActivity<SettingActivity> { }
}
private fun showRightStatusPopup(anchor: View) {
val menuBinding = PopupRightStatusMenuBinding.inflate(LayoutInflater.from(this))
val popup = PopupWindow(
menuBinding.root,
120.dp,
101.dp,
true
)
menuBinding.tvEnvSwitch.setOnClickListener {
popup.dismiss()
EnvSwitchDialog(this).show()
}
menuBinding.tvLog.setOnClickListener {
popup.dismiss()
startActivity<LogActivity> {
putExtra(LogActivity.IS_LOG_DIR, true)
}
}
popup.showAsDropDown(anchor)
}
fun sendCmd(cmd:String) {
lifecycleScope.launch {
val result = SerialPortManager.send(cmd)
log("发送命令${cmd}结果:${result}")
}
fun sendCmd(cmd: String) {
ScaleManager.sendCmd(cmd)
log("发送命令: $cmd")
}
val fileLogger by lazy { FileLogger(this) }
@@ -0,0 +1,69 @@
package com.shuwei.intelligent.shelves.base
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.shuwei.intelligent.shelves.GlobalData
import com.shuwei.intelligent.shelves.databinding.DialogEnvSwitchBinding
import com.shuwei.intelligent.shelves.utils.SpTool
import com.shuwei.intelligent.shelves.utils.ToastUtil
import com.shuwei.intelligent.shelves.utils.ext.dp
/**
* 环境切换弹窗
*
* 提供 TEST / UAT / PROD 三套环境的切换功能,
* 初始化时自动根据 [GlobalData.appBaseUrl] 选中当前环境,
* 确认后更新 [GlobalData.appBaseUrl] 并通过 [onEnvChanged] 回调通知外部。
*
* @param context 上下文
* @param onEnvChanged 确认切换后的回调,参数为新的 baseUrl
*/
class EnvSwitchDialog(
context: Context,
private val onEnvChanged: (newBaseUrl: String) -> Unit = {}
) : BaseDialog(
context,
defWidth = 600.dp,
defHeight = WindowManager.LayoutParams.WRAP_CONTENT
) {
private lateinit var binding: DialogEnvSwitchBinding
override fun getRootView(): View {
binding = DialogEnvSwitchBinding.inflate(LayoutInflater.from(context))
return binding.root
}
override fun initView() {
// 根据当前 appBaseUrl 预选对应 RadioButton,不匹配则不选
when (GlobalData.appBaseUrl) {
GlobalData.LOCAL_BASE_URL -> binding.rbTest.isChecked = true
GlobalData.TEST_BASE_URL -> binding.rbUat.isChecked = true
GlobalData.PROD_BASE_URL -> binding.rbProd.isChecked = true
}
// 取消按钮
binding.btnCancel.setOnClickListener { dismiss() }
// 确认按钮
binding.btnConfirm.setOnClickListener {
// 未选中任何选项时提示用户
if (binding.rgEnv.checkedRadioButtonId == -1) {
ToastUtil.show(context,"请选择环境")
return@setOnClickListener
}
val newUrl = when (binding.rgEnv.checkedRadioButtonId) {
binding.rbTest.id -> GlobalData.LOCAL_BASE_URL
binding.rbUat.id -> GlobalData.TEST_BASE_URL
binding.rbProd.id -> GlobalData.PROD_BASE_URL
else -> return@setOnClickListener
}
GlobalData.appBaseUrl = newUrl
SpTool.baseUrl = newUrl
onEnvChanged(newUrl)
dismiss()
}
}
}
@@ -0,0 +1,108 @@
package com.shuwei.intelligent.shelves.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.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.base.BaseDialog
import com.shuwei.intelligent.shelves.databinding.DialogChipSelectBinding
import com.shuwei.intelligent.shelves.utils.ext.dp
import com.shuwei.intelligent.shelves.utils.ext.hideKeyboard
import com.shuwei.intelligent.shelves.utils.ext.toast
/**
* 带ChipGroup选择的弹窗,支持传入选项列表,回调返回选中索引
*/
class ChipSelectDialog(context: Context) : Dialog(context, R.style.DialogTheme) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DialogChipSelectBinding.inflate(LayoutInflater.from(context))
setContentView(binding.root)
setCancelable(false)
setCanceledOnTouchOutside(false)
window?.apply {
//setLayout(defWidth, defHeight)
setBackgroundDrawable(ColorDrawable())
setGravity(Gravity.CENTER)
}
binding.root.setOnClickListener { it.hideKeyboard() }
initView()
}
private lateinit var binding: DialogChipSelectBinding
/** 弹窗标题 */
var dialogTitle: String? = null
/** 选项列表 */
var items: List<String?> = emptyList()
/** 选中回调,返回选中的索引,取消时不触发 */
var onItemSelected: ((Int) -> Unit)? = null
/** 当前选中的索引,默认-1表示未选中 */
private var selectedIndex: Int = -1
fun initView() {
binding.btnCancel.setOnClickListener {
dismiss()
}
binding.btnConfirm.setOnClickListener {
if (binding.chipGroup.checkedChipId == -1) {
context.toast("请选择$dialogTitle")
return@setOnClickListener
}
onItemSelected?.invoke(selectedIndex)
dismiss()
}
}
override fun show() {
super.show()
binding.tvDialogTitle.text = dialogTitle
setupChips()
}
/**
* 动态创建Chip并添加到ChipGroup中
*/
private fun setupChips() {
binding.chipGroup.removeAllViews()
selectedIndex = -1
items.forEachIndexed { index, label ->
val chip = Chip(context).apply {
text = label
isCheckable = true
isCheckedIconVisible = false
textSize = 22f
chipStartPadding = 18.dp.toFloat()
chipEndPadding = 18.dp.toFloat()
textStartPadding = 8.dp.toFloat()
textEndPadding = 8.dp.toFloat()
chipMinHeight = 50.dp.toFloat()
setTextColor(resources.getColorStateList(R.color.chip_text_color, null))
chipBackgroundColor = resources.getColorStateList(R.color.chip_bg_color, null)
chipStrokeWidth = 1f
chipStrokeColor = resources.getColorStateList(R.color.chip_stroke_color, null)
setOnClickListener {
selectedIndex = index
}
}
binding.chipGroup.apply {
isSingleLine = false
addView(chip)
}
}
}
}
@@ -1,6 +0,0 @@
package com.shuwei.intelligent.shelves.model
class DeviceConfigInfo {
var appPackageUrl:String? = null
var canteenId:String? = null
}
@@ -1,10 +0,0 @@
package com.shuwei.intelligent.shelves.model
import java.io.Serializable
data class GoodsModel(
var goodsId: String? = null,
var goodsName: String? = null,
var overdueDay: String? = null,
var isClicked: Boolean = false
) : Serializable
@@ -1,8 +0,0 @@
package com.shuwei.intelligent.shelves.model
data class GoodsRecord(
val total: Int = 0,
val size: Int = 0,
val page: Int = 0,
val records: MutableList<GoodsModel>? = null
)
@@ -1,11 +0,0 @@
package com.shuwei.intelligent.shelves.model
class ShelfBody {
var deviceId: String = ""
var canteenId: String = ""
var temperature: String? = null
var humidity: String = "0"
var goodsList: List<ShelfModel>? = null
}
@@ -1,21 +0,0 @@
package com.shuwei.intelligent.shelves.model
import java.io.Serializable
data class ShelfModel(
var id: String? = null,
var deviceNo: Int = 0,
var shelfName: String? = null,
var goodsId: String? = "",
var goodsName: String? = null,
var deviceId: String? = null,
var weight: Double = 0.0,
var weightBak: Double = 0.0,
var createTime: String? = null,
var putCabinetDay: String? = null,
var updateTime: String? = null,
var overdueDay: String? = null,
var temperature: String? = null,
var humidity: String = "0",
var overdue:Boolean ?= false
) : Serializable
@@ -1,8 +0,0 @@
package com.shuwei.intelligent.shelves.model
data class ShelfResult(
val placeId: String = "",
val canteenName: String = "",
val deviceName: String = "",
val containerGoodsList: List<ShelfModel>? = null
)
@@ -1,61 +0,0 @@
package com.shuwei.intelligent.shelves.net
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.model.DeviceConfigInfo
import com.shuwei.intelligent.shelves.model.GoodsModel
import com.shuwei.intelligent.shelves.model.ShelfBody
import com.shuwei.intelligent.shelves.model.ShelfResult
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.POST
import retrofit2.http.Query
import retrofit2.http.Url
interface ApiService {
/**
* device获取token
*/
@GET("/sys/getEquipmentToken")
suspend fun getDeviceToken(
@Query("qrcodeId") qrcodeId: String,
@Query("appVersion") appVersion: String = App.appVersion
): RespData<String>
/**
*获取配置信息
*/
@GET("/equipment/stEquipment/queryByEquipmentCode")
suspend fun getDeviceInfo(
@Query("equipmentCode") equipmentCode: String,
@Query("appVersion") appVersion: String = App.appVersion
): RespData<DeviceConfigInfo>
@GET
suspend fun getAccessToken(
@Url url: String = UrlConfig.GET_ACCESS_TOKEN,
@Query("qrcodeId") qrcodeId: String
): RespData<String?>
@GET
suspend fun getShelfList(
@Url url: String = UrlConfig.GET_SHELF_LIST,
@Query("deviceId") deviceId: String
): RespData<ShelfResult>
@GET
suspend fun getGoodsList(
@Url url: String = UrlConfig.GET_GOODS_LIST,
@Query("canteenId") canteenId: String = "0",
@Query("goodsName") goodsName: String? = null,
@Query("pageNo") pageNo: Int = 1,
@Query("pageSize") pageSize: Int = 50
): RespData<MutableList<GoodsModel>?>
@POST
suspend fun saveShelfGoodsList(
@Url url: String = UrlConfig.SAVE_SHELF_GOODS_LIST,
@Body body: ShelfBody
): RespData<Any?>
}
@@ -0,0 +1,21 @@
package com.shuwei.intelligent.shelves.net
import com.shuwei.intelligent.shelves.App
import okhttp3.Interceptor
import okhttp3.Response
/**
* v1.1 接口专用拦截器
* /nutrition/neglect/ 路径无需鉴权,仅注入基础请求头
*/
class CabinetRequestInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request().newBuilder()
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("X-DEVICE-CODE", App.deviceId)
.header("authorization", "57ee87183f2a4fa59683ec9ef41c8f5d")
.build()
return chain.proceed(request)
}
}
@@ -2,7 +2,11 @@ package com.shuwei.intelligent.shelves.net
import android.annotation.SuppressLint
import android.util.Log
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.BuildConfig
import com.shuwei.intelligent.shelves.GlobalData
import com.sw.scalefusion.shelf.net.ApiServiceV3
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
@@ -16,41 +20,47 @@ import java.security.SecureRandom
import java.security.cert.X509Certificate
import kotlin.apply
val apiService: ApiService = Retrofit.Builder()
// .baseUrl(UrlConfig.BASE_URL)
.baseUrl(UrlConfig.DEVICE_BASE_URL)
.client(HttpManager.instance.client)
/** 动态域名拦截器:将 Retrofit 请求的 baseUrl 实时替换为 [GlobalData.appBaseUrl] */
class DynamicBaseUrlInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val newUrl = GlobalData.appBaseUrl.toHttpUrlOrNull() ?: return chain.proceed(request)
val url = request.url.newBuilder()
.scheme(newUrl.scheme)
.host(newUrl.host)
.port(newUrl.port)
.build()
return chain.proceed(request.newBuilder().url(url).build())
}
}
/** V3 接口专用实例 */
val apiServiceV3: ApiServiceV3 = Retrofit.Builder()
.baseUrl(GlobalData.appBaseUrl)
.client(HttpManager.instance.cabinetClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
.create(ApiServiceV3::class.java)
class HttpManager private constructor() {
val client: OkHttpClient by lazy {
/** 接口专用 OkHttpClient,注入 Content-Type、Accept、X-DEVICE-CODE、authorization */
val cabinetClient: OkHttpClient by lazy {
OkHttpClient.Builder()
.apply {
connectTimeout(15, TimeUnit.SECONDS)
connectTimeout(30, TimeUnit.SECONDS)
readTimeout(30, TimeUnit.SECONDS)
writeTimeout(15, TimeUnit.SECONDS)
writeTimeout(30, TimeUnit.SECONDS)
sslSocketFactory(createSSLSocketFactory(), TrustAllCerts())
hostnameVerifier { _, _ -> true }
// addInterceptor(LoggingInterceptor())
addInterceptor(DynamicBaseUrlInterceptor())
addNetworkInterceptor(HttpLoggingInterceptor(logger = {
Log.d("HttpManager","okhttp logger ==>${it}")
Log.d("HttpManager", "v2 okhttp ==>${it}")
}).apply {
level =
// if (MyApp.DEBUG) {
HttpLoggingInterceptor.Level.BODY
// } else {
// HttpLoggingInterceptor.Level.NONE
// }
level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
else HttpLoggingInterceptor.Level.NONE
})
// addInterceptor { chain ->
// val request = chain.request().newBuilder()
// .header("x-access-token", App.accessToken)
// .build()
// chain.proceed(request)
// }
addInterceptor(RequestInterceptor())
addInterceptor(CabinetRequestInterceptor())
}
.build()
}
@@ -1,184 +0,0 @@
package com.shuwei.intelligent.shelves.net
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.model.ShelfBody
import com.shuwei.intelligent.shelves.model.ShelfModel
import com.shuwei.intelligent.shelves.net.HttpManager.Companion.instance
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class NetViewModel : ViewModel() {
// val apiService: ApiService = HttpManager.instance.apiService
// val apiService: ApiService = Retrofit.Builder()
// .baseUrl(UrlConfig.BASE_URL)
// .client(HttpManager.instance.client)
// .addConverterFactory(GsonConverterFactory.create())
// .build()
// .create(ApiService::class.java)
private val _getShelfListUiState = MutableStateFlow<UiState>(UiState.Initial)
val getShelfListUiState: StateFlow<UiState> = _getShelfListUiState
// private val _saveShelfGoodsListUiState = MutableStateFlow<UiState>(UiState.Initial)
// val saveShelfGoodsListUiState: StateFlow<UiState> = _saveShelfGoodsListUiState
private val _getGoodsListUiState = MutableStateFlow<UiState>(UiState.Initial)
val getGoodsListUiState: StateFlow<UiState> = _getGoodsListUiState
private val _getAccessTokenUiState = MutableStateFlow<UiState>(UiState.Initial)
val getAccessTokenUiState: StateFlow<UiState> = _getAccessTokenUiState
private val _getDeviceTokenUiState = MutableStateFlow<UiState>(UiState.Initial)
val getDeviceTokenUiState: StateFlow<UiState> = _getDeviceTokenUiState
private val _getDeviceConfigUiState = MutableStateFlow<UiState>(UiState.Initial)
val getDeviceConfigUiState: StateFlow<UiState> = _getDeviceConfigUiState
fun getDeviceToken(deviceId: String) {
viewModelScope.launch {
_getDeviceTokenUiState.value = UiState.Loading
runCatching {
val response = apiService.getDeviceToken(qrcodeId = deviceId)
if (response.isSuccess()) {
_getDeviceTokenUiState.value = UiState.Success(response)
} else {
_getDeviceTokenUiState.value = UiState.Error(response.msg ?: "请求失败")
}
}.onFailure {
_getDeviceTokenUiState.value = UiState.Error(it.message ?: "请求异常")
}
}
}
fun getDeviceConfig(deviceId: String, deviceToken: String) {
viewModelScope.launch {
_getDeviceTokenUiState.value = UiState.Loading
runCatching {
val response =
apiService.getDeviceInfo(equipmentCode = deviceId)
if (response.isSuccess()) {
_getDeviceTokenUiState.value = UiState.Success(response)
} else {
_getDeviceTokenUiState.value = UiState.Error(response.msg ?: "请求失败")
}
}.onFailure {
_getDeviceTokenUiState.value = UiState.Error(it.message ?: "请求异常")
}
}
}
fun getAccessToken(deviceId: String) {
viewModelScope.launch {
_getAccessTokenUiState.value = UiState.Loading
runCatching {
val response = apiService.getAccessToken(qrcodeId = deviceId)
if (response.isSuccess()) {
_getAccessTokenUiState.value = UiState.Success(response)
} else {
_getAccessTokenUiState.value = UiState.Error(response.msg ?: "请求失败")
}
}.onFailure {
_getAccessTokenUiState.value = UiState.Error(it.message ?: "请求异常")
}
}
}
fun getShelfList(deviceId: String) {
viewModelScope.launch {
_getShelfListUiState.value = UiState.Loading
runCatching {
val response = apiService.getShelfList(deviceId = deviceId)
if (response.isSuccess()) {
_getShelfListUiState.value = UiState.Success(response)
} else {
_getShelfListUiState.value = UiState.Error(response.msg ?: "请求失败")
}
}.onFailure {
_getShelfListUiState.value = UiState.Error(it.message ?: "请求异常")
}
}
}
fun updateOverdueState(block:(Boolean, List<ShelfModel>?)-> Unit) {
viewModelScope.launch {
runCatching {
val response = apiService.getShelfList(deviceId = App.deviceId)
if (response.isSuccess()) {
block(true, response.data?.containerGoodsList)
} else {
block(false, emptyList())
}
}.onFailure {
block(false, null)
}
}
}
// fun saveShelfGoodsList(body: ShelfBody) {
// viewModelScope.launch {
// _saveShelfGoodsListUiState.value = UiState.Loading
// runCatching {
// val response = apiService.saveShelfGoodsList(body)
// if (response.success) {
// _saveShelfGoodsListUiState.value = UiState.Success(response)
// } else {
// _saveShelfGoodsListUiState.value = UiState.Error(response.message ?: "请求失败")
// }
// }.onFailure {
// _saveShelfGoodsListUiState.value = UiState.Error(it.message ?: "请求异常")
// }
// }
// }
fun getGoodsList(
canteenId: String = "",
goodsName: String = "",
pageNo: Int = 1,
pageSize: Int = 50,
) {
viewModelScope.launch {
_getGoodsListUiState.value = UiState.Loading
runCatching {
if (App.configUrl.isNullOrBlank()) {
App.configUrl = UrlConfig.BASE_URL
}
val response = apiService.getGoodsList(
canteenId = canteenId,
goodsName = goodsName,
pageNo = pageNo,
pageSize = pageSize
)
if (response.isSuccess()) {
_getGoodsListUiState.value = UiState.Success(response)
} else {
_getGoodsListUiState.value = UiState.Error(response.msg ?: "请求失败")
}
}.onFailure {
_getGoodsListUiState.value = UiState.Error(it.message ?: "请求异常")
}
}
}
fun saveShelfGoodsList(body: ShelfBody) {
viewModelScope.launch {
runCatching {
val resp = apiService.saveShelfGoodsList(body = body)
Log.d("NetViewModel", "saveShelfGoodsList,performSync: resp:${resp.toJsonString()}")
}.onFailure {
it.printStackTrace()
Log.d("NetViewModel", "saveShelfGoodsList异常:${it.message}")
}
}
}
}
@@ -1,35 +0,0 @@
package com.shuwei.intelligent.shelves.net
import android.text.TextUtils
import com.shuwei.intelligent.shelves.App
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
/**
* 请求拦截器
*/
class RequestInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val requestBuilder = originalRequest.newBuilder()
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjYW50ZWVuSWQiOiJiZTE1NDgzMS0zNDY2LTNiYTItYTJlYS01NzY1MmM5MTlmZWQiLCJ0eXBlIjoiNCIsInVzZXJJZCI6IjAwMDAwMDAwMDAwMDAwMDAwMDEifQ.sN40cOC-O5WQFrF4IDUs8fFlkNdUKLbJt_rHyTsgYYM")
.header("X-DEVICE-CODE", App.deviceId)
.header("authorization", "57ee87183f2a4fa59683ec9ef41c8f5d")
val newRequest = requestBuilder.build()
return chain.proceed(newRequest)
}
// private fun getToken(originRequest: Request): String {
// val tokenParam = originRequest.header("X-Access-Token")
// if (!TextUtils.isEmpty(tokenParam)) return tokenParam!!
// // 从本地获取token的逻辑
// val spUtil = SPUtil.getInstance(context = App.getContext())
// return spUtil.get(GlobalKey.KEY_TOKEN, "") as String
//// return "eyJhbGciOiJIUzUxMiJ9.eyJpZCI6MTQ2LCJ1c2VyTmFtZSI6IjEzNjgxNDQ4ODU2IiwibmFtZSI6IuW-kOejiiIsInBhc3N3b3JkIjoiOTllOTQ1ZmVjZmZjNWIzNDI4MmUwNDRlODYyMzdjM2UxZjU5OWY5OCIsInNhbHQiOiI0NmEzMzUzYWU4OTA0MDYxYjMzODU5ZWNlYTBlMGE2NyIsInBob25lIjoiMTM2ODE0NDg4NTYiLCJzdGF0dXMiOjEsInVzZXJUeXBlIjoyLCJjcmVhdGVVc2VyTm8iOiIxNDEiLCJjcmVhdGVUaW1lIjoxNjI2OTQzNDE2MDAwLCJ1cGRhdGVVc2VyTm8iOiIxNDEiLCJ1cGRhdGVUaW1lIjoxNjI2OTQzNDE2MDAwLCJpc0RlbCI6ZmFsc2UsImVhSWQiOjk5LCJlYUlkTGlzdCI6Ijk5IiwiaXNTaG9wTWFuYWdlciI6dHJ1ZSwidXNlck5vIjoiMWY5Nzk5ZWMtODlkYi00MWYyLTk1YTEtY2UzNTA3Y2QyMTU2In0.f7wImPgBOYMV0AqRchnXGPkUWZN9dFJ9gLPsaB8uNldd21IfXLjJl8y-FiWVuVUvlwUvGpgqGDFR1JKj5H7amw"
// }
}
@@ -1,6 +1,7 @@
package com.shuwei.intelligent.shelves.net
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.GlobalData
object UrlConfig {
// const val DEVICE_BASE_URL = "http://device.shuziweidao.com:8889"
@@ -13,18 +14,24 @@ object UrlConfig {
// */
// const val DEVICE_CONFIG = "${DEVICE_BASE_URL}/equipment/stEquipment/queryByEquipmentCode"
const val BASE_URL = "https://dev.yixiong-tech.com:8081"
// const val BASE_URL = "https://yyjk.shuziweidao.com/gateway"
// const val BASE_URL = "http://192.168.1.201:14801"
const val DEVICE_BASE_URL = BASE_URL
// const val BASE_URL = "https://dev.yixiong-tech.com:8081"
//// const val BASE_URL = "https://yyjk.shuziweidao.com/gateway"
//// const val BASE_URL = "http://192.168.1.201:14801"
// const val DEVICE_BASE_URL = BASE_URL
var GET_ACCESS_TOKEN = "${App.configUrl}/restaurant/equipment/stEquipment/getEquipmentToken"
var GET_ACCESS_TOKEN = "${GlobalData.appBaseUrl}/restaurant/equipment/stEquipment/getEquipmentToken"
var GET_SHELF_LIST =
"${App.configUrl}/terminal/neglect/smartShelves/app/smartShelves/app/getShelvesListByDeviceId"
"${GlobalData.appBaseUrl}/terminal/neglect/smartShelves/app/smartShelves/app/getShelvesListByDeviceId"
var GET_GOODS_LIST =
"${App.configUrl}/terminal/neglect/smartShelves/app/smartShelves/app/getGoodsPageList"
"${GlobalData.appBaseUrl}/terminal/neglect/smartShelves/app/smartShelves/app/getGoodsPageList"
var SAVE_SHELF_GOODS_LIST =
"${App.configUrl}/terminal/neglect/smartShelves/app/smartShelves/app/saveShelvesGoodsList"
"${GlobalData.appBaseUrl}/terminal/neglect/smartShelves/app/smartShelves/app/saveShelvesGoodsList"
// v1.1 新接口
var CABINET_INIT = "${GlobalData.appBaseUrl}/nutrition/neglect/cabinet/init"
var CLEAN_PACKAGE_OPTIONS = "${GlobalData.appBaseUrl}/nutrition/neglect/cabinet/clean-package-options"
var MEAL_PACKAGE_OPTIONS = "${GlobalData.appBaseUrl}/nutrition/neglect/cabinet/meal-package-options"
var CABINET_RECORD_SYNC = "${GlobalData.appBaseUrl}/nutrition/neglect/cabinet/record/sync"
}
@@ -0,0 +1,24 @@
package com.shuwei.intelligent.shelves.serial
/**
* 心跳数据(命令 0x01 / 0x81,终端发起)
*
* @param scaleCount 秤的数量
* @param weights 各台秤的重量列表,索引从1开始
* @param simCardNo 物联卡号(20字节ASCII
* @param lock1Door 锁1门状态:0-关 1-开
* @param lock1Lock 锁1锁状态:0-关 1-开
* @param lock2Door 锁2门状态:0-关 1-开
* @param lock2Lock 锁2锁状态:0-关 1-开
* @param temperature 温度值(原始字节,单位由温控器决定)
*/
data class HeartbeatData(
val scaleCount: Int,
val weights: List<ScaleWeight>,
val simCardNo: String,
val lock1Door: Int,
val lock1Lock: Int,
val lock2Door: Int,
val lock2Lock: Int,
val temperature: Int
)
@@ -0,0 +1,198 @@
package com.shuwei.intelligent.shelves.serial
import com.shuwei.intelligent.shelves.App
/**
* 串口通信协议常量定义
* 统一管理所有协议头、协议尾、各类指令及帧解析偏移量
*/
object ProtocolConstants {
/** 协议头 */
const val HEADER = "D6DADEDB"
/** 协议尾 */
const val FOOTER = "FFFF"
// ----------------------------------------------------------------
// 指令码(cmd 字段,4字符)
// ----------------------------------------------------------------
/** 终端激活指令 */
const val CMD_ACTIVATE = "0001"
/** 心跳指令(服务端发起) */
const val CMD_HEARTBEAT = "0101"
/** 心跳指令(终端发起) */
const val CMD_HEARTBEAT_TERMINAL = "8101"
/** 开关锁反馈 */
const val CMD_LOCK_FEEDBACK = "0202"
/** 获取设备状态 */
const val CMD_DEVICE_STATUS = "0302"
/** 卡号上发 */
const val CMD_CARD_UPLOAD = "0501"
/** 操作记录上传 */
const val CMD_OPERATION_RECORD = "0B01"
/** 对时 */
const val CMD_TIME_SYNC = "0C01"
/** 终端位置上报 */
const val CMD_POSITION_REPORT = "0E01"
/** 温控信息上报 */
const val CMD_TEMP_REPORT = "1001"
/** 温控信息应答 */
const val CMD_TEMP_RESPONSE = "1002"
/** 温控应答(备用) */
const val CMD_TEMP_RESPONSE_ALT = "0F02"
// ----------------------------------------------------------------
// 帧数据偏移 / 尺寸常量
// ----------------------------------------------------------------
/** 心跳帧中重量数据起始偏移(相对帧起始) */
const val HEARTBEAT_WEIGHT_OFFSET = 14
/** 设备状态帧中重量数据起始偏移(含协议头长度) */
const val DEVICE_STATUS_WEIGHT_OFFSET = HEADER.length + 14
/** 货架数量(每侧5格,共10格,协议中12组) */
fun shelfSensorCount(): Int {
return if (device2Columns.contains(App.deviceId)) 12
else if (device3Columns.contains(App.deviceId)) 24
else 0
}
/** 每组重量数据字节数(十六进制字符数) */
const val BYTES_PER_WEIGHT = 8
/** 温度字段字符长度 */
const val TEMPERATURE_FIELD_LEN = 2
/** 心跳帧最小有效长度 */
fun heartbeatMinLength(): Int {
return if (device2Columns.contains(App.deviceId)) 200
else if (device3Columns.contains(App.deviceId)) 296
else 0
}
/** 心跳帧中温度字段起始偏移(经协议分析得出,前面含重量+其他传感器数据) */
fun heartbeatTemperatureStart(): Int {
return if (device2Columns.contains(App.deviceId)) 158
else if (device3Columns.contains(App.deviceId)) 158+96
else 0
}
/** 激活请求体有效长度 */
const val ACTIVATE_BODY_LENGTH = 44
/** 固定数据体有效长度(terminalId 30 + terminalVersion 10 + 其他 2 */
const val FIX_BODY_LENGTH = 42
// ----------------------------------------------------------------
// 完整指令
// ----------------------------------------------------------------
/** 激活指令(1楼餐厅) */
// const val ACTIVE_CMD =
// "${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}"
// 410激活码
// const val ACTIVE_CMD = "${HEADER}000281C5D70A7D42894EA17650F5D0BB516838E7863C9ABD766C38958AFF0F3C062D${FOOTER}"
/** 左货架开锁指令 */
const val LEFT_SHELF_OPEN_CMD =
"${HEADER}020101000000000000000000000000000000000000${FOOTER}"
/** 右货架开锁指令 */
const val RIGHT_SHELF_OPEN_CMD =
"${HEADER}020100010000000000000000000000000000000000${FOOTER}"
/** 获取设备信息指令 */
const val DEVICE_INFO_CMD = "${HEADER}0301000000000000000000000000${FOOTER}"
/** 启动温控指令 */
const val START_TEMP_CTRL_CMD = "${HEADER}0F01360000${FOOTER}"
/** 华氏温度单位指令 */
const val F_TEMP_CMD = "${HEADER}0F01390000${FOOTER}"
/** 摄氏温度单位指令 */
const val C_TEMP_CMD = "${HEADER}0F01390001${FOOTER}"
/** 关灯指令(继电器1关) */
const val LIGHT_CLOSE = "${HEADER}020102020102020000000000000000000000000000${FOOTER}"
/** 开灯指令(继电器1开) */
const val LIGHT_OPEN = "${HEADER}020102020002020000000000000000000000000000${FOOTER}"
/** 温控指令 */
const val TEMPERATURE_CTRL = "${HEADER}0F01040000${FOOTER}"
/**
* 设备2列,10格
*/
val device2Columns = listOf(
//原410货柜
"7a991439-3a12-3ef7-809b-c0258b839473",
//原1楼餐厅货柜
"4787e213-90ab-3e32-88e0-ac271a937751",
// TODO: 测试设备----------
"2987f0c5-5754-33e9-b00a-251db5e2e55f"
)
/**
* 设备3列,15格,左侧1列竖向编号1、2、3、4、5,右侧2列5行编号为6-7、8-9、10-11、12-13、14-15
*/
val device3ColumnsOrder = listOf(1, 6, 7, 2, 8, 9, 3, 10, 11, 4, 12, 13, 5, 14, 15)
/**
* 设备2列,10格,左侧1列竖向编号1、2、3、4、5,右侧1列6,7,8,9,10
*/
val device2ColumnsOrder = listOf(1, 6, 2, 7, 3, 8, 4, 9, 5, 10)
/**
* 设备3列,15格,左侧1列竖向编号1、2、3、4、5,右侧2列5行编号为6-7、8-9、10-11、12-13、14-15
*/
val device3Columns = listOf(
//新设备1
"d369f9b0-1c5b-3066-ba72-988e1449cecc",
//新设备2
"505ce1b1-facc-3eb2-855a-3dadda5ba358"
)
/**
* 设备 cabinetType 映射,用于 V3 API
* 1=毛菜柜,2=净菜柜,默认 2
*/
val deviceCabinetType = mapOf(
// 原410货柜 → 毛菜柜
"7a991439-3a12-3ef7-809b-c0258b839473" to 1,
// 原1楼餐厅货柜 → 净菜柜
"4787e213-90ab-3e32-88e0-ac271a937751" to 2,
// 新设备 → 净菜柜
"d369f9b0-1c5b-3066-ba72-988e1449cecc" to 2,
"505ce1b1-facc-3eb2-855a-3dadda5ba358" to 2,
)
fun cabinetType(): Int = deviceCabinetType[App.deviceId] ?: 2
/** 激活指令mapkey为设备号,value为激活码 */
val ACTIVE_MAP = mutableMapOf(
//原410货柜
"7a991439-3a12-3ef7-809b-c0258b839473" to "${HEADER}000281C5D70A7D42894EA17650F5D0BB516838E7863C9ABD766C38958AFF0F3C062D${FOOTER}",
//原1楼餐厅货柜
"4787e213-90ab-3e32-88e0-ac271a937751" to "${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}",
//新设备1,临时使用1楼餐厅激活码
"d369f9b0-1c5b-3066-ba72-988e1449cecc" to "${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}",
//新设备2,临时使用1楼餐厅激活码
"505ce1b1-facc-3eb2-855a-3dadda5ba358" to "${HEADER}000281C5D70A7D428B44A57454F5DACA241938938B4B9CBD73673E9C8E7FC0C4992D${FOOTER}",
)
}
@@ -0,0 +1,42 @@
package com.shuwei.intelligent.shelves.serial
/**
* 协议帧通用数据结构
* 每一帧解析后的原始信息,所有命令共用此结构
*
* @param cmd 命令字节,对应 ScaleProtocolConstants.CMD_* 常量
* @param flag 标志字节
* @param rawBody 数据体原始字节(不含协议头尾、命令、标志、固定数据体)
* @param terminalId 终端ID15字节),ASCII字符串
* @param firmwareVersion 固件版本(5字节),ASCII字符串
* @param cmdCount 命令次数
*/
data class ScaleFrame(
val cmd: Byte,
val flag: Byte,
val rawBody: ByteArray,
val terminalId: String,
val firmwareVersion: String,
val cmdCount: Int
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ScaleFrame) return false
return cmd == other.cmd &&
flag == other.flag &&
rawBody.contentEquals(other.rawBody) &&
terminalId == other.terminalId &&
firmwareVersion == other.firmwareVersion &&
cmdCount == other.cmdCount
}
override fun hashCode(): Int {
var result = cmd.toInt()
result = 31 * result + flag.toInt()
result = 31 * result + rawBody.contentHashCode()
result = 31 * result + terminalId.hashCode()
result = 31 * result + firmwareVersion.hashCode()
result = 31 * result + cmdCount
return result
}
}
@@ -0,0 +1,281 @@
package com.shuwei.intelligent.shelves.serial
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.BODY_OFFSET
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.BYTES_PER_WEIGHT
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FIRMWARE_VERSION_LEN
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FIXED_BODY_LEN
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FOOTER_HEX
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FOOTER_LEN
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.HEADER_HEX
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.SIM_CARD_NO_LEN
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.TERMINAL_ID_LEN
import com.shuwei.intelligent.shelves.utils.hexToBytes
/**
* 协议帧组装与解析器
*
* 职责一:将串口原始分片十六进制字符串拼装为完整协议帧
* 职责二:将完整帧解析为 ScaleFrame,自动提取固定数据体字段
* 职责三:提供心跳、状态等数据体的具体解析方法
* 职责四:提供重量字节解析工具(BCD编码、小端序、最高位符号位)
*
* 设计为无业务依赖,可独立复制到其他项目使用
*/
class ScaleFrameParser {
/** 分片拼装缓冲区 */
private val buffer = StringBuilder()
// ----------------------------------------------------------------
// 一、帧组装(串口分片 -> 完整帧十六进制字符串)
// ----------------------------------------------------------------
/**
* 追加串口原始分片数据,尝试拼装为完整帧
*
* @param srcData 串口收到的原始十六进制字符串片段
* @return 完整协议帧字符串;帧尚不完整时返回 null
*/
fun appendData(srcData: String): String? {
val hasHeader = srcData.contains(HEADER_HEX)
val hasFooter = srcData.contains(FOOTER_HEX)
return when {
hasHeader && hasFooter -> parseCompleteInSingleChunk(srcData)
hasHeader && !hasFooter -> {
// 只有帧头,等待后续分片
buffer.clear()
buffer.append(srcData.substring(srcData.lastIndexOf(HEADER_HEX))).append(",")
null
}
!hasHeader && !hasFooter -> {
// 中间分片,追加缓冲
buffer.append(srcData).append(",")
null
}
else -> {
// 只有帧尾,与缓冲区拼接成完整帧
val endIndex = srcData.indexOf(FOOTER_HEX) + FOOTER_HEX.length
buffer.append(srcData.substring(0, endIndex))
val frame = buffer.toString().replace(",", "")
buffer.clear()
frame.takeIf { it.isNotEmpty() }
}
}
}
/**
* 处理单个分片中同时含有帧头和帧尾的情况
*/
private fun parseCompleteInSingleChunk(srcData: String): String? {
buffer.clear()
val startIndex = srcData.lastIndexOf(HEADER_HEX)
val endIndex = srcData.indexOf(FOOTER_HEX) + FOOTER_HEX.length
return if (endIndex <= startIndex) {
// 帧尾在帧头之前:是上一帧的残留尾部 + 新帧头部
val partial = srcData.substring(startIndex)
if (partial.contains(FOOTER_HEX)) {
val newEnd = partial.indexOf(FOOTER_HEX) + FOOTER_HEX.length
partial.substring(0, newEnd)
} else {
buffer.append(partial).append(",")
null
}
} else {
// 正常完整帧
srcData.substring(startIndex, endIndex)
}
}
/** 清空分片缓冲区 */
fun reset() {
buffer.clear()
}
// ----------------------------------------------------------------
// 二、帧解析(完整帧十六进制字符串 -> ScaleFrame
// ----------------------------------------------------------------
/**
* 解析完整协议帧为 ScaleFrame
*
* 帧结构:[协议头4] [CMD1] [FLAG1] [数据体N] [终端ID15] [固件版本5] [命令次数1] [协议尾2]
*
* @param hexFrame 完整帧十六进制字符串(含协议头尾)
* @return 解析成功返回 ScaleFrame;校验失败或格式错误返回 null
*/
fun parseFrame(hexFrame: String): ScaleFrame? {
// 最小帧:协议头(8) + cmd(2) + flag(2) + 固定数据体(42) + 协议尾(4) = 58 字符
if (hexFrame.length < 58) return null
if (!hexFrame.startsWith(HEADER_HEX) || !hexFrame.endsWith(FOOTER_HEX)) return null
return runCatching {
val bytes = hexFrame.hexToBytes()
val totalLen = bytes.size
val cmd = bytes[ScaleProtocolConstants.HEADER_LEN]
val flag = bytes[ScaleProtocolConstants.HEADER_LEN + 1]
// 固定数据体位于协议尾之前
val fixedBodyStart = totalLen - FOOTER_LEN - FIXED_BODY_LEN
if (fixedBodyStart < BODY_OFFSET) return null
val fixedBody = bytes.copyOfRange(fixedBodyStart, totalLen - FOOTER_LEN)
// 解析固定数据体三个字段
val terminalId = String(fixedBody, 0, TERMINAL_ID_LEN, Charsets.US_ASCII)
val firmwareVersion = String(fixedBody, TERMINAL_ID_LEN, FIRMWARE_VERSION_LEN, Charsets.US_ASCII)
val cmdCount = fixedBody[TERMINAL_ID_LEN + FIRMWARE_VERSION_LEN].toInt() and 0xFF
// 命令专属数据体(固定数据体和协议头尾之间的部分)
val rawBody = bytes.copyOfRange(BODY_OFFSET, fixedBodyStart)
ScaleFrame(
cmd = cmd,
flag = flag,
rawBody = rawBody,
terminalId = terminalId,
firmwareVersion = firmwareVersion,
cmdCount = cmdCount
)
}.getOrNull()
}
// ----------------------------------------------------------------
// 三、数据体解析
// ----------------------------------------------------------------
/**
* 解析心跳数据体(命令 0x01 / 0x81,终端发起)
*
* rawBody 格式:
* [秤数量 1] [秤重量 N×4] [物联卡号 20] [锁1门 1] [锁1锁 1] [锁2门 1] [锁2锁 1] [温度 1]
*
* @param body ScaleFrame.rawBody
* @return 解析成功返回 HeartbeatData;数据不足返回 null
*/
fun parseHeartbeat(body: ByteArray): HeartbeatData? {
if (body.isEmpty()) return null
return runCatching {
var offset = 0
val scaleCount = body[offset++].toInt() and 0xFF
val minBodyLen = 1 + scaleCount * BYTES_PER_WEIGHT + SIM_CARD_NO_LEN + 4 + 1
if (body.size < minBodyLen) return null
val weights = (1..scaleCount).map { index ->
val grams = parseWeightBytes(body, offset)
offset += BYTES_PER_WEIGHT
ScaleWeight(index, grams)
}
// 物联卡号:ASCII字符串,去除尾部空字符
val simCardNo = String(body, offset, SIM_CARD_NO_LEN, Charsets.US_ASCII)
.trimEnd('\u0000').trim()
offset += SIM_CARD_NO_LEN
val lock1Door = body[offset++].toInt() and 0xFF
val lock1Lock = body[offset++].toInt() and 0xFF
val lock2Door = body[offset++].toInt() and 0xFF
val lock2Lock = body[offset++].toInt() and 0xFF
val temperature = body[offset].toInt() and 0xFF
HeartbeatData(
scaleCount = scaleCount,
weights = weights,
simCardNo = simCardNo,
lock1Door = lock1Door,
lock1Lock = lock1Lock,
lock2Door = lock2Door,
lock2Lock = lock2Lock,
temperature = temperature
)
}.getOrNull()
}
/**
* 解析获取状态响应数据体(命令 0x03,终端响应)
*
* rawBody 格式:
* [锁1锁 1] [锁1门 1] [锁2锁 1] [锁2门 1] [秤数量 1] [秤重量 N×4] [温度 1]
*
* @param body ScaleFrame.rawBody
* @return 解析成功返回 StatusData;数据不足返回 null
*/
fun parseStatus(body: ByteArray): StatusData? {
if (body.size < 6) return null
return runCatching {
var offset = 0
val lock1Lock = body[offset++].toInt() and 0xFF
val lock1Door = body[offset++].toInt() and 0xFF
val lock2Lock = body[offset++].toInt() and 0xFF
val lock2Door = body[offset++].toInt() and 0xFF
val scaleCount = body[offset++].toInt() and 0xFF
val minBodyLen = 5 + scaleCount * BYTES_PER_WEIGHT + 1
if (body.size < minBodyLen) return null
val weights = (1..scaleCount).map { index ->
val grams = parseWeightBytes(body, offset)
offset += BYTES_PER_WEIGHT
ScaleWeight(index, grams)
}
val temperature = body[offset].toInt() and 0xFF
StatusData(
lock1Lock = lock1Lock,
lock1Door = lock1Door,
lock2Lock = lock2Lock,
lock2Door = lock2Door,
scaleCount = scaleCount,
weights = weights,
temperature = temperature
)
}.getOrNull()
}
// ----------------------------------------------------------------
// 四、重量解析工具
// ----------------------------------------------------------------
/**
* 解析4字节小端序重量数据
*
* 编码规则(BCD + 小端序 + 最高位符号位):
* - 4字节小端序存储,低字节在前,高字节在后
* - 高字节最高位(bit7)为符号位:0=正数,1=负数
* - 其余位组成8位BCD十进制字符串,作为十进制整数读取,单位为克
*
* 示例:
* [0x13, 0x10, 0x00, 0x00] → 大端序 "00001013" → 十进制 1013g = 1.013KG
* [0x13, 0x01, 0x02, 0x00] → 大端序 "00020113" → 十进制 2113g = 20.113KG(注:原例实为20113g,见下)
* [0x13, 0x10, 0x00, 0x80] → 大端序 "80001013" → 符号位=1 → 十进制 -1013g = -1.013KG
*
* 注意:大端序十六进制字符串按十进制解析(非十六进制),这是BCD编码的关键
*
* @param bytes 字节数组
* @param offset 起始偏移量(连续4字节)
* @return 重量(克),负数表示低于去皮零点
*/
fun parseWeightBytes(bytes: ByteArray, offset: Int): Int {
val b0 = bytes[offset].toInt() and 0xFF // 最低字节
val b1 = bytes[offset + 1].toInt() and 0xFF
val b2 = bytes[offset + 2].toInt() and 0xFF
val b3 = bytes[offset + 3].toInt() and 0xFF // 最高字节(含符号位)
// 检查最高字节的最高位是否为1(负数标志)
val isNegative = (b3 and 0x80) != 0
val b3Cleared = b3 and 0x7F // 清除符号位
// 构造大端序8位十六进制字符串
val hexStr = "%02X%02X%02X%02X".format(b3Cleared, b2, b1, b0)
// 将十六进制字符串作为十进制整数解析(BCD解码)
// "00001013" → toLong() = 1013,而非 toLong(16) = 4115
val absValue = hexStr.toLongOrNull() ?: 0L
return if (isNegative) -absValue.toInt() else absValue.toInt()
}
}
@@ -0,0 +1,589 @@
package com.shuwei.intelligent.shelves.serial
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_ACTIVATE
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_CARD_UPLOAD
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_GET_STATUS
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_HEARTBEAT
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_HEARTBEAT_STORE
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_OPERATION_RECORD
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_POSITION_REPORT
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_TEMP_REPORT
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_TIME_SYNC
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.CMD_UNLOCK
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.FOOTER_HEX
import com.shuwei.intelligent.shelves.serial.ScaleProtocolConstants.HEADER_HEX
import com.shuwei.intelligent.shelves.utils.hexToBytes
import com.shuwei.intelligent.shelves.utils.toHexString2
import io.github.jeadyx.jserialport.AndroidSerialPort
import io.github.jeadyx.jserialport.SerialPort
import io.github.jeadyx.jserialport.SerialPortFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Locale
import java.util.TimeZone
/**
* 称重控制板管理器(单例入口)
*
* 职责:
* - 管理串口连接生命周期(start/release
* - 通过内部发送队列(Channel)保证指令按顺序写入串口
* - 接收串口原始分片数据,自动拼装帧并分发到对应回调
* - 内置各命令的自动应答逻辑(心跳/对时/卡号等)
* - 提供链式回调注册 和 常用指令构建
*
* 典型用法:
* ```kotlin
* lifecycleScope.launch {
* ScaleManager
* .init(activateCode = ACTIVE_MAP[deviceId] ?: "")
* .onHeartbeat { _, data ->
* data.weights.forEach { Log.d("Scale", "秤${it.index}: ${it.grams}g") }
* }
* .onLog { msg -> Log.d("Scale", msg) }
* .start { data ->
* // 主线程前置钩子,处理看门狗计时等副作用
* }
* }
*
* // 主动发送指令
* ScaleManager.sendCmd(ScaleManager.buildGetStatusCmd())
*
* // 页面销毁时释放(关闭串口 + 清空队列 + 清理回调)
* runBlocking { ScaleManager.release() }
* ```
*/
object ScaleManager {
/** 串口端口名,默认 /dev/ttyS1 */
var portName: String = "/dev/ttyS1"
/** 串口波特率,默认 115200 */
var baudRate: Int = 115200
private val parser = ScaleFrameParser()
private var serialPort: AndroidSerialPort? = null
private var scope = CoroutineScope(Dispatchers.IO)
/** 发送队列:保证串口写入顺序,避免并发写冲突 */
private val sendChannel = Channel<String>(capacity = Channel.UNLIMITED)
/** 当前设备激活码,非空时收到激活请求自动应答 */
private var activateCode: String = ""
/** 心跳应答:心跳上报间隔(秒),默认1秒,保证重量更新实时性 */
var heartbeatInterval: Int = 1
/** 心跳应答:开锁后未开门自动落锁时间(秒),默认6秒 */
var lockTimeout: Int = 6
// 各命令监听列表
private val heartbeatListeners = mutableListOf<(ScaleFrame, HeartbeatData) -> Unit>()
private val statusListeners = mutableListOf<(ScaleFrame, StatusData) -> Unit>()
private val lockListeners = mutableListOf<(ScaleFrame) -> Unit>()
private val cardListeners = mutableListOf<(ScaleFrame) -> Unit>()
private val operationListeners = mutableListOf<(ScaleFrame) -> Unit>()
private val timeSyncListeners = mutableListOf<(ScaleFrame) -> Unit>()
private val positionListeners = mutableListOf<(ScaleFrame) -> Unit>()
private val tempReportListeners = mutableListOf<(ScaleFrame) -> Unit>()
private val activateListeners = mutableListOf<(ScaleFrame) -> Unit>()
/** 任意命令的原始帧监听,用于协议中尚未提供专项解析的命令 */
private val rawListeners = mutableMapOf<Byte, MutableList<(ScaleFrame) -> Unit>>()
private val logListeners = mutableListOf<(String) -> Unit>()
// ----------------------------------------------------------------
// 初始化
// ----------------------------------------------------------------
/**
* 初始化,设置设备激活码
*
* @param activateCode 当前设备的激活应答帧十六进制字符串,非空时收到激活请求自动应答
* @return this,支持链式调用
*/
fun init(activateCode: String = ""): ScaleManager {
this.activateCode = activateCode
return this
}
// ----------------------------------------------------------------
// 串口生命周期
// ----------------------------------------------------------------
/**
* 打开串口并启动接收,在回调注册完成后调用(链式末尾)
*
* @param preHook 每帧数据到达时的前置钩子(主线程),用于看门狗计时、UI副作用等
* @return true=串口打开成功并已启动接收,false=串口打开失败
*/
suspend fun start(preHook: ((String) -> Unit)? = null): Boolean {
if (!openPort()) return false
startReceive(preHook)
return true
}
private suspend fun openPort(): Boolean {
if (!scope.isActive) {
scope = CoroutineScope(Dispatchers.IO)
}
return try {
serialPort = SerialPortFactory.create().apply {
open(
portName = portName,
baudRate = baudRate,
dataBits = 8,
stopBits = 1,
parity = SerialPort.PARITY_NONE
)
} as AndroidSerialPort?
// 启动单一消费者协程,顺序消费发送队列
scope.launch {
for (hexStr in sendChannel) {
try {
serialPort?.write(hexStr.hexToBytes())
} catch (e: Exception) {
e.printStackTrace()
log("发送命令失败: ${e.message}")
}
}
}
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
private fun startReceive(preHook: ((String) -> Unit)? = null) {
scope.launch {
while (isActive) {
try {
val flow = serialPort?.read()
flow?.collect { buffer ->
val data = buffer.toHexString2().uppercase(Locale.ROOT)
// IO 线程:帧拼装与解析
val parsed = tryParseCompleteFrame(data)
if (parsed != null) {
// IO 线程:发送自动应答(不占用主线程)
sendAutoResponse(parsed.first)
// IO 线程:心跳日志降频
if (parsed.first.cmd == CMD_HEARTBEAT || parsed.first.cmd == CMD_HEARTBEAT_STORE) {
logHeartbeatIfNeeded(parsed.first, parsed.second)
}
}
// 仅回调分发和 preHook 需要主线程
withContext(Dispatchers.Main) {
try {
preHook?.invoke(data)
if (parsed != null) {
invokeCallbacks(parsed.first)
}
} catch (e: Exception) {
e.printStackTrace()
log("串口数据处理异常: ${e.message}")
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
delay(10)
}
}
}
// ----------------------------------------------------------------
// 数据接收入口
// ----------------------------------------------------------------
/**
* 接收串口原始数据(公开 API,主线程安全)
*
* 内部自动完成分片拼装 → 帧解析 → 自动应答 → 回调分发
*
* @param hexData 串口收到的十六进制字符串(可能为分片数据)
*/
fun onDataReceived(hexData: String) {
val parsed = tryParseCompleteFrame(hexData) ?: return
sendAutoResponse(parsed.first)
invokeCallbacks(parsed.first)
}
/**
* IO 线程安全的帧拼装与解析(纯计算,无副作用)
*
* @return Pair<ScaleFrame, rawHex> 或 null(分片未完整/解析失败)
*/
private fun tryParseCompleteFrame(hexData: String): Pair<ScaleFrame, String>? {
val completeFrame = parser.appendData(hexData) ?: return null
val frame = parser.parseFrame(completeFrame)
if (frame == null) {
log("帧解析失败,原始数据:$completeFrame")
}
return frame?.let { it to completeFrame }
}
/**
* IO 线程:发送协议自动应答(不阻塞主线程)
*/
private fun sendAutoResponse(frame: ScaleFrame) {
when (frame.cmd) {
CMD_HEARTBEAT, CMD_HEARTBEAT_STORE -> {
val firmwareHex = frame.firmwareVersion.toAsciiHex()
val resp = "${HEADER_HEX}0102%02X%02X${firmwareHex}${FOOTER_HEX}".format(
heartbeatInterval and 0xFF, lockTimeout and 0xFF
)
sendCmd(resp)
}
CMD_UNLOCK -> {
val terminalIdHex = frame.terminalId.toAsciiHex()
val firmwareHex = frame.firmwareVersion.toAsciiHex()
sendCmd("${HEADER_HEX}020200${terminalIdHex}${firmwareHex}${FOOTER_HEX}")
}
CMD_CARD_UPLOAD -> sendCmd("${HEADER_HEX}050203${FOOTER_HEX}")
CMD_OPERATION_RECORD -> sendCmd("${HEADER_HEX}0B0203${FOOTER_HEX}")
CMD_TEMP_REPORT -> sendCmd("${HEADER_HEX}100200${FOOTER_HEX}")
CMD_POSITION_REPORT -> sendCmd("${HEADER_HEX}0E0200${FOOTER_HEX}")
CMD_TIME_SYNC -> {
val nowMs = System.currentTimeMillis()
val timeSec = nowMs / 1000 + TimeZone.getDefault().getOffset(nowMs) / 1000
val timeHex = "%08X".format(timeSec.toInt())
.chunked(2).reversed().joinToString("")
sendCmd("${HEADER_HEX}0C02${timeHex}${FOOTER_HEX}")
}
CMD_ACTIVATE -> {
if (activateCode.isNotBlank()) sendCmd(activateCode)
}
}
}
/**
* 主线程:仅回调分发(不含 sendCmd 和日志)
*/
private fun invokeCallbacks(frame: ScaleFrame) {
when (frame.cmd) {
CMD_ACTIVATE -> {
activateListeners.forEach { it(frame) }
rawListeners[frame.cmd]?.forEach { it(frame) }
}
CMD_HEARTBEAT, CMD_HEARTBEAT_STORE -> {
val data = parser.parseHeartbeat(frame.rawBody)
if (data != null) {
heartbeatListeners.forEach { it(frame, data) }
}
rawListeners[frame.cmd]?.forEach { it(frame) }
}
CMD_UNLOCK -> {
lockListeners.forEach { it(frame) }
rawListeners[frame.cmd]?.forEach { it(frame) }
}
CMD_GET_STATUS -> {
val data = parser.parseStatus(frame.rawBody)
if (data != null) {
statusListeners.forEach { it(frame, data) }
}
rawListeners[frame.cmd]?.forEach { it(frame) }
}
CMD_CARD_UPLOAD -> {
cardListeners.forEach { it(frame) }
rawListeners[frame.cmd]?.forEach { it(frame) }
}
CMD_OPERATION_RECORD -> {
operationListeners.forEach { it(frame) }
rawListeners[frame.cmd]?.forEach { it(frame) }
}
CMD_TIME_SYNC -> {
timeSyncListeners.forEach { it(frame) }
rawListeners[frame.cmd]?.forEach { it(frame) }
}
CMD_POSITION_REPORT -> {
positionListeners.forEach { it(frame) }
rawListeners[frame.cmd]?.forEach { it(frame) }
}
CMD_TEMP_REPORT -> {
tempReportListeners.forEach { it(frame) }
rawListeners[frame.cmd]?.forEach { it(frame) }
}
else -> {
rawListeners[frame.cmd]?.forEach { it(frame) }
}
}
}
// ----------------------------------------------------------------
// 回调注册(链式调用)
// ----------------------------------------------------------------
/**
* 注册心跳回调(命令 0x01 / 0x81,终端发起)
* 回调参数:[ScaleFrame 帧信息] [HeartbeatData 心跳数据(含重量、锁状态、温度)]
*/
fun onHeartbeat(listener: (ScaleFrame, HeartbeatData) -> Unit): ScaleManager {
heartbeatListeners.add(listener)
return this
}
/**
* 注册获取状态回调(命令 0x03,服务端请求后终端响应)
* 回调参数:[ScaleFrame 帧信息] [StatusData 状态数据(含重量、锁状态、温度)]
*/
fun onStatus(listener: (ScaleFrame, StatusData) -> Unit): ScaleManager {
statusListeners.add(listener)
return this
}
/**
* 注册开锁反馈回调(命令 0x02,终端发起,关门后上报)
* 回调参数:[ScaleFrame 帧信息],锁状态等信息在 ScaleFrame.rawBody 中
*/
fun onLockFeedback(listener: (ScaleFrame) -> Unit): ScaleManager {
lockListeners.add(listener)
return this
}
/**
* 注册卡号上发回调(命令 0x05,终端发起)
* 回调参数:[ScaleFrame 帧信息],卡号等信息在 ScaleFrame.rawBody 中
*/
fun onCardUpload(listener: (ScaleFrame) -> Unit): ScaleManager {
cardListeners.add(listener)
return this
}
/**
* 注册操作记录上传回调(命令 0x0B,终端发起)
* 回调参数:[ScaleFrame 帧信息],操作记录在 ScaleFrame.rawBody 中
*/
fun onOperationRecord(listener: (ScaleFrame) -> Unit): ScaleManager {
operationListeners.add(listener)
return this
}
/**
* 注册对时回调(命令 0x0C,终端发起)
* 管理器已自动回复当前时间戳,此回调用于业务侧感知对时事件
*/
fun onTimeSync(listener: (ScaleFrame) -> Unit): ScaleManager {
timeSyncListeners.add(listener)
return this
}
/**
* 注册终端位置上报回调(命令 0x0E,终端发起,仅4G版本)
* 回调参数:[ScaleFrame 帧信息],基站信息(MCC/MNC/LAC/CI)在 ScaleFrame.rawBody 中
*/
fun onPositionReport(listener: (ScaleFrame) -> Unit): ScaleManager {
positionListeners.add(listener)
return this
}
/**
* 注册温控信息上报回调(命令 0x10,终端发起)
* 回调参数:[ScaleFrame 帧信息],寄存器内容在 ScaleFrame.rawBody 中
*/
fun onTempReport(listener: (ScaleFrame) -> Unit): ScaleManager {
tempReportListeners.add(listener)
return this
}
/**
* 注册终端激活回调(命令 0x00,终端发起)
* 注意:激活应答(含激活码)需在此回调中手动调用 sendCmd() 发送
*/
fun onActivate(listener: (ScaleFrame) -> Unit): ScaleManager {
activateListeners.add(listener)
return this
}
/**
* 注册任意命令的原始帧监听(用于协议中尚未专项解析的命令,或扩展监听)
*
* @param cmd 命令字节,对应 ScaleProtocolConstants.CMD_* 常量
*/
fun onRawFrame(cmd: Byte, listener: (ScaleFrame) -> Unit): ScaleManager {
rawListeners.getOrPut(cmd) { mutableListOf() }.add(listener)
return this
}
/**
* 注册日志回调,所有内部日志通过此回调输出
*/
fun onLog(listener: (String) -> Unit): ScaleManager {
logListeners.add(listener)
return this
}
// ----------------------------------------------------------------
// 发送指令
// ----------------------------------------------------------------
/**
* 发送十六进制字符串指令,指令进入发送队列按顺序写入串口
*
* @param hexStr 完整帧十六进制字符串,含协议头尾
*/
fun sendCmd(hexStr: String) {
if (!scope.isActive) {
log("警告:ScaleManager 串口未打开或已释放")
return
}
sendChannel.trySend(hexStr)
}
// ----------------------------------------------------------------
// 常用指令构建
// ----------------------------------------------------------------
/**
* 构建获取设备状态指令
* 协议:CMD=03 FLAG=01 [预留12字节]
*/
fun buildGetStatusCmd(): String =
"${HEADER_HEX}0301${"00".repeat(12)}${FOOTER_HEX}"
/**
* 构建开锁/控制指令
*
* @param lock1 锁1操作:1=开 0=关 其他值(如0xFF)=不动作
* @param lock2 锁2操作:1=开 0=关 其他值=不动作
* @param relay1 继电器11=开 0=关 其他值=不动作
* @param relay2 继电器21=开 0=关 其他值=不动作
* @param relay3 继电器31=开 0=关 其他值=不动作
* @param orderId 订单号,超出14字节截断,不足补零
*/
fun buildUnlockCmd(
lock1: Int = 0xFF,
lock2: Int = 0xFF,
relay1: Int = 0xFF,
relay2: Int = 0xFF,
relay3: Int = 0xFF,
orderId: String = ""
): String {
val orderBytes = orderId.toByteArray(Charsets.US_ASCII).copyOf(14)
val orderHex = orderBytes.joinToString("") { "%02X".format(it) }
return "${HEADER_HEX}0201" +
"%02X%02X%02X%02X%02X".format(lock1 and 0xFF, lock2 and 0xFF, relay1 and 0xFF, relay2 and 0xFF, relay3 and 0xFF) +
orderHex +
FOOTER_HEX
}
/**
* 构建开锁1指令(左门)
* @param orderId 订单号,可选
*/
fun buildOpenLock1Cmd(orderId: String = ""): String =
buildUnlockCmd(lock1 = 1, lock2 = 0xFF, relay1 = 0xFF, relay2 = 0xFF, relay3 = 0xFF, orderId = orderId)
/**
* 构建开锁2指令(右门)
* @param orderId 订单号,可选
*/
fun buildOpenLock2Cmd(orderId: String = ""): String =
buildUnlockCmd(lock1 = 0xFF, lock2 = 1, relay1 = 0xFF, relay2 = 0xFF, relay3 = 0xFF, orderId = orderId)
/**
* 构建秤置零指令
* 协议:CMD=04 FLAG=01 [秤号1字节]
*
* @param scaleIndex 秤号,从1开始
*/
fun buildScaleZeroCmd(scaleIndex: Int): String =
"${HEADER_HEX}0401%02X${FOOTER_HEX}".format(scaleIndex and 0xFF)
/**
* 构建秤标定指令
* 协议:CMD=06 FLAG=01 [秤号1字节] [砝码值4字节小端序]
*
* @param scaleIndex 秤号,从1开始
* @param weightGrams 砝码重量(克),如10kg砝码传入10000
*/
fun buildScaleCalibrateCmd(scaleIndex: Int, weightGrams: Int): String {
// 砝码值转小端序4字节(BCD编码:克数按十进制写入十六进制位)
val weightHex = "%08d".format(weightGrams) // BCD:十进制值直接作为十六进制字符串
val leHex = weightHex.chunked(2).reversed().joinToString("")
return "${HEADER_HEX}0601%02X${leHex}${FOOTER_HEX}".format(scaleIndex and 0xFF)
}
/**
* 构建温控器控制指令
* 协议:CMD=0F FLAG=01 [操作编码1字节] [设定值2字节]
*
* @param opCode 操作编码(参考温控器说明书)
* @param setValue 设定值
*/
fun buildTempCtrlCmd(opCode: Int, setValue: Int): String =
"${HEADER_HEX}0F01%02X%04X${FOOTER_HEX}".format(opCode and 0xFF, setValue and 0xFFFF)
/**
* 构建临时参数设置指令
* 协议:CMD=11 FLAG=01 [参数编码1字节] [设定值1字节]
*
* @param paramCode 参数编码(1=关门语音触发条件 2=未关门语音提示 3=锁常开设置)
* @param value 设定值
*/
fun buildTempParamSetCmd(paramCode: Int, value: Int): String =
"${HEADER_HEX}1101%02X%02X${FOOTER_HEX}".format(paramCode and 0xFF, value and 0xFF)
// ----------------------------------------------------------------
// 资源释放
// ----------------------------------------------------------------
/**
* 释放所有资源:清空回调列表、发送函数及帧缓冲
* 通常在 Activity/Fragment 销毁或不再使用时调用
*/
suspend fun release() {
sendChannel.close()
scope.cancel()
serialPort?.close()
serialPort = null
heartbeatListeners.clear()
statusListeners.clear()
lockListeners.clear()
cardListeners.clear()
operationListeners.clear()
timeSyncListeners.clear()
positionListeners.clear()
tempReportListeners.clear()
activateListeners.clear()
rawListeners.clear()
logListeners.clear()
activateCode = ""
lastHeartbeatLogSecond = 0
parser.reset()
}
// ----------------------------------------------------------------
// 日志与工具
// ----------------------------------------------------------------
/** 上次心跳日志时间(秒),用于降频:同一秒内不重复记录心跳日志 */
private var lastHeartbeatLogSecond: Long = 0
/**
* IO 线程:心跳日志降频 — 每秒最多记录一次
*/
private fun logHeartbeatIfNeeded(frame: ScaleFrame, rawHex: String) {
val nowSec = System.currentTimeMillis() / 1000
if (nowSec == lastHeartbeatLogSecond) return
lastHeartbeatLogSecond = nowSec
val data = parser.parseHeartbeat(frame.rawBody)
log("收到[心跳]指令,终端ID${frame.terminalId},秤数量:${data?.scaleCount ?: 0},原始数据:$rawHex")
}
private fun log(message: String) {
logListeners.forEach { it(message) }
}
/**
* 将 ASCII 字符串转为十六进制字符串,用于指令构造
* 例:"V2.10" → "56322E3130"
*/
private fun String.toAsciiHex(): String =
toByteArray(Charsets.US_ASCII).joinToString("") { "%02X".format(it) }
}
@@ -0,0 +1,121 @@
package com.shuwei.intelligent.shelves.serial
/**
* 称重控制板接口协议常量
* 统一管理协议头尾、所有命令字节及帧结构偏移量
* 设计为独立常量对象,不依赖任何业务类,可复制到其他项目直接使用
*/
object ScaleProtocolConstants {
// ----------------------------------------------------------------
// 协议头尾
// ----------------------------------------------------------------
/** 协议头字节数组 */
val HEADER: ByteArray = byteArrayOf(0xD6.toByte(), 0xDA.toByte(), 0xDE.toByte(), 0xDB.toByte())
/** 协议头十六进制字符串 */
const val HEADER_HEX: String = "D6DADEDB"
/** 协议尾字节数组 */
val FOOTER: ByteArray = byteArrayOf(0xFF.toByte(), 0xFF.toByte())
/** 协议尾十六进制字符串 */
const val FOOTER_HEX: String = "FFFF"
// ----------------------------------------------------------------
// 命令字节(cmd 字段,1字节)
// 发起方说明:终端=秤控制板主动上报;服务端=Android端主动发送
// ----------------------------------------------------------------
/** 0x00 终端激活(终端发起) */
const val CMD_ACTIVATE: Byte = 0x00
/** 0x01 心跳(终端发起) */
const val CMD_HEARTBEAT: Byte = 0x01
/** 0x81 心跳(终端发起,需存储串口屏显示信息) */
const val CMD_HEARTBEAT_STORE: Byte = 0x81.toByte()
/** 0x02 开锁(服务端发起) */
const val CMD_UNLOCK: Byte = 0x02
/** 0x03 获取状态(服务端发起) */
const val CMD_GET_STATUS: Byte = 0x03
/** 0x04 秤置零(服务端发起) */
const val CMD_SCALE_ZERO: Byte = 0x04
/** 0x05 卡号上发(终端发起) */
const val CMD_CARD_UPLOAD: Byte = 0x05
/** 0x06 秤标定(服务端发起) */
const val CMD_SCALE_CALIBRATE: Byte = 0x06
/** 0x07 价签设置(服务端发起) */
const val CMD_PRICE_TAG_SET: Byte = 0x07
/** 0x08 串口屏(服务端发起) */
const val CMD_SERIAL_SCREEN: Byte = 0x08
/** 0x09 语音播报(服务端发起) */
const val CMD_VOICE_BROADCAST: Byte = 0x09
/** 0x0A 价签(第二块串口屏/透传)设置(服务端发起) */
const val CMD_PRICE_TAG_SET2: Byte = 0x0A
/** 0x0B 操作记录上传(终端发起) */
const val CMD_OPERATION_RECORD: Byte = 0x0B
/** 0x0C 对时(终端发起) */
const val CMD_TIME_SYNC: Byte = 0x0C
/** 0x0E 终端位置上报(终端发起) */
const val CMD_POSITION_REPORT: Byte = 0x0E
/** 0x0F 温控器控制(服务端发起) */
const val CMD_TEMP_CTRL: Byte = 0x0F
/** 0x10 温控信息上报(终端发起) */
const val CMD_TEMP_REPORT: Byte = 0x10
/** 0x11 临时参数设置(服务端发起) */
const val CMD_TEMP_PARAM_SET: Byte = 0x11
// ----------------------------------------------------------------
// 帧结构固定偏移量(单位:字节)
// ----------------------------------------------------------------
/** 协议头长度 */
const val HEADER_LEN: Int = 4
/** 命令字段长度 */
const val CMD_LEN: Int = 1
/** 标志字段长度 */
const val FLAG_LEN: Int = 1
/** 数据体起始偏移(协议头 + 命令 + 标志) */
const val BODY_OFFSET: Int = HEADER_LEN + CMD_LEN + FLAG_LEN
/** 协议尾长度 */
const val FOOTER_LEN: Int = 2
/** 单台秤重量字节数 */
const val BYTES_PER_WEIGHT: Int = 4
/** 物联卡号字节数 */
const val SIM_CARD_NO_LEN: Int = 20
/** 固定数据体:终端ID字节数 */
const val TERMINAL_ID_LEN: Int = 15
/** 固定数据体:固件版本字节数 */
const val FIRMWARE_VERSION_LEN: Int = 5
/** 固定数据体:命令次数字节数 */
const val CMD_COUNT_LEN: Int = 1
/** 固定数据体总长度(终端ID + 固件版本 + 命令次数) */
const val FIXED_BODY_LEN: Int = TERMINAL_ID_LEN + FIRMWARE_VERSION_LEN + CMD_COUNT_LEN
}
@@ -0,0 +1,15 @@
package com.shuwei.intelligent.shelves.serial
/**
* 单台秤的重量数据
*
* @param index 秤的编号,从1开始
* @param grams 重量,单位克,负数表示去皮/负重
*/
data class ScaleWeight(
val index: Int,
val grams: Int
) {
/** 重量转换为千克,保留3位小数 */
val kg: Double get() = grams / 1000.0
}
@@ -1,78 +0,0 @@
package com.shuwei.intelligent.shelves.serial
import android.annotation.SuppressLint
import androidx.lifecycle.lifecycleScope
import com.shuwei.intelligent.shelves.utils.hexToBytes
import com.shuwei.intelligent.shelves.utils.toHexString2
import io.github.jeadyx.jserialport.AndroidSerialPort
import io.github.jeadyx.jserialport.SerialPort
import io.github.jeadyx.jserialport.SerialPortFactory
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collectLatest
import java.nio.charset.Charset
import java.util.Locale
object SerialPortManager {
private const val portName: String = "/dev/ttyS1"
private const val baudRate: Int = 115200
private var serialPort: AndroidSerialPort? = null
// private var serialPort: SerialPort? = null
private val scope = CoroutineScope(Dispatchers.IO)
// 打开串口
suspend fun open(): Boolean {
return try {
serialPort = SerialPortFactory.create().apply {
open(
portName = portName,
baudRate = baudRate,
dataBits = 8,
stopBits = 1,
parity = SerialPort.PARITY_NONE
)
} as AndroidSerialPort?
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
// 发送数据
suspend fun send(data: String): Boolean {
return try {
serialPort?.write(data.hexToBytes())
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}
// 启动接收协程
@Suppress("DEPRECATION")
@SuppressLint("DefaultLocale")
fun startReceive(callback: (String) -> Unit) {
scope.launch {
while (isActive) {
try {
val flow = serialPort?.read()
flow?.collect { buffer ->
val data = buffer.toHexString2().toUpperCase()
callback(data)
}
} catch (e: Exception) {
e.printStackTrace()
}
delay(50)
}
}
}
// 关闭串口
suspend fun close() {
scope.cancel()
serialPort?.close()
}
}
@@ -0,0 +1,22 @@
package com.shuwei.intelligent.shelves.serial
/**
* 获取设备状态数据(命令 0x03,服务端发起后终端响应)
*
* @param lock1Lock 锁1锁状态:0-关 1-开
* @param lock1Door 锁1门状态:0-关 1-开
* @param lock2Lock 锁2锁状态:0-关 1-开
* @param lock2Door 锁2门状态:0-关 1-开
* @param scaleCount 秤的数量
* @param weights 各台秤的重量列表,索引从1开始
* @param temperature 温度值(原始字节,单位由温控器决定)
*/
data class StatusData(
val lock1Lock: Int,
val lock1Door: Int,
val lock2Lock: Int,
val lock2Door: Int,
val scaleCount: Int,
val weights: List<ScaleWeight>,
val temperature: Int
)
@@ -1,32 +0,0 @@
//package com.shuwei.intelligent.shelves.task
//
//import android.content.Context
//import android.util.Log
//import androidx.work.CoroutineWorker
//import androidx.work.WorkerParameters
//import com.shuwei.intelligent.shelves.activity.HomeActivity
//import com.shuwei.intelligent.shelves.serial.SerialPortManager
//
//class SyncDeviceTask(appContext: Context, workerParams: WorkerParameters) :
// CoroutineWorker(appContext, workerParams) {
//
// companion object {
// private const val TAG = "SyncDeviceTask"
// }
//
// override suspend fun doWork(): Result {
// return try {
// // 执行后台任务逻辑
// Log.d(TAG, "doWork: ----------SyncDeviceTask----------")
// SerialPortManager.send(HomeActivity.DEVICE_INFO_CMD)
//
// TaskManager.startDeviceTask()
//
// Result.success()
// } catch (e: Exception) {
// e.printStackTrace()
// Result.retry()
// }
// }
//
//}
@@ -1,67 +0,0 @@
//package com.shuwei.intelligent.shelves.task
//
//import android.content.Context
//import android.util.Log
//import androidx.work.CoroutineWorker
//import androidx.work.WorkerParameters
//import com.shuwei.intelligent.shelves.App
//import com.shuwei.intelligent.shelves.activity.HomeActivity
//import com.shuwei.intelligent.shelves.model.ShelfBody
//import com.shuwei.intelligent.shelves.net.apiService
//import com.shuwei.intelligent.shelves.utils.ext.toJsonString
//import kotlinx.coroutines.Dispatchers
//import kotlinx.coroutines.withContext
//
//class SyncTask(appContext: Context, workerParams: WorkerParameters) :
// CoroutineWorker(appContext, workerParams) {
//
// companion object {
// private const val TAG = "SyncTask"
// }
//
// override suspend fun doWork(): Result {
// return try {
// // 执行后台任务逻辑
// performSync()
//
// TaskManager.startTask()
//
// Result.success()
// } catch (e: Exception) {
// e.printStackTrace()
// Result.retry()
// }
// }
//
// private suspend fun performSync() {
// withContext(Dispatchers.IO) {
// val list = HomeActivity.list
// Log.d(TAG, "performSync: list:${list.toJsonString()}")
// val submitList = list.sortedBy { it.deviceNo }
// submitList.forEach {
// if (it.goodsId.isNullOrBlank()) {
// it.weight = it.weightBak
// }
// }
//// submitList.forEach {
//// it.temperature = HomeActivity.showTemperatureC
//// it.humidity = HomeActivity.showHumidity
//// }
// val body = ShelfBody().also {
// it.deviceId = App.deviceId
// it.canteenId = App.canteenId
// it.temperature = HomeActivity.showTemperatureC
// it.humidity = HomeActivity.showHumidity
// it.goodsList = submitList
// }
// Log.d(TAG, "performSync: body:${body.toJsonString()}")
// try {
// val resp = apiService.saveShelfGoodsList(body = body)
// Log.d(TAG, "performSync: resp:${resp.toJsonString()}")
// } catch (e: Exception) {
// e.printStackTrace()
// }
// }
// }
//
//}
@@ -1,59 +0,0 @@
//package com.shuwei.intelligent.shelves.task
//
//import androidx.work.ExistingWorkPolicy
//import androidx.work.OneTimeWorkRequestBuilder
//import androidx.work.WorkManager
//import com.shuwei.intelligent.shelves.App
//import java.util.concurrent.TimeUnit
//
//object TaskManager {
// const val TASK_NAME = "IntelligentShelvesSyncTask"
// const val DEVICE_TASK_NAME = "IntelligentShelvesDeviceTask"
//
// fun startTask() {
// val nextRequest = OneTimeWorkRequestBuilder<SyncTask>()
// .setInitialDelay(2, TimeUnit.MINUTES)
//// .setInitialDelay(30, TimeUnit.SECONDS)
//// .setInitialDelay(10, TimeUnit.MINUTES)
//// .setInputData(inputData)
// .build()
// WorkManager.getInstance(App.getInstance())
// .enqueueUniqueWork(TASK_NAME, ExistingWorkPolicy.REPLACE, nextRequest)
//
//// val constraints = Constraints.Builder()
//// .setRequiredNetworkType(NetworkType.CONNECTED)
//// .setRequiresBatteryNotLow(true)
//// .build()
//// val syncRequest = PeriodicWorkRequestBuilder<SyncTask>(
//// 3L, TimeUnit.MINUTES, // 最小间隔15分钟
//// 3L, TimeUnit.MINUTES // 弹性时间窗口
//// )
//// .setConstraints(constraints)
//// .build()
//// WorkManager.getInstance(App.get())
//// .enqueueUniquePeriodicWork(
//// TASK_NAME,
//// ExistingPeriodicWorkPolicy.KEEP,
//// syncRequest
//// )
// }
//
// fun cancelTask() {
// WorkManager.getInstance(App.getInstance())
// .cancelUniqueWork(TASK_NAME)
// }
//
// fun startDeviceTask() {
// val nextRequest = OneTimeWorkRequestBuilder<SyncDeviceTask>()
// .setInitialDelay(2, TimeUnit.MINUTES)
// .build()
// WorkManager.getInstance(App.getInstance())
// .enqueueUniqueWork(DEVICE_TASK_NAME, ExistingWorkPolicy.REPLACE, nextRequest)
// }
//
// fun cancelDeviceTask() {
// WorkManager.getInstance(App.getInstance())
// .cancelUniqueWork(DEVICE_TASK_NAME)
// }
//
//}
@@ -3,7 +3,7 @@ package com.shuwei.intelligent.shelves.utils
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.shuwei.intelligent.shelves.activity.InitActivity
import com.sw.scalefusion.shelf.InitActivity
import kotlin.jvm.java
class BootReceiver : BroadcastReceiver() {
@@ -1,8 +0,0 @@
package com.shuwei.intelligent.shelves.utils
/**
* 命令常亮定义
*/
object Constant {
}
@@ -39,11 +39,19 @@ class CrashHandler private constructor(private val context: Context) :
synchronized(CrashHandler::class.java) {
if (instance == null) {
instance = CrashHandler(context.applicationContext)
// 初始化时清理过期的崩溃日志(默认保留7天)
instance?.cleanupOldCrashReports()
}
}
}
}
/**
* 获取单例实例
* @return 已通过 init() 初始化时返回实例,否则返回 null
*/
fun getInstance(): CrashHandler? = instance
//fun getCrashReportFiles(context: Context): Array<File> {
// val crashDir = getCrashDir()
// return if (crashDir.exists() && crashDir.isDirectory) {
@@ -222,6 +230,8 @@ class CrashHandler private constructor(private val context: Context) :
* 清理旧的崩溃日志
*/
fun cleanupOldCrashReports(maxAgeDays: Int = 7) {
// 该方法会在 Application 启动及定时任务中调用,异常必须内部消化,避免影响主流程
try {
val crashDir = getCrashDir()
if (!crashDir.exists() || !crashDir.isDirectory) return
@@ -233,6 +243,9 @@ class CrashHandler private constructor(private val context: Context) :
file.delete()
}
}
} catch (e: Exception) {
Log.e(TAG, "清理崩溃日志失败", e)
}
}
private fun getCrashDir():File {
@@ -1,5 +0,0 @@
package com.shuwei.intelligent.shelves.utils
fun f2C(fahrenheit: Double): Double {
return (fahrenheit - 32) * 5 / 9
}
@@ -1,131 +1,122 @@
package com.shuwei.intelligent.shelves.utils
import android.content.Context
import com.shuwei.intelligent.shelves.utils.CrashHandler.Companion.CRASH_REPORTS_DIR
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
/**
* 文件日志记录器
* 功能:保存日志到本地文件,每条数据一行,每天生成新文件
* 文件日志记录器(异步版)
*
* log() 仅投递原始消息到 Channel(任意线程安全),
* 格式化与文件写入在单一后台协程顺序执行,避免 SimpleDateFormat 多线程竞争。
*/
class FileLogger(private val context: Context) {
class FileLogger(context: Context) {
companion object {
private const val LOG_DIR = "logs"
private const val FILE_PREFIX = "log_"
private const val FILE_EXTENSION = ".txt"
private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
private val timeFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
/** 日志保留天数,超过该天数的日志文件在应用启动时清理 */
private const val RETENTION_DAYS = 7L
/** 单个日志文件大小上限(100MB),超过后当天不再写入,防止异常刷屏撑爆存储 */
private const val MAX_LOG_FILE_SIZE = 100L * 1024 * 1024
/** 全局单线程日志写入 */
private val logChannel = Channel<RawEntry>(capacity = Channel.UNLIMITED)
private val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
init {
writerScope.launch {
// 单协程顺序消费:SimpleDateFormat 在此线程安全
val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val timeFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
for (entry in logChannel) {
try {
val fileName = "${FILE_PREFIX}${dateFormat.format(Date())}${FILE_EXTENSION}"
// 单文件超过大小上限时丢弃本条日志,防止异常刷屏撑爆存储(单协程检查,无并发问题)
val file = File(entry.appContext.filesDir, fileName)
if (file.exists() && file.length() > MAX_LOG_FILE_SIZE) continue
val timestamp = timeFormat.format(Date())
val logLine = "[$timestamp] [${entry.level}] ${entry.message}\n"
val output = entry.appContext.openFileOutput(
fileName, Context.MODE_APPEND
)
BufferedWriter(OutputStreamWriter(output)).use { it.write(logLine) }
} catch (_: Exception) {
// 写入失败静默丢弃
}
}
}
}
private data class RawEntry(
val appContext: Context,
val message: String,
val level: LogLevel
)
/**
* 记录日志
* @param message 日志消息
* @param level 日志级别
* 清理过期的日志文件,保留最近 retentionDays 天
* 按文件最后修改时间判断,最近仍在写入的文件不会被误删
* 建议在 Application 启动时调用一次
* @param context 上下文,用于定位 filesDir
* @param retentionDays 日志保留天数
*/
fun log(message: String, level: LogLevel = LogLevel.INFO) {
fun cleanupExpiredLogs(context: Context, retentionDays: Long = RETENTION_DAYS) {
try {
val logEntry = formatLogEntry(message, level)
writeToFile(logEntry)
} catch (e: IOException) {
val cutoff = System.currentTimeMillis() - retentionDays * 24 * 60 * 60 * 1000L
context.filesDir.listFiles { _, name ->
name.startsWith(FILE_PREFIX) && name.endsWith(FILE_EXTENSION)
}?.forEach { file ->
if (file.lastModified() < cutoff) {
file.delete()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* 格式化日志条目
*/
private fun formatLogEntry(message: String, level: LogLevel): String {
val timestamp = timeFormat.format(Date())
return "[$timestamp] [$level] $message\n"
}
/**
* 写入文件
*/
private fun writeToFile(logEntry: String) {
// val path = File(context.filesDir, LOG_DIR)
// if (path.exists().not()) {
// path.mkdirs()
// }
val fileName = getCurrentDateFileName()
// val file = File(path, fileName)
// if (file.exists().not()) {
// file.createNewFile()
// }
val output = context.openFileOutput(fileName, Context.MODE_APPEND)
val writer = BufferedWriter(OutputStreamWriter(output))
writer.use {
it.write(logEntry)
}
}
/** 持有 ApplicationContext 避免 Activity 泄漏 */
private val appContext: Context = context.applicationContext
/**
* 获取当前日期对应的文件名
* 记录日志(异步,线程安全)
*/
private fun getCurrentDateFileName(): String {
val date = dateFormat.format(Date())
return "${FILE_PREFIX}${date}${FILE_EXTENSION}"
fun log(message: String, level: LogLevel = LogLevel.INFO) {
logChannel.trySend(RawEntry(appContext, message, level))
}
/**
* 读取指定日期的日志文件
* @param date 日期字符串,格式:yyyy-MM-dd
*/
fun readLogsByDate(date: String): List<String> {
val fileName = "${FILE_PREFIX}${date}${FILE_EXTENSION}"
return readLogsByName(fileName)
return readLogsByName("${FILE_PREFIX}${date}${FILE_EXTENSION}")
}
fun readLogsByName(fileName: String): List<String> {
try {
val input = context.openFileInput(fileName)
val input = appContext.openFileInput(fileName)
val reader = BufferedReader(InputStreamReader(input))
val list: MutableList<String> = reader.useLines { lines ->
lines.toList().toMutableList()
}
// val input2 = FileInputStream(getCrashDir(context))
// val reader2 = BufferedReader(InputStreamReader(input2))
// val list2: MutableList<String> = reader2.useLines {lines ->
// lines.toList().toMutableList()
// }
// list.addAll(list2)
return list
} catch (e: FileNotFoundException) {
return reader.useLines { lines -> lines.toList().toMutableList() }
} catch (_: FileNotFoundException) {
return emptyList()
}
}
public fun getCrashDir(context: Context):File {
//val crashDir = File(context.getExternalFilesDir(null), CRASH_REPORTS_DIR)
var crashDir = File(context.filesDir, CRASH_REPORTS_DIR)
if (!crashDir.exists()) {
crashDir.mkdirs()
}
if (!(crashDir.exists())) {
crashDir = File(context.cacheDir, CRASH_REPORTS_DIR)
}
fun getCrashDir(context: Context): File {
var crashDir = File(context.filesDir, "crash_reports")
if (!crashDir.exists()) crashDir.mkdirs()
if (!crashDir.exists()) crashDir = File(context.cacheDir, "crash_reports")
return crashDir
}
/**
* 获取所有日志文件列表
*/
fun getLogFiles(): List<String> {
return context.fileList()
return appContext.fileList()
.filter { it.startsWith(FILE_PREFIX) && it.endsWith(FILE_EXTENSION) }
//.map { it.replace(FILE_EXTENSION, "") }
}
/**
* 日志级别枚举
*/
enum class LogLevel {
DEBUG, INFO, WARN, ERROR
}
enum class LogLevel { DEBUG, INFO, WARN, ERROR }
}
@@ -1,64 +0,0 @@
package com.shuwei.intelligent.shelves.utils;
public class HexUtils {
/**
* 将有符号十六进制字符串转换为十进制整数
* @param hex 十六进制字符串(支持负数补码表示)
* @return 对应的十进制整数
*/
public static int signedHexToDec(String hex) {
// 验证输入格式
if (hex == null || hex.isEmpty()) {
throw new IllegalArgumentException("输入不能为空");
}
if (!hex.matches("[0-9A-Fa-f]+")) {
throw new IllegalArgumentException("无效的十六进制格式: " + hex);
}
// 转换为无符号长整型
long unsignedValue = Long.parseLong(hex, 16);
// 判断是否为负数(最高位为1
int bitLength = hex.length() * 4; // 每个十六进制字符对应4位
long signBitMask = 1L << (bitLength - 1);
if ((unsignedValue & signBitMask) != 0) {
// 负数:计算补码
long maxValue = (1L << bitLength) - 1;
return (int) (unsignedValue - (maxValue + 1));
} else {
// 正数:直接转换
return (int) unsignedValue;
}
}
/**
* 测试方法
*/
public static void main(String[] args) {
// 测试用例
String[] testCases = {
"FF", // -1 (8位)
"FFFE", // -2 (16位)
"FFFFFFFE", // -2 (32位)
"7F", // 127
"80", // -128
"7FFF", // 32767
"8000" // -32768
};
System.out.println("有符号十六进制转换测试:");
for (String hex : testCases) {
try {
int result = signedHexToDec(hex);
System.out.println(hex + " -> " + result);
} catch (Exception e) {
System.out.println(hex + " -> 错误: " + e.getMessage());
}
}
}
}
@@ -1,101 +0,0 @@
package com.shuwei.intelligent.shelves.utils
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
/**
* 二维码生成工具类
*/
object QRCodeUtil {
/**
* 生成二维码(默认大小)
* @param content 二维码内容
* @return 生成的二维码Bitmap
*/
@JvmOverloads
fun generateQRCode(content: String, size: Int = 500): Bitmap? {
return generateQRCode(content, size, Color.BLACK, Color.WHITE)
}
/**
* 生成二维码(自定义颜色)
* @param content 二维码内容
* @param size 二维码边长(像素)
* @param colorCode 二维码颜色
* @param backgroundColor 背景颜色
* @return 生成的二维码Bitmap
*/
fun generateQRCode(
content: String,
size: Int,
colorCode: Int,
backgroundColor: Int
): Bitmap? {
if (content.isEmpty()) {
return null
}
return try {
val hints = mutableMapOf<EncodeHintType, Any>().apply {
put(EncodeHintType.CHARACTER_SET, "UTF-8")
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H) // 纠错级别
put(EncodeHintType.MARGIN, 1) // 边距
}
val bitMatrix = QRCodeWriter().encode(
content,
BarcodeFormat.QR_CODE,
size,
size,
hints
)
val pixels = IntArray(size * size).apply {
for (y in 0 until size) {
for (x in 0 until size) {
this[y * size + x] = if (bitMatrix.get(x, y)) colorCode else backgroundColor
}
}
}
Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply {
setPixels(pixels, 0, size, 0, 0, size, size)
}
} catch (e: WriterException) {
e.printStackTrace()
null
}
}
/**
* 生成带Logo的二维码
* @param content 二维码内容
* @param size 二维码边长(像素)
* @param logo Logo Bitmap
* @return 带Logo的二维码Bitmap
*/
fun generateQRCodeWithLogo(content: String, size: Int, logo: Bitmap?): Bitmap? {
val qrCode = generateQRCode(content, size) ?: return null
logo ?: return qrCode
val logoSize = size / 5 // Logo大小约为二维码的1/5
val scaledLogo = Bitmap.createScaledBitmap(logo, logoSize, logoSize, false)
val offset = (size - logoSize) / 2
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply {
val canvas = Canvas(this)
canvas.drawBitmap(qrCode, 0f, 0f, null)
canvas.drawBitmap(scaledLogo, offset.toFloat(), offset.toFloat(), null)
}
}
}
@@ -1,57 +0,0 @@
//package com.shuwei.intelligent.shelves.utils
//
//
//import android.serialport.*
////import io.github.jeadyx.jserialport.SerialPort
//import java.io.File
//import java.io.IOException
//import java.io.InputStream
//import java.io.OutputStream
//
//class SerialPortHelper(
// private val devicePath: String = "/dev/ttyS1",
// private val baudRate: Int = 115200
//) {
// private var serialPort: SerialPort? = null
// private var inputStream: InputStream? = null
// private var outputStream: OutputStream? = null
//
// // 打开串口
// fun open(): Boolean {
// return try {
// serialPort = SerialPort(File(devicePath), baudRate, 0)
// inputStream = serialPort?.inputStream
// outputStream = serialPort?.outputStream
// true
// } catch (e: IOException) {
// false
// }
// }
//
// // 发送数据
// fun send(data: ByteArray): Boolean {
// return try {
// outputStream?.write(data)
// outputStream?.flush()
// true
// } catch (e: IOException) {
// false
// }
// }
//
// // 接收数据(需在子线程调用)
// fun receive(buffer: ByteArray): Int {
// return inputStream?.read(buffer) ?: -1
// }
//
// // 关闭串口
// fun close() {
// try {
// inputStream?.close()
// outputStream?.close()
// serialPort?.close()
// } catch (e: IOException) {
// e.printStackTrace()
// }
// }
//}
@@ -1,6 +1,7 @@
package com.shuwei.intelligent.shelves.utils
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.GlobalKey
import com.shuwei.intelligent.shelves.utils.ext.put
import kotlin.to
@@ -28,4 +29,10 @@ object SpTool {
fun getBoolean(key: String, defValue: Boolean = false): Boolean {
return pref.getBoolean(key, defValue)
}
var baseUrl: String
get() = getString(GlobalKey.KEY_BASE_URL, "")
set(value) {
put(GlobalKey.KEY_BASE_URL, value)
}
}
@@ -1,36 +0,0 @@
package com.shuwei.intelligent.shelves.utils
import android.util.SparseArray
import androidx.core.util.containsKey
import com.shuwei.intelligent.shelves.model.ShelfModel
object StaleFoodRule {
private val shelfMap = SparseArray<ShelfModel>()
// fun load(list: MutableList<ShelfModel>) {
// if (list.isEmpty()) {
// return
// }
// list.forEach {
// shelfMap.put(it.deviceNo, it)
// }
// }
fun judge(item: ShelfModel, block:(Boolean)-> Unit = {}) {
val deviceNo = item.deviceNo
if (!shelfMap.containsKey(deviceNo)) {
//首次设置数据
shelfMap.put(deviceNo, item)
return
}
val lastItem = shelfMap.get(deviceNo)
if (lastItem.goodsId != item.goodsId) {
//柜子商品更换
shelfMap.put(deviceNo, item)
return
}
//同一产品
}
}
@@ -1,282 +0,0 @@
package com.shuwei.intelligent.shelves.utils;
//import cn.hutool.core.util.HexUtil;
//import cn.hutool.core.util.StrUtil;
//import com.chengyi.framework.utils.HexUtils;
//import lombok.Data;
//import lombok.extern.slf4j.Slf4j;
/**
* @Author: NThink
* @Date: 2021/12/10
* @Description: 鸿科HK70温控器信息消息解包
*/
public class TemperatureInfoHK70MsgBodyUnpack {
// 柜温探头温度
private Double gwttTemp;
// 蒸发探头温度
private Double zfttTemp;
// 冷凝探头温度
private Double lnttTemp;
// 停机温度
private Double tjTemp;
// 开机温度回差
private Double kjTempRange;
// 压缩机启动延时
private Integer ysjStartDelay;
// 首次通电压缩机启动延时
private Integer ysjStartDelayFirst;
// 柜温探头补偿
private Double gwttbcTemp;
// 停机温度可设置的最小值
private Double tjTempMin;
// 停机温度可设置的最大值
private Double tjTempMax;
// 压缩机最大待机时间
private Integer ysjMaxWait;
// 压缩机最短运行时间
private Integer ysjMinWork;
// 蒸发器探头状态
private Integer zfttStatus;
// 自动除霜周期
private Integer zdcszq;
// 除霜过程显示
private Integer csWorkShow;
// 除霜最长时间
private Integer cszcsj;
// 除霜中止温度
private Double cszzTemp;
// 除霜类型
private Integer csType;
// 风机运行模式
private Integer fanWorkType;
// 风机首次启动延时
private Integer fanFirstStartDelay;
// 滴水后风机启动延时
private Integer fanStartDelayAfterDrip;
// 开关机状态
private String powerStatus;
// 制冷状态
private String coolStatus;
// 除霜状态
private String csStatus;
// 滴水状态
private String dsStatus;
// 柜温探头报警
private String gwttAlarm;
// 除霜探头报警
private String csttAlarm;
// 冷凝探头报警
private String lnttAlarm;
// 终端ID
private String imei;
// 固件版本
private String version;
// 命令次数
private Integer cmdCount;
public TemperatureInfoHK70MsgBodyUnpack(String body) {
// ===================== 寄存器内容:110字节 =====================
String jcqContent = body.substring(0, 220);
// 柜温探头温度 [0, 4]
double gwttTemp = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(0, 4)) * 0.1));
// setGwttTemp(gwttTemp);
// // 蒸发探头温度 [4, 8]
// double zfttTemp = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(4, 8)) * 0.1));
// setZfttTemp(zfttTemp);
// // 冷凝探头温度 [8, 12]
// double lnttTemp = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(8, 12)) * 0.1));
// setLnttTemp(lnttTemp);
// // 停机温度 [12, 16]
// double tjTemp = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(12, 16)) * 1.0));
// setTjTemp(tjTemp);
// // 开机温度回差 [16, 20]
// double kjwdhc = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(16, 20)) * 0.1));
// setKjTempRange(kjwdhc);
// // 压缩机启动延时 [20, 24]
// int ysjqdys = Integer.parseInt(jcqContent.substring(20, 24), 16);
// setYsjStartDelay(ysjqdys);
// // 首次通电压缩机启动延时 [24, 28]
// int ysjqdysFirst = Integer.parseInt(jcqContent.substring(24, 28), 16);
// setYsjStartDelayFirst(ysjqdysFirst);
// // 柜温探头补偿 [28, 32]
// double gwttbc = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(28, 32)) * 0.1));
// setGwttbcTemp(gwttbc);
// // 停机温度可设置的最小值 [32, 36]
// double tjTempMin = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(32, 36)) * 1.0));
// setTjTempMin(tjTempMin);
// // 停机温度可设置的最大值 [36, 40]
// double tjTempMax = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(36, 40)) * 1.0));
// setTjTempMin(tjTempMax);
// // 压缩机最大待机时间 [40, 44]
// int ysjzddjsj = Integer.parseInt(jcqContent.substring(40, 44), 16);
// setYsjMaxWait(ysjzddjsj);
// // 压缩机最短运行时间 [44, 48]
// int ysjzdyxsj = Integer.parseInt(jcqContent.substring(44, 48), 16);
// setYsjMinWork(ysjzdyxsj);
// // 蒸发器探头选择 [48, 52]
// int zfqtt = Integer.parseInt(jcqContent.substring(48, 52), 16);
// setZfttStatus(zfqtt);
// // TODO 蒸发器探头补偿 [52, 56]
// // TODO 自动除霜周期计算方式 [56, 60]
// // 自动除霜周期 [60, 64]
// int zdcszq = Integer.parseInt(jcqContent.substring(60, 64), 16);
// setZdcszq(zdcszq);
// // 除霜过程显示选择 [64, 68]
// int csgcxx = Integer.parseInt(jcqContent.substring(64, 68), 16);
// setCsWorkShow(csgcxx);
// // 除霜最长时间 [68, 72]
// int cszcsj = Integer.parseInt(jcqContent.substring(68, 72), 16);
// setCszcsj(cszcsj);
// // 除霜终止温度 [72, 76]
// double cszzwd = Double.parseDouble(String.format("%.1f", HexUtils.signedHexToDec(jcqContent.substring(72, 76)) * 1.0));
// setCszzTemp(cszzwd);
// // TODO 除霜滴水时间 [76, 80]
// // TODO 除霜后柜温显示延时 [80, 84]
// // TODO 除霜启动延迟 [84, 88]
// // 除霜类型选择 [88, 92]
// int cslx = Integer.parseInt(jcqContent.substring(88, 92), 16);
// setCsType(cslx);
// // TODO 辅热提前启动时间 [92, 96]
// // TODO 强制除霜温度 [96, 100]
// // 风机运行模式 [100, 104]
// int fjyxms = Integer.parseInt(jcqContent.substring(100, 104), 16);
// setFanWorkType(fjyxms);
// // 风机首次启动延时 [104, 108]
// int fjscqdys = Integer.parseInt(jcqContent.substring(104, 108), 16);
// setFanFirstStartDelay(fjscqdys);
// // 滴水后风机启动延时 [108, 112]
// int dshfjqdys = Integer.parseInt(jcqContent.substring(108, 112), 16);
// setFanStartDelayAfterDrip(dshfjqdys);
// // TODO 风机工作最低温度 [112, 116]
// // TODO 风机工作最高温度 [116, 120]
// // TODO 风机循环开启时间 [120, 124]
// // TODO 风机循环关闭时间 [124, 128]
// // TODO 比例制冷压缩机停止时间 [128, 132]
// // TODO 比例制冷压缩机运行时间 [132, 136]
// // TODO 蜂鸣音报警 [136, 140]
// // TODO 柜温低温报警(绝对温度) [140, 144]
// // TODO 柜温高温报警(绝对温度) [144, 148]
// // TODO 柜温报警延时 [148, 152]
// // TODO 上电首次柜温报警延时 [152, 156]
// // TODO 辅助继电器功能选择 [156, 160]
// // TODO 门开关控制输出选择 [160, 164]
// // TODO 开门时蜂鸣器响应延时 [164, 168]
// // TODO 第三探头功能选择 [168, 172]
// // TODO 冷凝器高温报警启动值 [172, 176]
// // TODO 冷凝器高温报警下回差 [176, 180]
// // TODO 冷凝器高温保护启动值 [180, 184]
// // TODO 实时时钟功能开关 [不上报]
// // TODO 非营业模式开启时间 [不上报]
// // TODO 非营业模式关闭时间 [不上报]
// // TODO 非营业模式温度增量 [不上报]
// // TODO 非营业模式灯光开启时间 [不上报]
// // TODO 节假日设置 [不上报]
// // TODO 节假日非营业模式开启时间 [不上报]
// // TODO 除雾自动控制模式 [184, 188]
// // TODO 除雾自动开启时间 [188, 192]
// // TODO 除雾自动关闭时间 [192, 196]
// // TODO 开关机自动控制模式 [不上报]
// // TODO 自动开机时间 [不上报]
// // TODO 自动关机时间 [不上报]
// // TODO 单位选择 [196, 200]
// // TODO 柜温每升高 1℃显示延时 [204, 208]
// // TODO 显示分辨率选择 [208, 212]
// // TODO 机器地址 [212, 216]
// // TODO 管理员密码设定 [216, 220]
//
// // ===================== 状态位解析:4字节 =====================
// // 1.状态信息
// String statusHexStr = body.substring(220, 224);
// statusHexStr = HexUtils.reverse(statusHexStr);
// String statusBitStr = HexUtils.hexString2binaryString(statusHexStr);
// statusBitStr = StrUtil.reverse(statusBitStr);
// // 机组运行状态 0:停止 1:运行 [0, 1]
// String powerStatus = "0".equals(statusBitStr.substring(0, 1)) ? "close" : "open";
// setPowerStatus(powerStatus);
// // TODO 自检状态 0:停止 1:运行 [1, 2]
// // 压缩机运行状态 0:停止 1:运行 [2, 3]
// String coolStatus = "0".equals(statusBitStr.substring(3, 4)) ? "close" : "open";
// setCoolStatus(coolStatus);
// // 除霜状态 0:停止 1:运行 [3, 4]
// String csStatus = "0".equals(statusBitStr.substring(10, 11)) ? "close" : "open";
// setCsStatus(csStatus);
// // 滴水状态 0:关闭 1:运行中 [4, 5]
// String dsStatus = "0".equals(statusBitStr.substring(12, 13)) ? "close" : "open";
// setDsStatus(dsStatus);
// // TODO 风机状态 0:停止 1:运行 [5, 6]
// // TODO 除露状态 0:停止 1:运行 [6, 7]
// // TODO 灯光状态 0:停止 1:运行 [7, 8]
// // TODO 除霜加热或电磁阀状态 0:停止 1:运行 [8, 9]
// // TODO 辅助加热状态 0:停止 1:运行 [9, 10]
// // TODO 报警状态 0:停止 1:运行 [10, 11]
// // TODO 开门状态 0:停止 1:运行 [11, 12]
// // TODO 非营业(节能)状态 0:停止 1:运行 [12, 13]
// // TODO 节假日状态 0:停止 1:运行 [13, 14]
// // TODO 保留 0:停止 1:运行 [14, 15]
// // TODO 保留 0:停止 1:运行 [15, 16]
//
// // 2.报警信息
// String alarmHexStr = body.substring(224, 228);
// String alarmBitStr = HexUtils.hexString2binaryString(alarmHexStr);
// alarmBitStr = StrUtil.reverse(alarmBitStr);
// // 柜温探头故障 0:无报警 1:报警
// String gwttAlarm = "0".equals(alarmBitStr.substring(0, 1)) ? "normal" : "alarm";
// setGwttAlarm(gwttAlarm);
// // 除霜探头故障 0:无报警 1:报警
// String csAlarm = "0".equals(alarmBitStr.substring(1, 2)) ? "normal" : "alarm";
// setCsttAlarm(csAlarm);
// // 冷凝探头故障 0:无报警 1:报警
// String lnttAlarm = "0".equals(alarmBitStr.substring(2, 3)) ? "normal" : "alarm";
// setLnttAlarm(lnttAlarm);
// // TODO 柜温高温报警 0:无报警 1:报警
// // TODO 柜温低温报警 0:无报警 1:报警
// // TODO 冷凝高温报警 0:无报警 1:报警
// // TODO 冷凝保护报警 0:无报警 1:报警
// // TODO 门打开报警 0:无报警 1:报警
// // TODO 时钟故障报警 0:无报警 1:报警
//
// // 终端ID 15字节
// setImei(HexUtil.decodeHexStr(body.substring(228, 258)));
// // 固件版本 5字节
// setVersion(HexUtil.decodeHexStr(body.substring(258, 268)));
// // 命令次数
// setCmdCount(Integer.parseInt(body.substring(268, 270), 16));
}
public static void main(String[] args) {
// String reverse = HexUtils.reverse("8000");
// System.out.println(reverse);
}
}
@@ -1,70 +0,0 @@
package com.shuwei.intelligent.shelves.utils.ext
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import androidx.core.graphics.toColorInt
interface DrawableDsl {
fun shape(init: ShapeDsl.() -> Unit)
}
interface ShapeDsl {
fun solidColor(color: Int)
fun stroke(width: Int, color: Int)
fun cornerRadius(radius: Float)
}
class DrawableBuilder : DrawableDsl {
val drawables = mutableListOf<ShapeDrawable>()
override fun shape(init: ShapeDsl.() -> Unit) {
val shape = ShapeDrawable()
init(shape)
drawables.add(shape)
}
}
class ShapeDrawable : ShapeDsl {
var color: Int? = null
var strokeWidth: Int? = null
var strokeColor: Int? = null
var cornerRadius: Float? = null
override fun solidColor(color: Int) {
this.color = color
}
override fun stroke(width: Int, color: Int) {
this.strokeWidth = width
this.strokeColor = color
}
override fun cornerRadius(radius: Float) {
this.cornerRadius = radius
}
}
fun createCustomDrawable(
solidColor: String,
strokeWidth: Int,
strokeColor: String,
radius: Int
): Drawable {
val builder = DrawableBuilder()
builder.shape {
solidColor(solidColor.toColorInt())
stroke(strokeWidth, strokeColor.toColorInt())
cornerRadius(radius.toFloat())
}
return convertToDrawable(builder.drawables[0])
}
fun convertToDrawable(shapeDrawable: ShapeDrawable): Drawable {
val drawable = GradientDrawable()
shapeDrawable.color?.let { drawable.setColor(it) }
shapeDrawable.cornerRadius?.let { drawable.cornerRadius = it }
shapeDrawable.strokeWidth?.let { drawable.setStroke(it, shapeDrawable.strokeColor ?: Color.BLACK) }
return drawable
}
@@ -1,24 +0,0 @@
package com.shuwei.intelligent.shelves.utils.ext
import android.text.SpannableStringBuilder
import android.text.Spanned
inline fun buildSpannableString(builderAction: SpannableStringBuilder.() -> Unit): SpannableStringBuilder {
return SpannableStringBuilder().apply(builderAction)
}
fun SpannableStringBuilder.appendText(text: String, vararg spans: Any): SpannableStringBuilder {
val start = length
append(text)
spans.forEach { span ->
setSpan(span, start, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
return this
}
fun SpannableStringBuilder.withSpan(span: Any, block: SpannableStringBuilder.() -> Unit) {
val start = length
block()
setSpan(span, start, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
@@ -0,0 +1,477 @@
package com.sw.scalefusion.shelf
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityHomeV3Binding
import com.shuwei.intelligent.shelves.dialog.CommonDialog
import com.shuwei.intelligent.shelves.model.ClearShelfEvent
import com.shuwei.intelligent.shelves.model.SendWeightEvent
import com.shuwei.intelligent.shelves.net.Loading
import com.shuwei.intelligent.shelves.serial.ProtocolConstants
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.C_TEMP_CMD
import com.shuwei.intelligent.shelves.serial.ProtocolConstants.START_TEMP_CTRL_CMD
import com.shuwei.intelligent.shelves.serial.ScaleManager
import com.shuwei.intelligent.shelves.utils.IntervalExecutor
import com.shuwei.intelligent.shelves.utils.ext.dp
import com.shuwei.intelligent.shelves.utils.ext.gone
import com.shuwei.intelligent.shelves.utils.ext.toast
import com.shuwei.intelligent.shelves.utils.ext.visible
import com.sw.scalefusion.shelf.adapter.ShelfV3Adapter
import com.sw.scalefusion.shelf.model.SlotModel
import com.sw.scalefusion.shelf.model.SlotRecord
import com.sw.scalefusion.shelf.model.SlotWeight
import com.sw.scalefusion.shelf.model.SyncWeightRequest
import com.sw.scalefusion.shelf.net.NetViewModelV3
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class HomeV3Activity : BaseActivity() {
companion object {
/** 重量同步后台间隔(秒) */
private const val SYNC_INTERVAL_SECONDS = 30L
/** 首次同步延迟(秒) */
private const val SYNC_INITIAL_DELAY_SECONDS = 10L
}
override val enableRightStatusMenu: Boolean = true
private val list: MutableList<SlotModel> = mutableListOf()
/** 秤号(slotNo 数字部分)→ list 索引 的快速查找表,心跳回调中 O(1) 定位 */
private val scaleIndexToPosition = mutableMapOf<Int, Int>()
private var shelfIndex = 0
private fun isNeedOpenLock() = App.deviceId == "4787e213-90ab-3e32-88e0-ac271a937751"
private var deviceName = ""
private var cabinetType: Int = 0
private var cabinetId: String = ""
private var canteenId: Long = 0
private lateinit var binding: ActivityHomeV3Binding
private val viewModel: NetViewModelV3 by viewModels()
/** 记录每台秤的上次重量(克),用于跳过无变化的 UI 刷新和日志 */
private val lastWeightGrams = mutableMapOf<Int, Int>()
private fun initScaleManager() {
lifecycleScope.launch {
val ok = ScaleManager
.init(activateCode = ProtocolConstants.ACTIVE_MAP[App.deviceId] ?: "")
.onHeartbeat { _, data ->
data.weights.forEach { weight ->
val pos = scaleIndexToPosition[weight.index] ?: return@forEach
// 重量不变则跳过 UI 刷新、日志和 EventBus,避免主线程无效计算
if (lastWeightGrams[weight.index] == weight.grams) return@forEach
lastWeightGrams[weight.index] = weight.grams
val model = list[pos]
model.weight = weight.grams / 1000.0
shelfAdapter.notifyItemChanged(pos)
log("getWeightInfo: slotNo=${model.slotNo}, realWeight=${weight.grams}, temp=${data.temperature}")
EventBus.getDefault().post(SendWeightEvent(weight.index, weight.grams))
}
}
.onTempReport { frame ->
log("onTempReport: $frame")
updateLeftStatus(deviceName)
}
.onLog { message -> log(message) }
.start { data ->
lastDataReceivedTime = System.currentTimeMillis()
noDataWarningDialog?.takeIf { it.isShowing }?.dismiss()
log("receiveSerialPortData: $data")
}
log("onCreate: openState=$ok")
}
}
@SuppressLint("NotifyDataSetChanged")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHomeV3Binding.inflate(layoutInflater)
EventBus.getDefault().register(this)
setBackground()
setContentView(binding.root)
onBackPressedDispatcher.addCallback(this) {}
updateLeftStatus("")
initScaleManager()
binding.root.postDelayed({
sendCmd(START_TEMP_CTRL_CMD)
sendCmd(C_TEMP_CMD)
}, 5000)
saveGoodsTask()
overdueTask()
initRefreshLayout()
refreshSlots()
}
/** 配置格口列表下拉刷新 */
private fun initRefreshLayout() {
binding.refreshLayout.run {
setEnableRefresh(true)
setEnableLoadMore(false)
setOnRefreshListener { refreshSlots(fromPull = true) }
}
}
/**
* 拉取格口列表并刷新 UI。
* @param fromPull true 表示由下拉刷新触发:不弹 Loading,失败时保留现有格口数据仅提示
*/
private fun refreshSlots(fromPull: Boolean = false) {
viewModel.slots(
onLoading = { if (!fromPull) showProgress() },
onSuccess = { record ->
if (fromPull) finishRefresh()
updateUI(record)
},
onError = { msg ->
if (fromPull) {
finishRefresh()
// 列表已有数据时刷新失败仅提示,保留现有格口展示;无数据则走空视图重试
if (list.isEmpty()) showError(msg) else toast(msg)
} else {
showError(msg)
}
}
)
}
/** 结束下拉刷新动画 */
private fun finishRefresh() {
binding.refreshLayout.let {
if (it.state == RefreshState.Refreshing) it.finishRefresh(500)
}
}
private fun showProgress() {
Loading.show(this)
}
@SuppressLint("NotifyDataSetChanged")
private fun updateUI(record: SlotRecord?) {
binding.include.root.gone()
window?.decorView?.postDelayed({ Loading.dismiss() }, 500)
if (record == null) {
loadEmptyView()
return
}
deviceName = record.deviceName
cabinetType = record.cabinetType
cabinetId = record.cabinetId
canteenId = record.canteenId
updateLeftStatus(deviceName)
val slots = record.slots ?: mutableListOf()
if (slots.isEmpty()) {
loadEmptyView()
return
}
// val columns = if (ProtocolConstants.device3Columns.contains(App.deviceId)) 3 else 2
// val rows = if (slots.size % columns == 0) slots.size / columns else 5
// val columns = record.verticalCount
// val rows = record.horizontalRows
val rows = record.verticalCount
val columns = record.horizontalRows
log("updateUI: slots=${slots.size}, rows=$rows, columns=$columns")
list.clear()
list.addAll(reorderSlotsByDeviceLayout(slots, columns, rows))
buildScaleIndexMap()
val displayMetrics = resources.displayMetrics
// 减去 RecyclerView + item 自身的 margin
shelfAdapter.itemWidth = (displayMetrics.widthPixels - 24.dp) / columns - 24.dp
shelfAdapter.itemHeight = (displayMetrics.heightPixels - 68.dp) / rows - 24.dp
if (binding.rvShelf.adapter == null) {
initRecyclerView()
} else {
shelfAdapter.notifyDataSetChanged()
}
}
/**
* 按设备物理布局重排格口列表。
*
* API 返回的 slots 按 slotNo 升序排列。FlexboxLayoutManager(FlexDirection.COLUMN)
* 按列填充(先填满第一列 5 行,再换第二列),3 列设备需要重排才能正确显示:
*
* 期望显示: 列填充需要的列表序:
* [1] [6] [7] [1, 2, 3, 4, 5, ← 第1列
* [2] [8] [9] 6, 8, 10, 12, 14, ← 第2列
* [3][10] [11] 7, 9, 11, 13, 15] ← 第3列
* [4][12] [13]
* [5][14] [15]
*
* 2 列设备 API 原序 [1..10] 列填充后恰好正确,无需重排。
*
* @param slots API 返回的格口列表(按 slotNo 升序)
* @param columns 列数(API horizontalRows
* @param rows 行数(API verticalCount
*/
private fun reorderSlotsByDeviceLayout(
slots: List<SlotModel>,
columns: Int,
rows: Int
): List<SlotModel> {
// 2 列及以下无需重排,API 原序列填充后恰好正确
if (columns <= 2) return ArrayList(slots)
// 按 slotNo 数字部分建立查找表
val slotMap = HashMap<Int, SlotModel>(slots.size)
for (slot in slots) {
val num = slot.slotNo.filter { it.isDigit() }.toIntOrNull() ?: continue
slotMap[num] = slot
}
val result = ArrayList<SlotModel>(slots.size)
for (displayCol in 0 until columns) {
for (displayRow in 0 until rows) {
// 物理布局 → FlexDirection.COLUMN 列填充所需的列表位置
val slotNo = when (displayCol) {
0 -> displayRow + 1 // 左列: 1,2,3,4,5
1 -> rows + 1 + displayRow * 2 // 中列: 6,8,10,12,14
else -> rows + 2 + displayRow * 2 // 右列: 7,9,11,13,15
}
slotMap[slotNo]?.let { result.add(it) }
}
}
return result
}
/** 预建秤号→列表索引映射表,供心跳回调 O(1) 查找 */
private fun buildScaleIndexMap() {
scaleIndexToPosition.clear()
list.forEachIndexed { pos, model ->
val scaleNo = model.slotNo.filter { it.isDigit() }.toIntOrNull() ?: return@forEachIndexed
scaleIndexToPosition[scaleNo] = pos
}
}
private fun showError(message: String) {
Loading.dismiss()
toast(message)
loadEmptyView()
}
private var tipDialog: CommonDialog? = null
private var lastDataReceivedTime = System.currentTimeMillis()
private var noDataWarningDialog: CommonDialog? = null
private val noDataWatchdogTask = object : Runnable {
override fun run() {
if (isFinishing || isDestroyed) return
val elapsed = System.currentTimeMillis() - lastDataReceivedTime
if (elapsed >= 5 * 60 * 1000L) {
if (noDataWarningDialog == null) {
noDataWarningDialog = CommonDialog(this@HomeV3Activity).apply {
dialogTitle = "设备提示"
dialogContent =
"长时间未收到数据,若无法开门或秤重量不更新情况,请考虑断电重启设备"
}
}
if (noDataWarningDialog?.isShowing == false) {
noDataWarningDialog?.show()
}
}
handler.postDelayed(this, 30 * 1000L)
}
}
override fun onUserInactive() {
switchLight(false)
}
override fun onDestroy() {
handler.removeCallbacksAndMessages(null)
tipDialog?.dismiss()
tipDialog = null
noDataWarningDialog?.dismiss()
noDataWarningDialog = null
runBlocking { ScaleManager.release() }
saveTaskJob?.cancel()
overdueTaskJob?.cancel()
EventBus.getDefault().unregister(this)
super.onDestroy()
}
private val shelfAdapter by lazy {
ShelfV3Adapter(list).apply {
setOnItemClickListener { _, _, position ->
onShelfItemClicked(position)
}
}
}
private fun onShelfItemClicked(position: Int) {
shelfIndex = position
lifecycleScope.launch {
if (isNeedOpenLock()) {
val slotNum = list[position].slotNo?.filter { it.isDigit() }?.toIntOrNull() ?: 0
val openCmd = if (slotNum in 1..5)
ScaleManager.buildOpenLock1Cmd()
else
ScaleManager.buildOpenLock2Cmd()
ScaleManager.sendCmd(openCmd)
}
val model = list[position]
launch(Intent(this@HomeV3Activity, ShelfV3Activity::class.java).also {
it.putExtra(ShelfV3Activity.EXTRA_CABINET_TYPE, model.cabinetType)
it.putExtra(ShelfV3Activity.EXTRA_CABINET_ID, model.cabinetId)
it.putExtra(ShelfV3Activity.EXTRA_SLOT_NO, model.slotNo)
it.putExtra(ShelfV3Activity.EXTRA_CANTEEN_ID, canteenId)
it.putExtra(ShelfV3Activity.EXTRA_MATER_NAME, model.materName)
it.putExtra(ShelfV3Activity.EXTRA_VEG_TYPE_NAME, model.vegTypeName)
}) { result ->
result?.let { onShelfActivityResult(position, it) }
}
}
}
@Suppress("DEPRECATION")
private fun onShelfActivityResult(position: Int, intent: Intent) {
val model = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getSerializableExtra(ShelfV3Activity.SHELF_MODEL, SlotModel::class.java)
} else {
intent.getSerializableExtra(ShelfV3Activity.SHELF_MODEL) as? SlotModel
} ?: return
val weight = list[position].weight
model.weight = weight
list[position] = model
shelfAdapter.notifyItemChanged(position)
}
private fun initRecyclerView() {
val layoutManager = FlexboxLayoutManager(this).apply {
flexDirection = FlexDirection.COLUMN
flexWrap = FlexWrap.WRAP
}
binding.rvShelf.let {
it.layoutManager = layoutManager
it.adapter = shelfAdapter
it.itemAnimator.let { animator ->
if (animator is DefaultItemAnimator) {
animator.supportsChangeAnimations = false
}
}
}
}
private val handler = Handler(Looper.getMainLooper())
override fun onResume() {
super.onResume()
hideStatusBar()
handler.postDelayed(noDataWatchdogTask, 30 * 1000L)
}
override fun onPause() {
super.onPause()
handler.removeCallbacks(noDataWatchdogTask)
}
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
list.clear()
scaleIndexToPosition.clear()
shelfAdapter.notifyDataSetChanged()
binding.include?.let {
it.root.visible()
it.root.setOnClickListener { refreshSlots() }
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_white)
it.tvEmptyContent.setTextColor(Color.WHITE)
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun clearEmptyShelf(event: ClearShelfEvent) {
val index = scaleIndexToPosition[event.shelfNo] ?: return
list[index] = list[index].copy(materName = "")
shelfAdapter.notifyItemChanged(index)
}
private val taskExecutor by lazy { IntervalExecutor() }
private var saveTaskJob: Job? = null
private fun saveGoodsTask() {
saveTaskJob =
taskExecutor.startIntervalTaskWithInitialDelay(
SYNC_INITIAL_DELAY_SECONDS * 1000L,
SYNC_INTERVAL_SECONDS * 1000L
) {
syncShelfGoodsToServer()
}
}
private var overdueTaskJob: Job? = null
private fun overdueTask() {
// overdueTaskJob = taskExecutor.startIntervalTaskWithInitialDelay(5 * 1000L, 5 * 60 * 1000L) {
// viewModel.slots()
// }
}
// private fun applyOverdueState(items: List<RecordItem>) {
// if (items.size != list.size) return
// items.forEachIndexed { index, newItem ->
// val oldItem = list[index]
// if (oldItem.slotStatus != newItem.slotStatus) {
// list[index] = newItem
// shelfAdapter.notifyItemChanged(index)
// log("更新格口 ${newItem.slotNo} 物料:${newItem.materName} 的状态:${newItem.slotStatus}")
// }
// }
// }
/** 全量同步格口重量 */
private fun syncShelfGoodsToServer() {
if (list.isEmpty()) return
val submitList = list.sortedBy { it.slotNo.toIntOrNull() ?: 0 }
viewModel.syncWeight(
SyncWeightRequest(
cabinetType = cabinetType,
cabinetId = cabinetId,
slotList = submitList.map {
SlotWeight(slotNo = it.slotNo, weight = it.weight ?: 0.0)
}
)
)
}
}
@@ -0,0 +1,178 @@
package com.sw.scalefusion.shelf
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import android.view.animation.RotateAnimation
import androidx.activity.addCallback
import androidx.core.graphics.toColorInt
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.GlobalData
import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityInitBinding
import com.shuwei.intelligent.shelves.utils.AppUtil
import com.shuwei.intelligent.shelves.utils.NetworkUtils
import com.shuwei.intelligent.shelves.utils.SpTool
import com.shuwei.intelligent.shelves.utils.ext.invisible
import com.shuwei.intelligent.shelves.utils.ext.startActivity
class InitActivity : BaseActivity() {
companion object {
const val TAG = "InitActivity"
}
private lateinit var binding: ActivityInitBinding
private val handler = Handler(Looper.getMainLooper())
private var startTime = 0L
private var lastNetworkCheckTime = 0L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityInitBinding.inflate(layoutInflater)
setContentView(binding.root)
App.deviceId = AppUtil.getUDID(this)
// TODO: 测试设备号
// App.deviceId = "d369f9b0-1c5b-3066-ba72-988e1449cecc"
// App.deviceId = "25b777a9-6298-30d3-a5f8-3b3eef2a50f7"
// App.deviceId = "505ce1b1-facc-3eb2-855a-3dadda5ba358"
Log.d(TAG, "onCreate: deviceId = ${App.deviceId}")
SpTool.put(SpTool.DEVICE_ID, App.deviceId)
// val appBaseUrl = SpTool.baseUrl
// if (!appBaseUrl.isBlank()) {
// GlobalData.appBaseUrl = appBaseUrl
// } else {
// GlobalData.appBaseUrl = GlobalData.PROD_BASE_URL
// }
GlobalData.appBaseUrl = GlobalData.TEST_BASE_URL
App.canteenId = "0"
binding.ivQrCode.invisible()
binding.btnInit.invisible()
initViews()
// 禁用返回键
onBackPressedDispatcher.addCallback(this) {}
}
/**
* 初始化控件事件
*/
private fun initViews() {
binding.btnConnectNetwork.setOnClickListener {
openNetworkSettings()
}
startLoadingAnimation()
}
/**
* 启动加载动画 - ImageView 持续旋转
*/
private fun startLoadingAnimation() {
val rotateAnimation = RotateAnimation(
0f, 360f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f
).apply {
duration = 1200
repeatCount = RotateAnimation.INFINITE
repeatMode = RotateAnimation.RESTART
}
binding.ivLoading.startAnimation(rotateAnimation)
}
override fun onResume() {
super.onResume()
if (NetworkUtils.isNetworkConnected(this)) {
navigateToHome()
return
}
startCountdown()
}
override fun onPause() {
super.onPause()
handler.removeCallbacksAndMessages(null)
}
/**
* 启动 60 秒倒计时
*/
private fun startCountdown() {
startTime = SystemClock.elapsedRealtime()
lastNetworkCheckTime = 0
binding.llNetwork.setBackgroundColor(Color.TRANSPARENT)
binding.llLoading.visibility = android.view.View.VISIBLE
binding.llNetworkButton.visibility = android.view.View.GONE
binding.tvCountdown.text = "60秒"
scheduleCountdown()
}
/**
* 定时更新倒计时
*/
private fun scheduleCountdown() {
handler.postDelayed({
val elapsedTime = SystemClock.elapsedRealtime() - startTime
val remainingTime = 60 - (elapsedTime / 1000).toInt()
val currentNetworkCheckTime = (elapsedTime / 1000).toInt()
if (currentNetworkCheckTime > 0 && currentNetworkCheckTime % 10 == 0 && currentNetworkCheckTime != lastNetworkCheckTime.toInt()) {
lastNetworkCheckTime = currentNetworkCheckTime.toLong()
checkNetworkConnection()
}
if (remainingTime > 0) {
binding.tvCountdown.text = "${remainingTime}"
scheduleCountdown()
} else {
if (NetworkUtils.isNetworkConnected(this)) {
navigateToHome()
} else {
showNetworkButton()
}
}
}, 100)
}
/**
* 检测网络连接
*/
private fun checkNetworkConnection() {
if (NetworkUtils.isNetworkConnected(this)) {
handler.removeCallbacksAndMessages(null)
navigateToHome()
}
}
/**
* 跳转到 HomeV3Activity
*/
private fun navigateToHome() {
startActivity<HomeV3Activity>()
finish()
}
/**
* 显示"连接网络"按钮
*/
private fun showNetworkButton() {
binding.llNetwork.setBackgroundColor("#5C77F7".toColorInt())
binding.llLoading.visibility = android.view.View.GONE
binding.llNetworkButton.visibility = android.view.View.VISIBLE
}
/**
* 打开系统网络设置页面
*/
private fun openNetworkSettings() {
val intent = Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)
startActivity(intent)
}
}
@@ -0,0 +1,376 @@
package com.sw.scalefusion.shelf
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.core.view.updateLayoutParams
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter4.util.setOnDebouncedItemClick
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.base.BaseActivity
import com.shuwei.intelligent.shelves.databinding.ActivityShelfV3Binding
import com.shuwei.intelligent.shelves.dialog.ChipSelectDialog
import com.shuwei.intelligent.shelves.dialog.CommonDialog
import com.shuwei.intelligent.shelves.model.SendWeightEvent
import com.shuwei.intelligent.shelves.net.Loading
import com.shuwei.intelligent.shelves.serial.ScaleManager
import com.shuwei.intelligent.shelves.utils.KeyboardUtil
import com.shuwei.intelligent.shelves.utils.ext.addOnActionSearchListener
import com.shuwei.intelligent.shelves.utils.ext.clickWithDebounce
import com.shuwei.intelligent.shelves.utils.ext.dp
import com.shuwei.intelligent.shelves.utils.ext.gone
import com.shuwei.intelligent.shelves.utils.ext.toast
import com.shuwei.intelligent.shelves.utils.ext.visible
import com.sw.scalefusion.shelf.adapter.PendingInboundAdapter
import com.sw.scalefusion.shelf.model.FoodItem
import com.sw.scalefusion.shelf.model.PutSlotRequest
import com.sw.scalefusion.shelf.model.SearchFoodRequest
import com.sw.scalefusion.shelf.model.SlotDetailRequest
import com.sw.scalefusion.shelf.model.SlotModel
import com.sw.scalefusion.shelf.net.NetViewModelV3
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@SuppressLint("NotifyDataSetChanged")
class ShelfV3Activity : BaseActivity() {
companion object {
const val SHELF_MODEL = "shelfModelV3"
const val EXTRA_CABINET_TYPE = "cabinetType"
const val EXTRA_CABINET_ID = "cabinetId"
const val EXTRA_CANTEEN_ID = "canteenId"
const val EXTRA_SLOT_NO = "slotNo"
const val EXTRA_MATER_NAME = "materName"
const val EXTRA_VEG_TYPE_NAME = "vegTypeName"
const val YYYY_MM_DD__EEEE_HH_MM_SS = "yyyy年MM月dd日 EEEE***HH:mm:ss"
}
/** 缓存的日期格式化器,避免 onClockTick 每秒 new 对象 */
private val clockFormatter by lazy {
SimpleDateFormat(YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
}
private lateinit var binding: ActivityShelfV3Binding
private var shelfModel: SlotModel? = null
private var realWeight: Int = 0
private var startTime = 0L
private val viewModel: NetViewModelV3 by viewModels()
private val optionList: MutableList<FoodItem> = mutableListOf()
private val optionAdapter by lazy {
PendingInboundAdapter(optionList).apply {
setOnDebouncedItemClick { _, _, position ->
val vegTypeList = getItem(position)?.vegTypeList ?: emptyList()
if (vegTypeList.isEmpty()) {
selectCategory(position)
return@setOnDebouncedItemClick
}
val categoryList = vegTypeList.map { it.vegTypeName }
if (categoryList.isEmpty()) {
CommonDialog(this@ShelfV3Activity).apply {
dialogTitle = "净菜选择"
dialogContent = "暂无净菜类别,请联系管理员添加,或稍后重试"
show()
}
return@setOnDebouncedItemClick
}
showChipSelectDialog(categoryList) { index ->
getItem(position)?.typeSelectedIndex = index
selectCategory(position)
}
}
}
}
private fun selectCategory(position: Int) {
optionList.forEachIndexed { index, option -> option.isSelected = index == position }
optionAdapter.notifyDataSetChanged()
binding.tvFoodName.text = optionList[position].materName
val index = optionList[position].typeSelectedIndex
val typeList = optionList[position].vegTypeList ?: emptyList()
val selectType = typeList.getOrNull(index)?.vegTypeName ?: ""
binding.tvVegTypeName.text = selectType
KeyboardUtil.hideKeyboard(this@ShelfV3Activity.window.decorView)
}
private var cabinetType: Int = 0
private var canteenId: Long = 0
private var cabinetId: String = ""
private var slotNo: String = ""
private var materName: String = ""
private var vegTypeName: String = ""
@Suppress("DEPRECATION")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityShelfV3Binding.inflate(layoutInflater)
setBackground()
setContentView(binding.root)
EventBus.getDefault().register(this)
cabinetType = intent.getIntExtra(EXTRA_CABINET_TYPE, 0)
canteenId = intent.getLongExtra(EXTRA_CANTEEN_ID, 0)
cabinetId = intent.getStringExtra(EXTRA_CABINET_ID) ?: ""
slotNo = intent.getStringExtra(EXTRA_SLOT_NO) ?: ""
materName = intent.getStringExtra(EXTRA_MATER_NAME) ?: ""
vegTypeName = intent.getStringExtra(EXTRA_VEG_TYPE_NAME) ?: ""
binding.tvShelfName.text = slotNo
binding.tvFoodName.text = materName.ifBlank { "-" }
binding.tvVegTypeName.text = vegTypeName
initRecyclerView()
initSearchBox()
initButtons()
sendCmd(ScaleManager.buildGetStatusCmd())
viewModel.slotDetail(
request = SlotDetailRequest(cabinetType, cabinetId, slotNo),
onLoading = { showProgress() },
onSuccess = onSuccess@{ model ->
if (model == null) return@onSuccess
shelfModel = model
updateUI(model)
loadList()
},
onError = { msg -> showError(msg) }
)
}
/** 从 slotDetail 响应更新 UI */
private fun updateUI(model: SlotModel) {
binding.tvFoodName.text = if (model.materName.isNullOrBlank()) "-" else model.materName
binding.tvVegTypeName.text = model.vegTypeName
val weightG = model.weight ?: 0.0
realWeight = (weightG * 1000.0).toInt()
// 负漂移抑制:-5克以内的负读数显示时归零(realWeight 保持真实值)
val displayWeight = if (realWeight in -5..0) 0 else realWeight
binding.tvFoodWeight.text = if (weightG >= 1.0) "%.3f千克".format(weightG)
else "${displayWeight}"
startTime = System.currentTimeMillis()
}
private fun initRecyclerView() {
binding.rvSearch.run {
layoutManager = GridLayoutManager(this@ShelfV3Activity, 2)
adapter = optionAdapter
}
binding.refreshLayout.run {
setEnableRefresh(true)
setEnableLoadMore(false)
setOnRefreshListener { loadList() }
}
}
private fun initSearchBox() {
binding.etInputFood.run {
addOnActionSearchListener {
loadList()
KeyboardUtil.hideKeyboard(context, this)
}
addTextChangedListener(afterTextChanged = { editable ->
if (editable.isNullOrBlank()) loadList()
})
}
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
}
private fun initButtons() {
binding.ivBack.setOnClickListener { finish() }
binding.btnClearZero.setOnClickListener {
Loading.show(this@ShelfV3Activity)
clearZero()
window.decorView.postDelayed({ Loading.dismiss() }, 10000)
}
binding.btnClearEmpty.setOnClickListener { v ->
clearZero()
binding.tvFoodName.text = "-"
binding.tvVegTypeName.text = ""
Loading.show(this@ShelfV3Activity)
v.postDelayed({
Loading.dismiss()
val emptyModel = shelfModel?.copy(
materName = "",
materId = null,
weight = null,
traceCode = null,
storeTime = null,
inboundNo = null
)
val result = Intent().apply {
putExtra(SHELF_MODEL, emptyModel)
}
setResult(RESULT_OK, result)
finish()
}, 3000)
}
binding.btnConfirm.clickWithDebounce {
val item = optionList.firstOrNull { it.isSelected }
if (item == null) {
toast("请选择食材")
return@clickWithDebounce
}
val model = shelfModel ?: return@clickWithDebounce
val vegType = item.vegTypeList?.getOrNull(item.typeSelectedIndex)
viewModel.put(
request = PutSlotRequest(
cabinetType = cabinetType,
cabinetId = cabinetId,
slotNo = slotNo,
materId = item.materId,
materName = item.materName,
weight = shelfModel?.weight ?: 0.0
).also {
it.vegTypeId = vegType?.vegTypeId
},
onLoading = { showProgress() },
onSuccess = onSuccess@{ inboundNo ->
Loading.dismiss()
// if (inboundNo.isNullOrBlank()) {
// toast("入库失败")
// return@onSuccess
// }
val resultModel = item.toSlotModel(model).also {
// it.inboundNo = inboundNo
it.vegTypeId = vegType?.vegTypeId
it.vegTypeName = vegType?.vegTypeName
}
val result = Intent().apply {
putExtra(SHELF_MODEL, resultModel)
}
setResult(RESULT_OK, result)
finish()
},
onError = { msg -> showError(msg) }
)
}
}
private fun loadList() {
viewModel.searchFood(
request = SearchFoodRequest(
cabinetType = shelfModel?.cabinetType ?: 0,
keyword = binding.etInputFood.text.toString().trim()
),
onLoading = { showProgress() },
onSuccess = { items -> updateOptionList(items) },
onError = { msg -> showError(msg) }
)
}
private fun showProgress() {
Loading.show(this)
}
@SuppressLint("NotifyDataSetChanged")
private fun updateOptionList(items: List<FoodItem>?) {
finishRefresh()
binding.include.root.gone()
binding.root.postDelayed({ Loading.dismiss() }, 200)
if (items.isNullOrEmpty()) {
loadEmptyView(); return
}
optionList.clear()
optionList.addAll(items)
optionAdapter.notifyDataSetChanged()
}
private fun showError(message: String) {
finishRefresh()
Loading.dismiss()
toast(message)
loadEmptyView()
}
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
optionList.clear()
optionAdapter.notifyDataSetChanged()
binding.include?.let {
it.root.visible()
it.root.setOnClickListener { loadList() }
it.ivEmptyIcon.setImageResource(R.drawable.ic_empty_gray)
it.ivEmptyIcon.updateLayoutParams<LinearLayout.LayoutParams> {
val swDpValue = resources?.configuration?.smallestScreenWidthDp ?: 0
width = if (swDpValue > 600) 200.dp else 120.dp
}
}
binding.refreshLayout.run {
setEnableRefresh(false)
setEnableLoadMore(false)
}
}
private fun finishRefresh() {
binding.refreshLayout.let {
if (it.state == RefreshState.Refreshing) it.finishRefresh(500)
else if (it.state == RefreshState.Loading) it.finishLoadMore(500)
}
}
private fun clearZero() {
lifecycleScope.launch {
val slotNum = shelfModel?.slotNo?.filter { it.isDigit() }?.toIntOrNull() ?: 0
val zeroClearingCmd = ScaleManager.buildScaleZeroCmd(slotNum)
log("格口${shelfModel?.slotNo}执行清零指令:$zeroClearingCmd")
sendCmd(zeroClearingCmd)
realWeight = 0
sendCmd(ScaleManager.buildGetStatusCmd())
startTime = System.currentTimeMillis()
}
KeyboardUtil.hideKeyboard(window.decorView)
}
override fun onClockTick() {
val arr = clockFormatter.format(Date()).split("***")
updateLeftStatus(arr[0])
updateRightStatus(arr[1])
}
override fun onResume() {
super.onResume()
hideStatusBar()
}
override fun onDestroy() {
EventBus.getDefault().unregister(this)
super.onDestroy()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun receiveWeightEvent(event: SendWeightEvent) {
val slotNum = shelfModel?.slotNo?.filter { it.isDigit() }?.toIntOrNull() ?: return
if (event.shelfNo != slotNum) return
val intervalTime = System.currentTimeMillis() - startTime
val weight = event.weight
log("格口${shelfModel?.slotNo}获取重量:${weight}克,间隔:${intervalTime}ms")
// 负漂移抑制:-5克以内的负读数显示时归零
val displayWeight = if (weight in -5..0) 0 else weight
binding.tvFoodWeight.text = if (displayWeight < 1000) "${displayWeight}"
else "%.3f千克".format(displayWeight / 1000.0)
startTime = System.currentTimeMillis()
window.decorView.postDelayed({ Loading.dismiss() }, 1000)
}
private fun showChipSelectDialog(categoryList: List<String?>, callback: (Int) -> Unit) {
ChipSelectDialog(this).apply {
dialogTitle = "净菜分类"
items = categoryList
onItemSelected = callback
show()
}
}
}
@@ -0,0 +1,49 @@
package com.sw.scalefusion.shelf.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.databinding.ListItemSearchBinding
import com.sw.scalefusion.shelf.model.FoodItem
class PendingInboundAdapter(list: MutableList<FoodItem>) :
BaseQuickAdapter<FoodItem, PendingInboundAdapter.VH>(list) {
inner class VH(val binding: ListItemSearchBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val binding = ListItemSearchBinding.inflate(LayoutInflater.from(context), parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: FoodItem?) {
item ?: return
val isSelected = item.isSelected
val binding = holder.binding
// 名称与编码:选中蓝字,未选中灰字
val nameColor = getColor(if (isSelected) R.color.shelf_name_blue else R.color.black999)
binding.tvFoodName.run {
text = item.materName
setTextColor(nameColor)
}
binding.tvMaterCode.run {
text = item.materCode
setTextColor(nameColor)
}
// 选中蓝边框,未选中灰边框
binding.cardFood.strokeColor =
(if (isSelected) "#4969F5" else "#E6E6E6").toColorInt()
// 仅今日已验收的食材显示右上角绿色圆点
binding.viewAcceptedDot.visibility =
if (item.todayAccepted == true) View.VISIBLE else View.GONE
}
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
}
@@ -0,0 +1,85 @@
package com.sw.scalefusion.shelf.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.google.android.flexbox.FlexboxLayoutManager
import com.shuwei.intelligent.shelves.R
import com.shuwei.intelligent.shelves.databinding.ListItemShelfV3Binding
import com.sw.scalefusion.shelf.model.SlotModel
import kotlin.math.abs
class ShelfV3Adapter(list: MutableList<SlotModel>) :
BaseQuickAdapter<SlotModel, ShelfV3Adapter.VH>(list) {
/** 每个格口 item 的高度(像素),由 Activity 动态计算 */
var itemHeight: Int = 0
/** 每个格口 item 的宽度(像素),由 Activity 动态计算 */
var itemWidth: Int = 0
inner class VH(val binding: ListItemShelfV3Binding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val binding = ListItemShelfV3Binding.inflate(LayoutInflater.from(context), parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: SlotModel?) {
item ?: return
// 动态设置 item 宽高
val lp = holder.itemView.layoutParams as? FlexboxLayoutManager.LayoutParams
lp?.apply {
if (itemWidth > 0) width = itemWidth
if (itemHeight > 0) height = itemHeight
}
val binding = holder.binding
// 格口编号
binding.tvShelfName.text = item.slotNo.padStart(2, '0')
val weightG = item.weight ?: 0.0
// 负漂移抑制:空秤零点可能出现 -5克以内的负读数,显示时归零
val displayG = if (weightG in -0.005..0.0) 0.0 else weightG
binding.tvFoodWeight.run {
setTextColor(getColor(R.color.food_weight_orange))
text = if (abs(displayG) >= 1.0) "%.3f千克".format(displayG)
else "${(displayG * 1000.0).toInt()}"
}
val isBlank = item.materName.isNullOrBlank()
if (isBlank) {
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_blue))
binding.tvShelfName.setTextColor(getColor(R.color.shelf_name_white))
binding.tvFoodName.run {
setTextColor(getColor(R.color.white))
text = ""
}
binding.tvStoreDate.run {
setTextColor(getColor(R.color.food_weight_blue))
text = "-"
}
binding.tvFoodType.text = ""
return
}
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_white))
binding.tvShelfName.setTextColor(getColor(R.color.shelf_name_blue))
binding.tvFoodName.run {
setTextColor(getColor(R.color.food_name_black))
text = item.materName
}
binding.tvStoreDate.run {
setTextColor(getColor(R.color.black999))
text = item.storeTime
}
binding.tvFoodType.text = item.vegTypeName
binding.tvFoodType.setTextColor(getColor(R.color.black666))
}
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
}
@@ -0,0 +1,29 @@
package com.sw.scalefusion.shelf.model
data class PendingInboundRequest(
var cabinetType: Int,
var canteenId: Long,
var cabinetId: String
)
data class SearchFoodRequest(
var cabinetType: Int,
var keyword: String? = null
)
data class PutSlotRequest(
val cabinetType: Int? = null,
val cabinetId: String? = null,
val slotNo: String? = null,
val materId: Long? = null,
var vegTypeId: Long? = null,
val materName: String? = null,
val traceCode: String? = null,
val weight: Double? = null,
)
data class SlotDetailRequest(
var cabinetType: Int,
var cabinetId: String,
var slotNo: String
)
@@ -0,0 +1,29 @@
package com.sw.scalefusion.shelf.model
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
import java.util.Date
data class FoodItem(
var materId:Long? = null,
var materName:String? = null,
/** 食材编码(一级分类+二级分类+自编码,全局唯一) */
var materCode:String? = null,
/** 今日是否在验收秤有验收记录 */
var todayAccepted:Boolean? = null,
var materUrl:String? = null,
var vegTypeList:List<FoodType>? = null,
var isSelected:Boolean = false,
var typeSelectedIndex:Int = -1
) {
/** 转换为 SlotModel,保留原格口的 slotNo/cabinetId 等 */
fun toSlotModel(model: SlotModel) = model.copy(
materId = materId ,
materName = materName,
storeTime = DateTimeUtil.formatDateTime(dateTime = Date()),
)
}
data class FoodType(
var vegTypeId:Long? = null,
var vegTypeName:String? = null
)
@@ -0,0 +1,32 @@
package com.sw.scalefusion.shelf.model
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
import java.util.Date
/**
* /pending-inbound 接口响应 — 待入柜物料
*/
data class PendingInboundItem(
val id: Long = 0,
val materId: Long = 0,
val materName: String = "",
val traceCode: String? = null,
val weight: Double = 0.0,
val inboundNo: String = "",
val inboundTime: String? = null,
val vegTypeId: Long? = null,
val vegTypeName: String? = null,
val spec: String? = null,
var isSelected: Boolean = false
) {
/** 转换为 SlotModel,保留原格口的 slotNo/cabinetId 等 */
fun toSlotModel(model: SlotModel) = model.copy(
materId = materId ,
materName = materName,
traceCode = traceCode,
inboundNo = inboundNo,
storeTime = DateTimeUtil.formatDateTime(dateTime = Date()),
// weight = weight
)
}
@@ -0,0 +1,23 @@
package com.sw.scalefusion.shelf.model
import java.io.Serializable
/**
* /slots 接口响应模型 — 格口分组数据
*/
data class SlotModel(
val id: String = "",
val slotNo: String = "",
val cabinetId: String,
val cabinetType: Int,
val hasContent: Boolean = false,
var inboundNo: String? = null,
val materId: Long? = null,
val materName: String? = null,
val traceCode: String? = null,
var vegTypeId: Long? = null,
var vegTypeName: String? = null,
//weight单位千克
var weight: Double? = 0.0,
var storeTime: String? = null,
): Serializable
@@ -0,0 +1,12 @@
package com.sw.scalefusion.shelf.model
data class SlotRecord(
val cabinetType: Int,
val cabinetId: String,
val deviceName: String,
val canteenId: Long,
val canteenName: String,
val horizontalRows: Int,
val verticalCount: Int,
val slots: List<SlotModel>? = null
)
@@ -0,0 +1,15 @@
package com.sw.scalefusion.shelf.model
/**
* /sync-weight 接口请求体
*/
data class SyncWeightRequest(
val cabinetType: Int,
val cabinetId: String,
val slotList: List<SlotWeight>
)
data class SlotWeight(
val slotNo: String,
val weight: Double
)
@@ -0,0 +1,9 @@
package com.sw.scalefusion.shelf.net
data class ApiResponse<T>(
val code: String,
val msg: String? = "",
val data: T? = null
) {
fun isSuccess(): Boolean = ("00000" == code)
}
@@ -0,0 +1,43 @@
package com.sw.scalefusion.shelf.net
import com.shuwei.intelligent.shelves.App
import com.sw.scalefusion.shelf.model.FoodItem
import com.sw.scalefusion.shelf.model.PendingInboundItem
import com.sw.scalefusion.shelf.model.PendingInboundRequest
import com.sw.scalefusion.shelf.model.PutSlotRequest
import com.sw.scalefusion.shelf.model.SearchFoodRequest
import com.sw.scalefusion.shelf.model.SlotDetailRequest
import com.sw.scalefusion.shelf.model.SlotModel
import com.sw.scalefusion.shelf.model.SlotRecord
import com.sw.scalefusion.shelf.model.SyncWeightRequest
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Query
interface ApiServiceV3 {
/** 格口列表 */
@GET("/nutrition/neglect/mater-cabinet/init")
suspend fun slots(@Query("cabinetId") cabinetId: String = App.deviceId): ApiResponse<SlotRecord?>
/** 待入柜列表 */
@POST("/nutrition/neglect/mater-cabinet/pending-inbound")
suspend fun pendingInbound(@Body request: PendingInboundRequest): ApiResponse<List<PendingInboundItem>?>
/** 搜索净菜、毛菜 */
@POST("/nutrition/neglect/mater-cabinet/ingredients")
suspend fun searchFood(@Body request: SearchFoodRequest): ApiResponse<List<FoodItem>?>
/** 全量同步重量 */
@POST("/nutrition/neglect/mater-cabinet/sync-weight")
suspend fun syncWeight(@Body request: SyncWeightRequest): ApiResponse<Any?>
/** 格口入柜 */
@POST("/nutrition/neglect/mater-cabinet/put")
suspend fun put(@Body request: PutSlotRequest): ApiResponse<String?>
/** 格口详情 */
@POST("/nutrition/neglect/mater-cabinet/slot-detail")
suspend fun slotDetail(@Body request: SlotDetailRequest): ApiResponse<SlotModel?>
}
@@ -0,0 +1,66 @@
package com.sw.scalefusion.shelf.net
import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonParseException
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import javax.net.ssl.SSLHandshakeException
abstract class BaseRepository {
suspend fun <T> safeApiCall(apiCall: suspend () -> ApiResponse<T>): ApiResponse<T> {
return try {
apiCall()
} catch (e: Exception) {
Log.e("BaseRepository","safeApiCall Exception: ${e.stackTraceToString()}")
when (e) {
is HttpException -> {
// 优先解析错误响应体中后台返回的业务 msg,解析失败再回退到 HTTP 状态短语
val bodyMsg = e.parseApiMessage()
ApiResponse(code = "${e.code()}", msg = bodyMsg ?: e.message())
}
is SocketTimeoutException -> {
ApiResponse(code = "-2", msg = "请求超时: ${e.message}")
}
is ConnectException -> {
ApiResponse(code = "-3", msg = "连接失败: ${e.message}")
}
is SSLHandshakeException -> {
ApiResponse(code = "-4", msg = "SSL握手失败: ${e.message}")
}
is JsonParseException -> {
ApiResponse(code = "-5", msg = "JSON解析错误: ${e.message}")
}
is IOException -> {
ApiResponse(code = "-6", msg = "网络IO错误: ${e.message}")
}
else -> {
ApiResponse(code = "-1", msg = "未知错误: ${e.message ?: "无错误信息"}")
}
}
}
}
/**
* 从 HttpException 的错误响应体中解析后台返回的业务 msg。
* 后端业务错误通常以非 2xx 状态码返回,body 仍为 {"code":...,"msg":...,"data":...} 结构,
* 此处提取 msg 供上层 toast 直接展示;解析失败返回 null,由调用方回退到 HTTP 状态短语。
*/
private fun HttpException.parseApiMessage(): String? {
return try {
val raw = response()?.errorBody()?.string() ?: return null
val parsed = Gson().fromJson(raw, ApiResponse::class.java)
parsed?.msg
} catch (_: Exception) {
null
}
}
}
@@ -0,0 +1,95 @@
package com.sw.scalefusion.shelf.net
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sw.scalefusion.shelf.model.FoodItem
import com.sw.scalefusion.shelf.model.PendingInboundItem
import com.sw.scalefusion.shelf.model.PendingInboundRequest
import com.sw.scalefusion.shelf.model.PutSlotRequest
import com.sw.scalefusion.shelf.model.SearchFoodRequest
import com.sw.scalefusion.shelf.model.SlotDetailRequest
import com.sw.scalefusion.shelf.model.SlotModel
import com.sw.scalefusion.shelf.model.SlotRecord
import com.sw.scalefusion.shelf.model.SyncWeightRequest
import kotlinx.coroutines.launch
class NetViewModelV3 : ViewModel() {
private val repository = ShelfRepository()
/** 格口列表 */
fun slots(
onLoading: () -> Unit = {},
onSuccess: (SlotRecord?) -> Unit,
onError: (String) -> Unit = {}
) {
viewModelScope.launch {
onLoading()
val response = repository.slots()
if (response.isSuccess()) onSuccess(response.data)
else onError(response.msg ?: "请求失败")
}
}
/** 待入柜列表 */
fun pendingInbound(
request: PendingInboundRequest,
onLoading: () -> Unit = {},
onSuccess: (List<PendingInboundItem>?) -> Unit,
onError: (String) -> Unit = {}
) {
viewModelScope.launch {
onLoading()
val response = repository.pendingInbound(request)
if (response.isSuccess()) onSuccess(response.data)
else onError(response.msg ?: "请求失败")
}
}
/** 搜索净菜、毛菜 */
fun searchFood(request: SearchFoodRequest, onLoading: () -> Unit = {}, onSuccess: (List<FoodItem>?) -> Unit, onError: (String) -> Unit = {}) {
viewModelScope.launch {
onLoading()
val response = repository.searchFood(request)
if (response.isSuccess()) onSuccess(response.data)
else onError(response.msg ?: "请求失败")
}
}
/** 格口详情 */
fun slotDetail(
request: SlotDetailRequest,
onLoading: () -> Unit = {},
onSuccess: (SlotModel?) -> Unit,
onError: (String) -> Unit = {}
) {
viewModelScope.launch {
onLoading()
val response = repository.slotDetail(request)
if (response.isSuccess()) onSuccess(response.data)
else onError(response.msg ?: "请求失败")
}
}
/** 全量同步重量(无回调,fire-and-forget */
fun syncWeight(request: SyncWeightRequest) {
viewModelScope.launch {
repository.syncWeight(request)
}
}
/** 格口入柜(无回调,fire-and-forget */
fun put(
request: PutSlotRequest,
onLoading: () -> Unit = {},
onSuccess: (String?) -> Unit,
onError: (String) -> Unit = {}
) {
viewModelScope.launch {
onLoading()
val response = repository.put(request)
if (response.isSuccess()) onSuccess(response.data)
else onError(response.msg ?: "请求失败")
}
}
}
@@ -0,0 +1,39 @@
package com.sw.scalefusion.shelf.net
import com.shuwei.intelligent.shelves.App
import com.shuwei.intelligent.shelves.net.apiServiceV3
import com.sw.scalefusion.shelf.model.FoodItem
import com.sw.scalefusion.shelf.model.PendingInboundItem
import com.sw.scalefusion.shelf.model.PendingInboundRequest
import com.sw.scalefusion.shelf.model.PutSlotRequest
import com.sw.scalefusion.shelf.model.SearchFoodRequest
import com.sw.scalefusion.shelf.model.SlotDetailRequest
import com.sw.scalefusion.shelf.model.SlotModel
import com.sw.scalefusion.shelf.model.SlotRecord
import com.sw.scalefusion.shelf.model.SyncWeightRequest
class ShelfRepository : BaseRepository() {
/** 格口列表 */
suspend fun slots(cabinetId: String = App.deviceId): ApiResponse<SlotRecord?> =
safeApiCall { apiServiceV3.slots(cabinetId) }
/** 待入柜列表 */
suspend fun pendingInbound(request: PendingInboundRequest): ApiResponse<List<PendingInboundItem>?> =
safeApiCall { apiServiceV3.pendingInbound(request) }
/** 搜索净菜、毛菜 */
suspend fun searchFood(request: SearchFoodRequest): ApiResponse<List<FoodItem>?> =
safeApiCall { apiServiceV3.searchFood(request) }
/** 全量同步重量 */
suspend fun syncWeight(request: SyncWeightRequest): ApiResponse<Any?> =
safeApiCall { apiServiceV3.syncWeight(request) }
/** 格口入柜 */
suspend fun put(request: PutSlotRequest): ApiResponse<String?> =
safeApiCall { apiServiceV3.put(request) }
/** 格口详情 */
suspend fun slotDetail(request: SlotDetailRequest): ApiResponse<SlotModel?> =
safeApiCall { apiServiceV3.slotDetail(request) }
}
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/bg_card_blue" android:state_checked="true" />
<item android:color="@color/white" android:state_checked="false" />
</selector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/bg_card_blue" android:state_checked="false" />
<item android:color="@android:color/transparent" android:state_checked="true" />
</selector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white" android:state_checked="true" />
<item android:color="@color/bg_card_blue" android:state_checked="false" />
</selector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#30000000">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<corners android:radius="8dp" />
<stroke
android:width="1dp"
android:color="@color/bg_card_blue" />
</shape>
</item>
</ripple>
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#30000000">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/bg_card_blue" />
<corners android:radius="8dp" />
</shape>
</item>
</ripple>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/white" android:state_pressed="false" />
<item android:drawable="@color/gray_edit" android:state_pressed="true" />
</selector>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#90000000"/>
<corners android:radius="5dp"/>
<solid android:color="@color/white"/>
<corners android:radius="12dp"/>
</shape>
+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="240dp"
android:height="240dp"
android:viewportWidth="1024"
android:viewportHeight="1024">
<!-- 由小到大排列的圆点,构成旋转加载指示器 -->
<path
android:fillColor="#ffffff"
android:pathData="M876.864,782.592c3.264,0 6.272,-3.2 6.272,-6.656c0,-3.456 -3.008,-6.592 -6.272,-6.592c-3.264,0 -6.272,3.2 -6.272,6.592c0,3.456 3.008,6.656 6.272,6.656z" />
<path
android:fillColor="#ffffff"
android:pathData="M736.32,935.936c2.304,2.432 5.568,3.84 8.768,3.84a12.16,12.16 0,0 0,8.832 -3.84a13.76,13.76 0,0 0,0 -18.56a12.224,12.224 0,0 0,-8.832 -3.84a12.16,12.16 0,0 0,-8.768 3.84a13.696,13.696 0,0 0,0 18.56z" />
<path
android:fillColor="#ffffff"
android:pathData="M552.32,1018.24c3.456,3.648 8.32,5.76 13.184,5.76a18.368,18.368 0,0 0,13.184 -5.76a20.608,20.608 0,0 0,0 -27.968a18.368,18.368 0,0 0,-13.184 -5.824a18.368,18.368 0,0 0,-13.184 5.76a20.608,20.608 0,0 0,0 28.032z" />
<path
android:fillColor="#ffffff"
android:pathData="M353.984,1012.48c4.608,4.8 11.072,7.68 17.6,7.68a24.448,24.448 0,0 0,17.536 -7.68a27.456,27.456 0,0 0,0 -37.248a24.448,24.448 0,0 0,-17.536 -7.68a24.448,24.448 0,0 0,-17.6 7.68a27.52,27.52 0,0 0,0 37.184z" />
<path
android:fillColor="#ffffff"
android:pathData="M178.304,920.64c5.76,6.08 13.824,9.6 21.952,9.6a30.592,30.592 0,0 0,22.016 -9.6a34.368,34.368 0,0 0,0 -46.592a30.592,30.592 0,0 0,-22.016 -9.6a30.592,30.592 0,0 0,-21.952 9.6a34.368,34.368 0,0 0,0 46.592z" />
<path
android:fillColor="#ffffff"
android:pathData="M57.152,761.28c6.912,7.36 16.64,11.648 26.368,11.648a36.736,36.736 0,0 0,26.432 -11.584a41.28,41.28 0,0 0,0 -55.936a36.736,36.736 0,0 0,-26.432 -11.584a36.8,36.8 0,0 0,-26.368 11.52a41.28,41.28 0,0 0,0 56z" />
<path
android:fillColor="#ffffff"
android:pathData="M12.736,564.672a42.88,42.88 0,0 0,30.784 13.44a42.88,42.88 0,0 0,30.784 -13.44a48.128,48.128 0,0 0,0 -65.216a42.88,42.88 0,0 0,-30.72 -13.44a42.88,42.88 0,0 0,-30.848 13.44a48.128,48.128 0,0 0,0 65.216z" />
<path
android:fillColor="#ffffff"
android:pathData="M52.544,369.28a48.96,48.96 0,0 0,35.2 15.36a48.96,48.96 0,0 0,35.2 -15.36a54.976,54.976 0,0 0,0 -74.56a48.96,48.96 0,0 0,-35.2 -15.424a48.96,48.96 0,0 0,-35.2 15.424a54.976,54.976 0,0 0,0 74.56z" />
<path
android:fillColor="#ffffff"
android:pathData="M168.32,212.48c10.368,11.008 24.96,17.408 39.68,17.408c14.592,0 29.184,-6.4 39.552,-17.408a61.888,61.888 0,0 0,0 -83.84a55.104,55.104 0,0 0,-39.616 -17.408c-14.656,0 -29.248,6.4 -39.616,17.408a61.888,61.888 0,0 0,0 83.84z" />
<path
android:fillColor="#ffffff"
android:pathData="M337.344,124.8c11.52,12.16 27.712,19.264 43.968,19.264c16.256,0 32.448,-7.04 43.968,-19.264a68.672,68.672 0,0 0,0 -93.184a61.248,61.248 0,0 0,-43.968 -19.264a61.248,61.248 0,0 0,-43.968 19.264a68.736,68.736 0,0 0,0 93.184z" />
<path
android:fillColor="#ffffff"
android:pathData="M526.976,123.712c12.672,13.44 30.528,21.248 48.448,21.248s35.712,-7.808 48.384,-21.248a75.584,75.584 0,0 0,0 -102.464A67.392,67.392 0,0 0,575.36 0c-17.92,0 -35.776,7.808 -48.448,21.248a75.584,75.584 0,0 0,0 102.464z" />
<path
android:fillColor="#ffffff"
android:pathData="M700.8,210.304c13.824,14.592 33.28,23.104 52.736,23.104c19.584,0 39.04,-8.512 52.8,-23.104a82.432,82.432 0,0 0,0 -111.744a73.472,73.472 0,0 0,-52.8 -23.168c-19.52,0 -38.912,8.512 -52.736,23.168a82.432,82.432 0,0 0,0 111.744z" />
<path
android:fillColor="#ffffff"
android:pathData="M824.832,368.832c14.976,15.872 36.032,25.088 57.216,25.088c21.12,0 42.24,-9.216 57.152,-25.088a89.344,89.344 0,0 0,0 -121.088a79.616,79.616 0,0 0,-57.152 -25.088c-21.184,0 -42.24,9.216 -57.216,25.088a89.344,89.344 0,0 0,0 121.088z" />
<path
android:fillColor="#ffffff"
android:pathData="M875.264,572.864c16.128,17.088 38.784,27.008 61.632,27.008c22.784,0 45.44,-9.92 61.568,-27.008a96.256,96.256 0,0 0,0 -130.432a85.76,85.76 0,0 0,-61.568 -27.072c-22.848,0 -45.44,9.984 -61.632,27.072a96.192,96.192 0,0 0,0 130.432z" />
</vector>
@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:innerRadiusRatio="3"
android:thicknessRatio="8"
android:useLevel="false">
<gradient
android:type="sweep"
android:startColor="#FF6B6B"
android:centerColor="#4ECDC4"
android:endColor="#FF6B6B"
android:angle="0" />
</shape>
@@ -1,7 +0,0 @@
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">
<item android:id="@android:id/mask">
<color android:color="@android:color/white" />
</item>
</ripple>
+1 -1
View File
@@ -23,7 +23,7 @@
android:layout_gravity="start"
android:textSize="24sp"
android:fontFamily="sans-serif-medium"
tools:text="1-1冷藏柜 -2°C / 87%" />
android:text=" " />
<TextView
android:id="@+id/tv_right_status"
-27
View File
@@ -1,27 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:background="@color/bg_page">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvShelf"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
android:overScrollMode="never"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
tools:listitem="@layout/list_item_shelf"/>
<include
android:id="@+id/include"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/layout_empty_view"
android:visibility="gone"/>
</FrameLayout>
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:background="@color/bg_page">
<!-- 格口列表支持下拉刷新:重新拉取 /init 格口数据 -->
<com.scwang.smart.refresh.layout.SmartRefreshLayout
android:id="@+id/refreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.scwang.smart.refresh.header.ClassicsHeader
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srlAccentColor="@color/white"
app:srlPrimaryColor="@color/bg_page"
app:srlEnableLastTime="false" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvShelf"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
android:overScrollMode="never"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
tools:listitem="@layout/list_item_shelf_v3"/>
</com.scwang.smart.refresh.layout.SmartRefreshLayout>
<include
android:id="@+id/include"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="@layout/layout_empty_view"
android:visibility="gone"/>
</FrameLayout>
+6 -6
View File
@@ -73,9 +73,9 @@
<!-- 加载动画 -->
<ImageView
android:id="@+id/ivLoading"
android:layout_width="160dp"
android:layout_height="160dp"
android:src="@drawable/loading_spinner"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="@drawable/loading"
android:contentDescription="加载中" />
<!-- 倒计时文字 -->
@@ -85,7 +85,7 @@
android:layout_height="wrap_content"
android:text="60秒"
android:textSize="40sp"
android:textColor="@color/black"
android:textColor="@color/white"
android:textStyle="bold"
android:layout_marginTop="50dp" />
@@ -95,7 +95,7 @@
android:layout_height="wrap_content"
android:text="网络连接检测中,请稍后……"
android:textSize="22sp"
android:textColor="#555555"
android:textColor="@color/white"
android:layout_marginTop="20dp" />
</LinearLayout>
@@ -123,7 +123,7 @@
android:layout_height="wrap_content"
android:text="网络连接失败"
android:textSize="36sp"
android:textColor="@color/black"
android:textColor="@color/white"
android:textStyle="bold"
android:layout_marginBottom="40dp" />
+53 -1
View File
@@ -1,6 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
@@ -39,8 +44,55 @@
android:text="查找1001指令"/>
</FrameLayout>
<EditText
android:id="@+id/etSearch"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginHorizontal="12dp"
android:layout_marginTop="8dp"
android:background="@android:color/white"
android:hint="搜索日志..."
android:paddingHorizontal="12dp"
android:textSize="14sp"
android:singleLine="true"
tools:ignore="Autofill,TextFields" />
<HorizontalScrollView
android:id="@+id/hsvTimeNav"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="8dp"
android:scrollbars="none">
<LinearLayout
android:id="@+id/llTimeNav"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingHorizontal="12dp" />
</HorizontalScrollView>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvLogList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fabJump"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@android:drawable/ic_menu_sort_by_size"
app:fabSize="normal"
tools:ignore="ContentDescription" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
</FrameLayout>
@@ -74,6 +74,16 @@
android:textStyle="bold"
tools:text="金针菇" />
<TextView
android:id="@+id/tvVegTypeName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/food_name_black"
android:textSize="22sp"
tools:text="金针菇" />
<Space
android:layout_width="wrap_content"
android:layout_height="0dp"
@@ -129,22 +139,25 @@
android:layout_height="match_parent"
android:orientation="vertical">
<!-- 搜索框 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginStart="48dp"
android:layout_marginTop="48dp"
android:layout_marginTop="36dp"
android:layout_marginEnd="48dp"
android:background="@drawable/shape_search"
android:gravity="center_vertical"
android:orientation="horizontal">
android:orientation="horizontal"
android:visibility="visible">
<ImageView
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:src="@drawable/ic_search_food" />
android:src="@drawable/ic_search_food"
tools:ignore="ContentDescription" />
<EditText
android:id="@+id/etInputFood"
@@ -153,7 +166,7 @@
android:layout_marginEnd="24dp"
android:background="@null"
android:fontFamily="sans-serif-medium"
android:hint="输入食材名称"
android:hint="输入名称搜索"
android:imeOptions="actionSearch"
android:inputType="text"
android:maxLines="1"
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardBackgroundColor="@color/white"
app:cardCornerRadius="12dp"
app:cardElevation="0dp">
<LinearLayout
android:layout_width="500dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- 标题 -->
<TextView
android:id="@+id/tvDialogTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:gravity="center"
android:textColor="#ff141428"
android:textSize="32sp"
android:textStyle="bold" />
<!-- ChipGroup 选择区域 -->
<com.google.android.material.chip.ChipGroup
android:id="@+id/chipGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginHorizontal="30dp"
android:layout_marginVertical="50dp"
app:chipSpacingHorizontal="30dp"
app:chipSpacingVertical="18dp"
app:selectionRequired="false"
app:singleSelection="true" />
<!-- 分割线 -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#FFDCDCF0" />
<!-- 底部按钮 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="72dp"
android:gravity="center"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnCancel"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/bg_pressed"
android:text="取消"
android:textColor="@android:color/darker_gray"
android:textSize="24sp" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#FFDCDCF0" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnConfirm"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/bg_pressed"
android:text="确定"
android:textColor="@color/bg_card_blue"
android:textSize="24sp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
@@ -0,0 +1,106 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="600dp"
android:layout_height="wrap_content"
android:background="@drawable/bg_white_radius12"
android:orientation="vertical"
android:paddingHorizontal="40dp"
android:paddingVertical="36dp">
<!-- 标题 -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="环境切换"
android:textColor="#ff141428"
android:textSize="36sp"
android:textStyle="bold" />
<!-- 分割线 -->
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="24dp"
android:background="#FFDCDCF0" />
<!-- 环境选项 -->
<RadioGroup
android:id="@+id/rgEnv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:orientation="vertical">
<RadioButton
android:id="@+id/rbTest"
android:layout_width="match_parent"
android:layout_height="72dp"
android:gravity="center_vertical"
android:paddingStart="16dp"
android:text="本地环境"
android:textColor="#ff141428"
android:textSize="28sp" />
<RadioButton
android:id="@+id/rbUat"
android:layout_width="match_parent"
android:layout_height="72dp"
android:gravity="center_vertical"
android:paddingStart="16dp"
android:text="测试环境"
android:textColor="#ff141428"
android:textSize="28sp" />
<RadioButton
android:id="@+id/rbProd"
android:layout_width="match_parent"
android:layout_height="72dp"
android:gravity="center_vertical"
android:paddingStart="16dp"
android:text="生产环境"
android:textColor="#ff141428"
android:textSize="28sp" />
</RadioGroup>
<!-- 分割线 -->
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="24dp"
android:background="#FFDCDCF0" />
<!-- 底部按钮 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="88dp"
android:layout_marginTop="24dp"
android:gravity="center"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnCancel"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginEnd="20dp"
android:layout_weight="1"
android:background="@drawable/bg_cancel"
android:text="取消"
android:textColor="@color/bg_card_blue"
android:textSize="28sp" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnConfirm"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_weight="1"
android:background="@drawable/bg_confirm"
android:text="确认"
android:textColor="#FFFFFF"
android:textSize="28sp" />
</LinearLayout>
</LinearLayout>
+48 -36
View File
@@ -1,48 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<!--<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"-->
<!-- xmlns:tools="http://schemas.android.com/tools"-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="80dp"-->
<!-- android:layout_margin="12dp">-->
<!-- <TextView-->
<!-- android:id="@+id/btnFoodName"-->
<!-- android:layout_width="wrap_content"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:layout_gravity="center"-->
<!-- android:ellipsize="end"-->
<!-- android:gravity="center"-->
<!-- android:maxLines="1"-->
<!-- android:paddingStart="5dp"-->
<!-- android:paddingEnd="5dp"-->
<!-- android:fontFamily="sans-serif-medium"-->
<!-- android:textColor="@color/black999"-->
<!-- android:textSize="30sp"-->
<!-- tools:text="土豆丝" />-->
<!--</FrameLayout>-->
<com.google.android.material.button.MaterialButton xmlns:android="http://schemas.android.com/apk/res/android"
<!-- 搜索食材列表 item:食材名 + 编码副行,今日已验收时右上角显示绿色圆点 -->
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/btnFoodName"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:id="@+id/cardFood"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_height="96dp"
android:layout_margin="12dp"
app:cardBackgroundColor="@color/white"
app:cardCornerRadius="12dp"
app:cardElevation="0dp"
app:strokeColor="#E6E6E6"
app:strokeWidth="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingStart="5dp"
android:paddingTop="10dp"
android:paddingEnd="5dp">
<TextView
android:id="@+id/tvFoodName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:insetTop="0dp"
android:insetBottom="0dp"
android:maxLines="1"
app:paddingStart="5dp"
app:paddingEnd="5dp"
android:insetRight="0dp"
android:insetLeft="0dp"
android:paddingHorizontal="8dp"
android:textColor="@color/black999"
android:textSize="30sp"
app:cornerRadius="12dp"
app:strokeWidth="2dp"
tools:text="土豆丝土豆丝土豆丝土豆丝土豆丝土豆丝"
/>
tools:text="土豆丝土豆丝土豆丝" />
<TextView
android:id="@+id/tvMaterCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:ellipsize="end"
android:gravity="center"
android:maxLines="1"
android:textColor="@color/black999"
android:textSize="16sp"
tools:text="0102003" />
</LinearLayout>
<!-- 今日已验收标识圆点,默认隐藏,由 Adapter 控制显示 -->
<View
android:id="@+id/viewAcceptedDot"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_gravity="top|end"
android:layout_margin="10dp"
android:background="@drawable/shape_accepted_dot"
android:visibility="gone"
tools:visibility="visible" />
</com.google.android.material.card.MaterialCardView>
@@ -3,8 +3,8 @@
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layoutCard"
android:layout_width="match_parent"
android:layout_height="216dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="12dp"
app:cardBackgroundColor="@color/bg_card_blue"
app:cardCornerRadius="12dp"
@@ -38,15 +38,28 @@
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:includeFontPadding="false"
android:textColor="@color/white"
android:textSize="30sp"
android:textStyle="bold"
tools:text="空" />
<TextView
android:id="@+id/tvFoodType"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:ellipsize="end"
android:gravity="center"
android:includeFontPadding="false"
android:maxLines="1"
android:textColor="@color/white"
android:textSize="20sp"
tools:text="切块" />
<Space
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.833" />
android:layout_weight="0.8" />
<TextView
android:id="@+id/tvFoodWeight"
@@ -62,7 +75,7 @@
<Space
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.933" />
android:layout_weight="0.9" />
<TextView
android:id="@+id/tvStoreDate"
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:elevation="8dp"
android:orientation="vertical">
<TextView
android:id="@+id/tv_env_switch"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="切换环境"
android:textColor="#333333"
android:textSize="14sp" />
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="#E0E0E0" />
<TextView
android:id="@+id/tv_log"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="查看日志"
android:textColor="#333333"
android:textSize="14sp" />
</LinearLayout>
+2
View File
@@ -17,7 +17,9 @@
<color name="food_name_black">#0A143C</color>
<color name="food_weight_blue">#C8C8FF</color>
<color name="food_weight_orange">#FF6400</color>
<color name="accepted_green">#34C77B</color>
<color name="black999">#999999</color>
<color name="black666">#666666</color>
<color name="white_f6">#F6F6F6</color>
<color name="gray_edit">#E6EBF0</color>
</resources>
@@ -0,0 +1,475 @@
package com.shuwei.intelligent.shelves.serial
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* ScaleFrameParser 单元测试
*
* 测试数据来源:秤心跳数据.md 中的实际抓包数据
* 关键验证点:重量使用 BCD 解码(而非十六进制),与旧代码存在差异
*/
class ScaleFrameParserTest {
private lateinit var parser: ScaleFrameParser
// ----------------------------------------------------------------
// 测试数据常量(来自 秤心跳数据.md)
// ----------------------------------------------------------------
/** 旧设备(12台秤)心跳帧1 */
private val OLD_HEARTBEAT_1 =
"D6DADEDB01010C0000000008000000020000800100008000000000010000800500008001000080030000800200008099180080721800800000000000000000000000000000000000000000010101015037414645333633333334333731373056322E313007FFFF"
/** 旧设备(12台秤)心跳帧2 */
private val OLD_HEARTBEAT_2 =
"D6DADEDB01010C0900000027170000122500007511000001000000090000001100000012000000430000000800008000150080591500800000000000000000000000000000000000000000010100005031323136334238423134303233303456322E313112FFFF"
/** 新设备(24台秤)心跳帧1 */
private val NEW_HEARTBEAT_1 =
"D6DADEDB0101189322000000000000053300001534000079230000611100000000000007000080030000000300000004000080010000000100008003000000180600004214008083130080741200800115008066130080501400800411008033120080631600800000000000000000000000000000000000000000010101015031463137334238423134303233303456322E313130FFFF"
/** 旧设备(12台秤)获取状态响应 */
private val OLD_STATUS =
"D6DADEDB0302010100000C1100000027170000122500007711000001000000110000001300000012000000430000001000008000150080441500805031323136334238423134303233303456322E313113FFFF"
/** 新设备(24台秤)获取状态响应 */
private val NEW_STATUS =
"D6DADEDB030201010101181422000037110000783100009033000054000080100000000100000028240000070000000100008006000080030000801806000009000000461100004014008081130080721200800115008064130080501400809810008033120080651600805031463137334238423134303233303456322E31314AFFFF"
@Before
fun setUp() {
parser = ScaleFrameParser()
}
// ================================================================
// 一、重量 BCD 解析测试
// ================================================================
/**
* 协议文档示例:13 10 00 00 = 1.013KG = 1013g
* 旧代码(hex):0x1013 = 4115g ← 错误
* 新代码(BCD):"00001013".toLong() = 1013g ← 正确
*/
@Test
fun testWeight_protocolExample_1013g() {
val bytes = byteArrayOf(0x13, 0x10, 0x00, 0x00)
val result = parser.parseWeightBytes(bytes, 0)
assertEquals("协议示例 1.013KG 解析错误", 1013, result)
}
/**
* 协议文档示例:13 01 02 00 = 20.113KG = 20113g
* 旧代码(hex):0x20113 = 131347... 越界 ← 错误
* 新代码(BCD):"00020113".toLong() = 20113g ← 正确
*/
@Test
fun testWeight_protocolExample_20113g() {
val bytes = byteArrayOf(0x13, 0x01, 0x02, 0x00)
val result = parser.parseWeightBytes(bytes, 0)
assertEquals("协议示例 20.113KG 解析错误", 20113, result)
}
/**
* 协议文档示例:13 10 00 80 = -1.013KG = -1013g(负数,最高位为1
*/
@Test
fun testWeight_protocolExample_negative_1013g() {
val bytes = byteArrayOf(0x13, 0x10, 0x00, 0x80.toByte())
val result = parser.parseWeightBytes(bytes, 0)
assertEquals("协议示例 -1.013KG 解析错误", -1013, result)
}
/** 零重量 */
@Test
fun testWeight_zero() {
val bytes = byteArrayOf(0x00, 0x00, 0x00, 0x00)
assertEquals(0, parser.parseWeightBytes(bytes, 0))
}
/**
* 实际心跳数据:08 00 00 00 = 8g(正数,小值时 BCD 与 hex 相同)
*/
@Test
fun testWeight_actual_8g() {
val bytes = byteArrayOf(0x08, 0x00, 0x00, 0x00)
assertEquals(8, parser.parseWeightBytes(bytes, 0))
}
/**
* 实际心跳数据:02 00 00 80 = -2g(负数小值)
*/
@Test
fun testWeight_actual_negative_2g() {
val bytes = byteArrayOf(0x02, 0x00, 0x00, 0x80.toByte())
assertEquals(-2, parser.parseWeightBytes(bytes, 0))
}
/**
* 实际心跳数据:99 18 00 80 = -1899g
* 旧代码(hex):-0x1899 = -6297g ← 错误(差3倍多)
* 新代码(BCD):-1899g ← 正确(约1.9KG货物)
*/
@Test
fun testWeight_actual_negative_1899g() {
val bytes = byteArrayOf(0x99.toByte(), 0x18, 0x00, 0x80.toByte())
val result = parser.parseWeightBytes(bytes, 0)
assertEquals("心跳数据 -1899g 解析错误,旧代码会给出 -6297g", -1899, result)
}
/**
* 实际心跳数据:72 18 00 80 = -1872g
* 旧代码(hex):-0x1872 = -6258g ← 错误
* 新代码(BCD):-1872g ← 正确
*/
@Test
fun testWeight_actual_negative_1872g() {
val bytes = byteArrayOf(0x72, 0x18, 0x00, 0x80.toByte())
assertEquals(-1872, parser.parseWeightBytes(bytes, 0))
}
/**
* 实际状态数据:27 17 00 00 = 1727g
* 旧代码(hex):0x1727 = 5927g ← 错误(3.4倍)
* 新代码(BCD):1727g ← 正确(约1.7KG货物,合理)
*/
@Test
fun testWeight_actual_1727g() {
val bytes = byteArrayOf(0x27, 0x17, 0x00, 0x00)
val result = parser.parseWeightBytes(bytes, 0)
assertEquals("状态数据 1727g 解析错误,旧代码会给出 5927g", 1727, result)
}
/**
* 实际状态数据:12 25 00 00 = 2512g
* 旧代码(hex):0x2512 = 9490g ← 错误
* 新代码(BCD):2512g ← 正确
*/
@Test
fun testWeight_actual_2512g() {
val bytes = byteArrayOf(0x12, 0x25, 0x00, 0x00)
assertEquals(2512, parser.parseWeightBytes(bytes, 0))
}
/** 验证 offset 参数:从字节数组中间某位置解析 */
@Test
fun testWeight_withOffset() {
val bytes = byteArrayOf(
0x00, 0x00, // 前缀,不参与解析
0x13, 0x10, 0x00, 0x00 // 1013g,从 offset=2 解析
)
assertEquals(1013, parser.parseWeightBytes(bytes, 2))
}
// ================================================================
// 二、帧结构解析测试(parseFrame)
// ================================================================
@Test
fun testParseFrame_oldHeartbeat1_basicFields() {
val frame = parser.parseFrame(OLD_HEARTBEAT_1)
assertNotNull("帧解析不应返回 null", frame)
frame!!
assertEquals("CMD 应为 0x01(心跳)", 0x01.toByte(), frame.cmd)
assertEquals("FLAG 应为 0x01(终端发起)", 0x01.toByte(), frame.flag)
}
@Test
fun testParseFrame_oldHeartbeat1_fixedBody() {
val frame = parser.parseFrame(OLD_HEARTBEAT_1)!!
// 37414645333633333334333731373056322E313007FFFF 前固定数据体
// 终端ID: 37 41 46 45 33 36 33 33 33 34 33 37 31 37 30 → "7AFE36333437170"
assertEquals("终端ID长度应为15", 15, frame.terminalId.length)
assertEquals("终端ID解析错误", "7AFE36333437170", frame.terminalId)
// 固件版本: 56 32 2E 31 30 → "V2.10"
assertEquals("固件版本解析错误", "V2.10", frame.firmwareVersion)
assertEquals("命令次数解析错误", 7, frame.cmdCount)
}
@Test
fun testParseFrame_oldHeartbeat2_fixedBody() {
val frame = parser.parseFrame(OLD_HEARTBEAT_2)!!
// 终端ID: 50 31 32 31 36 33 42 38 42 31 34 30 32 33 30 → "P12163B8B140230"
assertEquals("终端ID解析错误", "12163B8B1402304", frame.terminalId)
assertEquals("固件版本解析错误", "V2.11", frame.firmwareVersion)
assertEquals("命令次数解析错误", 18, frame.cmdCount)
}
@Test
fun testParseFrame_newHeartbeat1_fixedBody() {
val frame = parser.parseFrame(NEW_HEARTBEAT_1)!!
// 终端ID: 50 31 46 31 37 33 42 38 42 31 34 30 32 33 30 → "P1F173B8B140230"
assertEquals("新设备终端ID解析错误", "1F173B8B1402304", frame.terminalId)
assertEquals("新设备固件版本解析错误", "V2.11", frame.firmwareVersion)
assertEquals("新设备命令次数解析错误", 48, frame.cmdCount)
}
@Test
fun testParseFrame_invalidData_returnsNull() {
assertNull("空字符串应返回 null", parser.parseFrame(""))
assertNull("过短数据应返回 null", parser.parseFrame("D6DADEDB0101FFFF"))
assertNull("无效协议头应返回 null", parser.parseFrame("AABBCCDD0101FFFF"))
}
// ================================================================
// 三、心跳数据解析测试(parseHeartbeat
// ================================================================
@Test
fun testHeartbeat_oldDevice_scaleCount() {
val frame = parser.parseFrame(OLD_HEARTBEAT_1)!!
val data = parser.parseHeartbeat(frame.rawBody)
assertNotNull("心跳数据不应为 null", data)
assertEquals("旧设备秤数量应为12", 12, data!!.scaleCount)
}
@Test
fun testHeartbeat_oldDevice_weights() {
val frame = parser.parseFrame(OLD_HEARTBEAT_1)!!
val data = parser.parseHeartbeat(frame.rawBody)!!
val weights = data.weights
assertEquals("秤列表大小应与秤数量一致", 12, weights.size)
// 秤100000000 → 0g
assertEquals("秤1重量", 0, weights[0].grams)
assertEquals("秤1编号", 1, weights[0].index)
// 秤208000000 → 8g
assertEquals("秤2重量", 8, weights[1].grams)
// 秤302000080 → -2g(负数)
assertEquals("秤3重量(去皮负值)", -2, weights[2].grams)
// 秤401000080 → -1g
assertEquals("秤4重量", -1, weights[3].grams)
// 秤500000000 → 0g
assertEquals("秤5重量", 0, weights[4].grams)
// 秤705000080 → -5g
assertEquals("秤7重量", -5, weights[6].grams)
// 秤1199180080 → -1899gBCD;旧代码 hex 会得到 -6297g
assertEquals("秤11重量(BCD:-1899ghex错误值:-6297g", -1899, weights[10].grams)
// 秤1272180080 → -1872gBCD;旧代码 hex 会得到 -6258g
assertEquals("秤12重量(BCD:-1872ghex错误值:-6258g", -1872, weights[11].grams)
}
@Test
fun testHeartbeat_oldDevice_lockStates() {
val frame = parser.parseFrame(OLD_HEARTBEAT_1)!!
val data = parser.parseHeartbeat(frame.rawBody)!!
assertEquals("锁1门状态应为开(1)", 1, data.lock1Door)
assertEquals("锁1锁状态应为开(1)", 1, data.lock1Lock)
assertEquals("锁2门状态应为开(1)", 1, data.lock2Door)
assertEquals("锁2锁状态应为开(1)", 1, data.lock2Lock)
}
@Test
fun testHeartbeat_oldDevice_temperature() {
val frame = parser.parseFrame(OLD_HEARTBEAT_1)!!
val data = parser.parseHeartbeat(frame.rawBody)!!
// 温度字节 0x50 = 80
assertEquals("温度字节应为 800x50", 80, data.temperature)
}
@Test
fun testHeartbeat_newDevice_scaleCount() {
val frame = parser.parseFrame(NEW_HEARTBEAT_1)!!
val data = parser.parseHeartbeat(frame.rawBody)!!
assertEquals("新设备秤数量应为24", 24, data.scaleCount)
assertEquals("秤列表大小应为24", 24, data.weights.size)
}
@Test
fun testHeartbeat_newDevice_weight1() {
val frame = parser.parseFrame(NEW_HEARTBEAT_1)!!
val data = parser.parseHeartbeat(frame.rawBody)!!
// 秤193220000 → big-endian "00002293" → BCD 2293g
assertEquals("新设备秤1重量(BCD:2293ghex错误值:8851g)", 2293, data.weights[0].grams)
}
@Test
fun testHeartbeat_newDevice_weight3() {
val frame = parser.parseFrame(NEW_HEARTBEAT_1)!!
val data = parser.parseHeartbeat(frame.rawBody)!!
// 秤305330000 → big-endian "00003305" → BCD 3305g
assertEquals("新设备秤3重量(BCD:3305ghex错误值:13061g)", 3305, data.weights[2].grams)
}
@Test
fun testHeartbeat_weightKg() {
val weight = ScaleWeight(index = 1, grams = 1013)
assertEquals("kg 转换错误", 1.013, weight.kg, 0.0001)
val negWeight = ScaleWeight(index = 2, grams = -1899)
assertEquals("负重量 kg 转换错误", -1.899, negWeight.kg, 0.0001)
}
// ================================================================
// 四、获取状态数据解析测试(parseStatus
// ================================================================
@Test
fun testStatus_oldDevice_lockStates() {
val frame = parser.parseFrame(OLD_STATUS)!!
assertEquals("CMD 应为 0x03(获取状态)", 0x03.toByte(), frame.cmd)
val data = parser.parseStatus(frame.rawBody)!!
assertEquals("锁1锁状态", 1, data.lock1Lock)
assertEquals("锁1门状态", 1, data.lock1Door)
assertEquals("锁2锁状态", 0, data.lock2Lock)
assertEquals("锁2门状态", 0, data.lock2Door)
}
@Test
fun testStatus_oldDevice_scaleCount() {
val frame = parser.parseFrame(OLD_STATUS)!!
val data = parser.parseStatus(frame.rawBody)!!
assertEquals("旧设备状态秤数量应为12", 12, data.scaleCount)
}
@Test
fun testStatus_oldDevice_weights() {
val frame = parser.parseFrame(OLD_STATUS)!!
val data = parser.parseStatus(frame.rawBody)!!
val weights = data.weights
// 秤111000000 → big-endian "00000011" → BCD 11ghex也是17g,差异小但仍不同)
assertEquals("状态秤1重量(BCD:11ghex:17g)", 11, weights[0].grams)
// 秤227170000 → big-endian "00001727" → BCD 1727ghex:5927g,差异巨大)
assertEquals("状态秤2重量(BCD:1727ghex错误值:5927g)", 1727, weights[1].grams)
// 秤312250000 → BCD 2512ghex:9490g
assertEquals("状态秤3重量(BCD:2512ghex错误值:9490g)", 2512, weights[2].grams)
// 秤477110000 → BCD 1177ghex:4471g
assertEquals("状态秤4重量(BCD:1177ghex错误值:4471g)", 1177, weights[3].grams)
// 秤501000000 → 1g
assertEquals("状态秤5重量", 1, weights[4].grams)
// 秤1010000080 → -10g(负数)
assertEquals("状态秤10重量(去皮负值)", -10, weights[9].grams)
// 秤1100150080 → big-endian "80001500",清符号位 "00001500" → BCD -1500g
assertEquals("状态秤11重量(BCD:-1500ghex:-5376g)", -1500, weights[10].grams)
// 秤1244150080 → "00001544" → BCD -1544g
assertEquals("状态秤12重量(BCD:-1544ghex:-5444g)", -1544, weights[11].grams)
}
@Test
fun testStatus_newDevice_scaleCount() {
val frame = parser.parseFrame(NEW_STATUS)!!
val data = parser.parseStatus(frame.rawBody)!!
assertEquals("新设备状态秤数量应为24", 24, data.scaleCount)
}
@Test
fun testStatus_newDevice_weight1() {
val frame = parser.parseFrame(NEW_STATUS)!!
val data = parser.parseStatus(frame.rawBody)!!
// 秤114220000 → big-endian "00002214" → BCD 2214g
assertEquals("新设备状态秤1重量(BCD:2214g)", 2214, data.weights[0].grams)
}
// ================================================================
// 五、分片拼装测试(appendData
// ================================================================
@Test
fun testAppendData_completeFrame_returnedImmediately() {
val result = parser.appendData(OLD_HEARTBEAT_1)
assertNotNull("完整帧应直接返回", result)
assertEquals("返回的帧内容应完整", OLD_HEARTBEAT_1, result)
}
@Test
fun testAppendData_twoFragments() {
// 将完整帧从中间切分为两段
val mid = OLD_HEARTBEAT_1.length / 2
val part1 = OLD_HEARTBEAT_1.substring(0, mid)
val part2 = OLD_HEARTBEAT_1.substring(mid)
// 第一段(含帧头,不含帧尾)→ 应返回 null
val result1 = parser.appendData(part1)
assertNull("第一分片不应返回完整帧", result1)
// 第二段(含帧尾,不含帧头)→ 应拼装完成并返回完整帧
val result2 = parser.appendData(part2)
assertNotNull("第二分片拼装后应返回完整帧", result2)
assertEquals("拼装后帧内容应与原始数据一致", OLD_HEARTBEAT_1, result2)
}
@Test
fun testAppendData_threeFragments() {
// 将完整帧切成三段
val len = OLD_HEARTBEAT_1.length
val part1 = OLD_HEARTBEAT_1.substring(0, len / 3)
val part2 = OLD_HEARTBEAT_1.substring(len / 3, len * 2 / 3)
val part3 = OLD_HEARTBEAT_1.substring(len * 2 / 3)
assertNull("第1段不应返回完整帧", parser.appendData(part1))
assertNull("第2段不应返回完整帧", parser.appendData(part2))
val result = parser.appendData(part3)
assertNotNull("第3段拼装后应返回完整帧", result)
assertEquals("三段拼装结果应与原始数据一致", OLD_HEARTBEAT_1, result)
}
@Test
fun testAppendData_reset_clearsBuffer() {
val mid = OLD_HEARTBEAT_1.length / 2
// 先追加第一段(写入缓冲)
parser.appendData(OLD_HEARTBEAT_1.substring(0, mid))
// 重置后再追加完整帧,应正常返回
parser.reset()
val result = parser.appendData(OLD_HEARTBEAT_1)
assertNotNull("reset 后追加完整帧应正常返回", result)
}
@Test
fun testAppendData_newFrameAfterComplete() {
// 模拟连续两帧数据,第二帧紧跟在第一帧末尾
val twoFrames = OLD_HEARTBEAT_1 + OLD_HEARTBEAT_2
// 包含帧头和帧尾,应只返回第一帧
val result = parser.appendData(twoFrames)
assertNotNull("连续两帧中应能解析出完整帧", result)
assertTrue("应返回以协议头开头的帧", result!!.startsWith("D6DADEDB"))
assertTrue("应返回以协议尾结尾的帧", result.endsWith("FFFF"))
}
// ================================================================
// 六、端到端集成测试(appendData + parseFrame + parseHeartbeat
// ================================================================
@Test
fun testEndToEnd_oldHeartbeat_fragmentedThenParse() {
val mid = OLD_HEARTBEAT_1.length / 2
parser.appendData(OLD_HEARTBEAT_1.substring(0, mid))
val frameHex = parser.appendData(OLD_HEARTBEAT_1.substring(mid))!!
val frame = parser.parseFrame(frameHex)!!
val data = parser.parseHeartbeat(frame.rawBody)!!
assertEquals(0x01.toByte(), frame.cmd)
assertEquals(12, data.scaleCount)
assertEquals(8, data.weights[1].grams) // 秤2: 8g
assertEquals(-1899, data.weights[10].grams) // 秤11: -1899g
assertEquals("7AFE36333437170", frame.terminalId)
}
@Test
fun testEndToEnd_newHeartbeat_parseComplete() {
val frameHex = parser.appendData(NEW_HEARTBEAT_1)!!
val frame = parser.parseFrame(frameHex)!!
val data = parser.parseHeartbeat(frame.rawBody)!!
assertEquals(24, data.scaleCount)
assertEquals(2293, data.weights[0].grams) // 秤1: 2293g
assertEquals("1F173B8B1402304", frame.terminalId)
assertEquals("V2.11", frame.firmwareVersion)
}
}
+2 -2
View File
@@ -4,5 +4,5 @@
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Tue Jan 13 10:38:32 CST 2026
sdk.dir=C\:\\Users\\HUAWEI\\AppData\\Local\\Android\\Sdk
#Thu Jul 02 16:04:28 CST 2026
sdk.dir=C\:\\Users\\MZF\\AppData\\Local\\Android\\Sdk
+76
View File
@@ -0,0 +1,76 @@
// 测试列表转换逻辑
data class TestModel(var deviceId: String = "", val value: Int)
fun testTransform(tempList: List<TestModel>): List<TestModel> {
val list = mutableListOf<TestModel>()
val deviceId = "test-device"
val leftSize = (tempList.size + 1) / 2 // 左列长度(向上取整)
val rightSize = tempList.size / 2 // 右列长度(向下取整)
repeat(rightSize) { index ->
list.add(tempList[index].also { it.deviceId = deviceId })
list.add(tempList[leftSize + index].also { it.deviceId = deviceId })
}
// 处理奇数长度:左列比右列多一个
if (tempList.size % 2 != 0) {
list.add(tempList[rightSize].also { it.deviceId = deviceId })
}
return list
}
fun main() {
// 测试用例 1: 奇数 5 个元素
println("=== 测试 1: 奇数 [1,2,3,4,5] ===")
val test1 = listOf(1, 2, 3, 4, 5).map { TestModel(value = it) }
val result1 = testTransform(test1)
println("输入: ${test1.map { it.value }}")
println("输出: ${result1.map { it.value }}")
println("期望: [1, 4, 2, 5, 3]")
println("匹配: ${result1.map { it.value } == listOf(1, 4, 2, 5, 3)}\n")
// 测试用例 2: 偶数 6 个元素
println("=== 测试 2: 偶数 [1,2,3,4,5,6] ===")
val test2 = listOf(1, 2, 3, 4, 5, 6).map { TestModel(value = it) }
val result2 = testTransform(test2)
println("输入: ${test2.map { it.value }}")
println("输出: ${result2.map { it.value }}")
println("期望: [1, 4, 2, 5, 3, 6]")
println("匹配: ${result2.map { it.value } == listOf(1, 4, 2, 5, 3, 6)}\n")
// 测试用例 3: 偶数 10 个元素(实际业务场景)
println("=== 测试 3: 偶数 [1,2,3,4,5,6,7,8,9,10] ===")
val test3 = (1..10).map { TestModel(value = it) }
val result3 = testTransform(test3)
println("输入: ${test3.map { it.value }}")
println("输出: ${result3.map { it.value }}")
println("期望: [1, 6, 2, 7, 3, 8, 4, 9, 5, 10]")
println("匹配: ${result3.map { it.value } == listOf(1, 6, 2, 7, 3, 8, 4, 9, 5, 10)}\n")
// 测试用例 4: 奇数 7 个元素
println("=== 测试 4: 奇数 [1,2,3,4,5,6,7] ===")
val test4 = (1..7).map { TestModel(value = it) }
val result4 = testTransform(test4)
println("输入: ${test4.map { it.value }}")
println("输出: ${result4.map { it.value }}")
println("期望: [1, 5, 2, 6, 3, 7, 4]")
println("匹配: ${result4.map { it.value } == listOf(1, 5, 2, 6, 3, 7, 4)}\n")
// 测试用例 5: 边界情况 2 个元素
println("=== 测试 5: 边界 [1,2] ===")
val test5 = listOf(1, 2).map { TestModel(value = it) }
val result5 = testTransform(test5)
println("输入: ${test5.map { it.value }}")
println("输出: ${result5.map { it.value }}")
println("期望: [1, 2]")
println("匹配: ${result5.map { it.value } == listOf(1, 2)}\n")
// 测试用例 6: 边界情况 1 个元素
println("=== 测试 6: 边界 [1] ===")
val test6 = listOf(1).map { TestModel(value = it) }
val result6 = testTransform(test6)
println("输入: ${test6.map { it.value }}")
println("输出: ${result6.map { it.value }}")
println("期望: [1]")
println("匹配: ${result6.map { it.value } == listOf(1)}\n")
}
+74
View File
@@ -0,0 +1,74 @@
协议头 4 字节
命令 1 字节
标志 1 字节
数据体 :不同命令不固定,详细见下方
协议尾 2字节
协议头 0xD6 0xDA 0xDE 0xDB
命令:
◼ 0x00:终端激活(终端发起)
◼ 0x01:心跳(终端发起)
◼ 0x81:心跳(终端发起,当终端发送此命令时需要服务端存储串口屏显示信息)
◼ 0x02:开锁(服务端发起)
◼ 0x03:获取状态(服务端发起)
◼ 0x04:秤置零(服务端发起)
◼ 0x06:秤标定(服务端发起)
◼ 0x05:卡号上发(终端发起)
◼ 0x07:价签设置(服务端发起)
◼ 0x08:串口屏(服务端发起)
◼ 0x09:语音播报(服务端发起)
◼ 0x0A:价签(第二块串口屏/透传)设置(服务端发起)
◼ 0x0B:操作记录上传(终端发起)
◼ 0x0C:对时(终端发起)
◼ 0x0E:终端位置上报(终端发起)
◼ 0x0F:温控器控制(服务端发起)
◼ 0x10:温控信息上报(终端发起)
◼ 0x11:临时参数设置(服务端发起)
固定数据体 :(终端ID :15 字节,固件版本 :5字节,命令次数 :1字节)
0x01心跳终端发起数据体内容格式:
秤数量 1 字节
N个秤重量数据 :N x 4字节
物联卡号 20 字节
锁1门状态 1 字节
锁1锁状态 1 字节
锁2门状态 1 字节
锁2锁状态 1 字节
温度 1 字节
固定数据体 :(终端ID :15 字节,固件版本 :5字节,命令次数 :1字节)
0x03获取状态服务端响应数据体内容格式:
锁1锁状态 1 字节
锁1门状态 1 字节
锁2锁状态 1 字节
锁2门状态 1 字节
秤数量 1 字节
N个秤重量数据 :N x 4字节
温度 1 字节
固定数据体 :(终端ID :15 字节,固件版本 :5字节,命令次数 :1字节)
示例数据见下方----------------------------
旧设备10台秤心跳数据:
D6DADEDB01010C0000000008000000020000800100008000000000010000800500008001000080030000800200008099180080721800800000000000000000000000000000000000000000010101015037414645333633333334333731373056322E313007FFFF
D6DADEDB01010C0900000027170000122500007511000001000000090000001100000012000000430000000800008000150080591500800000000000000000000000000000000000000000010100005031323136334238423134303233303456322E313112FFFF
新设备15台秤心跳数据:
D6DADEDB0101189322000000000000053300001534000079230000611100000000000007000080030000000300000004000080010000000100008003000000180600004214008083130080741200800115008066130080501400800411008033120080631600800000000000000000000000000000000000000000010101015031463137334238423134303233303456322E313130FFFF
D6DADEDB0101181422000037110000823100009233000054000080100000000100000030240000050000000300008002000080050000802006000007000000441100004014008081130080721200800315008064130080521400809610008033120080631600800000000000000000000000000000000000000000010101015031463137334238423134303233303456322E313147FFFF
D6DADEDB0101180635000075190000842800000100008014000080060000800100008004000080050000801500008007000000080000800700008003000000050000008118008054180080231800801018008059170080221800809418008075320080761900800000000000000000000000000000000000000000010101015033453137334238423134303233303456322E313139FFFF
旧设备10台秤获取状态数据:
D6DADEDB0302010100000C1100000027170000122500007711000001000000110000001300000012000000430000001000008000150080441500805031323136334238423134303233303456322E313113FFFF
新设备15台秤获取状态数据:
D6DADEDB030201010101180635000077190000842800000100008014000080040000800100008004000080050000801500008007000000080000800900008005000000030000008118008054180080231800801018008059170080221800809418008079320080761900805033453137334238423134303233303456322E31313CFFFF
D6DADEDB030201010101181422000037110000783100009033000054000080100000000100000028240000070000000100008006000080030000801806000009000000461100004014008081130080721200800115008064130080501400809810008033120080651600805031463137334238423134303233303456322E31314AFFFF
Binary file not shown.
+241
View File
@@ -0,0 +1,241 @@
# 货柜设备端 — API 文档
> Controller: `NutCabinetController`(毛菜柜/净菜柜通用,通过 `cabinetType` 区分)
> 路径前缀: `/neglect/mater-cabinet`Nacos 白名单,无需 Sa-Token
> 日期: 2026-06-24
---
## 一、货柜初始化
设备端首次加载调用,后端从 `nut_terminal.device_type` 推导毛菜/净菜类型,懒创建空置格口,返回柜体元信息 + 全量格口。
```
GET /neglect/mater-cabinet/init?cabinetId=CAB-001
```
**参数**`cabinetId` — 必填,智能柜编号(即 `nut_terminal.device_code`
**响应**
```json
{
"cabinetType": 1, // 1=毛菜柜,2=净菜柜(后端推导)
"cabinetId": "CAB-001",
"deviceName": "毛菜柜-A区",
"canteenId": 100,
"canteenName": "第一食堂",
"horizontalRows": 4,
"verticalCount": 5,
"slots": [
{
"id": 1,
"slotNo": "1",
"cabinetId": "CAB-001",
"cabinetType": 1,
"hasContent": true,
"inboundNo": "IN20260623001",
"materId": 10001,
"materName": "菠菜",
"traceCode": "TC20260601",
"vegTypeId": 10,
"weight": 5.2,
"storeTime": "2026-06-23 10:30:00"
},
{
"id": null,
"slotNo": "2",
"cabinetId": "CAB-001",
"cabinetType": 1,
"hasContent": false,
"weight": null,
"storeTime": null
}
]
}
```
**说明**
- `cabinetType` 由后端根据 `nut_terminal.device_type` 推导(`raw_cabinet`→1 / `clean_cabinet`→2),前端无需传
- `hasContent=true` 时有存放数据,业务字段(inboundNo/materId 等)有值
- `hasContent=false` 时空置,业务字段均为 null
- 格口按 slotNo 数值升序排列
- 每次调用均幂等:格口数不足时自动补建,已足则跳过
---
## 二、格口入柜
```
POST /neglect/mater-cabinet/put
```
**请求体**
```json
{
"cabinetType": 1, // 必填 — 1=毛菜柜,2=净菜柜
"cabinetId": "CAB-001", // 必填 — 智能柜编号
"slotNo": "1", // 必填 — 格口编号
"materId": 10001, // 必填 — 食材id
"materName": "菠菜", // 必填 — 食材名称
"traceCode": "TC20260601", // 选填 — 溯源码(净菜柜用于精确匹配)
"weight": 5.2 // 必填 — 入柜重量(kg)
}
```
**说明**
- 后端按食材+重量匹配对应入库记录(选重量最接近的一条),将其标记为"已入柜"
- 传 traceCode 时先按溯源码精确过滤,再按重量匹配
- 格口必须已由 `/init` 预置,否则报错"格口未初始化"
- 格口已有物品时拒绝入柜
- 格口行 UPDATE,流水表 INSERT
**响应**
```json
{ "code": 200, "data": "IN20260623001", "msg": "操作成功" }
```
---
## 三、格口列表(全部格口)
```
POST /neglect/mater-cabinet/slots
```
**请求体**
```json
{
"cabinetType": 1, // 必填 — 1=毛菜柜,2=净菜柜
"cabinetId": "CAB-001" // 必填 — 智能柜编号
}
```
**响应** — 与 `/init` 返回的 `slots` 字段结构完全相同
```json
[{
"id": 1,
"slotNo": "1",
"cabinetId": "CAB-001",
"cabinetType": 1,
"hasContent": true,
"inboundNo": "IN20260623001",
"materId": 10001,
"materName": "菠菜",
"traceCode": "TC20260601",
"vegTypeId": 10,
"weight": 5.2,
"storeTime": "2026-06-23 10:30:00"
}]
```
---
## 四、待入柜列表
```
POST /neglect/mater-cabinet/pending-inbound
```
**请求体**
```json
{
"cabinetType": 1, // 必填 — 货柜类型
"cabinetId": "CAB-001", // 必填 — 智能柜编号(DTO 校验要求,实际查询用 canteenId)
"canteenId": 100 // 必填 — 食堂id
}
```
**响应**
```json
[{
"id": 1,
"materId": 10001,
"materName": "菠菜",
"traceCode": "TC20260601",
"weight": 10.0,
"inboundNo": "IN20260623001",
"inboundTime": "2026-06-23 09:00:00",
"vegTypeId": 10,
"vegTypeName": "净菜包",
"spec": "500g"
}]
```
---
## 五、格口详情
```
POST /neglect/mater-cabinet/slot-detail
```
**请求体**
```json
{
"cabinetType": 1, // 必填
"cabinetId": "CAB-001", // 必填
"slotNo": "1" // 必填
}
```
**响应** — 与 `/init` 返回的 `slots` 元素结构相同
```json
{
"id": 1,
"slotNo": "1",
"cabinetId": "CAB-001",
"cabinetType": 1,
"hasContent": true,
"inboundNo": "IN20260623001",
"materId": 10001,
"materName": "菠菜",
"traceCode": "TC20260601",
"vegTypeId": 10,
"weight": 5.2,
"storeTime": "2026-06-23 10:30:00"
}
```
---
## 六、全量同步格口重量
```
POST /neglect/mater-cabinet/sync-weight
```
**请求体**
```json
{
"cabinetType": 1, // 必填 — 货柜类型
"cabinetId": "CAB-001", // 必填 — 智能柜编号
"slotList": [
{ "slotNo": "1", "weight": 5.1 },
{ "slotNo": "2", "weight": 3.0 },
{ "slotNo": "3", "weight": 0 }
]
}
```
**说明**
- 终端定时上报整柜各格口当前重量,后端比对变化写流水
- `weight: 0` 表示空格口,空置格口不产生重量变化流水
- 建议上报所有格口(含空格口),不要只报有变化的格口
**响应**
```json
{ "code": 200, "msg": "操作成功" }
```
---
## 七、前端注意事项
1. **调用顺序**:设备端启动后先调 `/init` 获取柜体元信息(行列数、食堂名)+ 全量格口。后续定时刷新格口状态走 `/sync-weight`
2. **`cabinetType`**`/init` **无需传**,后端从 `nut_terminal.device_type` 推导;其余接口仍需传(毛菜柜=1,净菜柜=2)
3. **`deviceType` / `deviceCode`**:由后端自动从请求头 `X-DEVICE-CODE` 填充,前端无需传
4. **sync-weight 的 `slotList`**:上报所有格口(含空格口 weight=0),不要只报有变化的格口
5. **格口编号**:毛菜柜和净菜柜的 slotNo 均为数字字符串("1", "2", …),最大编号 = horizontalRows × verticalCount
6. **格口结构**:一个格口即一条数据库记录,响应为扁平对象,无嵌套